text
stringlengths
7
3.69M
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin') const webpack = require('webpack') const CopyWebpackPlugin = require('copy-webpack-plugin'); const NODE_ENV = process.env.NODE_ENV || 'development' const config = { entry: './src/js/index.js', devtool: 'inline-source-map', devServer: { contentBase: './dist' }, output: { filename: '[name].js', path: path.resolve(__dirname, 'dist') }, resolve: { modules: ['node_modules', 'src'], alias: { 'froala-editor-js': path.resolve(__dirname, 'node_modules/froala-editor/js/froala_editor.pkgd.min.js'), 'froala-code-view-plugin': path.resolve(__dirname, 'node_modules/froala-editor/js/plugins/code_view.min.js'), 'codemirror-html-plugin': path.resolve(__dirname, 'node_modules/codemirror/mode/xml/xml.js'), 'froala-draggable-plugin': path.resolve(__dirname, 'node_modules/froala-editor/js/plugins/draggable.min.js') }, }, module: { rules: [{ test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['env'], plugins: ['babel-plugin-transform-object-rest-spread', "babel-plugin-transform-object-assign"] } } }, { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ] }, { test: /\.(png|gif|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?name=[name].[ext]' }, { test: /\.json$/, loader: 'json-loader' }, { test: /\.less$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' }, { loader: 'less-loader' } ] }, // { // test: /\.(png|ico|jpg|jpeg|gif)$/, // use: [ // // {loader: 'url-loader'}, // {loader: 'file-loader'}, // ] // } ] }, plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', CodeMirror: 'codemirror' }), new HtmlWebpackPlugin({ template: './src/index.html' }), new CopyWebpackPlugin([ { from: 'src/images', to: 'images' } ]) ] }; if (NODE_ENV === 'production') { config.plugins = config.plugins.concat([ new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ]) } module.exports = config
import React, { Component } from 'react'; import classnames from 'classnames'; import PropTypes from 'prop-types'; class Dislike extends Component { state = { isActive: false } componentDidMount() { const userDislike = this.props.userDislike; // console.log('dislike component') this.setState({isActive: (userDislike ? true: false)}); } componentWillReceiveProps(nextProps) { // Load new data when the dataSource property changes. // console.log('dislike receive props', nextProps) if (nextProps.userDislike != this.props.userDislike) { this.setState({isActive: (nextProps.userDislike ? true: false)}); } } render() { const {isDisabled, onDislike, totalDislike} = this.props; return ( <React.Fragment> <button className={classnames('btn btn-transparent', {linkActive: this.state.isActive})} disabled={isDisabled} onClick={()=> onDislike()}> <i className="fas fa-thumbs-down" /> {(totalDislike > 0 || totalDislike === 0) && ( <span>{totalDislike}</span> )} </button> </React.Fragment> ) } } Dislike.propTypes = { isDisabled: PropTypes.bool.isRequired, onDislike: PropTypes.func.isRequired, totalDislike: PropTypes.number, userDislike: PropTypes.number }; export default Dislike;
import React, { Component } from 'react' import { Link, NavLink } from 'react-router-dom' export default class Header extends Component { render() { return ( <header> <nav class="navbar navbar-dark bg-primary"> <div class="container"> <div class="row"> <div class="col-md-12"> <Link className="navbar-brand" to="/">FS</Link> <NavLink className="nav-link" exact to="/" activeClassName="active">Home</NavLink> <NavLink className="nav-link" to="/create" activeClassName="active">Create Furniture</NavLink> <NavLink className="nav-link" to="/profile" activeClassName="active">My Furniture</NavLink> <NavLink className="nav-link" to="/logout" activeClassName="active">Logout</NavLink> <NavLink className="nav-link" to="/login" activeClassName="active">Login</NavLink> <NavLink className="nav-link" to="/register" activeClassName="active">Register</NavLink> <span>72 items in catalog</span> </div> </div> </div> </nav> </header> ); } }
import { initRootVM } from 'mp/runtime/instance/index' import { callHook } from './call-hook' import { installHooks } from './install-hooks' const app = {} const hooks = [ 'onShow', 'onHide', 'onError', 'onPageNotFound' ] app.init = function (vueOptions) { let mpApp /* istanbul ignore else */ if (typeof my === 'undefined') { mpApp = App } else { // 支付宝小程序中 App() 必须在 app.js 里调用,且不能调用多次。 mpApp = my.__megalo.App // eslint-disable-line } const appOptions = { data: {}, globalData: {}, onLaunch (options = {}) { const rootVM = this.rootVM = initRootVM(this, vueOptions, options.query) const { globalData } = rootVM.$options this.globalData = ( globalData && ( typeof globalData === 'function' ? globalData.call(rootVM, options) : globalData ) || {} ) rootVM.globalData = this.globalData rootVM.$mount() callHook(rootVM, 'onLaunch', options) } } installHooks(appOptions, vueOptions.options, hooks) mpApp(appOptions) } export default app
/** * 组编辑JS */ /* * ========================= Query初始化 ========================= */ $(document).ready(function() { initForm(); getGroup(); }); /** * 初始化form */ function initForm() { // 设置from setFrom(); // 提交 $('#submitBtn').click(function() { $("#commForm").submit(); }); } // 设置form function setFrom() { // 校验form var vform = $("#commForm").validate({ rules : { gName : { required : true } }, messages : { gName : { required : '请输入组名!' } }, submitHandler : function(form) { $(form).ajaxSubmit({ type:"put", success : function(data) { if ("success" == data.code) { location.href=BASE+"/groups"; } else { alert(data.msg); } } }); }, errorPlacement : function(error, element) { error.insertAfter(element.parent()); element[0].focus(); return false; } }); } //获得组信息 var getGroup=function(){ $.ajax({ url : BASE + "groups/"+$("#gId").val(), dataType : "json", type:"get", async : true, data : { }, beforeSend : function() { }, error : function() { }, success : function(data) { if(data.code=='success'){ //写入组 $("#gName").val(data.obj.gName); $("#gDetail").val(data.obj.gDetail); } else{ alert(data.msg); } } }); }
import Ember from 'ember'; export default Ember.Route.extend({ actions: { sentLookup(params) { this.transitionTo('getSentResults', params.sent); } } });
require("common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/building/business" ], { "3b68": function(e, n, t) { t.r(n); var o = t("a9f6"), i = t.n(o); for (var s in o) [ "default" ].indexOf(s) < 0 && function(e) { t.d(n, e, function() { return o[e]; }); }(s); n.default = i.a; }, "3e35": function(e, n, t) { t.d(n, "b", function() { return o; }), t.d(n, "c", function() { return i; }), t.d(n, "a", function() {}); var o = function() { var e = this; e.$createElement; e._self._c; }, i = []; }, "536c": function(e, n, t) { var o = t("f442"); t.n(o).a; }, a9f6: function(e, n, t) { function o(e) { return e && e.__esModule ? e : { default: e }; } function i(e, n, t, o, i, s, u) { try { var a = e[s](u), r = a.value; } catch (e) { return void t(e); } a.done ? n(r) : Promise.resolve(r).then(o, i); } function s(e) { return function() { var n = this, t = arguments; return new Promise(function(o, s) { function u(e) { i(r, o, s, u, a, "next", e); } function a(e) { i(r, o, s, u, a, "throw", e); } var r = e.apply(n, t); u(void 0); }); }; } function u(e, n) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); n && (o = o.filter(function(n) { return Object.getOwnPropertyDescriptor(e, n).enumerable; })), t.push.apply(t, o); } return t; } function a(e) { for (var n = 1; n < arguments.length; n++) { var t = null != arguments[n] ? arguments[n] : {}; n % 2 ? u(Object(t), !0).forEach(function(n) { r(e, n, t[n]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : u(Object(t)).forEach(function(n) { Object.defineProperty(e, n, Object.getOwnPropertyDescriptor(t, n)); }); } return e; } function r(e, n, t) { return n in e ? Object.defineProperty(e, n, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[n] = t, e; } Object.defineProperty(n, "__esModule", { value: !0 }), n.default = void 0; var c = o(t("a34a")), l = t("2f62"), h = o(t("80d6")), d = o(t("8e44")), _ = o(t("b4fd")), g = o(t("295f")), f = o(t("31e7")), p = (o(t("ceca")), o(t("ba1b"))), m = o(t("95f1")), b = t("9554"), v = (t("d8e2"), o(t("d80f"))), y = o(t("e12f")), w = o(t("41f4")), P = t("371c"), x = o(t("ae93")), S = t("f51f"), k = o(t("75e7")), T = o(t("2de8")), C = o(t("f9d4")), O = o(t("b512")), L = o(t("6453")), B = o(t("b9bb")), A = o(t("03a3")), E = o(t("d02f")), I = o(t("d973")), j = t("83e9"), D = o(t("757e")), H = o(t("ea60")), U = o(t("8f42")), R = ((0, S.getNavigationInfo)().navigation_height, function() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}; return [ { name: "户型图", type: "layout", class: "apartment-img", show: e.layout_image_exists }, { name: "楼盘动态", type: "events", class: "events", show: !1 }, { name: "楼盘详情", type: "detail", show: Boolean(e.details) }, { name: "周边配套", type: "around", show: e.around_facility_exists }, { name: "楼盘图片", type: "common", class: "house-img", show: e.common_image_exists } ]; }), M = { mixins: [ T.default, C.default, O.default, v.default, y.default, I.default, L.default, D.default, B.default, A.default, H.default, E.default ], data: function() { return a(a({}, x.default), {}, { show_billboard: !1, show_share_option: !1, house: { view_count: 0, current_houses: [], favourite: !0 }, loading: !0, tabs: R(), current_house: { attachment_urls: {} }, current_house_index: 0, current_houses_tabs: [], excellent_consultants: [], is_consultant: !1, events: { items: [], customer_service_info: {}, is_consultant: !1, building_event_author: !1, total_count: 0, loading: !0 }, surplus_apartment_count: 0, surplus_houses: [], not_lottery_houses: [], show_mask: !1, scene_from: "", type: "", is_default_consultants: !1, weixin_phone_number: "", history_lot_houses: [], history_lot_houses_all: [], show_more_history: !1, lottery_loaded: !1, you_like_buidings: {}, you_like_buidings_loaded: !1, house_id: "", show_bm: !1, saving: !1, show_inner_tips: !0, consultant: {}, is_building_consultant: !1, follow_building_tip: "", baseinfos: [], rankingType: { views: "人气", follows: "关注", in_rate: "热门" }, gfzzjQr: "https://cdn.vip-wifi.com/hzfangchan/version-img/1.14.25/qr/gfzzj.jpeg", icons: [], layout_items: [], show_article: !1, getUserLoading: !0, show_activity_f: !1, predict_open: null, activity_aaa_thematic_building: !1, history_trend_data: [], historyTrendOpts: { global: { appendPadding: [ 12, 0, 6, 0 ] }, defs: { x: { tickCount: 8 }, y: { min: 0, ticks: [ 0, 20, 40, 60, 80, 100 ] } }, axis: [ "y", { grid: { stroke: "#eee" } } ], axisX: [ "x", {} ], legend: !1, color: [ "#00B08D" ], area: !0, area_color: "l(90) 0:#00B08D 1:#f7f7f7", tooltipOpts: { crosshairsStyle: { stroke: "#00B08D", lineWidth: 1 }, background: { radius: 2, fill: "#00B08D" }, showItemMarker: !1 } }, special_banner: [] }); }, computed: a(a({}, (0, l.mapState)([ "consultantCard", "showVideo", "share_by_consultant_uid", "buildingCardInfo", "current_consultant_uid", "showCommentRedPacketActivity", "commentRedPacketActivity", "wkBanner" ])), {}, { is_vip: function() { return "尊享版" === this.house.vip_type || "business" === this.type; }, qr_img: function() { return "https://cdn.vip-wifi.com/hzfangchan/version-img/1.14.25/qr/hangzhou/normal-qr.png?_=145367"; }, is_selling: function() { return !this.getSceneParam().house_id && "在售" === this.house.status; }, open_type: function() { return this.is_consultant ? "" : "share"; }, is_opened: function() { var e = this.house; return e.current_houses && e.current_houses.length; }, show_result: function() { var e = this.is_opened, n = this.current_house; return e && "即将取证" !== n.status; }, show_surplus_houses: function() { return this.surplus_houses && this.surplus_houses.length > 0; }, show_not_lottery_houses: function() { return "not_lottery_houses" === this.scene_from && this.not_lottery_houses && this.not_lottery_houses.length; }, price_desc: function() { var e = this.current_house.price_desc; return "正在计算" === e ? "待定" : e; }, show_house_count_table: function() { var e = this.current_house, n = e.total_apartments, t = e.show_reg, o = e.show_prob, i = e.ross_apartments, s = e.rd_apartments, u = e.common_apartments; return n && (t || o || i || s || u); }, show_top_tip: function() { return this.house.today_opening_house_count || "正在登记" === this.house.status; } }), onLoad: function(e) { var n = this; this.history_lot_houses = [], this.lottery_loaded = !1, this.you_like_buidings = {}, this.you_like_buidings_loaded = !1; var t = this.getSceneParam().type; this.type = t, g.default.getTips().then(function(e) { var t; e.forEach(function(e) { switch (e.tip_type) { case "follow_building": n.follow_building_tip = e.content[0], t = e.id; } }), t && t && g.default.viewTips(t); }); }, onUnload: function() { var e = getCurrentPages().filter(function(e) { return e && "pages/building/main" === e.route; }).length; e && 1 === e && this.setCurrentConsultantUid(""); }, onReady: function() { var e = this.getSceneParam(), n = e.building_id, t = e.prices_house_id, o = e.scene_params, i = e.share_by_consultant_uid; if ((o || i) && this.setShareByConsultantUid(o || i), t) wx.navigateTo({ url: "/pages/building/price/main?house_id=".concat(t, "&building_id=").concat(n || "") }); else { var s = this.$root.$mp.query.ccb_sub_page; s ? wx.navigateTo({ url: decodeURIComponent(s) }) : this.checkSubPage(); } }, onShareAppMessage: function() { var e = this.getSceneParam(), n = e.building_id, t = e.house_id, o = e.consultant_group_id, i = e.from, s = e.type, u = encodeURIComponent("/pages/building/main?house_id=".concat(t || "", "&building_id=").concat(n || "", "&consultant_group_id=").concat(o || "", "&from=").concat(i, "&type=").concat(s)); return this.getShareInfo({ title: (0, k.default)(this.house, this.current_house, this.is_opened), path: "/pages/index/main?sub_page=".concat(u), imageUrl: this.house.photos_urls && this.house.photos_urls.length ? this.house.photos_urls[0] : "" }); }, onPullDownRefresh: function() { this.loading || this.getData(); }, onShow: function() { var e = this, n = this.getSceneParam(), t = n.from, o = n.building_id, i = n.scene_params, s = n.house_id, u = n.share_by_consultant_uid; (i || u) && this.setShareByConsultantUid(i || u), P.UserLog.viewBuilding(o, i || ""), this.scene_from = t, this.house_id = s, d.default.init().then(function() { e.getData(); }); }, methods: a(a({}, (0, l.mapActions)([ "setShareByConsultantUid", "setCurrentConsultantUid" ])), {}, { goBrands: function() { (0, P.sendCtmEvtLog)("楼盘详情页-开发商活动入口"), wx.navigateTo({ url: "/pages/activity_a/brands/main" }); }, getYouLike: function() { var e = this; if (this.is_vip) this.you_like_buidings_loaded = !0; else { var n = this.getSceneParam().building_id; p.default.getYouLike(n).then(function(n) { e.you_like_buidings_loaded = !0, e.you_like_buidings = n; }); } }, onShowMoreHistory: function() { this.show_more_history = !this.show_more_history, this.history_lot_houses = this.show_more_history ? this.history_lot_houses_all : this.history_lot_houses_all.slice(0, 1); }, getLottery: function() { var e = this, n = this.getSceneParam(), t = n.building_id, o = n.consultant_group_id; n.house_id ? this.lottery_loaded = !0 : p.default.getHistoryLottery(t).then(function(n) { var i = n.items; i.forEach(function(e) { e.common_probability = (0, S.getProbability)(e.common_probability), e.rd_probability = (0, S.getProbability)(e.rd_probability), e.href = "/pages/building/main?building_id=".concat(t, "&house_id=").concat(e.id, "&consultant_group_id=").concat(o || ""); }), e.lottery_loaded = !0, e.show_more_history || (e.history_lot_houses = i.slice(0, 1), e.history_lot_houses_all = i, e.history_trend_data = i.map(function(e) { return { type: "摇中概率", x: "".concat(e.presell_date), y: Number(e.total_probability) || 100 }; })); }); }, historyTrendValueFormatter: function(e) { return e + "%"; }, historyTrendAxisXLabelFormatter: function(e, n, t) { var o = { textAlign: "center", textBaseline: "middle" }; return t > 2 && (o.textAlign = "end", o.rotate = -Math.PI / 4), o; }, showShareOption: function() { this.is_consultant && (this.show_share_option = !0); }, hideShareOption: function() { this.show_share_option = !1; }, toggleBillboard: function() { this.show_billboard = !this.show_billboard; }, getData: function() { var e = this, n = this.getSceneParam(), t = n.house_id, o = n.building_id, i = n.consultant_group_id, s = n.from, u = (n.type, n.scene_params), r = (n.prices_house_id, n.share_by_consultant_uid), c = n.status; this.scene_from = s; var l = this.current_consultant_uid || this.share_by_consultant_uid || u || r; m.default.get(o, t, i, c, l).then(function(n) { e.activity_aaa_thematic_building = n.activities && n.activities.indexOf("activity_aaa_thematic_building") > -1, n.current_houses = n.current_houses || [], e.current_houses_tabs = n.current_houses.map(function(e) { return e.name; }), (0, S.handleHouseNum)(n), n.current_houses.forEach(function(e) { e.has_house_price = e.exist_values && e.exist_values.indexOf("house_prices") > -1, "清水" === e.decoration_type && (e.decoration_type = "毛坯"); }), e.current_house = n.current_houses.length ? n.current_houses[0] : {}, e.current_house_index = 0, n.planar_graph_url = (0, j.getSmallPlanar)(n.planar_graph_url), n.favourite = n.follow_info && n.follow_info.id, n.showCommentRedPacketActivity = e.showCommentRedPacketActivity, e.tabs = R(n), e.icons = (0, S.initIconsData)(n); var t = n.details, i = n.surplus_apartment_count, s = n.not_lottery_houses, u = n.surplus_houses, r = n.usage; e.surplus_apartment_count = i, e.surplus_houses = u, e.not_lottery_houses = s; var c = (0, S.getInfoItems)(r); n.house_info = c.reduce(function(e, n) { return t && t[n] && e.push({ key: n, value: t[n] }), e; }, []), e.baseinfos = n.house_info.slice(0, 5); var l = t["预开盘信息"]; l && (e.predict_open = Object.keys(l).reduce(function(e, n) { var t = l[n]; return null != t && void 0 != t && "" != t && e.push({ key: n, val: t }), e; }, [])), n.longitude = n.location ? n.location.split(",")[0] : "", n.latitude = n.location ? n.location.split(",")[1] : "", n.status = n.ln_status || n.status, n.ln_status && delete n.ln_status, n.view_count = n.view_count >= 1e4 ? "".concat((n.view_count / 1e4).toFixed(1), "w") : n.view_count, e.house = n, U.default.addBuilding(a(a({}, n), {}, { cover_photo_url: n.photos_urls && n.photos_urls.length ? n.photos_urls[0] : "" })), e.loading = !1, n.current_consultant && setTimeout(function() { e.show_inner_tips = !1; }, 5e3), e.getExcellentConsultant(o), e.getUser(), e.getSecondhandPrice(), e.getEvents(), e.getLayouts(), e.$refs.house_comments.getData(e.house.id), e.$refs.building_article.getData(e.house.id, e.house.weixin_account_id).then(function(n) { e.show_article = n; }), e.getLottery(), e.getYouLike(), wx.stopPullDownRefresh(), console.log({ house: e.house }); }).catch(function(e) { console.error(e), 404 === e && wx.switchTab({ url: "/pages/index/main" }); }), f.default.getBuildingBanner().then(function(n) { var t = n.special_banner; e.special_banner = t.filter(function(e) { return e.building_id == o; }); }); }, onCollapse: function(e) { this.baseinfos = e ? this.house.house_info.map(function(e) { return e; }) : this.house.house_info.slice(0, 5); }, getExcellentConsultant: function(e) { var n = this; p.default.excellentConsultants(e).then(function(e) { n.excellent_consultants = e.slice(0, 3); }); }, getEvents: function() { var e = this, n = this.getSceneParam().building_id; p.default.getEvent(n, { page: 1, per: 1 }).then(function(n) { e.events = { items: n.items.slice(0, 1), customer_service_info: n.customer_service_info, is_consultant: n.is_consultant, building_event_author: n.building_event_author, total_count: n.total_count, loading: !1 }, e.$set(e.tabs, 1, a(a({}, e.tabs[1]), {}, { show: Boolean(n.total_count) })); }); }, getLayouts: function() { var e = this; return s(c.default.mark(function n() { var t, o, i; return c.default.wrap(function(n) { for (;;) switch (n.prev = n.next) { case 0: return t = e.getSceneParam(), o = t.building_id, n.next = 3, p.default.getImgs(o, "layout", {}); case 3: i = n.sent, e.layoutItemsSort(i.items); case 5: case "end": return n.stop(); } }, n); }))(); }, layoutItemsSort: function(e) { var n = this.house.current_houses.map(function(e) { return e.id; }), t = e.sort(function(e, t) { return n.indexOf(e.house_id) > -1 && -1 === n.indexOf(t.house_id) ? -1 : 1; }); this.layout_items = t; }, getUser: function() { var e = this, n = this.getSceneParam().building_id; w.default.user.get().then(function(t) { e.is_consultant = t.is_consultant, e.getUserLoading = !1, e.show_activity_f = t.activity_menus && t.activity_menus.indexOf("activity_f-活动入口") > -1, t.is_consultant && d.default.getMyConsultant(!1).then(function(t) { e.consultant = t, e.is_building_consultant = t.buildings.map(function(e) { return e.id; }).indexOf(Number(n)) > -1; }), t.weixin_phone_number ? e.weixin_phone_number = t.weixin_phone_number : d.default.getUserInfo().then(function(n) { var t = n.weixin_phone_number; e.weixin_phone_number = t; }); }); }, openMap: function() { var e = this.house, n = e.latitude, t = e.longitude, o = e.name, i = e.address; n && t && wx.openLocation({ latitude: Number(n), longitude: Number(t), name: o, address: i }); }, goAddComments: function() { var e = this.house, n = e.name, t = e.building_id; wx.navigateTo({ url: "/pages/building/comments/add/main?building_id=".concat(t || "", "&name=").concat(n) }); }, goTab: function(e) { var n = this, t = e.currentTarget.dataset, o = t.type, i = t.name, s = t.index; this.tabs[s].show && (0, b.askAuth)(e, function() { "common" === o || "layout" === o ? n.goPreview(o, i) : "events" === o ? n.goEvents() : "around" === o ? n.goAround("metro") : n.goHouseInfo(o); }); }, goEvents: function() { if (wx.createSelectorQuery) { var e = wx.createSelectorQuery(), n = e.select("#events"); n && (n.boundingClientRect(), e.selectViewport().scrollOffset(), e.exec(function(e) { e.length && e[0].top && wx.pageScrollTo && wx.pageScrollTo({ scrollTop: e[0].top, duration: 0 }); })); } }, goLink: function(e) { (0, b.askAuthNavigator)(e, e.currentTarget.dataset.href); }, goHouseInfo: function(e) { var n = this.getSceneParam(), t = n.id, o = n.building_id; this.goSubPagePath("/pages/building/info/main?type=".concat(e, "&id=").concat(t, "&building_id=").concat(o || "")); }, goHousePrice: function(e) { var n = this.getSceneParam().building_id, t = this.current_house.id, o = this.house.name; this.goSubPagePath("/pages/building/price/main?title=".concat(o, "&house_id=").concat(t, "&building_id=").concat(n || "")); }, goSurplusApartments: function(e) { var n = this.getSceneParam().building_id, t = e.currentTarget.dataset, o = t.name, i = t.id; this.goSubPagePath("/pages/building/price/main?building_id=".concat(n, "&title=").concat(o, "&house_id=").concat(i, "&type=surplus_apartments")); }, goPreview: function(e, n) { var t = this.getSceneParam().building_id, o = "".concat(this.house.name, "-").concat(n), i = this.house.current_houses.map(function(e) { return e.id; }).join(","); "price" === e && (i = this.current_house.id), this.goSubPagePath("/pages/building/img_preview/main?house_id=".concat(i || "", "&type=").concat(e, "&title=").concat(o, "&building_id=").concat(t || "")), "户型图" === n && (0, P.sendCtmEvtLog)("楼盘详情-".concat(n, "-更多")); }, goArticle: function() { this.goSubPagePath("/pages/packageC/fangchan_release/main?id=".concat(this.house.weixin_account_id)); }, goAround: function() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : ""; this.goSubPagePath("/pages/building/around_facilities/map/main?id=".concat(this.house.id, "&category=").concat(e)); }, goComments: function() { this.goSubPagePath("/pages/building/comments/main?building_id=".concat(this.house.id || "", "&name=").concat(this.house.name)); }, goPredict: function() { this.goSubPagePath("/pages/packageC/interest_forecast/main?building_id=".concat(this.house.id, "&house_id=").concat(this.current_house.id)); }, goMaterial: function() { this.goSubPagePath("/pages/building/material/main?building_id=".concat(this.house.id, "&house_id=").concat(this.current_house.id)); }, changeCurrentHouse: function(e) { this.current_house = this.house.current_houses[e], this.current_house_index = e; }, goBuildingArticle: function() { var e = this.getSceneParam().building_id; this.goSubPagePath("/pages/building/article/main?building_id=".concat(e)); }, goEvent: function() { var e = this.getSceneParam().building_id; this.goSubPagePath("/pages/building/event/main?building_id=".concat(e)); }, openLayoutDetail: function(e) { var n = this.getSceneParam().building_id; (0, P.sendCtmEvtLog)("楼盘详情户型图列表点击"), this.goSubPagePath("/pages/building/layout_detail/main?building_id=".concat(n, "&layout_id=").concat(e)); }, goQulification: function() { wx.navigateTo({ url: "/pages/check_condition/main?verify_type=杭州购房资格查询" }); }, getphonenumber: function(e) { var n = this, t = (this.getSceneParam().building_id, e.target), o = t.iv, i = t.encryptedData, s = t.errMsg; _.default.postWeixinPhone(o, i, s).then(function(e) { 422 === Number(e.code) ? wx.showToast({ title: e.error_message, icon: "none" }) : (n.weixin_phone_number = e.phone, d.default.getUserInfo(), n.toCcbLoanApprove()); }); }, toCcbLoanApprove: function() { var e = this.getSceneParam().building_id; wx.navigateTo({ url: "/pages/packageA/ccb_loan_approve/main?mobile=".concat(this.weixin_phone_number, "&building_id=").concat(e, "&building_name=").concat(this.house.name) }); }, openBm: function(e) { var n = this; (0, b.askAuth)(e, function() { n.show_bm = !0; }); }, onCloseBm: function() { this.show_bm = !1; }, onSaveQr: function(e) { var n = this; wx.showLoading(), this.saving = !0, h.default.saveImgFromInternet({ url: this.current_house.registration_method_qrcode_url }).then(function(e) { n.finishSave(), wx.showToast({ title: "保存成功" }), n.show_bm = !1; }).catch(function() { n.finishSave(), wx.showToast({ title: "保存失败", icon: "none" }); }); }, finishSave: function() { this.saving = !1, setTimeout(wx.hideLoading, 1500); }, onHideThis: function() { this.show_inner_tips = !1; }, sendEvtLog: function(e) { var n = e.currentTarget.dataset.name; console.error(n), (0, P.sendCtmEvtLog)(n); } }), components: { FullLoading: function() { t.e("components/views/full_loading").then(function() { return resolve(t("f65e")); }.bind(null, t)).catch(t.oe); }, ListLoading: function() { t.e("components/views/loading").then(function() { return resolve(t("7756")); }.bind(null, t)).catch(t.oe); }, TopSwiper: function() { Promise.all([ t.e("pages/building/common/vendor"), t.e("pages/building/_components/_swiper") ]).then(function() { return resolve(t("833d")); }.bind(null, t)).catch(t.oe); }, TopHeader: function() { t.e("pages/building/_components/_top_header").then(function() { return resolve(t("50fe")); }.bind(null, t)).catch(t.oe); }, HouseTab: function() { t.e("pages/building/_components/_house_tab").then(function() { return resolve(t("2cab")); }.bind(null, t)).catch(t.oe); }, TopTabs: function() { t.e("pages/building/_components/_top_tabs").then(function() { return resolve(t("62e9")); }.bind(null, t)).catch(t.oe); }, BaseInfo: function() { t.e("pages/building/_components/_base_info").then(function() { return resolve(t("d0c8")); }.bind(null, t)).catch(t.oe); }, OpeningInfo: function() { t.e("pages/building/_components/_opening_info").then(function() { return resolve(t("b2e0")); }.bind(null, t)).catch(t.oe); }, SurplusHouses: function() { t.e("pages/building/_components/_surplus_houses").then(function() { return resolve(t("3294")); }.bind(null, t)).catch(t.oe); }, RegPredict: function() { t.e("pages/building/_components/_predict").then(function() { return resolve(t("a715")); }.bind(null, t)).catch(t.oe); }, HouseCount: function() { t.e("components/views/_house_count").then(function() { return resolve(t("5527")); }.bind(null, t)).catch(t.oe); }, VipTimeline: function() { t.e("pages/building/_components/_vip_timeline_v2").then(function() { return resolve(t("f247")); }.bind(null, t)).catch(t.oe); }, HouseContent: function() { Promise.all([ t.e("pages/building/common/vendor"), t.e("pages/building/_components/_content") ]).then(function() { return resolve(t("1cd3")); }.bind(null, t)).catch(t.oe); }, HouseAttachs: function() { t.e("pages/building/_components/_house_attachs").then(function() { return resolve(t("53fc")); }.bind(null, t)).catch(t.oe); }, HouseResult: function() { t.e("pages/building/_components/_result").then(function() { return resolve(t("bec4")); }.bind(null, t)).catch(t.oe); }, HouseComments: function() { Promise.all([ t.e("common/vendor"), t.e("pages/building/_components/_comments") ]).then(function() { return resolve(t("88de")); }.bind(null, t)).catch(t.oe); }, ExcellentConsultants: function() { t.e("pages/building/_components/_excellent_consultants").then(function() { return resolve(t("d91a")); }.bind(null, t)).catch(t.oe); }, ShareOptions: function() { t.e("components/business/share_options").then(function() { return resolve(t("012a")); }.bind(null, t)).catch(t.oe); }, Billboard: function() { t.e("pages/building/_components/_billboard").then(function() { return resolve(t("e061")); }.bind(null, t)).catch(t.oe); }, YouLike: function() { Promise.all([ t.e("common/vendor"), t.e("pages/building/common/vendor"), t.e("pages/building/_components/_you_like") ]).then(function() { return resolve(t("3b54")); }.bind(null, t)).catch(t.oe); }, BuildingFooter: function() { Promise.all([ t.e("common/vendor"), t.e("components/building/_footer") ]).then(function() { return resolve(t("801a")); }.bind(null, t)).catch(t.oe); }, DiscussLink: function() { t.e("pages/building/_components/_discuss").then(function() { return resolve(t("dc1b")); }.bind(null, t)).catch(t.oe); }, BuildingArticle: function() { Promise.all([ t.e("common/vendor"), t.e("pages/building/article/_articles") ]).then(function() { return resolve(t("118e")); }.bind(null, t)).catch(t.oe); }, BuildingEvent: function() { Promise.all([ t.e("pages/building/common/vendor"), t.e("pages/building/_components/_event") ]).then(function() { return resolve(t("c7cc")); }.bind(null, t)).catch(t.oe); }, BusinessHeader: function() { t.e("pages/building/_components/_business_header").then(function() { return resolve(t("129b")); }.bind(null, t)).catch(t.oe); }, LikeTip: function() { Promise.all([ t.e("common/vendor"), t.e("pages/building/_components/_like_tip") ]).then(function() { return resolve(t("ca0b")); }.bind(null, t)).catch(t.oe); }, SecPrice: function() { t.e("pages/building/_components/_sec_price").then(function() { return resolve(t("e4aa")); }.bind(null, t)).catch(t.oe); }, OnlineSalesTips: function() { t.e("components/views/online_sales_tips").then(function() { return resolve(t("66d1")); }.bind(null, t)).catch(t.oe); }, TopTip: function() { Promise.all([ t.e("common/vendor"), t.e("pages/building/_components/_top_tip") ]).then(function() { return resolve(t("8dea")); }.bind(null, t)).catch(t.oe); }, BuildingRank: function() { t.e("pages/building/_components/_building_rank").then(function() { return resolve(t("f0df")); }.bind(null, t)).catch(t.oe); }, AuthPhone: function() { t.e("components/building/_auth_phone").then(function() { return resolve(t("7038")); }.bind(null, t)).catch(t.oe); }, PlanarGraph: function() { t.e("pages/building/_components/_planar_graph").then(function() { return resolve(t("1314")); }.bind(null, t)).catch(t.oe); }, PredictOpen: function() { t.e("pages/building/_components/_predict_open").then(function() { return resolve(t("07cb")); }.bind(null, t)).catch(t.oe); }, Web720: function() { t.e("pages/building/_components/_web_720").then(function() { return resolve(t("d81a")); }.bind(null, t)).catch(t.oe); }, TopTools: function() { t.e("pages/building/_components/_top_tools").then(function() { return resolve(t("2e8d")); }.bind(null, t)).catch(t.oe); }, Layout: function() { t.e("pages/building/_components/_layout").then(function() { return resolve(t("bf95")); }.bind(null, t)).catch(t.oe); }, BuildingTopTab: function() { t.e("pages/building/_components/_building_top_tab").then(function() { return resolve(t("bc2a")); }.bind(null, t)).catch(t.oe); }, CommentRedPacketActivity: function() { t.e("pages/building/comments/_red_packet_activity").then(function() { return resolve(t("6ffc")); }.bind(null, t)).catch(t.oe); }, TimelineBillboard: function() { t.e("pages/building/_components/_timeline_billboard").then(function() { return resolve(t("4d37")); }.bind(null, t)).catch(t.oe); }, F2Charts: function() { Promise.all([ t.e("common/vendor"), t.e("components/f2/index") ]).then(function() { return resolve(t("5064")); }.bind(null, t)).catch(t.oe); }, SecondHand: function() { t.e("pages/building/_components/_second_hand").then(function() { return resolve(t("8820")); }.bind(null, t)).catch(t.oe); }, Disclaimer: function() { Promise.all([ t.e("common/vendor"), t.e("components/views/disclaimer") ]).then(function() { return resolve(t("db46")); }.bind(null, t)).catch(t.oe); } } }; n.default = M; }, b6d3: function(e, n, t) { (function(e) { function n(e) { return e && e.__esModule ? e : { default: e }; } t("6cdc"), n(t("66fd")), e(n(t("ea1d")).default); }).call(this, t("543d").createPage); }, ea1d: function(e, n, t) { t.r(n); var o = t("3e35"), i = t("3b68"); for (var s in i) [ "default" ].indexOf(s) < 0 && function(e) { t.d(n, e, function() { return i[e]; }); }(s); t("536c"); var u = t("f0c5"), a = Object(u.a)(i.default, o.b, o.c, !1, null, "46404dc4", null, !1, o.a, void 0); n.default = a.exports; }, f442: function(e, n, t) {} }, [ [ "b6d3", "common/runtime", "common/vendor", "pages/building/common/vendor" ] ] ]);
// === Sylvester === // Vector and Matrix mathematics modules for JavaScript // Copyright (c) 2007 James Coglan // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. var Sylvester = { version: '0.1.3', precision: 1e-6 }; function Matrix() {} Matrix.prototype = { // Returns element (i,j) of the matrix e: function(i,j) { if (i < 1 || i > this.elements.length || j < 1 || j > this.elements[0].length) { return null; } return this.elements[i-1][j-1]; }, // Returns row k of the matrix as a vector row: function(i) { if (i > this.elements.length) { return null; } return Vector.create(this.elements[i-1]); }, // Returns column k of the matrix as a vector col: function(j) { if (j > this.elements[0].length) { return null; } var col = [], n = this.elements.length, k = n, i; do { i = k - n; col.push(this.elements[i][j-1]); } while (--n); return Vector.create(col); }, // Returns the number of rows/columns the matrix has dimensions: function() { return {rows: this.elements.length, cols: this.elements[0].length}; }, // Returns the number of rows in the matrix rows: function() { return this.elements.length; }, // Returns the number of columns in the matrix cols: function() { return this.elements[0].length; }, // Returns true iff the matrix is equal to the argument. You can supply // a vector as the argument, in which case the receiver must be a // one-column matrix equal to the vector. eql: function(matrix) { var M = matrix.elements || matrix; if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } if (this.elements.length != M.length || this.elements[0].length != M[0].length) { return false; } var ni = this.elements.length, ki = ni, i, nj, kj = this.elements[0].length, j; do { i = ki - ni; nj = kj; do { j = kj - nj; if (Math.abs(this.elements[i][j] - M[i][j]) > Sylvester.precision) { return false; } } while (--nj); } while (--ni); return true; }, // Returns a copy of the matrix dup: function() { return Matrix.create(this.elements); }, // Maps the matrix to another matrix (of the same dimensions) according to the given function map: function(fn) { var els = [], ni = this.elements.length, ki = ni, i, nj, kj = this.elements[0].length, j; do { i = ki - ni; nj = kj; els[i] = []; do { j = kj - nj; els[i][j] = fn(this.elements[i][j], i + 1, j + 1); } while (--nj); } while (--ni); return Matrix.create(els); }, // Returns true iff the argument has the same dimensions as the matrix isSameSizeAs: function(matrix) { var M = matrix.elements || matrix; if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } return (this.elements.length == M.length && this.elements[0].length == M[0].length); }, // Returns the result of adding the argument to the matrix add: function(matrix) { var M = matrix.elements || matrix; if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } if (!this.isSameSizeAs(M)) { return null; } return this.map(function(x, i, j) { return x + M[i-1][j-1]; }); }, // Returns the result of subtracting the argument from the matrix subtract: function(matrix) { var M = matrix.elements || matrix; if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } if (!this.isSameSizeAs(M)) { return null; } return this.map(function(x, i, j) { return x - M[i-1][j-1]; }); }, // Returns true iff the matrix can multiply the argument from the left canMultiplyFromLeft: function(matrix) { var M = matrix.elements || matrix; if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } // this.columns should equal matrix.rows return (this.elements[0].length == M.length); }, // Returns the result of multiplying the matrix from the right by the argument. // If the argument is a scalar then just multiply all the elements. If the argument is // a vector, a vector is returned, which saves you having to remember calling // col(1) on the result. multiply: function(matrix) { if (!matrix.elements) { return this.map(function(x) { return x * matrix; }); } var returnVector = matrix.modulus ? true : false; var M = matrix.elements || matrix; if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } if (!this.canMultiplyFromLeft(M)) { return null; } var ni = this.elements.length, ki = ni, i, nj, kj = M[0].length, j; var cols = this.elements[0].length, elements = [], sum, nc, c; do { i = ki - ni; elements[i] = []; nj = kj; do { j = kj - nj; sum = 0; nc = cols; do { c = cols - nc; sum += this.elements[i][c] * M[c][j]; } while (--nc); elements[i][j] = sum; } while (--nj); } while (--ni); var M = Matrix.create(elements); return returnVector ? M.col(1) : M; }, x: function(matrix) { return this.multiply(matrix); }, // Returns a submatrix taken from the matrix // Argument order is: start row, start col, nrows, ncols // Element selection wraps if the required index is outside the matrix's bounds, so you could // use this to perform row/column cycling or copy-augmenting. minor: function(a, b, c, d) { var elements = [], ni = c, i, nj, j; var rows = this.elements.length, cols = this.elements[0].length; do { i = c - ni; elements[i] = []; nj = d; do { j = d - nj; elements[i][j] = this.elements[(a+i-1)%rows][(b+j-1)%cols]; } while (--nj); } while (--ni); return Matrix.create(elements); }, // Returns the transpose of the matrix transpose: function() { var rows = this.elements.length, cols = this.elements[0].length; var elements = [], ni = cols, i, nj, j; do { i = cols - ni; elements[i] = []; nj = rows; do { j = rows - nj; elements[i][j] = this.elements[j][i]; } while (--nj); } while (--ni); return Matrix.create(elements); }, // Returns true iff the matrix is square isSquare: function() { return (this.elements.length == this.elements[0].length); }, // Returns the (absolute) largest element of the matrix max: function() { var m = 0, ni = this.elements.length, ki = ni, i, nj, kj = this.elements[0].length, j; do { i = ki - ni; nj = kj; do { j = kj - nj; if (Math.abs(this.elements[i][j]) > Math.abs(m)) { m = this.elements[i][j]; } } while (--nj); } while (--ni); return m; }, // Returns the indeces of the first match found by reading row-by-row from left to right indexOf: function(x) { var index = null, ni = this.elements.length, ki = ni, i, nj, kj = this.elements[0].length, j; do { i = ki - ni; nj = kj; do { j = kj - nj; if (this.elements[i][j] == x) { return {i: i+1, j: j+1}; } } while (--nj); } while (--ni); return null; }, // If the matrix is square, returns the diagonal elements as a vector. // Otherwise, returns null. diagonal: function() { if (!this.isSquare) { return null; } var els = [], n = this.elements.length, k = n, i; do { i = k - n; els.push(this.elements[i][i]); } while (--n); return Vector.create(els); }, // Make the matrix upper (right) triangular by Gaussian elimination. // This method only adds multiples of rows to other rows. No rows are // scaled up or switched, and the determinant is preserved. toRightTriangular: function() { var M = this.dup(), els; var n = this.elements.length, k = n, i, np, kp = this.elements[0].length, p; do { i = k - n; if (M.elements[i][i] == 0) { for (j = i + 1; j < k; j++) { if (M.elements[j][i] != 0) { els = []; np = kp; do { p = kp - np; els.push(M.elements[i][p] + M.elements[j][p]); } while (--np); M.elements[i] = els; break; } } } if (M.elements[i][i] != 0) { for (j = i + 1; j < k; j++) { var multiplier = M.elements[j][i] / M.elements[i][i]; els = []; np = kp; do { p = kp - np; // Elements with column numbers up to an including the number // of the row that we're subtracting can safely be set straight to // zero, since that's the point of this routine and it avoids having // to loop over and correct rounding errors later els.push(p <= i ? 0 : M.elements[j][p] - M.elements[i][p] * multiplier); } while (--np); M.elements[j] = els; } } } while (--n); return M; }, toUpperTriangular: function() { return this.toRightTriangular(); }, // Returns the determinant for square matrices determinant: function() { if (!this.isSquare()) { return null; } var M = this.toRightTriangular(); var det = M.elements[0][0], n = M.elements.length - 1, k = n, i; do { i = k - n + 1; det = det * M.elements[i][i]; } while (--n); return det; }, det: function() { return this.determinant(); }, // Returns true iff the matrix is singular isSingular: function() { return (this.isSquare() && this.determinant() === 0); }, // Returns the trace for square matrices trace: function() { if (!this.isSquare()) { return null; } var tr = this.elements[0][0], n = this.elements.length - 1, k = n, i; do { i = k - n + 1; tr += this.elements[i][i]; } while (--n); return tr; }, tr: function() { return this.trace(); }, // Returns the rank of the matrix rank: function() { var M = this.toRightTriangular(), rank = 0; var ni = this.elements.length, ki = ni, i, nj, kj = this.elements[0].length, j; do { i = ki - ni; nj = kj; do { j = kj - nj; if (Math.abs(M.elements[i][j]) > Sylvester.precision) { rank++; break; } } while (--nj); } while (--ni); return rank; }, rk: function() { return this.rank(); }, // Returns the result of attaching the given argument to the right-hand side of the matrix augment: function(matrix) { var M = matrix.elements || matrix; if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } var T = this.dup(), cols = T.elements[0].length; var ni = T.elements.length, ki = ni, i, nj, kj = M[0].length, j; if (ni != M.length) { return null; } do { i = ki - ni; nj = kj; do { j = kj - nj; T.elements[i][cols + j] = M[i][j]; } while (--nj); } while (--ni); return T; }, // Returns the inverse (if one exists) using Gauss-Jordan inverse: function() { if (!this.isSquare() || this.isSingular()) { return null; } var ni = this.elements.length, ki = ni, i, j; var M = this.augment(Matrix.I(ni)).toRightTriangular(); var np, kp = M.elements[0].length, p, els, divisor; var inverse_elements = [], new_element; // Matrix is non-singular so there will be no zeros on the diagonal // Cycle through rows from last to first do { i = ni - 1; // First, normalise diagonal elements to 1 els = []; np = kp; inverse_elements[i] = []; divisor = M.elements[i][i]; do { p = kp - np; new_element = M.elements[i][p] / divisor; els.push(new_element); // Shuffle of the current row of the right hand side into the results // array as it will not be modified by later runs through this loop if (p >= ki) { inverse_elements[i].push(new_element); } } while (--np); M.elements[i] = els; // Then, subtract this row from those above it to // give the identity matrix on the left hand side for (j = 0; j < i; j++) { els = []; np = kp; do { p = kp - np; els.push(M.elements[j][p] - M.elements[i][p] * M.elements[j][i]); } while (--np); M.elements[j] = els; } } while (--ni); return Matrix.create(inverse_elements); }, inv: function() { return this.inverse(); }, // Returns the result of rounding all the elements round: function() { return this.map(function(x) { return Math.round(x); }); }, // Returns a copy of the matrix with elements set to the given value if they // differ from it by less than Sylvester.precision snapTo: function(x) { return this.map(function(p) { return (Math.abs(p - x) <= Sylvester.precision) ? x : p; }); }, // Returns a string representation of the matrix inspect: function() { var matrix_rows = []; var n = this.elements.length, k = n, i; do { i = k - n; matrix_rows.push(Vector.create(this.elements[i]).inspect()); } while (--n); return matrix_rows.join('\n'); }, // Set the matrix's elements from an array. If the argument passed // is a vector, the resulting matrix will be a single column. setElements: function(els) { var i, elements = els.elements || els; if (typeof(elements[0][0]) != 'undefined') { var ni = elements.length, ki = ni, nj, kj, j; this.elements = []; do { i = ki - ni; nj = elements[i].length; kj = nj; this.elements[i] = []; do { j = kj - nj; this.elements[i][j] = elements[i][j]; } while (--nj); } while(--ni); return this; } var n = elements.length, k = n; this.elements = []; do { i = k - n; this.elements.push([elements[i]]); } while (--n); return this; } }; // Constructor function Matrix.create = function(elements) { var M = new Matrix(); return M.setElements(elements); }; // Identity matrix of size n Matrix.I = function(n) { var els = [], k = n, i, nj, j; do { i = k - n; els[i] = []; nj = k; do { j = k - nj; els[i][j] = (i == j) ? 1 : 0; } while (--nj); } while (--n); return Matrix.create(els); }; // Diagonal matrix - all off-diagonal elements are zero Matrix.Diagonal = function(elements) { var n = elements.length, k = n, i; var M = Matrix.I(n); do { i = k - n; M.elements[i][i] = elements[i]; } while (--n); return M; }; // Rotation matrix about some axis. If no axis is // supplied, assume we're after a 2D transform Matrix.Rotation = function(theta, a) { if (!a) { return Matrix.create([ [Math.cos(theta), -Math.sin(theta)], [Math.sin(theta), Math.cos(theta)] ]); } var axis = a.dup(); if (axis.elements.length != 3) { return null; } var mod = axis.modulus(); var x = axis.elements[0]/mod, y = axis.elements[1]/mod, z = axis.elements[2]/mod; var s = Math.sin(theta), c = Math.cos(theta), t = 1 - c; // Formula derived here: http://www.gamedev.net/reference/articles/article1199.asp // That proof rotates the co-ordinate system so theta // becomes -theta and sin becomes -sin here. return Matrix.create([ [ t*x*x + c, t*x*y - s*z, t*x*z + s*y ], [ t*x*y + s*z, t*y*y + c, t*y*z - s*x ], [ t*x*z - s*y, t*y*z + s*x, t*z*z + c ] ]); }; // Special case rotations Matrix.RotationX = function(t) { var c = Math.cos(t), s = Math.sin(t); return Matrix.create([ [ 1, 0, 0 ], [ 0, c, -s ], [ 0, s, c ] ]); }; Matrix.RotationY = function(t) { var c = Math.cos(t), s = Math.sin(t); return Matrix.create([ [ c, 0, s ], [ 0, 1, 0 ], [ -s, 0, c ] ]); }; Matrix.RotationZ = function(t) { var c = Math.cos(t), s = Math.sin(t); return Matrix.create([ [ c, -s, 0 ], [ s, c, 0 ], [ 0, 0, 1 ] ]); }; // Random matrix of n rows, m columns Matrix.Random = function(n, m) { return Matrix.Zero(n, m).map( function() { return Math.random(); } ); }; // Matrix filled with zeros Matrix.Zero = function(n, m) { var els = [], ni = n, i, nj, j; do { i = n - ni; els[i] = []; nj = m; do { j = m - nj; els[i][j] = 0; } while (--nj); } while (--ni); return Matrix.create(els); }; // Utility functions var $M = Matrix.create;
var mainApp = angular.module('CCController', []).controller('mainController', function($scope, $http) { $scope.formData = {}; //is the data shown/entered on the form $scope.todoData = {}; //is the data shown on the page? //add new registration to the registered table $scope.createReg = function(regID) { if( Object.keys($scope.formData).length == 7 ){ $http.post('/api/v1/registerUser', $scope.formData) .success(function(data) { console.log("registration successful"); $scope.formData = {}; //clears the form on the page $scope.todoData = data; //puts data into a global? localStorage.clear(); $('.registrationForm').hide(); $('.mainBodyFadeOut').fadeIn(500); $('.registrationError').hide(); }) .error(function(error) { console.log('Error: ' + error); }); } else { //show a message to the user console.log("Client side error message"); $('.registrationError').show(); } }; $('#messagesButton').on('click', function(){ if($scope.formData.plateSearch !== undefined && $scope.formData.plateState !== undefined ){ $('.messages').show(); $('.plateAndStateForm').hide(); $('.plateMessageError').hide(); } else { $('.plateMessageError').show(); } }); //look through the licenseplates, and send a message back if find it? $scope.sendByPlate = function(msg) { if($scope.formData.plateSearch !== undefined && $scope.formData.plateState !== undefined){ //$scope.formData.plateState $http.get('/api/v1/sendMessageByPlate/'+$scope.formData.plateSearch + '/' + msg) .success(function(data){ console.log($scope); if(data.messageSent){ console.log("message sent"); $('.messages').hide(); $('.plateMessageGroup').hide(); $('.mainBodyFadeOut').fadeIn(500); } $scope.formData = {}; //clears the form of the page console.log( data); if(data.userDoesNotExist){ console.log("user does not exist"); } }) .error(function(error){ console.log('Error: ' + error); }) } else { //show an error message to the user $('.plateMessageError').show(); } } });
let coolerFragmentShader = `precision highp float; uniform float time; uniform vec2 resolution; uniform vec3 light; varying vec3 fPosition; varying vec3 fNormal; varying vec3 localPos; varying vec3 vColor; float ComputeLightingModifier(); float Grid(float val, float dst); float rand(vec2 co); void main() { float alpha = 1.0; vec3 color = vec3(0.8, 0.2, 0.2); float lightingModifier = ComputeLightingModifier(); float noise = Grid(localPos.x, 5.0) + Grid(localPos.y, 5.0) + Grid(localPos.z, 5.0); float grid = Grid(localPos.x + localPos.y, 50.0) + Grid(localPos.x + localPos.z, 50.0); float strip = Grid(localPos.y, 8.0); if(localPos.z > 0.0) { if(localPos.x > 0.0 && localPos.y > 0.0) { if(mod(noise, 2.0) > 0.0) { color.y = rand(fPosition.yz); color.z = rand(fPosition.xz); } } else if(localPos.x < 0.0 && localPos.y > 0.0) { if(grid > .5) { discard; } } else if(localPos.x < 0.0 && localPos.y < 0.0) { color.x = vColor.x; color.y = vColor.y; color.z = vColor.z; } else { if(strip > .5) { color.x = vColor.x; color.y = vColor.x; color.z = vColor.x; alpha = 0.0; } else { color.x = vColor.y; color.y = vColor.y; color.z = vColor.x; } } } else { if(localPos.x > 0.0 && localPos.y > 0.0) { color.x = vColor.x; color.y = vColor.y; color.z = vColor.z; } else if(localPos.x < 0.0 && localPos.y > 0.0) { if(mod(noise, 2.0) > 0.0) { color.y = rand(fPosition.yz); color.z = rand(fPosition.xz); } } else if(localPos.x < 0.0 && localPos.y < 0.0) { if(strip > .5) { color.x = vColor.x; color.y = vColor.x; color.z = vColor.x; alpha = 0.0; } else { color.x = vColor.y; color.y = vColor.y; color.z = vColor.x; } } else { if(grid > .5) { discard; } } } gl_FragColor = vec4(color * lightingModifier, alpha); } float ComputeLightingModifier() { vec3 light = normalize(vec3(1.0, 1.0, 1.0)); vec3 eye = normalize(-fPosition); vec3 normal = normalize(fNormal); vec3 halfVec = normalize((eye + light) / length(eye + light)); float ambientColor = 0.1; float specularConstant = 2.0; float diffuseConstant = 0.1; float specularExp = 50.0; float intensity = 3.0; float diffuseComponent = max(0.0, dot(light, normal)) * intensity * diffuseConstant; float specularComponent = pow(max(0.0, dot(halfVec, normal)), specularExp) * intensity * specularConstant; float ambientComponent = ambientColor * intensity; return (diffuseComponent + specularComponent + ambientComponent); } float Grid(float val, float dst) { return floor(mod(val*dst,1.0)+.5); } // a common glsl one liner for generting some sort of pseudorandom number float rand(vec2 co){ return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453); }`
'use strict'; import { async } from 'metal'; import { dom } from 'metal-dom'; import CancellablePromise from 'metal-promise'; import globals from '../../src/globals/globals'; import utils from '../../src/utils/utils'; import App from '../../src/app/App'; import Route from '../../src/route/Route'; import Screen from '../../src/screen/Screen'; import HtmlScreen from '../../src/screen/HtmlScreen'; import Surface from '../../src/surface/Surface'; describe('App', function() { before((done) => { detectCanScrollIFrame(done); }); beforeEach(() => { var requests = this.requests = []; this.xhr = sinon.useFakeXMLHttpRequest(); this.xhr.onCreate = (xhr) => { requests.push(xhr); }; // Prevent log messages from showing up in test output. sinon.stub(console, 'log'); }); afterEach(() => { if (this.app && !this.app.isDisposed()) { this.app.dispose(); } this.app = null; this.xhr.restore(); console.log.restore(); }); it('should add route', () => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); var route = this.app.findRoute('/path'); assert.ok(this.app.hasRoutes()); assert.ok(route instanceof Route); assert.strictEqual('/path', route.getPath()); assert.strictEqual(Screen, route.getHandler()); }); it('should remove route', () => { this.app = new App(); var route = new Route('/path', Screen); this.app.addRoutes(route); assert.ok(this.app.removeRoute(route)); }); it('should add route from object', () => { this.app = new App(); this.app.addRoutes({ path: '/path', handler: Screen }); var route = this.app.findRoute('/path'); assert.ok(this.app.hasRoutes()); assert.ok(route instanceof Route); assert.strictEqual('/path', route.getPath()); assert.strictEqual(Screen, route.getHandler()); }); it('should add route from array', () => { this.app = new App(); this.app.addRoutes([{ path: '/path', handler: Screen }, new Route('/pathOther', Screen)]); var route = this.app.findRoute('/path'); assert.ok(this.app.hasRoutes()); assert.ok(route instanceof Route); assert.strictEqual('/path', route.getPath()); assert.strictEqual(Screen, route.getHandler()); var routeOther = this.app.findRoute('/pathOther'); assert.ok(routeOther instanceof Route); assert.strictEqual('/pathOther', routeOther.getPath()); assert.strictEqual(Screen, routeOther.getHandler()); }); it('should not find route for not registered paths', () => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); assert.strictEqual(null, this.app.findRoute('/pathOther')); }); it('should not allow navigation for urls with hashbang when navigating to same basepath', () => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); globals.window = { location: { hash: '', hostname: '', pathname: '/path', search: '' } }; assert.strictEqual(false, this.app.canNavigate('/path#hashbang')); globals.window = window; }); it('should allow navigation for urls with hashbang when navigating to different basepath', () => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); globals.window = { location: { hash: '', hostname: '', pathname: '/path1', search: '' } }; assert.strictEqual(true, this.app.canNavigate('/path#hashbang')); globals.window = window; }); it('should find route for urls with hashbang for different basepath', () => { this.app = new App(); this.app.addRoutes(new Route('/pathOther', Screen)); globals.window = { location: { pathname: '/path', search: '' } }; assert.ok(this.app.findRoute('/pathOther#hashbang')); globals.window = window; }); it('should find route for urls ending with or without slash', () => { this.app = new App(); this.app.addRoutes(new Route('/pathOther', Screen)); globals.window = { location: { pathname: '/path/', search: '' } }; assert.ok(this.app.findRoute('/pathOther')); assert.ok(this.app.findRoute('/pathOther/')); globals.window = window; }); it('should ignore query string on findRoute when ignoreQueryStringFromRoutePath is enabled', () => { this.app = new App(); this.app.setIgnoreQueryStringFromRoutePath(true); this.app.addRoutes(new Route('/path', Screen)); assert.ok(this.app.findRoute('/path?foo=1')); }); it('should not ignore query string on findRoute when ignoreQueryStringFromRoutePath is disabled', () => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); assert.ok(!this.app.findRoute('/path?foo=1')); }); it('should add surface', () => { this.app = new App(); this.app.addSurfaces(new Surface('surfaceId')); assert.ok(this.app.surfaces.surfaceId); assert.strictEqual('surfaceId', this.app.surfaces.surfaceId.getId()); }); it('should add surface from surface id', () => { this.app = new App(); this.app.addSurfaces('surfaceId'); assert.ok(this.app.surfaces.surfaceId); assert.strictEqual('surfaceId', this.app.surfaces.surfaceId.getId()); }); it('should add surface from array', () => { this.app = new App(); this.app.addSurfaces([new Surface('surfaceId'), 'surfaceIdOther']); assert.ok(this.app.surfaces.surfaceId); assert.ok(this.app.surfaces.surfaceIdOther); assert.strictEqual('surfaceId', this.app.surfaces.surfaceId.getId()); assert.strictEqual('surfaceIdOther', this.app.surfaces.surfaceIdOther.getId()); }); it('should create screen instance to a route', () => { this.app = new App(); var screen = this.app.createScreenInstance('/path', new Route('/path', Screen)); assert.ok(screen instanceof Screen); }); it('should create screen instance to a route for Screen class child', () => { this.app = new App(); var screen = this.app.createScreenInstance('/path', new Route('/path', HtmlScreen)); assert.ok(screen instanceof HtmlScreen); }); it('should create screen instance to a route with function handler', () => { this.app = new App(); var stub = sinon.stub(); var route = new Route('/path', stub); var screen = this.app.createScreenInstance('/path', route); assert.strictEqual(1, stub.callCount); assert.strictEqual(route, stub.args[0][0]); assert.strictEqual(undefined, stub.returnValues[0]); assert.ok(screen instanceof Screen); }); it('should get same screen instance to a route', () => { this.app = new App(); var route = new Route('/path', Screen); var screen = this.app.createScreenInstance('/path', route); this.app.screens['/path'] = screen; assert.strictEqual(screen, this.app.createScreenInstance('/path', route)); }); it('should use same screen instance when simulating navigate refresh', () => { this.app = new App(); var route = new Route('/path', HtmlScreen); var screen = this.app.createScreenInstance('/path', route); this.app.screens['/path'] = screen; this.app.activePath = '/path'; this.app.activeScreen = screen; var screenRefresh = this.app.createScreenInstance('/path', route); assert.strictEqual(screen, screenRefresh); }); it('should store screen for path with query string when ignoreQueryStringFromRoutePath is enabled', (done) => { class NoCacheScreen extends Screen { constructor() { super(); } } this.app = new App(); this.app.setIgnoreQueryStringFromRoutePath(true); this.app.addRoutes(new Route('/path', NoCacheScreen)); this.app.navigate('/path?foo=1').then(() => { assert.ok(this.app.screens['/path?foo=1']); done(); }); }); it('should create different screen instance when navigate to same path with different query strings if ignoreQueryStringFromRoutePath is enabled', (done) => { class NoCacheScreen extends Screen { constructor() { super(); } } this.app = new App(); this.app.setIgnoreQueryStringFromRoutePath(true); this.app.addRoutes(new Route('/path1', NoCacheScreen)); this.app.addRoutes(new Route('/path2', NoCacheScreen)); this.app.navigate('/path1?foo=1').then(() => { var screenFirstNavigate = this.app.screens['/path1?foo=1']; this.app.navigate('/path2').then(() => { this.app.navigate('/path1?foo=2').then(() => { assert.notStrictEqual(screenFirstNavigate, this.app.screens['/path1?foo=2']); done(); }); }); }); }); it('should create different screen instance navigate when not cacheable', (done) => { class NoCacheScreen extends Screen { constructor() { super(); this.cacheable = false; } } this.app = new App(); this.app.addRoutes(new Route('/path1', NoCacheScreen)); this.app.addRoutes(new Route('/path2', NoCacheScreen)); this.app.navigate('/path1').then(() => { var screenFirstNavigate = this.app.screens['/path1']; this.app.navigate('/path2').then(() => { this.app.navigate('/path1').then(() => { assert.notStrictEqual(screenFirstNavigate, this.app.screens['/path1']); done(); }); }); }); }); it('should use same screen instance navigate when is cacheable', (done) => { class CacheScreen extends Screen { constructor() { super(); this.cacheable = true; } } this.app = new App(); this.app.addRoutes(new Route('/path1', CacheScreen)); this.app.addRoutes(new Route('/path2', CacheScreen)); this.app.navigate('/path1').then(() => { var screenFirstNavigate = this.app.screens['/path1']; this.app.navigate('/path2').then(() => { this.app.navigate('/path1').then(() => { assert.strictEqual(screenFirstNavigate, this.app.screens['/path1']); done(); }); }); }); }); it('should clear screen cache', () => { this.app = new App(); this.app.screens['/path'] = this.app.createScreenInstance('/path', new Route('/path', HtmlScreen)); this.app.clearScreensCache(); assert.strictEqual(0, Object.keys(this.app.screens).length); }); it('should clear all screen caches on app dispose', () => { this.app = new App(); var screen1 = this.app.createScreenInstance('/path1', new Route('/path1', HtmlScreen)); var screen2 = this.app.createScreenInstance('/path2', new Route('/path2', HtmlScreen)); this.app.activePath = '/path1'; this.app.activeScreen = screen1; this.app.screens['/path1'] = screen1; this.app.screens['/path2'] = screen2; this.app.dispose(); assert.strictEqual(0, Object.keys(this.app.screens).length); }); it('should clear screen cache and remove surfaces', () => { this.app = new App(); var surface = new Surface('surfaceId'); surface.remove = sinon.stub(); this.app.addSurfaces(surface); this.app.screens['/path'] = this.app.createScreenInstance('/path', new Route('/path', HtmlScreen)); this.app.clearScreensCache(); assert.strictEqual(1, surface.remove.callCount); }); it('should clear screen cache for activeScreen but not remove it', () => { this.app = new App(); this.app.screens['/path'] = this.app.createScreenInstance('/path', new Route('/path', HtmlScreen)); this.app.activePath = '/path'; this.app.activeScreen = this.app.screens['/path']; this.app.clearScreensCache(); assert.strictEqual(1, Object.keys(this.app.screens).length); assert.strictEqual(null, this.app.activeScreen.getCache()); }); it('should get allow prevent navigate', () => { this.app = new App(); assert.strictEqual(true, this.app.getAllowPreventNavigate()); this.app.setAllowPreventNavigate(false); assert.strictEqual(false, this.app.getAllowPreventNavigate()); }); it('should get default title', () => { globals.document.title = 'default'; this.app = new App(); assert.strictEqual('default', this.app.getDefaultTitle()); this.app.setDefaultTitle('title'); assert.strictEqual('title', this.app.getDefaultTitle()); }); it('should get basepath', () => { this.app = new App(); assert.strictEqual('', this.app.getBasePath()); this.app.setBasePath('/base'); assert.strictEqual('/base', this.app.getBasePath()); }); it('should get update scroll position', () => { this.app = new App(); assert.strictEqual(true, this.app.getUpdateScrollPosition()); this.app.setUpdateScrollPosition(false); assert.strictEqual(false, this.app.getUpdateScrollPosition()); }); it('should get loading css class', () => { this.app = new App(); assert.strictEqual('senna-loading', this.app.getLoadingCssClass()); this.app.setLoadingCssClass(''); assert.strictEqual('', this.app.getLoadingCssClass()); }); it('should get form selector', () => { this.app = new App(); assert.strictEqual('form[enctype="multipart/form-data"]:not([data-senna-off])', this.app.getFormSelector()); this.app.setFormSelector(''); assert.strictEqual('', this.app.getFormSelector()); }); it('should get link selector', () => { this.app = new App(); assert.strictEqual('a:not([data-senna-off])', this.app.getLinkSelector()); this.app.setLinkSelector(''); assert.strictEqual('', this.app.getLinkSelector()); }); it('should get link selector', () => { this.app = new App(); assert.strictEqual('a:not([data-senna-off])', this.app.getLinkSelector()); this.app.setLinkSelector(''); assert.strictEqual('', this.app.getLinkSelector()); }); it('should test if can navigate to url', () => { this.app = new App(); globals.window = { history: {}, location: { hostname: 'localhost', pathname: '/path', search: '' } }; this.app.setBasePath('/base'); this.app.addRoutes([new Route('/', Screen), new Route('/path', Screen)]); assert.ok(this.app.canNavigate('http://localhost/base/')); assert.ok(this.app.canNavigate('http://localhost/base')); assert.ok(this.app.canNavigate('http://localhost/base/path')); assert.ok(!this.app.canNavigate('http://localhost/base/path1')); assert.ok(!this.app.canNavigate('http://localhost/path')); assert.ok(!this.app.canNavigate('http://external/path')); assert.ok(!this.app.canNavigate('tel:+0101010101')); assert.ok(!this.app.canNavigate('mailto:contact@sennajs.com')); globals.window = window; }); it('should test if can navigate to url with base path ending in "/"', () => { this.app = new App(); globals.window = { history: {}, location: { hostname: 'localhost', pathname: '/path', search: '' } }; this.app.setBasePath('/base/'); this.app.addRoutes([new Route('/', Screen), new Route('/path', Screen)]); assert.ok(this.app.canNavigate('http://localhost/base/')); assert.ok(this.app.canNavigate('http://localhost/base')); assert.ok(this.app.canNavigate('http://localhost/base/path')); assert.ok(!this.app.canNavigate('http://localhost/base/path1')); assert.ok(!this.app.canNavigate('http://localhost/path')); assert.ok(!this.app.canNavigate('http://external/path')); globals.window = window; }); it('should be able to navigate to route that ends with "/"', () => { this.app = new App(); globals.window = { history: {}, location: { hostname: 'localhost', pathname: '/path', search: '' } }; this.app.addRoutes([new Route('/path/', Screen), new Route('/path/(\\d+)/', Screen)]); assert.ok(this.app.canNavigate('http://localhost/path')); assert.ok(this.app.canNavigate('http://localhost/path/')); assert.ok(this.app.canNavigate('http://localhost/path/123')); assert.ok(this.app.canNavigate('http://localhost/path/123/')); globals.window = window; }); it('should store proper senna state after navigate', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.navigate('/path').then(() => { assert.deepEqual({ form: false, redirectPath: '/path', path: '/path', senna: true, scrollTop: 0, scrollLeft: 0 }, globals.window.history.state); done(); }); }); it('should navigate emit startNavigate and endNavigate custom event', (done) => { var startNavigateStub = sinon.stub(); var endNavigateStub = sinon.stub(); this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.on('startNavigate', startNavigateStub); this.app.on('endNavigate', endNavigateStub); this.app.navigate('/path').then(() => { assert.strictEqual(1, startNavigateStub.callCount); assert.strictEqual('/path', startNavigateStub.args[0][0].path); assert.strictEqual(false, startNavigateStub.args[0][0].replaceHistory); assert.strictEqual(1, endNavigateStub.callCount); assert.strictEqual('/path', endNavigateStub.args[0][0].path); done(); }); }); it('should navigate emit startNavigate and endNavigate custom event with replace history', (done) => { var startNavigateStub = sinon.stub(); var endNavigateStub = sinon.stub(); this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.on('startNavigate', startNavigateStub); this.app.on('endNavigate', endNavigateStub); this.app.navigate('/path', true).then(() => { assert.strictEqual(1, startNavigateStub.callCount); assert.strictEqual('/path', startNavigateStub.args[0][0].path); assert.strictEqual(true, startNavigateStub.args[0][0].replaceHistory); assert.strictEqual(1, endNavigateStub.callCount); assert.strictEqual('/path', endNavigateStub.args[0][0].path); done(); }); }); it('should navigate overwrite event.path on beforeNavigate custom event', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path1', Screen)); this.app.on('beforeNavigate', (event) => { event.path = '/path1'; }); this.app.navigate('/path').then(() => { assert.strictEqual('/path1', globals.window.location.pathname); done(); }); }); it('should cancel navigate', (done) => { var stub = sinon.stub(); this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.on('endNavigate', (payload) => { assert.ok(payload.error instanceof Error); stub(); }); this.app.navigate('/path').catch((reason) => { assert.ok(reason instanceof Error); assert.strictEqual(1, stub.callCount); done(); }).cancel(); }); it('should clear pendingNavigate after navigate', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.navigate('/path').then(() => { assert.ok(!this.app.pendingNavigate); done(); }); assert.ok(this.app.pendingNavigate); }); it('should wait for pendingNavigate if navigate to same path', (done) => { class CacheScreen extends Screen { constructor() { super(); this.cacheable = true; } } this.app = new App(); this.app.addRoutes(new Route('/path', CacheScreen)); this.app.navigate('/path').then(() => { var pendingNavigate1 = this.app.navigate('/path'); var pendingNavigate2 = this.app.navigate('/path'); assert.ok(pendingNavigate1); assert.ok(pendingNavigate2); assert.strictEqual(pendingNavigate1, pendingNavigate2); done(); }); }); it('should navigate back when clicking browser back button', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path1', Screen)); this.app.addRoutes(new Route('/path2', Screen)); this.app.navigate('/path1') .then(() => this.app.navigate('/path2')) .then(() => { var activeScreen = this.app.activeScreen; assert.strictEqual('/path2', globals.window.location.pathname); this.app.once('endNavigate', () => { assert.strictEqual('/path1', globals.window.location.pathname); assert.notStrictEqual(activeScreen, this.app.activeScreen); done(); }); globals.window.history.back(); }); }); it('should not navigate back on a hash change', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path1', Screen)); this.app.addRoutes(new Route('/path2', Screen)); this.app.navigate('/path1') .then(() => this.app.navigate('/path1#hash')) .then(() => { var startNavigate = sinon.stub(); this.app.on('startNavigate', startNavigate); dom.once(globals.window, 'popstate', () => { assert.strictEqual(0, startNavigate.callCount); done(); }); globals.window.history.back(); }); }); it('should only call beforeNavigate when waiting for pendingNavigate if navigate to same path', (done) => { class CacheScreen extends Screen { constructor() { super(); this.cacheable = true; } } this.app = new App(); this.app.addRoutes(new Route('/path', CacheScreen)); this.app.navigate('/path').then(() => { this.app.navigate('/path'); var beforeNavigate = sinon.stub(); var startNavigate = sinon.stub(); this.app.on('beforeNavigate', beforeNavigate); this.app.on('startNavigate', startNavigate); this.app.navigate('/path'); assert.strictEqual(1, beforeNavigate.callCount); assert.strictEqual(0, startNavigate.callCount); done(); }); }); it('should not wait for pendingNavigate if navigate to different path', (done) => { class CacheScreen extends Screen { constructor() { super(); this.cacheable = true; } } this.app = new App(); this.app.addRoutes(new Route('/path1', CacheScreen)); this.app.addRoutes(new Route('/path2', CacheScreen)); this.app.navigate('/path1') .then(() => this.app.navigate('/path2')) .then(() => { var pendingNavigate1 = this.app.navigate('/path1'); var pendingNavigate2 = this.app.navigate('/path2'); assert.ok(pendingNavigate1); assert.ok(pendingNavigate2); assert.notStrictEqual(pendingNavigate1, pendingNavigate2); done(); }); }); it('should simulate refresh on navigate to the same path', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.once('startNavigate', (payload) => { assert.ok(!payload.replaceHistory); }); this.app.navigate('/path').then(() => { this.app.once('startNavigate', (payload) => { assert.ok(payload.replaceHistory); }); this.app.navigate('/path').then(() => { done(); }); }); }); it('should add loading css class on navigate', (done) => { var containsLoadingCssClass = () => { return globals.document.documentElement.classList.contains(this.app.getLoadingCssClass()); }; this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.on('startNavigate', () => assert.ok(containsLoadingCssClass())); this.app.on('endNavigate', () => { assert.ok(!containsLoadingCssClass()); done(); }); this.app.navigate('/path').then(() => assert.ok(!containsLoadingCssClass())); }); it('should not remove loading css class on navigate if there is pending navigate', (done) => { var containsLoadingCssClass = () => { return globals.document.documentElement.classList.contains(this.app.getLoadingCssClass()); }; this.app = new App(); this.app.addRoutes(new Route('/path1', Screen)); this.app.addRoutes(new Route('/path2', Screen)); this.app.once('startNavigate', () => { this.app.once('startNavigate', () => assert.ok(containsLoadingCssClass())); this.app.once('endNavigate', () => assert.ok(containsLoadingCssClass())); this.app.navigate('/path2').then(() => { assert.ok(!containsLoadingCssClass()); done(); }); }); this.app.navigate('/path1'); }); it('should not navigate to unrouted paths', (done) => { this.app = new App(); this.app.on('endNavigate', (payload) => { assert.ok(payload.error instanceof Error); }); this.app.navigate('/path', true).catch((reason) => { assert.ok(reason instanceof Error); done(); }); }); it('should store scroll position on page scroll', (done) => { if (!canScrollIFrame_) { done(); return; } showPageScrollbar(); this.app = new App(); setTimeout(() => { assert.strictEqual(100, globals.window.history.state.scrollTop); assert.strictEqual(100, globals.window.history.state.scrollLeft); hidePageScrollbar(); done(); }, 300); globals.window.scrollTo(100, 100); }); it('should not store page scroll position during navigate', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.on('startNavigate', () => { this.app.onScroll_(); // Coverage assert.ok(!this.app.captureScrollPositionFromScrollEvent); }); assert.ok(this.app.captureScrollPositionFromScrollEvent); this.app.navigate('/path').then(() => { assert.ok(this.app.captureScrollPositionFromScrollEvent); done(); }); }); it('should update scroll position on navigate', (done) => { if (!canScrollIFrame_) { done(); return; } showPageScrollbar(); this.app = new App(); this.app.addRoutes(new Route('/path1', Screen)); this.app.addRoutes(new Route('/path2', Screen)); this.app.navigate('/path1').then(() => { setTimeout(() => { this.app.navigate('/path2').then(() => { assert.strictEqual(0, window.pageXOffset); assert.strictEqual(0, window.pageYOffset); hidePageScrollbar(); done(); }); }, 300); globals.window.scrollTo(100, 100); }); }); it('should not update scroll position on navigate if updateScrollPosition is disabled', (done) => { if (!canScrollIFrame_) { done(); return; } showPageScrollbar(); this.app = new App(); this.app.setUpdateScrollPosition(false); this.app.addRoutes(new Route('/path1', Screen)); this.app.addRoutes(new Route('/path2', Screen)); this.app.navigate('/path1').then(() => { setTimeout(() => { this.app.navigate('/path2').then(() => { assert.strictEqual(100, window.pageXOffset); assert.strictEqual(100, window.pageYOffset); hidePageScrollbar(); done(); }); }, 100); globals.window.scrollTo(100, 100); }); }); it('should restore scroll position on navigate back', (done) => { if (!canScrollIFrame_) { done(); return; } showPageScrollbar(); this.app = new App(); this.app.addRoutes(new Route('/path1', Screen)); this.app.addRoutes(new Route('/path2', Screen)); this.app.navigate('/path1').then(() => { setTimeout(() => { this.app.navigate('/path2').then(() => { assert.strictEqual(0, window.pageXOffset); assert.strictEqual(0, window.pageYOffset); this.app.once('endNavigate', () => { assert.strictEqual(100, window.pageXOffset); assert.strictEqual(100, window.pageYOffset); hidePageScrollbar(); done(); }); globals.window.history.back(); }); }, 300); globals.window.scrollTo(100, 100); }); }); it('should dispatch navigate to current path', (done) => { globals.window.history.replaceState({}, '', '/path1?foo=1#hash'); this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.on('endNavigate', (payload) => { assert.strictEqual('/path1?foo=1#hash', payload.path); globals.window.history.replaceState({}, '', utils.getCurrentBrowserPath()); done(); }); this.app.dispatch(); }); it('should not navigate if active screen forbid deactivate', (done) => { class NoNavigateScreen extends Screen { beforeDeactivate() { return true; } } this.app = new App(); this.app.addRoutes(new Route('/path1', NoNavigateScreen)); this.app.addRoutes(new Route('/path2', Screen)); this.app.navigate('/path1').then(() => { this.app.on('endNavigate', (payload) => { assert.ok(payload.error instanceof Error); }); this.app.navigate('/path2').catch((reason) => { assert.ok(reason instanceof Error); done(); }); }); }); it('should prefetch paths', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.prefetch('/path').then(() => { assert.ok(this.app.screens['/path'] instanceof Screen); done(); }); }); it('should prefetch fail on navigate to unrouted paths', (done) => { this.app = new App(); this.app.on('endNavigate', (payload) => { assert.ok(payload.error instanceof Error); }); this.app.prefetch('/path').catch((reason) => { assert.ok(reason instanceof Error); done(); }); }); it('should cancel prefetch', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.on('endNavigate', (payload) => { assert.ok(payload.error instanceof Error); }); this.app.prefetch('/path').catch((reason) => { assert.ok(reason instanceof Error); done(); }).cancel(); }); it('should navigate when clicking on routed links', () => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); dom.triggerEvent(enterDocumentLinkElement('/path'), 'click'); assert.ok(this.app.pendingNavigate); exitDocumentLinkElement(); }); it('should pass original event object to "beforeNavigate" when a link is clicked', () => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.on('beforeNavigate', (data) => { assert.ok(data.event); assert.equal('click', data.event.type); }); dom.triggerEvent(enterDocumentLinkElement('/path'), 'click'); exitDocumentLinkElement(); assert.notEqual('/path', window.location.pathname); }); it('should prevent navigation on both senna and the browser via beforeNavigate', () => { this.app = new App(); this.app.addRoutes(new Route('/preventedPath', Screen)); this.app.on('beforeNavigate', (data, event) => { data.event.preventDefault(); event.preventDefault(); }); dom.triggerEvent(enterDocumentLinkElement('/preventedPath'), 'click'); exitDocumentLinkElement(); assert.notEqual('/preventedPath', window.location.pathname); }); it('should not navigate when clicking on external links', () => { var link = enterDocumentLinkElement('http://sennajs.com'); this.app = new App(); this.app.setAllowPreventNavigate(false); dom.on(link, 'click', preventDefault); dom.triggerEvent(link, 'click'); assert.strictEqual(null, this.app.pendingNavigate); exitDocumentLinkElement(); }); it('should not navigate when clicking on links outside basepath', () => { var link = enterDocumentLinkElement('/path'); this.app = new App(); this.app.setAllowPreventNavigate(false); this.app.setBasePath('/base'); dom.on(link, 'click', preventDefault); dom.triggerEvent(link, 'click'); assert.strictEqual(null, this.app.pendingNavigate); exitDocumentLinkElement(); }); it('should not navigate when clicking on unrouted links', () => { var link = enterDocumentLinkElement('/path'); this.app = new App(); this.app.setAllowPreventNavigate(false); dom.on(link, 'click', preventDefault); dom.triggerEvent(link, 'click'); assert.strictEqual(null, this.app.pendingNavigate); exitDocumentLinkElement(); }); it('should not navigate when clicking on links with invalid mouse button or modifier keys pressed', () => { var link = enterDocumentLinkElement('/path'); this.app = new App(); this.app.setAllowPreventNavigate(false); this.app.addRoutes(new Route('/path', Screen)); dom.on(link, 'click', preventDefault); dom.triggerEvent(link, 'click', { altKey: true }); dom.triggerEvent(link, 'click', { ctrlKey: true }); dom.triggerEvent(link, 'click', { metaKey: true }); dom.triggerEvent(link, 'click', { shiftKey: true }); dom.triggerEvent(link, 'click', { button: true }); assert.strictEqual(null, this.app.pendingNavigate); exitDocumentLinkElement(); }); it('should not navigate when navigate fails synchronously', () => { var link = enterDocumentLinkElement('/path'); this.app = new App(); this.app.setAllowPreventNavigate(false); this.app.addRoutes(new Route('/path', Screen)); this.app.navigate = () => { throw new Error(); }; dom.on(link, 'click', preventDefault); dom.triggerEvent(link, 'click'); assert.strictEqual(null, this.app.pendingNavigate); exitDocumentLinkElement(); }); it('should reload page on navigate back to a routed page without history state', (done) => { this.app = new App(); this.app.reloadPage = sinon.stub(); this.app.addRoutes(new Route('/path1', Screen)); this.app.addRoutes(new Route('/path2', Screen)); this.app.navigate('/path1').then(() => { window.history.replaceState(null, null, null); this.app.navigate('/path2').then(() => { dom.once(globals.window, 'popstate', () => { assert.strictEqual(1, this.app.reloadPage.callCount); done(); }); globals.window.history.back(); }); }); }); it('should not reload page on navigate back to a routed page with same path containing hashbang without history state', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.reloadPage = sinon.stub(); this.app.navigate('/path').then(() => { globals.window.location.hash = 'hash1'; window.history.replaceState(null, null, null); this.app.navigate('/path').then(() => { dom.once(globals.window, 'popstate', () => { assert.strictEqual(0, this.app.reloadPage.callCount); done(); }); globals.window.history.back(); }); }); }); it('should reload page on navigate back to a routed page with different path containing hashbang without history state', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path1', Screen)); this.app.addRoutes(new Route('/path2', Screen)); this.app.reloadPage = sinon.stub(); this.app.navigate('/path1').then(() => { globals.window.location.hash = 'hash1'; window.history.replaceState(null, null, null); this.app.navigate('/path2').then(() => { dom.once(globals.window, 'popstate', () => { assert.strictEqual(1, this.app.reloadPage.callCount); done(); }); globals.window.history.back(); }); }); }); it('should not reload page on clicking links with same path containing different hashbang without history state', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.reloadPage = sinon.stub(); window.history.replaceState(null, null, '/path#hash1'); dom.once(globals.window, 'popstate', () => { assert.strictEqual(0, this.app.reloadPage.callCount); done(); }); dom.triggerEvent(globals.window, 'popstate'); }); it('should resposition scroll to hashed anchors on hash popstate', (done) => { if (!canScrollIFrame_) { done(); return; } showPageScrollbar(); var link = enterDocumentLinkElement('/path'); link.style.position = 'absolute'; link.style.top = '1000px'; link.style.left = '1000px'; this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.navigate('/path').then(() => { globals.window.location.hash = 'link'; window.history.replaceState(null, null, null); globals.window.location.hash = 'other'; window.history.replaceState(null, null, null); dom.once(globals.window, 'popstate', () => { assert.strictEqual(1000, window.pageXOffset); assert.strictEqual(1000, window.pageYOffset); exitDocumentLinkElement(); hidePageScrollbar(); dom.once(globals.window, 'popstate', () => { done(); }); globals.window.history.back(); }); globals.window.history.back(); }); }); it('should not reload page on navigate back to a routed page without history state and skipLoadPopstate is active', (done) => { this.app = new App(); this.app.reloadPage = sinon.stub(); this.app.addRoutes(new Route('/path1', Screen)); this.app.addRoutes(new Route('/path2', Screen)); this.app.navigate('/path1').then(() => { window.history.replaceState(null, null, null); this.app.navigate('/path2').then(() => { dom.once(globals.window, 'popstate', () => { assert.strictEqual(0, this.app.reloadPage.callCount); done(); }); this.app.skipLoadPopstate = true; globals.window.history.back(); }); }); }); it('should navigate when submitting routed forms', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); dom.triggerEvent(enterDocumentFormElement('/path', 'post'), 'submit'); assert.ok(this.app.pendingNavigate); this.app.on('endNavigate', () => { exitDocumentFormElement(); done(); }); }); it('should not navigate when submitting routed forms if submit event was prevented', () => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); var form = enterDocumentFormElement('/path', 'post'); dom.once(form, 'submit', preventDefault); dom.triggerEvent(form, 'submit'); assert.ok(!this.app.pendingNavigate); exitDocumentFormElement(); }); it('should not capture form element when submit event was prevented', () => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); var form = enterDocumentFormElement('/path', 'post'); dom.once(form, 'submit', preventDefault); dom.triggerEvent(form, 'submit'); assert.ok(!globals.capturedFormElement); exitDocumentFormElement(); }); it('should expose form reference in event data when submitting routed forms', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); dom.triggerEvent(enterDocumentFormElement('/path', 'post'), 'submit'); this.app.on('startNavigate', (data) => { assert.ok(data.form); }); this.app.on('endNavigate', (data) => { assert.ok(data.form); exitDocumentFormElement(); done(); }); }); it('should not navigate when submitting forms with method get', () => { var form = enterDocumentFormElement('/path', 'get'); this.app = new App(); this.app.setAllowPreventNavigate(false); this.app.addRoutes(new Route('/path', Screen)); dom.on(form, 'submit', preventDefault); dom.triggerEvent(form, 'submit'); assert.strictEqual(null, this.app.pendingNavigate); exitDocumentFormElement(); }); it('should not navigate when submitting on external forms', () => { var form = enterDocumentFormElement('http://sennajs.com', 'post'); this.app = new App(); this.app.setAllowPreventNavigate(false); dom.on(form, 'submit', preventDefault); dom.triggerEvent(form, 'submit'); assert.strictEqual(null, this.app.pendingNavigate); exitDocumentFormElement(); }); it('should not navigate when submitting on forms outside basepath', () => { var form = enterDocumentFormElement('/path', 'post'); this.app = new App(); this.app.setAllowPreventNavigate(false); this.app.setBasePath('/base'); dom.on(form, 'submit', preventDefault); dom.triggerEvent(form, 'submit'); assert.strictEqual(null, this.app.pendingNavigate); exitDocumentFormElement(); }); it('should not navigate when submitting on unrouted forms', () => { var form = enterDocumentFormElement('/path', 'post'); this.app = new App(); this.app.setAllowPreventNavigate(false); dom.on(form, 'submit', preventDefault); dom.triggerEvent(form, 'submit'); assert.strictEqual(null, this.app.pendingNavigate); exitDocumentFormElement(); }); it('should not capture form if navigate fails when submitting forms', () => { var form = enterDocumentFormElement('/path', 'post'); this.app = new App(); this.app.setAllowPreventNavigate(false); dom.on(form, 'submit', preventDefault); dom.triggerEvent(form, 'submit'); assert.ok(!globals.capturedFormElement); exitDocumentFormElement(); }); it('should capture form on beforeNavigate', (done) => { const form = enterDocumentFormElement('/path', 'post'); this.app = new App(); this.app.setAllowPreventNavigate(false); this.app.addRoutes(new Route('/path', Screen)); this.app.on('beforeNavigate', (event) => { assert.ok(event.form); exitDocumentFormElement(); globals.capturedFormElement = null; done(); }); dom.on(form, 'submit', sinon.stub()); dom.triggerEvent(form, 'submit'); assert.ok(globals.capturedFormElement); }); it('should capture form button when submitting', () => { const form = enterDocumentFormElement('/path', 'post'); const button = globals.document.createElement('button'); form.appendChild(button); this.app = new App(); this.app.setAllowPreventNavigate(false); this.app.addRoutes(new Route('/path', Screen)); dom.on(form, 'submit', sinon.stub()); dom.triggerEvent(form, 'submit'); assert.ok(globals.capturedFormButtonElement); globals.capturedFormButtonElement = null; }); it('should capture form button when clicking submit button', () => { const form = enterDocumentFormElement('/path', 'post'); const button = globals.document.createElement('button'); button.type = 'submit'; button.tabindex = 1; form.appendChild(button); this.app = new App(); this.app.setAllowPreventNavigate(false); this.app.addRoutes(new Route('/path', Screen)); button.click(); assert.ok(globals.capturedFormButtonElement); globals.capturedFormButtonElement = null; }); it('should set redirect path if history path was redirected', (done) => { class RedirectScreen extends Screen { beforeUpdateHistoryPath() { return '/redirect'; } } this.app = new App(); this.app.addRoutes(new Route('/path', RedirectScreen)); this.app.navigate('/path').then(() => { assert.strictEqual('/redirect', this.app.redirectPath); assert.strictEqual('/path', this.app.activePath); done(); }); }); it('should update the state with the redirected path', (done) => { class RedirectScreen extends Screen { beforeUpdateHistoryPath() { return '/redirect'; } } this.app = new App(); this.app.addRoutes(new Route('/path', RedirectScreen)); this.app.navigate('/path').then(() => { assert.strictEqual('/redirect', globals.window.location.pathname); done(); }); }); it('should restore hashbang if redirect path is the same as requested path', (done) => { class RedirectScreen extends Screen { beforeUpdateHistoryPath() { return '/path'; } } this.app = new App(); this.app.addRoutes(new Route('/path', RedirectScreen)); this.app.navigate('/path#hash').then(() => { assert.strictEqual('/path#hash', utils.getCurrentBrowserPath()); done(); }); }); it('should not restore hashbang if redirect path is not the same as requested path', (done) => { class RedirectScreen extends Screen { beforeUpdateHistoryPath() { return '/redirect'; } } this.app = new App(); this.app.addRoutes(new Route('/path', RedirectScreen)); this.app.navigate('/path#hash').then(() => { assert.strictEqual('/redirect', utils.getCurrentBrowserPath()); done(); }); }); it('should skipLoadPopstate before page is loaded', (done) => { this.app = new App(); this.app.onLoad_(); // Simulate assert.ok(this.app.skipLoadPopstate); setTimeout(() => { assert.ok(!this.app.skipLoadPopstate); done(); }, 0); }); it('should respect screen lifecycle on navigate', (done) => { class StubScreen1 extends Screen { } StubScreen1.prototype.activate = sinon.spy(); StubScreen1.prototype.beforeDeactivate = sinon.spy(); StubScreen1.prototype.deactivate = sinon.spy(); StubScreen1.prototype.flip = sinon.spy(); StubScreen1.prototype.load = sinon.stub().returns(CancellablePromise.resolve()); StubScreen1.prototype.disposeInternal = sinon.spy(); StubScreen1.prototype.evaluateStyles = sinon.spy(); StubScreen1.prototype.evaluateScripts = sinon.spy(); class StubScreen2 extends Screen { } StubScreen2.prototype.activate = sinon.spy(); StubScreen2.prototype.beforeDeactivate = sinon.spy(); StubScreen2.prototype.deactivate = sinon.spy(); StubScreen2.prototype.flip = sinon.spy(); StubScreen2.prototype.load = sinon.stub().returns(CancellablePromise.resolve()); StubScreen2.prototype.evaluateStyles = sinon.spy(); StubScreen2.prototype.evaluateScripts = sinon.spy(); this.app = new App(); this.app.addRoutes(new Route('/path1', StubScreen1)); this.app.addRoutes(new Route('/path2', StubScreen2)); this.app.navigate('/path1').then(() => { this.app.navigate('/path2').then(() => { var lifecycleOrder = [ StubScreen1.prototype.load, StubScreen1.prototype.evaluateStyles, StubScreen1.prototype.flip, StubScreen1.prototype.evaluateScripts, StubScreen1.prototype.activate, StubScreen1.prototype.beforeDeactivate, StubScreen2.prototype.load, StubScreen1.prototype.deactivate, StubScreen2.prototype.evaluateStyles, StubScreen2.prototype.flip, StubScreen2.prototype.evaluateScripts, StubScreen2.prototype.activate, StubScreen1.prototype.disposeInternal ]; for (var i = 1; i < lifecycleOrder.length - 1; i++) { assert.ok(lifecycleOrder[i - 1].calledBefore(lifecycleOrder[i])); } done(); }); }); }); it('should render surfaces', (done) => { class ContentScreen extends Screen { getSurfaceContent(surfaceId) { return surfaceId; } getId() { return 'screenId'; } } var surface = new Surface('surfaceId'); surface.addContent = sinon.stub(); this.app = new App(); this.app.addRoutes(new Route('/path', ContentScreen)); this.app.addSurfaces(surface); this.app.navigate('/path').then(() => { assert.strictEqual(1, surface.addContent.callCount); assert.strictEqual('screenId', surface.addContent.args[0][0]); assert.strictEqual('surfaceId', surface.addContent.args[0][1]); done(); }); }); it('should pass extracted params to "getSurfaceContent"', (done) => { var screen; class ContentScreen extends Screen { constructor() { super(); screen = this; } getId() { return 'screenId'; } } ContentScreen.prototype.getSurfaceContent = sinon.stub(); var surface = new Surface('surfaceId'); this.app = new App(); this.app.addRoutes(new Route('/path/:foo(\\d+)/:bar', ContentScreen)); this.app.addSurfaces(surface); this.app.navigate('/path/123/abc').then(() => { assert.strictEqual(1, screen.getSurfaceContent.callCount); assert.strictEqual('surfaceId', screen.getSurfaceContent.args[0][0]); var expectedParams = { foo: '123', bar: 'abc' }; assert.deepEqual(expectedParams, screen.getSurfaceContent.args[0][1]); done(); }); }); it('should pass extracted params to "getSurfaceContent" with base path', (done) => { var screen; class ContentScreen extends Screen { constructor() { super(); screen = this; } getId() { return 'screenId'; } } ContentScreen.prototype.getSurfaceContent = sinon.stub(); var surface = new Surface('surfaceId'); this.app = new App(); this.app.setBasePath('/path'); this.app.addRoutes(new Route('/:foo(\\d+)/:bar', ContentScreen)); this.app.addSurfaces(surface); this.app.navigate('/path/123/abc').then(() => { assert.strictEqual(1, screen.getSurfaceContent.callCount); assert.strictEqual('surfaceId', screen.getSurfaceContent.args[0][0]); var expectedParams = { foo: '123', bar: 'abc' }; assert.deepEqual(expectedParams, screen.getSurfaceContent.args[0][1]); done(); }); }); it('should extract params for the given route and path', () => { this.app = new App(); this.app.setBasePath('/path'); var route = new Route('/:foo(\\d+)/:bar', () => { }); var params = this.app.extractParams(route, '/path/123/abc'); var expectedParams = { foo: '123', bar: 'abc' }; assert.deepEqual(expectedParams, params); }); it('should render default surface content when not provided by screen', (done) => { class ContentScreen1 extends Screen { getSurfaceContent(surfaceId) { if (surfaceId === 'surfaceId1') { return 'content1'; } } getId() { return 'screenId1'; } } class ContentScreen2 extends Screen { getSurfaceContent(surfaceId) { if (surfaceId === 'surfaceId2') { return 'content2'; } } getId() { return 'screenId2'; } } dom.enterDocument('<div id="surfaceId1"><div id="surfaceId1-default">default1</div></div>'); dom.enterDocument('<div id="surfaceId2"><div id="surfaceId2-default">default2</div></div>'); var surface1 = new Surface('surfaceId1'); var surface2 = new Surface('surfaceId2'); surface1.addContent = sinon.stub(); surface2.addContent = sinon.stub(); this.app = new App(); this.app.addRoutes(new Route('/path1', ContentScreen1)); this.app.addRoutes(new Route('/path2', ContentScreen2)); this.app.addSurfaces([surface1, surface2]); this.app.navigate('/path1').then(() => { assert.strictEqual(1, surface1.addContent.callCount); assert.strictEqual('screenId1', surface1.addContent.args[0][0]); assert.strictEqual('content1', surface1.addContent.args[0][1]); assert.strictEqual(1, surface2.addContent.callCount); assert.strictEqual('screenId1', surface2.addContent.args[0][0]); assert.strictEqual(undefined, surface2.addContent.args[0][1]); assert.strictEqual('default2', surface2.getChild('default').innerHTML); this.app.navigate('/path2').then(() => { assert.strictEqual(2, surface1.addContent.callCount); assert.strictEqual('screenId2', surface1.addContent.args[1][0]); assert.strictEqual(undefined, surface1.addContent.args[1][1]); assert.strictEqual('default1', surface1.getChild('default').innerHTML); assert.strictEqual(2, surface2.addContent.callCount); assert.strictEqual('screenId2', surface2.addContent.args[1][0]); assert.strictEqual('content2', surface2.addContent.args[1][1]); dom.exitDocument(surface1.getElement()); dom.exitDocument(surface2.getElement()); done(); }); }); }); it('should add surface content after history path is updated', (done) => { var surface = new Surface('surfaceId'); surface.addContent = () => { assert.strictEqual('/path', globals.window.location.pathname); }; this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.addSurfaces(surface); this.app.navigate('/path').then(() => { done(); }); }); it('should not navigate when HTML5 History api is not supported', () => { var original = utils.isHtml5HistorySupported; assert.throws(() => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); utils.isHtml5HistorySupported = () => { return false; }; this.app.navigate('/path'); }, Error); utils.isHtml5HistorySupported = original; }); it('should set document title from screen title', (done) => { class TitledScreen extends Screen { getTitle() { return 'title'; } } this.app = new App(); this.app.addRoutes(new Route('/path', TitledScreen)); this.app.navigate('/path').then(() => { assert.strictEqual('title', globals.document.title); done(); }); }); it('should set globals.capturedFormElement to null after navigate', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path', Screen)); this.app.navigate('/path').then(() => { assert.strictEqual(null, globals.capturedFormElement); done(); }); }); it('should cancel nested promises on canceled navigate', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path', HtmlScreen)); this.app.navigate('/path') .then(() => assert.fail()) .catch(() => { assert.ok(this.requests[0].aborted); done(); }) .cancel(); }); it('should cancel nested promises on canceled prefetch', (done) => { this.app = new App(); this.app.addRoutes(new Route('/path', HtmlScreen)); this.app.prefetch('/path') .then(() => assert.fail()) .catch(() => { assert.ok(this.requests[0].aborted); done(); }) .cancel(); }); it('should wait for pendingNavigate before removing screen on double back navigation', (done) => { class CacheScreen extends Screen { constructor() { super(); this.cacheable = true; } load(path) { return new CancellablePromise(resolve => setTimeout(resolve, 100)); } } var app = new App(); this.app = app; app.addRoutes(new Route('/path1', CacheScreen)); app.addRoutes(new Route('/path2', CacheScreen)); app.addRoutes(new Route('/path3', CacheScreen)); app.navigate('/path1') .then(() => app.navigate('/path2')) .then(() => app.navigate('/path3')) .then(() => { var pendingNavigate; app.on('startNavigate', () => { pendingNavigate = app.pendingNavigate; assert.ok(app.screens['/path2']); }); app.once('endNavigate', () => { if (app.isNavigationPending) { assert.ok(!app.screens['/path2']); done(); } else { pendingNavigate.thenAlways(() => { assert.ok(!app.screens['/path2']); done(); }); pendingNavigate.cancel(); } }); globals.window.history.go(-1); setTimeout(() => globals.window.history.go(-1) , 50); }); }); it('should scroll to anchor element on navigate', (done) => { if (!canScrollIFrame_) { done(); return; } showPageScrollbar(); var link = enterDocumentLinkElement('/path2'); link.style.position = 'absolute'; link.style.top = '1000px'; link.style.left = '1000px'; this.app = new App(); this.app.addRoutes(new Route('/path1', Screen)); this.app.addRoutes(new Route('/path2', Screen)); this.app.navigate('/path1').then(() => { this.app.on('endNavigate', () => { assert.strictEqual(1000, window.pageXOffset); assert.strictEqual(1000, window.pageYOffset); hidePageScrollbar(); exitDocumentLinkElement(); done(); }); this.app.navigate('/path2#link'); }); }); }); var canScrollIFrame_ = false; /** * Checks if the current browser allows scrolling iframes. Mobile Safari doesn't * allow it, so we have to skip any tests that require window scrolling, since * these tests all run inside an iframe. */ function detectCanScrollIFrame(done) { showPageScrollbar(); dom.once(document, 'scroll', () => { canScrollIFrame_ = true; }); window.scrollTo(100, 100); setTimeout(() => { hidePageScrollbar(); done(); }, 1000); } function enterDocumentLinkElement(href) { dom.enterDocument('<a id="link" href="' + href + '">link</a>'); return document.getElementById('link'); } function enterDocumentFormElement(action, method) { dom.enterDocument('<form id="form" action="' + action + '" method="' + method + '" enctype="multipart/form-data"></form>'); return document.getElementById('form'); } function exitDocumentLinkElement() { dom.exitDocument(document.getElementById('link')); } function exitDocumentFormElement() { dom.exitDocument(document.getElementById('form')); } function preventDefault(event) { event.preventDefault(); } function showPageScrollbar() { globals.document.documentElement.style.height = '9999px'; globals.document.documentElement.style.width = '9999px'; } function hidePageScrollbar() { globals.document.documentElement.style.height = ''; globals.document.documentElement.style.width = ''; }
import React from 'react'; import classes from './ItemInput.module.css' import Aux from '../../hoc/Auxi' import Input from '../UI/Input/Input'; import AddButton from '../UI/Button/Button' const ItemInput = (props) => ( <Aux> <label>Add an item to the list</label> <div className={classes.content}> <Input changed={props.changed} value={props.value} /> <AddButton btnClass={classes.addBtn} clicked={props.clicked} >Add</AddButton> </div> </Aux> ) export default ItemInput;
import Picker from '../lib/Picker' import ReactDOM from 'react-dom' import React, { Component, PropTypes } from 'react' class TestComponent extends Component { constructor (props) { super(props) this.state = { enteredGif: '' } } log (gif) { console.log(gif) this.setState({enteredGif: gif}) } renderLoader() { return (<p style={{textAlign: 'center'}}>Loading...</p>) } render () { const {enteredGif} = this.state let url = '' if (enteredGif.fixed_width !== undefined) { url = enteredGif.fixed_width.url } return ( <div> <Picker onSelected={::this.log} modal={false} loader={this.renderLoader()} /> <img src={url} /> </div> ) } } ReactDOM.render( <TestComponent />, document.getElementById('root') )
/** * Sample React Native App * https://github.com/facebook/react-native */ import React, { AppRegistry, Component, Image, ListView, StyleSheet, Text, View, } from 'react-native'; var GeolocationExample = React.createClass({ watchID: (null: ?number), getInitialState: function() { return { initialPosition: 'unknown', lastPosition: 'unknown', }; }, // componentDidMount: function () { // this.timer = setInterval(function () { // navigator.geolocation.getCurrentPosition( // (position) => { // var initialPosition = JSON.stringify(position); // this.setState({initialPosition}); // }, // (error) => alert(error.message), // {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000} // ); // // // this.watchID = navigator.geolocation.watchPosition((position) => { // var lastPosition = JSON.stringify(position); // this.setState({lastPosition}); // }); // }.bind(this), 1000); // }, componentDidMount: function() { navigator.geolocation.getCurrentPosition( (position) => { var initialPosition = JSON.stringify(position); this.setState({initialPosition}); }, (error) => alert(error.message), {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000} ); this.watchID = navigator.geolocation.watchPosition( (position) => { var lastPosition = JSON.stringify(position); this.setState({lastPosition}); } ); }, componentWillUnmount: function() { navigator.geolocation.clearWatch(this.watchID); }, render: function() { return ( <View> <Text> <Text style={styles.title}>初始位置: </Text> {this.state.initialPosition} </Text> <Text> <Text style={styles.title}>当前位置: </Text> {this.state.lastPosition} </Text> </View> ); } }); var styles = StyleSheet.create({ title: { fontWeight: '500', }, }); AppRegistry.registerComponent('mapview', () => GeolocationExample);
import React from 'react'; import StarRatingComponent from 'react-star-rating-component'; import axios from 'axios'; class RecipeRating extends React.Component { state = { averageRating: 3, //ustawic na ocene z backendu, highlightedStar: 0, snackbarOpen: false } componentDidMount = () => { this.getRating(); } getRating = () => { axios.get(`/recipe/${this.props.recipeId}/${this.props.ratingType}Rating`) .then(response => { this.setState({ averageRating: response.data }); this.setState({ highlightedStar: response.data }); //moze lekko zbugowac podswietlanie na hoverze jesli odpowiedz przyjdzie pozniej }); } handleStarClick = (value) => { axios.post(`/recipe/${this.props.recipeId}/${this.props.ratingType}Rating`, null, { params: { rating: value } }) .then(() => { this.getRating(); this.props.onRatingAdded(); }); } handleStarHover = (hoveredStar) => { this.setState({ highlightedStar: hoveredStar }); } handleSnackbarClose = (e, reason) => { if (reason !== "clickaway") this.setState({ snackbarOpen: false }); } render = () => { return ( <div className="ratingContainer"> <StarRatingComponent name={`${this.props.ratingType}${this.props.recipeId}`} /* name of the radio input, it is required */ value={this.state.highlightedStar} /* number of selected icon (`0` - none, `1` - first) */ onStarClick={this.handleStarClick} /* on icon click handler */ onStarHover={this.handleStarHover} /* on icon hover handler */ onStarHoverOut={() => this.setState({ highlightedStar: this.state.averageRating })} /* on icon hover out handler */ renderStarIcon={() => this.props.icon} /* it should return string or react component */ starColor={this.props.ratingType === "quality" ? "#FE9801" : "rgba(0, 0, 0, 0.87)"} /* color of selected icons, default `#ffb400` */ emptyStarColor="#bfbfbf" editing={true} /* is component available for editing, default `true` */ /> </div> ); } }; export default RecipeRating;
import $ from '$'; import _ from 'underscore'; import Clipboard from 'clipboard'; import Observee from 'utils/Observee'; class Reference extends Observee { constructor(data, tagtree){ super(); var self = this, tag_ids = data.tags; this.data = data; this.data.tags = []; tag_ids.forEach(function(v){self.add_tag(tagtree.dict[v]);}); } static sortCompare(a,b){ if (a.data.authors > b.data.authors) return 1; if (a.data.authors < b.data.authors) return -1; return 0; } print_self(show_taglist){ var taglist = show_taglist || false, content = [ '<h4>Reference details:</h4>', '<p class="ref_small">{0}</p>'.printf(this.data.journal), '<p class="ref_title">{0}</p>'.printf(this.data.title), '<p class="ref_small">{0}</p>'.printf(this.data.authors || Reference.no_authors_text), ]; if(taglist){ content = content.concat(this.print_taglist()); } content.push('<p>{0}</p>'.printf(this.data.abstract)); content.push(this.getLinks()); return content; } print_taglist(){ var title = (window.isEdit) ? 'click to remove' : '', cls = (window.isEdit) ? 'refTag refTagEditing' : 'refTag'; return _.map(this.data.tags, function(d){ return $('<span title="{0}" class="{1}">{2}</span>' .printf(title, cls, d.get_full_name())).data('d', d); }); } print_name(){ this.$list = $('<p class="reference">{0} {1}</p>'.printf( this.data.authors || Reference.no_authors_text, this.data.year || '')) .data('d', this); return this.$list; } select_name(){ this.$list.addClass('selected'); } deselect_name(){ this.$list.removeClass('selected'); } getLinks(){ var links = $('<p>'); if (this.data.full_text_url){ links.append($('<a>') .attr('class', 'btn btn-mini btn-primary') .attr('target', '_blank') .attr('href', this.data.full_text_url) .text('Full text link ') .append('<i class="fa fa-fw fa-file-pdf-o"></i>')); links.append('<span>&nbsp;</span>'); } _.chain(this.data.identifiers) .filter(function(v){return v.url.length>0;}) .sortBy(function(v){return v.database_id;}) .each(function(v){ let grp = $('<div class="btn-group">'), link = `<a class="btn btn-mini btn-success" target="_blank" href="${v.url}" title="View ${v.id}">${v.database}</a>`, copyID = $(`<button type="button" class="btn btn-mini btn-success" title="Copy ID ${v.id} to clipboard"><i class="fa fa-clipboard"></i></button>`); // copy ID to clipboard new Clipboard(copyID.get(0), {text: () => v.id}); links.append(grp.append(link, copyID)); links.append('<span>&nbsp;</span>'); }); _.chain(this.data.identifiers) .reject(function(v){return v.url.length > 0 || v.database === 'External link';}) .sortBy(function(v){return v.database_id;}) .each(function(v){ let copyID = $(`<button class="btn btn-mini" title="Copy ID ${v.id} to clipboard">${v.database} <i class="fa fa-clipboard"></i></button>`); // copy ID to clipboard new Clipboard(copyID.get(0), {text: () => v.id}); links.append(copyID); links.append('<span>&nbsp;</span>'); }); return (links.children().length>0) ? links : null; } print_div_row(){ var self = this, data = this.data, div = $('<div>'), abs_btn = this.get_abstract_button(div), edit_btn = this.get_edit_button(), get_title = function(){ if(data.title) return '<p class="ref_title">{0}</p>'.printf(data.title); }, get_journal = function(){ let journal = (data.journal)? `${data.journal}<br/>`: ''; return `<p class="ref_small">${journal}HAWC ID: ${data.pk}</p>`; }, get_abstract = function(){ if(data.abstract) return '<p class="abstracts" style="display: none">{0}</p>'.printf(data.abstract); }, get_authors_row = function(){ var p = $('<p class="ref_small">{0} {1}</p>'.printf( data.authors || Reference.no_authors_text, data.year || '')); if(abs_btn || edit_btn){ var ul = $('<ul class="dropdown-menu">'); if (abs_btn) ul.append($('<li>').append(abs_btn)); if (edit_btn) ul.append($('<li>').append(edit_btn)); $('<div class="btn-group pull-right">') .append('<a class="btn btn-small dropdown-toggle" data-toggle="dropdown">Actions <span class="caret"></span></a>') .append(ul) .appendTo(p); } return p; }, get_searches = function(){ if(data.searches){ let links = data.searches .map((d) => `<a href="${d.url}">${d.title}</a>`) .join('<span>,&nbsp;</span>'), text = `<p><strong>HAWC searches/imports:</strong> ${links}</p>`; return $('<div>').append(text); } }, populate_div = function(){ return [ '<hr>', get_authors_row(), get_title(), get_journal(), get_abstract(), self.getLinks(), ]; }; return div.html(populate_div().concat(this.print_taglist())).append(get_searches()); } get_abstract_button(div){ // get abstract button if abstract available, or return undefined if(this.data.abstract){ return $('<a>') .text('Show abstract') .attr('class', 'abstractToggle') .on('click', function(){ var sel = $(this); if(sel.text() === 'Show abstract'){ div.find('.abstracts').show(); sel.text('Hide abstract'); } else { div.find('.abstracts').hide(); sel.text('Show abstract'); } }); } } get_edit_button(){ // return content or undefined if(window.canEdit){ return $('<div>') .append('<li><a href="{0}" target="_blank">Edit tags</a></li>'.printf( this.edit_tags_url())) .append('<li><a href="{0}" target="_blank">Edit reference</a></li>'.printf( this.edit_reference_url())); } } add_tag(tag){ var tag_already_exists = false; this.data.tags.forEach(function(v){if(tag===v){tag_already_exists=true;}}); if(tag_already_exists) return; this.data.tags.push(tag); tag.addObserver(this); this.notifyObservers(); } edit_tags_url(){ return '/lit/reference/{0}/tag/'.printf(this.data.pk); } edit_reference_url(){ return '/lit/reference/{0}/edit/'.printf(this.data.pk); } remove_tag(tag){ this.data.tags.splice_object(tag); tag.removeObserver(this); this.notifyObservers(); } remove_tags(){ this.data.tags = []; this.notifyObservers(); } save(success, failure){ var data = {'pk': this.data.pk, 'tags': this.data.tags.map(function(v){return v.data.pk;})}; $.post('.', data, function(v) { return (v.status==='success') ? success() : failure(); }).fail(failure); } update(status){ if (status.event =='tag removed'){this.remove_tag(status.object);} } } _.extend(Reference, { no_authors_text: '[No authors listed]', }); export default Reference;
import React, { Component } from 'react'; import { connect } from 'react-redux' import _ from 'lodash'; import UserList from './user-list.jsx'; import VoteSelect from './vote-select.jsx'; import VoteSubmitted from './vote-submitted.jsx'; import * as actionCreators from '../../action_creators'; class Room extends Component{ constructor(props) { super(props); } componentWillMount(){ console.log('cwm'); if(!this.props.room && (this.props.username && this.props.params.roomId)) { this.props.joinRoom(this.props.username, this.props.params.roomId); } console.log(this.props.room); console.log(this.props); } castVote(vote) { this.props.castVote(vote, this.props.room.id); } render(){ return( this.props.room ? <div className="row"> <div className="col-sm-6"> {this.props.voteCast ? <VoteSubmitted voteCast={this.props.voteCast} onChangeVote={()=>{this.castVote('')}} onResetVote={()=>{this.props.resetVote(this.props.room.id)}} voteComplete={this.props.voteComplete} /> : <VoteSelect vote={this.castVote.bind(this)} /> } </div> <div className="col-sm-6"> <UserList room={this.props.room} voteComplete={this.props.voteComplete} /> </div> </div> : <div>Creating room</div> ) } } function select(state) { if(state){ return { room: state.get('room'), voteCast: state.get('voteCast'), voteComplete: state.get('voteComplete'), username: state.get('username') } } else { return {} } } export default connect(select, actionCreators)(Room);
import { test, moduleForComponent } from 'ember-qunit'; import Ember from 'ember'; moduleForComponent('topic-details', 'Unit - TopicDetailsComponent'); test('render topic details component', function() { expect(2); // creates the component instance var component = this.subject(); equal(component.state, 'preRender'); // appends the component to the page this.append(); equal(component.state, 'inDOM'); }); test("show topic details table", function() { ok(this.subject() instanceof Ember.Component); ok(this.$().find(':first-child').is('table'), 'is a table'); });
import DataType from 'sequelize'; import to from 'await-to-js'; import Model from '../sequelize'; const TradeFee = Model.define('TradeFee', { id: { type: DataType.INTEGER(11), primaryKey: true, allowNull: false, autoIncrement: true, }, makerFee: { type: DataType.DECIMAL(4, 4), allowNull: false, }, takerFee: { type: DataType.DECIMAL(4, 4), allowNull: false, }, minVolume: { type: DataType.INTEGER, allowNull: true, }, maxVolume: { type: DataType.INTEGER, allowNull: true, }, // pairId: { // type: DataType.INTEGER(11), // references: { // model: 'Pair', // key: 'id', // }, // }, }); export const initialize = async () => { const data = [ { id: 1, pairId: 1, makerFee: 0.002, takerFee: 0.002, }, { id: 2, pairId: 2, makerFee: 0.002, takerFee: 0.002, }, { id: 3, pairId: 3, makerFee: 0.002, takerFee: 0.002, }, ]; const [err] = await to( TradeFee.bulkCreate(data, { fields: Object.keys(data[0]), updateOnDuplicate: 'id', }), ); if (err) { console.warn(`problem with adding initial TradeFee to Wallet table: `, err); } else { console.warn(`initial rows added to TradeFee table successfully.`); } }; export default TradeFee;
let navBtns = {}; function createNavBtns() { navBtns.div = createDiv(); navBtns.div.addClass('nav'); //Data navBtns.home = createButton('Home'); navBtns.home.mouseReleased(function(){goToPage("/index.html")}); navBtns.home.parent(navBtns.div); //Data navBtns.data = createButton('Data Structures'); navBtns.data.mouseReleased(function(){goToPage("/Data-Structures/index.html")}); navBtns.data.parent(navBtns.div); //Sorting navBtns.sorting = createButton('Sorting Algorithms'); navBtns.sorting.mouseReleased(function(){goToPage("/Sorting-Algorithms/index.html")}); navBtns.sorting.parent(navBtns.div); //Search navBtns.search = createButton('Search Algorithms'); navBtns.search.mouseReleased(function(){goToPage("/Search-Algorithms/index.html")}); navBtns.search.parent(navBtns.div); //Daily navBtns.daily = createButton('Daily Coding Problems'); navBtns.daily.mouseReleased(function(){goToPage("/Daily-Coding-Problems/index.html")}); navBtns.daily.parent(navBtns.div); } let goToPage = function(path) { location.href=path; } function windowResized() { //TODO move to its own file let s = 0.65; let x = (windowWidth * 0.4375) / 800; let xx = -((1-x)*800)/2; let h = windowHeight - 50; //TODO fix to correct number when css nav btns let y = (h * s) / 600; let yy = -((1-y)*600)/2; console.log(y + ' vs ' + yy); let c = select("#defaultCanvas0"); c.style('transform', "translate("+xx+"px, "+yy+"px)scale("+x+"," + y + ")"); }
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ /*global Windows:true */ var MediaFile = require('org.apache.cordova.media-capture.MediaFile'); var CaptureError = require('org.apache.cordova.media-capture.CaptureError'); var CaptureAudioOptions = require('org.apache.cordova.media-capture.CaptureAudioOptions'); var CaptureImageOptions = require('org.apache.cordova.media-capture.CaptureImageOptions'); var CaptureVideoOptions = require('org.apache.cordova.media-capture.CaptureVideoOptions'); var MediaFileData = require('org.apache.cordova.media-capture.MediaFileData'); module.exports = { captureAudio:function(successCallback, errorCallback, args) { var options = args[0]; var audioOptions = new CaptureAudioOptions(); if (typeof(options.duration) == 'undefined') { audioOptions.duration = 3600; // Arbitrary amount, need to change later } else if (options.duration > 0) { audioOptions.duration = options.duration; } else { errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT)); return; } var cameraCaptureAudioDuration = audioOptions.duration; var mediaCaptureSettings; var initCaptureSettings = function () { mediaCaptureSettings = null; mediaCaptureSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings(); mediaCaptureSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.audio; }; initCaptureSettings(); var mediaCapture = new Windows.Media.Capture.MediaCapture(); mediaCapture.initializeAsync(mediaCaptureSettings).done(function () { Windows.Storage.KnownFolders.musicLibrary.createFileAsync("captureAudio.mp3", Windows.Storage.NameCollisionOption.generateUniqueName).then(function (storageFile) { var mediaEncodingProfile = new Windows.Media.MediaProperties.MediaEncodingProfile.createMp3(Windows.Media.MediaProperties.AudioEncodingQuality.auto); var stopRecord = function () { mediaCapture.stopRecordAsync().then(function (result) { storageFile.getBasicPropertiesAsync().then(function (basicProperties) { var results = []; results.push(new MediaFile(storageFile.name, storageFile.path, storageFile.contentType, basicProperties.dateModified, basicProperties.size)); successCallback(results); }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_NO_MEDIA_FILES)); }); }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_NO_MEDIA_FILES)); }); }; mediaCapture.startRecordToStorageFileAsync(mediaEncodingProfile, storageFile).then(function () { setTimeout(stopRecord, cameraCaptureAudioDuration * 1000); }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_NO_MEDIA_FILES)); }); }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_NO_MEDIA_FILES)); }); }); }, captureImage:function (successCallback, errorCallback, args) { var options = args[0]; var imageOptions = new CaptureImageOptions(); var cameraCaptureUI = new Windows.Media.Capture.CameraCaptureUI(); cameraCaptureUI.photoSettings.allowCropping = true; cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.highestAvailable; cameraCaptureUI.photoSettings.format = Windows.Media.Capture.CameraCaptureUIPhotoFormat.jpeg; cameraCaptureUI.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo).then(function (file) { file.moveAsync(Windows.Storage.KnownFolders.picturesLibrary, "cameraCaptureImage.jpg", Windows.Storage.NameCollisionOption.generateUniqueName).then(function () { file.getBasicPropertiesAsync().then(function (basicProperties) { var results = []; results.push(new MediaFile(file.name, file.path, file.contentType, basicProperties.dateModified, basicProperties.size)); successCallback(results); }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_NO_MEDIA_FILES)); }); }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_NO_MEDIA_FILES)); }); }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_NO_MEDIA_FILES)); }); }, captureVideo:function (successCallback, errorCallback, args) { var options = args[0]; var videoOptions = new CaptureVideoOptions(); if (options.duration && options.duration > 0) { videoOptions.duration = options.duration; } if (options.limit > 1) { videoOptions.limit = options.limit; } var cameraCaptureUI = new Windows.Media.Capture.CameraCaptureUI(); cameraCaptureUI.videoSettings.allowTrimming = true; cameraCaptureUI.videoSettings.format = Windows.Media.Capture.CameraCaptureUIVideoFormat.mp4; cameraCaptureUI.videoSettings.maxDurationInSeconds = videoOptions.duration; cameraCaptureUI.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.video).then(function (file) { file.moveAsync(Windows.Storage.KnownFolders.videosLibrary, "cameraCaptureVedio.mp4", Windows.Storage.NameCollisionOption.generateUniqueName).then(function () { file.getBasicPropertiesAsync().then(function (basicProperties) { var results = []; results.push(new MediaFile(file.name, file.path, file.contentType, basicProperties.dateModified, basicProperties.size)); successCallback(results); }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_NO_MEDIA_FILES)); }); }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_NO_MEDIA_FILES)); }); }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_NO_MEDIA_FILES)); }); }, getFormatData: function (successCallback, errorCallback, args) { Windows.Storage.StorageFile.getFileFromPathAsync(args[0]).then( function (storageFile) { var mediaTypeFlag = String(storageFile.contentType).split("/")[0].toLowerCase(); if (mediaTypeFlag === "audio") { storageFile.properties.getMusicPropertiesAsync().then(function (audioProperties) { successCallback(new MediaFileData(null, audioProperties.bitrate, 0, 0, audioProperties.duration / 1000)); }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT)); }); } else if (mediaTypeFlag === "video") { storageFile.properties.getVideoPropertiesAsync().then(function (videoProperties) { successCallback(new MediaFileData(null, videoProperties.bitrate, videoProperties.height, videoProperties.width, videoProperties.duration / 1000)); }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT)); }); } else if (mediaTypeFlag === "image") { storageFile.properties.getImagePropertiesAsync().then(function (imageProperties) { successCallback(new MediaFileData(null, 0, imageProperties.height, imageProperties.width, 0)); }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT)); }); } else { errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT)); } }, function () { errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT)); } ); } }; require("cordova/windows8/commandProxy").add("Capture",module.exports);
import React, { Component } from 'react' import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import Login from './Login'; export default class Registration extends Component { constructor(){ super(); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(e){ e.preventDefault(); window.alert("A confirmation mail was sent to your email address. Please, follow the instructions from the email"); window.location = "./Login"; } render() { return ( <form onSubmit={this.handleSubmit} className="form-page"> <h3>Sign Up</h3> <div className="form-group"> <label>First name</label> <input type="text" className="form-control" placeholder="First name" /> </div> <div className="form-group"> <label>Last name</label> <input type="text" className="form-control" placeholder="Last name" /> </div> <div className="form-group"> <label>Email address</label> <input type="email" className="form-control" placeholder="Enter email" /> </div> <div className="form-group"> <label>Password</label> <input type="password" className="form-control" placeholder="Enter password" /> </div> <button type="submit" className="btn btn-primary btn-block">Sign Up</button> <p className="forgot-password text-right"> Already registered? <a href="/login">Sign in</a> </p> </form> ); } }
/* * Module code goes here. Use 'module.exports' to export things: * module.exports.thing = 'a thing'; * * You can import it from another modules like this: * var mod = require('role.filler'); * mod.thing == 'a thing'; // true */ var logger = require("screeps.logger"); logger = new logger("role.filler"); var obj = function() { } var base = require('role.worker'); obj.prototype = new base(); global.utils.extendFunction(obj, "init", function(name, roomManager) { this._init(name, roomManager); this.allowMining = false; this.requiredCreeps = 0; }); global.utils.extendFunction(obj, "tickInit", function() { if (this.roomManager.room.controller.level >= 2 && this.roomManager.room.energyCapacityAvailable >= 500) { this.requiredCreeps = 1; } // if (this.roomManager.room.controller.level >= 4) { // this.requiredCreeps = 2; // } if (this.roomManager.remoteMode) { this.requiredCreeps = 1; } if (this.workerCreepIds.length < this.requiredCreeps) { //need some creeps var minBodies = 1; if (this.roomManager.creepCrisis()) { minBodies = 0; } var priority = 4; if (this.numCreeps == 0) priority = 160; var req = global.utils.makeCreepRequest(this.name, "workerCreepIds", [CARRY, CARRY, MOVE], [CARRY, CARRY, MOVE], priority, false, 30, minBodies) req.useMaxEnergy = true; this.roomManager.requestCreep(req); return; } }); global.utils.extendFunction(obj, "tick", function() { this._tick(); }); global.utils.extendFunction(obj, "tickEnd", function() { }); obj.prototype.getEnergy = function(creep) { //logger.log("---===----",creep); if (!creep.getEnergyFromSpawnContainers()) { if (!creep.getEnergyFromAnywhere()) { if (!creep.pickupEnergy()) { logger.log(creep.name, "Cant find energy") return false } } } return true; } obj.prototype.doWork = function(creep) { if (!creep.stashEnergyInSpawns()) { if (!creep.stashEnergyInTowers()) { logger.log(this.name, creep.pos.roomName, 'nothing to do') creep.memory.doneWorking = true; } } } module.exports = obj;
import React from "react"; import { getCompanyDetails, search } from "../../redux/onBoarding/onBoarding.actions"; import { connect } from "react-redux"; import Footer from "./footer"; const Business_details = (props) => { const doneStatus = props.doneSteps.some((item) => 2 === item); const display_none = props.currentStep !== 2 && doneStatus ? "display_none" : ""; if (props.currentStep !== 2 && !doneStatus) { return null; } const isValidated = () => { props.wizard_next(); }; const search_company = () => { props.getCompanyDetails(props.company_search); }; const searchText = (value) => { props.search(value); } const createCompanyProfileform = () => { if(!props.company_profile) return (<tr className='error'><td>Some error accured</td></tr>) return props.company_details.map(detail => { return (<tr><td> {detail.name}</td><td>{props.company_profile[detail.label]}</td> </tr>) }) } return ( <div className={display_none}> <div className="row"> <div className="col-md-8 form-horizontal"> <div className="form-group"> <label htmlFor="date" className="col-sm-5 control-label"> Company Name: </label> <div className="col-sm-7"> <div className="input-group margin"> <input className="form-control required" id="companyname" onChange={(e) => searchText(e.target.value)} name="companyname" value={props.company_search} /> <input className="form-control" type="hidden" id="cin_" name="cin" /> <span className="input-group-btn"> <button className="btn btn-block btn-outline btn-danger" type="button" onClick={() => search_company()} > Find </button> </span> </div> </div> </div> </div> </div> <div className="row"> <div className="col-md-12"> <div className=" box-body"> <div className="table-responsive"> {props.show_company_details && <table className="table no-margin table-bordered" id="partner-details" > <thead></thead> <tbody> {createCompanyProfileform()} </tbody> </table> } </div> </div> </div> </div> <Footer {...props} isValidated={isValidated} /> </div> ); }; function mapStateToProps(state) { return { company_profile: state.onBoarding.company_profile, show_company_details: state.onBoarding.show_company_details, company_details: state.onBoarding.company_details, company_search: state.onBoarding.company_search } } export default connect(mapStateToProps, { getCompanyDetails, search })(Business_details);
require(['./pkg/test'], function (test) { require.ready(function () { test.log(); }); });
/* * 取指定id的文章 */ function getArticle(id){ console.log("Getting article"); var url = "http://localhost:2222/article"; var param = { id: id }; $.get(url,param,function(data){ var article = data.data; $("#article-title-1").html(article.title); $("#article-outline-1").html(article.outline); $("#article-cover-1").attr('src',article.cover); }); } /* * 加载文章 */ $(document).ready(function(){ getLatestThreeArticles(); }) /* * 加载最新的几篇文章 */ function getLatestThreeArticles() { console.log("Getting three latest articles"); var url = "http://localhost:2222/latestArticles"; $.get(url,function(data){ var articles = data.data; for (var i=0;i<articles.length;i++) { var article = articles[i]; $("#article-title-" + i).html(article.title); $("#article-outline-" + i).html(article.outline); $("#article-cover-" + i).attr('src',article.cover); } }); }
import createIcon from "./createIcon"; const menuIcon = () => createIcon("outline", "M4 6h16M4 12h16M4 18h16"); const crossIcon = () => createIcon("outline", "M6 18L18 6M6 6l12 12"); const homeIcon = () => createIcon( "outline", "M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" ); const quickTaskIcon = () => createIcon("outline", "M12 4v16m8-8H4"); const userProfileIcon = () => createIcon( "outline", "M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z" ); const inboxIcon = () => createIcon( "outline", "M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" ); const chevronIcon = () => createIcon( "solid", "M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" ); const hashtagIcon = () => createIcon( "solid", "M9.243 3.03a1 1 0 01.727 1.213L9.53 6h2.94l.56-2.243a1 1 0 111.94.486L14.53 6H17a1 1 0 110 2h-2.97l-1 4H15a1 1 0 110 2h-2.47l-.56 2.242a1 1 0 11-1.94-.485L10.47 14H7.53l-.56 2.242a1 1 0 11-1.94-.485L5.47 14H3a1 1 0 110-2h2.97l1-4H5a1 1 0 110-2h2.47l.56-2.243a1 1 0 011.213-.727zM9.03 8l-1 4h2.938l1-4H9.031z" ); const checkIcon = () => createIcon( "solid", "M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" ); const plusIcon = () => createIcon( "solid", "M10 5a1 1 0 011 1v3h3a1 1 0 110 2h-3v3a1 1 0 11-2 0v-3H6a1 1 0 110-2h3V6a1 1 0 011-1z" ); export { menuIcon, crossIcon, homeIcon, quickTaskIcon, userProfileIcon, inboxIcon, chevronIcon, hashtagIcon, checkIcon, plusIcon, };
//员工状态格式化 function employeeStateFormat(value,row,index){ if(value==0){ return "<span style='color: green;'>正常</span>" }else if(value==-1){ return "<span style='color: grey;text-decoration:line-through '>离职</span>" }else { return ""; } } //对象格式化 function objFormat(value,row,index){ return value?value.name||value.realname||value.username:""; } $(function(){ //登录输入框效果 $('.form_text_ipt input').focus(function(){ $(this).parent().css({ 'box-shadow':'0 0 3px #bbb', }); }); $('.form_text_ipt input').blur(function(){ $(this).parent().css({ 'box-shadow':'none', }); //$(this).parent().next().hide(); }); //表单验证 $('.form_text_ipt input').bind('input propertychange',function(){ if($(this).val()==""){ $(this).css({ 'color':'red', }); $(this).parent().css({ 'border':'solid 1px red', }); //$(this).parent().next().find('span').html('helow'); $(this).parent().next().show(); }else{ $(this).css({ 'color':'#ccc', }); $(this).parent().css({ 'border':'solid 1px #ccc', }); $(this).parent().next().hide(); } }); });
import React from "react"; import { useDispatch } from "react-redux"; import { useHistory } from "react-router-dom"; import Typography from "@material-ui/core/Typography"; import useQuery from "src/util/useQuery"; import ItemForm from "src/components/items/ItemForm"; import Item from "src/types/Item"; import { createItem } from "src/redux/items/actions"; const NewItem = () => { const { category } = useQuery(); const dispatch = useDispatch(); const history = useHistory(); const postItem = async formData => { const createdItem = await dispatch(createItem(formData)); history.push(`/items/${createdItem._id}`); }; return ( <> <Typography variant="h2">Create a new item</Typography> <ItemForm submitAction={postItem} initialItem={new Item(category)} /> </> ); }; export default NewItem;
export { default } from '@smile-io/ember-smile-polaris/components/polaris-drop-zone/file-upload';
import { connect } from 'react-redux' import { changeLangAction } from '../actions' import ChangeLangButton from '../components/ChangeLangButton' const mapStateToProps = (state) => { return { lang: state.langReducer.lang } } const mapDispatchToProps = ({ onChange: changeLangAction }) const ChangeLangContainer = connect( mapStateToProps, mapDispatchToProps )(ChangeLangButton) export default ChangeLangContainer
var classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1commonstyle_1_1scrollbars_1_1_scroll_bar_overview_activity = [ [ "onCreate", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1commonstyle_1_1scrollbars_1_1_scroll_bar_overview_activity.html#a4a89dc0c4b2ef9812bb60f426c78ccb8", null ], [ "LOG_TAG", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1commonstyle_1_1scrollbars_1_1_scroll_bar_overview_activity.html#a6218e34e6c5d7dd28b26b2df867303fd", null ] ];
// UserPool window.$Qmatic.components.popover.UserPoolPopoverComponent = function(options) { window.$Qmatic.components.popover.PoolPopoverComponent.call(this, options); } window.$Qmatic.components.popover.UserPoolPopoverComponent.prototype = Object.create(window.$Qmatic.components.popover.PoolPopoverComponent.prototype); // correct the constructor pointer window.$Qmatic.components.popover.UserPoolPopoverComponent.prototype.constructor = window.$Qmatic.components.popover.UserPoolPopoverComponent; window.$Qmatic.components.popover.UserPoolPopoverComponent.prototype._call = function () { this.disposeInstance(); userPool.callFromPool(this.visitId); };
import React from 'react'; import { View, StatusBar, Image, Text, StyleSheet, TextInput, TouchableOpacity, ScrollView, Modal, TouchableHighlight, Touchable, Dimensions } from 'react-native'; import { Calendar, Agenda } from 'react-native-calendars'; import { connect } from 'react-redux'; import { Ionicons } from '@expo/vector-icons'; // import check from "../assets/icons/check-circle-2.png" import dotCircle from "../assets/icons/dot-circle.png" import * as Styled from '../assets/styles/styled'; import Header from '../components/Header'; import Footer from '../components/Footer'; import * as functions from '../services/functions.service'; const ChoiceSessions = (props) => { const [modalIsVisible, setModalIsVisible] = React.useState(false); const [clickedSession, setClickedSession] = React.useState({}); const [userToLogin, setUserToLogin] = React.useState({ email: '', password: '' }); const loginUser = (user) => { // if(user.email == 'teste@hinoselouvores.com' && user.password == '123456') // navigation.navigate('Home'); // else // Alert.alert('Erro', 'Usuário ou senha incorretos'); props.navigation.navigate('Market'); } const [info, setInfo] = React.useState(props.route.params); React.useEffect(() => { // console.log({ props }) setInfo(props.route.params); }, [props.route.params]); const [idActive, setIdActive] = React.useState(false); const [modal, setModal] = React.useState({ title: "Em desenvolvimento", desc: "Esta função que você tentou acessar ainda está em desenvolvimento" }); const [nextClasses, setNextClasses] = React.useState([ { id: 1, day: "20", month: "out", color: "#C43A57" }, { id: 2, day: "20", month: "out", color: "#B94162" }, ]); const [sessions, setSessions] = React.useState([ { id: 1, month: 'SETEMBRO', date: '01', day: 'ter' }, { id: 2, month: 'SETEMBRO', date: '02', day: 'qua' }, { id: 3, month: 'SETEMBRO', date: '03', day: 'qui' }, { id: 4, month: 'SETEMBRO', date: '07', day: 'seg' }, { id: 5, month: 'SETEMBRO', date: '08', day: 'ter' }, { id: 6, month: 'SETEMBRO', date: '09', day: 'qua' }, { id: 7, month: 'SETEMBRO', date: '10', day: 'qui' }, { id: 8, month: 'SETEMBRO', date: '11', day: 'sex' }, { id: 9, month: 'SETEMBRO', date: '17', day: 'qui' }, { id: 10, month: 'SETEMBRO', date: '18', day: 'sex' }, { id: 11, month: 'SETEMBRO', date: '21', day: 'seg' }, { id: 12, month: 'SETEMBRO', date: '22', day: 'ter' }, { id: 13, month: 'SETEMBRO', date: '28', day: 'seg' }, { id: 14, month: 'SETEMBRO', date: '30', day: 'qua' }, { id: 15, month: 'OUTUBRO', date: '11', day: 'sex' }, { id: 16, month: 'OUTUBRO', date: '17', day: 'qui' }, { id: 17, month: 'OUTUBRO', date: '18', day: 'sex' }, { id: 18, month: 'OUTUBRO', date: '21', day: 'seg' }, { id: 19, month: 'OUTUBRO', date: '22', day: 'ter' }, { id: 20, month: 'OUTUBRO', date: '28', day: 'seg' }, { id: 21, month: 'OUTUBRO', date: '30', day: 'qua' }, { id: 22, month: 'NOVEMBRO', date: '09', day: 'qua' }, { id: 23, month: 'NOVEMBRO', date: '10', day: 'qui' }, { id: 24, month: 'NOVEMBRO', date: '11', day: 'sex' }, { id: 25, month: 'NOVEMBRO', date: '17', day: 'qui' }, { id: 26, month: 'NOVEMBRO', date: '18', day: 'sex' }, { id: 27, month: 'NOVEMBRO', date: '21', day: 'seg' }, { id: 28, month: 'NOVEMBRO', date: '22', day: 'ter' }, ]); const [months, setMonths] = React.useState(['SETEMBRO', 'OUTUBRO', 'NOVEMBRO']); const [selectedMonth, setSelectedMonth] = React.useState(months[0]); React.useEffect(() => { // console.log({ consultations: props.consultations }) }, []); const [test, setTest] = React.useState({}); return ( <Styled.Container style={{ paddingTop: 0 }}> <Header screenTitle="Home" psychologist navigation={props.navigation} /> <Modal animationType="slide" transparent={true} visible={modalIsVisible} onRequestClose={() => { Alert.alert('Modal has been closed.'); }}> <View style={styles.centeredView}> <View style={styles.modalView}> <Text style={styles.modalTitle}>Informações da sessão</Text> <Text style={styles.modalText}>Nome: {clickedSession.first_name}</Text> <Text style={styles.modalText}>Sobrenome: {clickedSession.last_name}</Text> <Text style={styles.modalText}>E-mail: {clickedSession.email}</Text> <Text style={styles.modalText}>Status: {clickedSession.status}</Text> <Text style={styles.modalText}>Sexo: {clickedSession.sex}</Text> <Text style={styles.modalText}>Descrição: {clickedSession.description}</Text> {/* <Text style={styles.modalText}>{clickedSession.status}</Text> */} <TouchableHighlight style={{ ...styles.openButton, backgroundColor: '#C43A57' }} onPress={() => { setModalIsVisible(!modalIsVisible); }}> <Text style={styles.textStyle}>Fechar</Text> </TouchableHighlight> </View> </View> </Modal> {/* <Styled.Scroll> */} <Styled.ScrollContainer> <Styled.SectionTitle style={{ width: '90%' }}>{props.consultations?.length > 0 ? "Próximas sessões" : "Agende uma sessão"}</Styled.SectionTitle> {/* <Styled.TxtQuestion style={{ fontSize: 18, fontWeight: '400', width: '90%', textAlign: 'left' }}>Próximas sessões</Styled.TxtQuestion> */} <Styled.ScrollHorizontal> {props.consultations && props.consultations.map((c, index, arr) => { // console.log({ c }) let opacity = (((arr.length - (index + 1)) / arr.length) + (1 / arr.length)); // let opacity = (index + 1) / arr.length; // console.log({ opacity }) return ( <Styled.ClassBoxCircleContainer // style={{ backgroundColor: c.color }} key={c.id}> onPress={() => { setClickedSession(c) setModalIsVisible(true) }} activeOpacity={0.7} style={{ backgroundColor: 'rgba(196, 58, 87, ' + opacity + ')' }} key={c.id}> <Styled.ClassBoxCircleDay>{(c.date).split("/")[0]}</Styled.ClassBoxCircleDay> <Styled.ClassBoxCircleMonth>{(functions.getMonthName(parseInt((c.date).split("/")[1]), 1))}</Styled.ClassBoxCircleMonth> </Styled.ClassBoxCircleContainer> ); })} </Styled.ScrollHorizontal> <Styled.TxtQuestion style={{ fontSize: 18, fontWeight: '600', width: '90%', textAlign: 'center' }}>Escolha uma data</Styled.TxtQuestion> {months && months.map((m, index) => { return ( <View key={m} style={{ marginTop: 10, marginBottom: -5, width: '90%', alignItems: 'center', justifyContent: 'space-between', flexDirection: 'row', flexWrap: 'nowrap', }}> {((index > 0 && months.length > 1) && selectedMonth == m) && <TouchableOpacity onPress={() => setSelectedMonth(months[index - 1])}> <Text style={{ color: "#C43A57" }}>{"<"}</Text> </TouchableOpacity> } {selectedMonth == m && <Text style={{ flex: 1, textAlign: 'center', color: "#C43A57", fontSize: 18, fontWeight: '300' }}>{m}</Text>} {(((index >= 0 && months.length > 1) && index < months.length - 1) && selectedMonth == m) && <TouchableOpacity onPress={() => setSelectedMonth(months[index + 1])}> <Text style={{ color: "#C43A57" }}>{">"}</Text> </TouchableOpacity> } </View> ); })} <Styled.ClassListContainer style={{ flexDirection: 'row', flexWrap: 'wrap' }}> {sessions && sessions.map(session => { if (session.month == selectedMonth) return ( <TouchableOpacity style={{ backgroundColor: idActive == session.id ? "#C43A57" : "#FFEBF1", paddingHorizontal: 1, paddingVertical: 5, margin: 5, borderRadius: 5, alignItems: 'center', justifyContent: 'center', width: 64 }} key={session.id} onPress={() => setIdActive(session.id)} > <Text style={{ color: idActive == session.id ? "#FFEBF1" : "#C43A57", fontSize: 30, fontWeight: '800', marginBottom: -5 }}>{session.date}</Text> <Text style={{ color: idActive == session.id ? "#FFEBF1" : "#C43A57", fontSize: 12, fontWeight: '400' }}>{session.day}</Text> </TouchableOpacity> ); })} </Styled.ClassListContainer> <Styled.TxtQuestion style={{ width: '90%', fontWeight: '500', fontSize: 14, color: "#E59EB6" }}>Obs: datas não disponíveis não aparecerão nessa tela</Styled.TxtQuestion> <Styled.BtnCTA2 onPress={() => props.navigation.navigate('ChoicePsychologistHour')} style={{ borderRadius: 50 }}> <Styled.TxtBtnCTA2>ESCOLHER HORÁRIO</Styled.TxtBtnCTA2> </Styled.BtnCTA2> <View style={{ backgroundColor: 'gray', width: '100%', marginBottom: 10 }}> <Calendar style={{ width: '100%', paddingVertical: 5 }} theme={{ monthTextColor: 'blue', textMonthFontSize: 20, arrowColor: 'orange', }} hideExtraDays={true} dayComponent={({ date, state }) => { return ( <TouchableOpacity onPress={() => { let now = new Date(); let atualDate = functions.getFormattedDate(now, "-") console.log(atualDate); console.log(date.dateString + " - " + test.dateString) console.log(atualDate < date.dateString); console.log(new Date(atualDate), new Date(date.dateString)); if (atualDate < date.dateString) setTest(date); }} style={{ backgroundColor: test.dateString == date.dateString ? "#C43A57" : "#FFEBF1", paddingHorizontal: 1, paddingVertical: 5, borderRadius: 10, borderWidth: 3, borderColor: '#fff', alignItems: 'center', justifyContent: 'center', width: 64 }} > <Text style={{ color: test.dateString == date.dateString ? "#FFEBF1" : "#C43A57", fontSize: 30, fontWeight: '800', marginBottom: -5 }} > {date.day} </Text> </TouchableOpacity> ); }} markedDates={{ test: { marked: true } }} /> </View> {/* </Styled.Scroll> */} </Styled.ScrollContainer> <Footer screenTitle="Home" client navigation={props.navigation} /> </Styled.Container > ); }; const styles = StyleSheet.create({ centeredView: { flex: 1, justifyContent: 'center', alignItems: 'center', marginTop: 22, }, modalView: { margin: 20, backgroundColor: 'white', borderRadius: 20, padding: 35, alignItems: 'center', shadowColor: '#000', shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 3.84, elevation: 5, }, openButton: { backgroundColor: '#F194FF', borderRadius: 20, padding: 10, elevation: 2, }, textStyle: { color: 'white', fontWeight: 'bold', textAlign: 'center', }, modalText: { marginBottom: 5, textAlign: 'left', }, modalTitle: { marginBottom: 15, textAlign: 'center', fontWeight: 'bold' }, }); const mapStateToProps = (state) => { return { //modal modalInfoVisible: state.modalReducer.modalInfoVisible, //consultations consultations: state.consultationReducer.consultations, } }; const mapDispatchToProps = (dispatch) => { return { //modal setModalInfoVisible: (modalInfoVisible) => dispatch({ type: 'SET_MODAL_INFO_VISIBLE', payload: { modalInfoVisible } }), } }; export default connect(mapStateToProps, mapDispatchToProps)(ChoiceSessions);
import Vue from 'vue'; import Vuex from 'vuex'; import mutations from './mutations'; import actions from './actions'; Vue.use(Vuex); export const store = new Vuex.Store({ state: { news: [], jobs: [], ask: [], user: {}, item: {} }, getters: { fetchedNews: (state) => state.news, fetchedJobs: (state) => state.jobs, fetchedAsk: (state) => state.ask, fetchedUser: (state) => state.user, fetchedItem: (state) => state.item }, mutations, actions })
/** * @file /utils/db.js * @description 通过 mongoose 框架 链接数据库对象 */ const { db_connection } = require('./index') const log4js = require('../utils/log') const mongoose = require('mongoose') mongoose.connect(db_connection, { useNewUrlParser: true, useUnifiedTopology: true }) // 通过链接实例,监听数据库链接结果 const db = mongoose.connection; db.on('error', () => { log4js.error("链接数据库出错!") }) db.once('open', function() { log4js.debug("链接数据库成功!") })
const http = require('http'); http.createServer((req, res) => { res.write('<h1>Hello Sohyun</h1>'); res.end('<p>Hello Jihwan</p>'); }).listen(9000, () => { console.log('9000번 포트에서 서버 실행 중이지롱!!!'); });
import axios from 'axios'; // axios.defaults.baseURL = 'http://192.168.15.44:3333'; //casa // axios.defaults.baseURL = 'http://192.168.15.34:3333'; //casa // axios.defaults.baseURL = 'http://192.168.0.5:3333'; //escritório axios.defaults.baseURL = 'http://18.216.58.135/api'; //servidor export default axios;
$(document).ready(function(){ $('.closeIntro').click(function(){ $('h1').removeClass('introOpacity'); $('.intro').removeClass('fadeInDown'); $('.intro').addClass('fadeOutDown'); setTimeout(function(){ $('.intro').addClass('pointerNone'); $('.intro').hide(); }, 500); setTimeout(function(){ $('audio').attr('src','newyork.mp3'); $('.iframe').attr('src', 'https://www.google.com/maps/embed?pb=!1m0!3m2!1sen!2sus!4v1435391046756!6m8!1m7!1spc6vu5MTxR4ub0aAEoyAfg!2m2!1d40.758466!2d-73.985446!3f61!4f0!5f0.7820865974627469'); }, 500); $('.location').click(function(){ $('.locationList').toggleClass('showList hideList'); $('.locationList').removeClass('pageLoadHide'); $('.listLoc').toggleClass('fadeOutLeft fadeInLeft'); }); function jumper(){ $('.iframe').addClass('loading'); setTimeout(function(){ $('.iframe').removeClass('loading'); }, 1000); } $(".muteButton").click(function(){ $("audio").prop('muted', !$("audio").prop('muted')); $('.muteButton').toggleClass('muted sound'); $('.muteIcon').toggleClass('fa-volume-off fa-volume-up'); }); $('.listLoc').click(function(){ var theID = $(this).attr('id'); switch(theID) { case 'WhiteHouse': $('.selectedLoc').html('The White House'); $('iframe').attr('src', 'https://www.google.com/maps/embed?pb=!1m0!3m2!1sen!2sus!4v1435393888812!6m8!1m7!1siKije2lto_r5OcgKX4sleg!2m2!1d38.897766!2d-77.036504!3f154.63696753722124!4f-6.370048137996378!5f0.7820865974627469'); setTimeout(function(){ $('audio').attr('src', 'whitehouse.mp3'); }, 1000); jumper(); break; case 'NewYork': $('.selectedLoc').html('New York'); $('.iframe').attr('src', 'https://www.google.com/maps/embed?pb=!1m0!3m2!1sen!2sus!4v1435391046756!6m8!1m7!1spc6vu5MTxR4ub0aAEoyAfg!2m2!1d40.758466!2d-73.985446!3f61!4f0!5f0.7820865974627469'); setTimeout(function(){ $('audio').attr('src', 'newyork.mp3'); }, 1000); jumper(); break; case 'Tokyo': $('.selectedLoc').html('Tokyo'); $('.iframe').attr('src', 'https://www.google.com/maps/embed?pb=!1m0!3m2!1sen!2sus!4v1435393529969!6m8!1m7!1sWAs0hkiNv6Bn9e3GJV1FKA!2m2!1d35.659565!2d139.700546!3f263.520569547412!4f1.2564718939410824!5f0.7820865974627469'); setTimeout(function(){ $('audio').attr('src', 'tokyo.mp3'); }, 1000); jumper(); break; case 'Antarctica': $('.selectedLoc').html('Antarctica'); $('.iframe').attr('src', 'https://www.google.com/maps/embed?pb=!1m0!3m2!1sen!2sus!4v1435396021135!6m8!1m7!1sTO2U5IICpbjaqgbpLcCF7A!2m2!1d-62.595457!2d-59.902478!3f67.47017658493495!4f-14.041705695303278!5f0.7820865974627469'); setTimeout(function(){ $('audio').attr('src', 'antarctica.mp3'); }, 1000); jumper(); break; case 'Stonehenge': $('.selectedLoc').html('Stonehenge'); $('.iframe').attr('src', 'https://www.google.com/maps/embed?pb=!1m0!3m2!1sen!2sus!4v1435398126430!6m8!1m7!1sVBnrlmeoNKPv-TFzV2uGkg!2m2!1d51.178924!2d-1.826257!3f100.4164472443403!4f-10.51059042667464!5f0.7820865974627469'); setTimeout(function(){ $('audio').attr('src', 'celtic.mp3'); }, 1000); jumper(); break; } }); }); });
/** * A code block with annotation. * @param {Object} param0 * @param {boolean} [param0.reverse=false] Show annotation on the left. Default `false`. On `sm` annotation will always go first. */ export default function JS({ children, alt, id, reverse, src, img, p = true }) { const c = children[0].trim() let annotation if (alt) { alt = alt.split('\n').map((current) => { // eslint-disable-next-line react/jsx-key return (<p>{current}</p>) }) const aCl = reverse ? {} : { 'order-1': true, 'order-md-2': true } annotation = <column {...aCl} md-4 d-flex align-items-center justify-content-between flex-column dangerouslySetInnerHTML={!p ? { __html: alt } : undefined}> {p && <div>{alt}</div>} {src && <splendid-img img-fluid placeholder-auto src={src} alt={img}/>} </column> } const colCl = (reverse || !annotation) ? {} : { 'order-2': true, 'order-md-1': true } const col = <column {...colCl} d-flex justify-content-center align-items-center dangerouslySetInnerHTML={{ __html: c }}/> const ch = [annotation, col] return (<row id={id}> {ch} </row>) }
; (function($, window, document) { // start closure 'use strict'; // use strict mode var defaults = { 'theme': 'custom-scroll-bar', 'created': function(e, ui) { // initialized scrollbar }, 'destroyed': function(e, ui) { // destroyed scrollbar }, 'scrollstarted': function(e, ui) { // the scroll has started }, 'scrollended': function(e, ui) { // the scroll has ended }, 'thumbclick': function(e, ui) { // the thumb was clicked } }; // get the width of the scrollbars var scrollbarWidth = function() { var parent; var child; var width; if (width === undefined) { parent = $('<div style="width:50px;height:50px;overflow:auto;position:absolute;top:-100px;left:-100px"><div/></div>')['appendTo']('body'); child = parent['children'](); width = child['innerWidth']() - child['height'](99)['innerWidth'](); parent['remove'](); } return width; }; //define some methods var methods = { 'init': function(options) { if (options) { // extend the defaults with the options $['extend'](defaults, options); } var $body = $(document.body); var $node = $(this); if ($node['hasClass']('customScrollBar_processed')) { return false; } $node['addClass']('original-content'); // add a class to the element // define variables var $dragging = null; var scrollTriggerFunction; var scrolling; var scrollEnded; // class collections var scrollClasses = "scrolling scrolling-horizontally scrolling-vertically"; var clickClasses = "clicked clicked-horizontally clicked-vertically"; // markup var scrollbarHelpers = '<div class="scrollbar-corner"/>'; scrollbarHelpers += '<div class="scrollbar-resizer"/>'; var newScrollbar = function(axis) { var scrollbar = '<div class="scrollbar '; scrollbar += axis; scrollbar += '"><div class="scrollbar-button start increment"/><div class="scrollbar-button start decrement"/><div class="scrollbar-track"><div class="scrollbar-track-piece start"/><div class="scrollbar-thumb"/><div class="scrollbar-track-piece end"/></div><div class="scrollbar-button end increment"/><div class="scrollbar-button end decrement"/></div>'; return scrollbar; }; // the wrapper var scrollWrapper = '<div class="scroll-wrapper customScrollBar ' + defaults['theme'] + '"><div class="scroll-area"/></div>'; // prepare the content $node['wrap'](scrollWrapper); // get the elements var $wrapper = $node['closest']('.scroll-wrapper'); var $area = $node['closest']('.scroll-area'); // get the dimensions var nodeDimensions = { h: $node['outerHeight'](), w: $node['outerWidth']() }; var wrapperDimensions = { h: $wrapper['height'](), w: $wrapper['width']() }; var areaScroll = { x: $area['scrollLeft'](), y: $area['scrollTop']() }; // gather all our info in one object var data = { x: { wrapperSize: wrapperDimensions.w, contentSize: nodeDimensions.w, scrollDir: 'horizontal', getScroll: function() { var scrollPos = $area['scrollLeft'](); return scrollPos; }, scrollOpts: function(v) { var opts = { 'scrollLeft': v }; return opts } }, y: { wrapperSize: wrapperDimensions.h, contentSize: nodeDimensions.h, scrollDir: 'vertical', getScroll: function() { var scrollPos = $area['scrollTop'](); return scrollPos; }, scrollOpts: function(v) { var opts = { 'scrollTop': v }; return opts; } } }; // create scrollbars when necessary $([data.x, data.y])['map'](function(index, value) { if (value.contentSize > value.wrapperSize) { $wrapper['append'](newScrollbar(value.scrollDir)); $wrapper['addClass']('scrollbar-' + value.scrollDir); var opts = { 'paddingRight': scrollbarWidth() } if (index === 0) { opts = { 'paddingBottom': scrollbarWidth() } } $area['css'](opts); } }); // and add the helpers if both scrollbars are appended if (data.x.contentSize > data.x.wrapperSize && data.y.contentSize > data.y.wrapperSize) { $wrapper['append'](scrollbarHelpers); } // extend our data $([data.x, data.y])['map'](function(index, value) { // set the values for each direction value.clickPos = 0; value.delta = 0; value.scrollbar = $wrapper['find']('.scrollbar.' + value.scrollDir); value.scrollbarTrack = value.scrollbar['find']('.scrollbar-track'); value.trackSize = (index === 0 ? value.scrollbarTrack['outerWidth']() : value.scrollbarTrack['outerHeight']()) value.scrollTrackPiece = value.scrollbarTrack['find']('.scrollbar-track-piece'); value.scrollbarTrackPieceStart = value.scrollTrackPiece['filter']('.start'); value.scrollbarTrackPieceEnd = value.scrollTrackPiece['filter']('.end'); value.scrollbarThumb = value.scrollbarTrack['find']('.scrollbar-thumb'); value.scaleFactor = value.contentSize / value.wrapperSize; value.scrollThumbSize = value.trackSize / value.scaleFactor; value.scrollFactor = value.wrapperSize / value.scrollThumbSize; value.scrollThumbSize = (value.scrollThumbSize < 30 ? 30 : value.scrollThumbSize); value.scrollTrigger = value.scrollbar['find']('.scrollbar-button'); value.scrollTriggerInc = value.scrollTrigger['filter']('.increment'); value.scrollTriggerDec = value.scrollTrigger['filter']('.decrement'); // scrolling per triggers (buttons) value.triggerScroll = function(dir) { // set the basics (vertical scrolling) var intervalDur = 1; var modifier = '-='; modifier = (dir === 'inc' ? '+=' : modifier); // get some nice interval but never below 1 intervalDur = (value.scaleFactor >= 2 ? value.scaleFactor / 2 : intervalDur); var opts = value.scrollOpts(modifier + value.scaleFactor + 'px') scrollTriggerFunction = setInterval(function() { // perform the scrolling action relative to the content // (bigger factor = faster scroll) $area['stop'](true, true)['animate'](opts, value.scaleFactor); }, intervalDur); }; // call this value when a scroll is performed (we are using a flag to throttle these calls) value.performScroll = function() { var newPos = value.getScroll() / value.scrollFactor; var newPieceStart = (newPos + value.scrollThumbSize / 2); var newPieceEnd = value.trackSize - value.scrollThumbSize / 2 - newPos; $wrapper['addClass']('scrolling-' + value.scrollDir + 'ly'); var thumbOpts = { 'top': newPos } var pieceStartOpts = { 'height': newPieceStart } var pieceEndOpts = { 'height': newPieceEnd } if (index === 0) { thumbOpts = { 'left': newPos } pieceStartOpts = { 'width': newPieceStart } pieceEndOpts = { 'width': newPieceEnd } } value.scrollbarThumb['css'](thumbOpts); value.scrollbarTrackPieceStart['css'](pieceStartOpts); value.scrollbarTrackPieceEnd['css'](pieceEndOpts); } // set the correct dimension for our thumb var setThumbDimensions = function() { var height = value.scrollThumbSize; var width = ''; if (index === 0) { height = ''; width = value.scrollThumbSize; } var dimensions = { 'height': height, 'width': width } value.scrollbarThumb['css'](dimensions); }; setThumbDimensions(); // trigger scroll by dragging the thumb value.scrollbarThumb['on']('mousedown', function(e) { if (e.which != 1 || e.button != 0) { return false; } var $target = $(e.target); var trackOffset = $target['position']()['top']; if (index === 0) { trackOffset = $target['position']()['left']; } var pageP = e.pageY; pageP = (index === 0 ? e.pageX : pageP) // prevent the cursor from changing to text-input e.preventDefault(); // calculate the correct offset value.clickPos = pageP - trackOffset; if ($target['hasClass']('scrollbar-thumb')) { $dragging = $target; } $wrapper['addClass']('clicked clicked-' + value.scrollDir + 'ly'); defaults['thumbclick'](this, $wrapper); $node['trigger']('thumbclick'); }); // trigger scroll by clicking the buttons value.scrollTriggerInc['on']('mousedown', function(e) { if (e.which != 1 || e.button != 0) { return false; } value.triggerScroll('inc'); }); value.scrollTriggerDec['on']('mousedown', function(e) { if (e.which != 1 || e.button != 0) { return false; } value.triggerScroll('dec'); }); // trigger scroll by clicking the track-pieces value.scrollTrackPiece['on']('mousedown', function(e) { if (e.which != 1 || e.button != 0) { return false; } var delta = e.pageY - value.scrollbarTrack['offset']()['top']; if (index === 0) { delta = e.pageX - value.scrollbarTrack['offset']()['left']; $area['scrollLeft'](delta * value.scaleFactor); } else { $area['scrollTop'](delta * value.scaleFactor); } }); }); // call when the scoll has ended (throttled by a flag) var scrollHasEnded = function(e, el) { $(el)['removeClass'](scrollClasses); $node['trigger']('scrollend'); defaults['scrollended'](e, el); scrolling = false; }; // define the actions when the area is being scrolled $area['on']('scroll', function(e) { var currentAreaScroll = { x: $area['scrollLeft'](), y: $area['scrollTop']() } // scrolling vertically? if (currentAreaScroll.y != areaScroll.y) { data.y.performScroll(); } // scrolling horizontally? if (currentAreaScroll.x != areaScroll.x) { data.x.performScroll(); } // if we this is the first scrollevent we can send the scrollstart events // will only get called once until the next scrollend if (!scrolling) { $node['trigger']('scrollstart'); defaults['scrollstarted'](this, $wrapper); } // we are currently scrolling scrolling = true; $wrapper['addClass']('scrolling'); // we don't want to end our scroll yet clearTimeout(scrollEnded); // but it will end if we don't scroll for 200ms scrollEnded = setTimeout(function() { scrollHasEnded(e, $wrapper) }, 200); }); // events on the body (will perform as long as flags are active) $body['on']('mousemove', function(e) { if ($dragging) { if ($dragging['closest']('.scrollbar')['hasClass']('horizontal')) { data.x.delta = e.pageX - data.x.clickPos; $area['scrollLeft'](data.x.delta * data.x.scrollFactor) } if ($dragging['closest']('.scrollbar')['hasClass']('vertical')) { data.y.delta = e.pageY - data.y.clickPos; $area['scrollTop'](data.y.delta * data.y.scrollFactor) } } })['on']('mouseup mouseleave blur', function() { clearInterval(scrollTriggerFunction); $dragging = null; $wrapper['removeClass'](clickClasses); }); // prepare our element for interaction $area['css']({ 'height': wrapperDimensions.h }); data.y.performScroll(); data.x.performScroll(); $wrapper['removeClass'](scrollClasses); defaults['created'](this, $wrapper); $node['trigger']('create'); $node['addClass']('customScrollBar_processed'); }, 'destroy': function() { var $node = $(this); if ($node['hasClass']('customScrollBar_processed')) { var $rest = $node['closest']('.customScrollBar'); $rest['find']('.scroll-area')['off']('scroll'); $node['removeClass']('original-content customScrollBar_processed')['insertAfter']($rest); $rest['remove'](); defaults['destroyed'](this, $rest); $node['trigger']('destroy'); } else { return false; } } }; $['fn']['customScrollBar'] = function(method) { var args = arguments; return this['each'](function() { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(args)); } else if (typeof method === 'object' || !method) { return methods['init'].apply(this, Array.prototype.slice.call(args, 0)); } else { $.error('Method ' + method + ' does not exist'); } }); }; })(jQuery, window, document);
import React from 'react'; import { Formik, Form } from 'formik'; import axios from 'axios'; import router from 'next/router'; import * as yup from 'yup'; import Link from 'next/link'; import Input from '../Input/Input'; const validationSchema = yup.object().shape({ email: yup .string() .email() .required(), }); const RequestPasswordResetForm = () => ( <Formik initialValues={{ email: '', }} validationSchema={validationSchema} onSubmit={async values => { const { data } = await axios({ method: 'POST', url: '/catsapi/v1/auth/forgotpassword', data: values, }); if (data.success) { router.push('/login'); } }} > {({ values, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting, }) => ( <Form onSubmit={handleSubmit}> <Input type="email" name="email" label="Email" /> <button type="submit" className="btn btn-primary btn-block"> Reset Password </button> </Form> )} </Formik> ); export default RequestPasswordResetForm;
import React from 'react' import { makeStyles } from '@material-ui/core/styles' import Typography from '@material-ui/core/Typography' const useStyles = makeStyles(theme => ({ root: { backgroundColor: '#2D2D2D', color: theme.palette.common.white, }, component: { padding: theme.spacing(8), }, })) export default function SupportComponent() { const classes = useStyles() return ( <div className={classes.root}> <div className={classes.component}> <Typography>Contact us at support@real.app</Typography> <Typography>REAL 2019</Typography> </div> </div> ) }
import React from "react"; import { View } from "react-native"; import ViewCard from "./ViewCardV2"; import { useSelector } from 'react-redux'; import HeadingText from "./../HeadingText"; import { useDispatch } from 'react-redux'; import { useNavigation } from '@react-navigation/native'; /* const onReview = (correct) => { if (correct) { this.setState({ numCorrect: this.state.numCorrect + 1 }); } this.setState({ numReviewed: this.state.numReviewed + 1 }); };*/ const CardList = () => { //currentReview let tempCurrentReview = useSelector(state => state.currentReview); let reviews = tempCurrentReview.questions; let currentReview = tempCurrentReview.currentQuestionIndex; let dispatch = useDispatch(); const navigation = useNavigation(); console.log("tempCurrentReview:", tempCurrentReview) console.log("reviews::", reviews); console.log("currentReview:", currentReview); if (reviews.length == 0){ console.log("reviews:", reviews.length); return ( <View> <HeadingText> CardList({reviews.length})! </HeadingText> </View> ); } let reviews2 = reviews[currentReview]; console.log("reviews2:", reviews2); return ( <View> <HeadingText> CardList({reviews.length})! </HeadingText> <ViewCard answers={reviews2.answers} prompt={reviews2.prompt} correctAnswer={reviews2.correctAnswer} dispatch={dispatch} navigation={navigation} dataCount={reviews.length} /> </View> ); } /* [ { "orientation": "back", "cardID": "b8f2674791824c792264abd8bf15dc8b", "prompt": "the cat", "correctAnswer": "die Katze", "answers": [ "das Brot", "die Frau", "der Hund", "die Katze" ] }, { "orientation": "front", "cardID": "b8f2674791824c792264abd8bf15dc8b", "prompt": "die Katze", "correctAnswer": "the cat", "answers": [ "the bread", "the woman", "the dog", "the cat" ] } ] */ export default CardList;
require('./build/gulp-tasks');
/* * @lc app=leetcode.cn id=451 lang=javascript * * [451] 根据字符出现频率排序 * * https://leetcode-cn.com/problems/sort-characters-by-frequency/description/ * * algorithms * Medium (65.73%) * Likes: 195 * Dislikes: 0 * Total Accepted: 34.8K * Total Submissions: 52.7K * Testcase Example: '"tree"' * * 给定一个字符串,请将字符串里的字符按照出现的频率降序排列。 * * 示例 1: * * * 输入: * "tree" * * 输出: * "eert" * * 解释: * 'e'出现两次,'r'和't'都只出现一次。 * 因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。 * * * 示例 2: * * * 输入: * "cccaaa" * * 输出: * "cccaaa" * * 解释: * 'c'和'a'都出现三次。此外,"aaaccc"也是有效的答案。 * 注意"cacaca"是不正确的,因为相同的字母必须放在一起。 * * * 示例 3: * * * 输入: * "Aabb" * * 输出: * "bbAa" * * 解释: * 此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的。 * 注意'A'和'a'被认为是两种不同的字符。 * * */ // @lc code=start /** * @param {string} s * @return {string} */ // tree var frequencySort = function(s) { if (!s.length) return; let map = new Map(); let arr = []; let str = ''; // 首先是先遍历然后把字母的当前次数存下来 for (let i = 0; i < s.length; i++) { map.set(s[i], map.has(s[i]) ? map.get(s[i]) + 1 : 1); } for (let [key, value] of map.entries()) { arr.push({key,value}) } // 降序 arr.sort((a, b) => {return b.value - a.value}); arr.forEach(item => { let temp = item.key.repeat(item.value); str += temp; }) return str; }; // @lc code=end
export const black = "#262626"; export const themeColor = "#e60052"; export const gray = "#c0c0c0"; export const grayLight = "#c0c0c0";
export function buildCodeNode(node, code) { node.textContent = `${code}`; hljs.highlightElement(node); }
$(document).ready(function() { var tabladatos=$('#datos'); var fechaInicio=$('#fechaInicio').val(); var fechaFin=$('#fechaFin').val(); var idProducto=$('#idProducto').val(); var idAlmacen=$('#idAlmacen').val(); Mostrar(idProducto); var route = "/reportKardexDatos/"+fechaInicio+"/"+fechaFin+"/"+idProducto+"/"+idAlmacen; $('#datos').empty(); debugger; $.get(route,function(res){ $(res).each(function(key,value){ debugger; tabladatos.append("<tr>"+ "<td>"+value.fecha+"</td>"+ "<td>"+value.transaccion+"</td>"+ "<td>"+value.origen+"</td>"+ "<td>"+value.ingresos+"</td>"+ "<td>"+value.egresos+"</td>"+ "</tr>"); }); }); }); function imprimir(){ var ficha = document.getElementById('imprmir'); var ventimp = window.open(' ', 'popimpr'); ventimp.document.write( ficha.innerHTML ); ventimp.document.close(); ventimp.print( ); ventimp.close(); } $("#descargar").click(function(){ debugger; var fechaInicio=$('#fechaInicio').val(); var fechaFin=$('#fechaFin').val(); var idProducto=$('#idProducto').val(); var idAlmacen=$('#idAlmacen').val() var route = "/descargarreportekardex/"+fechaInicio+"/"+fechaFin+"/"+idProducto+"/"+idAlmacen; $.get(route,function(res){ $(res).each(function(key,value){ value; debugger; }); }); }); function Mostrar(idProducto){ var route = "/Producto/"+idProducto+"/edit"; $.get(route, function(res){ $(res).each(function(key,value){ $("#nombre").text(value.nombre); $("#descripcion").text(value.descripcion); $("#codigoInterno").text(value.codigoInterno); $("#codigoBarra").text(value.codigoDeBarra); $("#material").text(value.material); $("#color").text(value.material); $("#tamano").text(value.tamano); $("#precioVenta").text(value.precioVenta); }); }); }
var searchData= [ ['inicio_350',['inicio',['../structlista.html#abf27655afeb33ece3637153953f32776',1,'lista']]] ];
import Vue from "../../dist/vue.mjs"; export default { state: { types: {}, }, mutations: { addDashboardType(state, v) { Vue.set(state.types, v.type, v.component); }, }, };
var express = require('express'); var bodyParser = require('body-parser'); var oracleHandler = require('oracle-handler'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'Express' }); }); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'Home' }); }); // Process the login form router.post('/login', function(req, res) { var username = req.body.username; var password = req.body.password; var getUsersStatement = 'SELECT FROM USERS (USER_NAME, PASSWORD, DATE_REGISTERED) '+ 'VALUES (\''+username+'\', \''+password+'\', SYSTIMESTAMP)'; var results = oracleHandler.oracleQuery(getUsersStatement); }); module.exports = router;
var Modeler = require("../Modeler.js"); var className = 'TypeCallMLParameters6'; var TypeCallMLParameters6 = function(json, parentObj) { parentObj = parentObj || this; // Class property definitions here: Modeler.extend(className, { primarysearch: { type: "Typemlprimarysearch", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "primarysearch", type: "tns:mlprimarysearch" }, mask: Modeler.GET | Modeler.SET, required: false }, ipaddress: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "ipaddress", "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 15 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, overridedecision: { type: "Typeoverridedecision", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "overridedecision", type: "tns:overridedecision" }, mask: Modeler.GET | Modeler.SET, required: false }, subsequentsearch: { type: "Typesubsequentsearch", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "subsequentsearch", type: "tns:subsequentsearch" }, mask: Modeler.GET | Modeler.SET, required: false }, addresslinksearch: { type: "Typeaddresslinksearch", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "addresslinksearch", type: "tns:addresslinksearch" }, mask: Modeler.GET | Modeler.SET, required: false }, yourreference: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "yourreference", "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 50 }, "s:minLength": { value: 1 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false } }, parentObj, json); }; module.exports = TypeCallMLParameters6; Modeler.register(TypeCallMLParameters6, "TypeCallMLParameters6");
import React from "react"; import ReactDOM from "react-dom/client"; import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom"; import Cookies from "universal-cookie"; import "bootstrap/dist/css/bootstrap.min.css"; import "./assets/css/animate.min.css"; import "./assets/scss/light-bootstrap-dashboard-react.scss?v=2.0.0"; import "./assets/css/demo.css"; import "@fortawesome/fontawesome-free/css/all.min.css"; import "./assets/css/style.css" import AdminLayout from "layouts/Admin.js"; const cookies = new Cookies(); const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <BrowserRouter> <Switch> <Route path="/admin" render={(props) => <AdminLayout {...props} />} /> <Redirect from="/" to="/admin/dashboard" /> </Switch> </BrowserRouter> );
import React from 'react'; import PropTypes from 'prop-types'; import TableCell from '@material-ui/core/TableCell'; import { makeStyles } from '@material-ui/styles'; const useStyles = makeStyles({ cell: { color: '#FFFFFF' }, rootCell: { textAlign: 'center', }, }); function Td({ components }) { const classes = useStyles(); return ( <TableCell classes={{ root: classes.rootCell }} className={classes.cell}> {components} </TableCell> ); } Td.propTypes = { components: PropTypes.string.isRequired, path: PropTypes.string.isRequired, }; export default Td;
#!/usr/bin/env node // NPM Imports import { Command } from "commander"; import * as fs from "fs"; import * as path from "path"; import * as util from "util"; import cli from "./cli"; // logging require("log-timestamp"); const fsWriteFile = util.promisify(fs.writeFile); const program = new Command(); program .name("morphir test-coverage") .description("Generates report on number of branches in a Morphir value and TestCases covered") .option("-i, --ir <path>", "Source location where the Morphir IR will be loaded from.", "morphir-ir.json") .option("-t, --tests <path>", "Source location where the Morphir Test Json will be loaded from.", "morphir-tests.json") .option("-o, --output <path>", "Source location where the Morphir Test Coverage result will be ouput to.", ".") .parse(process.argv); const { ir: irPath, tests: irTestPath, output: output } = program.opts(); cli.testCoverage(irPath, irTestPath, output, program.opts()) .then((data) => { fsWriteFile( path.join(output, "morphir-test-coverage.json"), JSON.stringify(data) ); }) .catch((err) => { console.log("err --", err); process.exit(1); });
import gql from 'graphql-tag'; const GET_BLOG_QUERY = gql` query GetPost ($id: String) { blogPost ( id: $id ) { post_id title content } } `; export default { queries: { getBlogQuery: GET_BLOG_QUERY }, mutations: {} };
'use strict'; let BASE_API_URL = 'https://mgrinko.github.io/js-20180329-1900/api'; const PhonesService = { loadPhones(filter, callback) { this._sendRequest('/phones') .then(phones => { const filteredPhones = this._filter(phones, filter.search); const sortedPhones = this._sort(filteredPhones, filter.sort); return callback(sortedPhones); }) .catch(error => { return callback(error.code); }); }, loadPhoneOne(phoneId, callback) { this._sendRequest(`/phones/${phoneId}`) .then(phones => { return callback(phones); }) .catch(error => { return callback(error.code); }); }, _filter(phones, search) { if (!search) { return phones; } let normalizedQuery = search.toLowerCase(); return phones.filter((phone) => { return phone.name.toLowerCase().includes(normalizedQuery); }); }, _sort(phones, orderField) { return phones.sort((phoneA, phoneB) => { return (phoneA[orderField] > phoneB[orderField]) ? 1 : -1; }); }, _sendRequest(url, {method = 'GET'}={}) { return new Promise( function(resolve, reject) { let xhr = new XMLHttpRequest(); let fullUrl = BASE_API_URL + url + '.json'; xhr.open(method, fullUrl, true); xhr.send(); xhr.onload = function() { if (this.status === 200) { let data = JSON.parse(xhr.responseText); resolve(data); } else { let error = new Error(this.statusText); console.log(this.status); error.code = this.status; reject(error); } }; xhr.onerror = function() { reject(new Error("Network Error")); }; }); } }; export default PhonesService;
/** * Created by mac on 12/11/2014. */ 'use strict'; var express = require('../../node_modules/express'); var bodyParser = require('../../node_modules/body-parser'); var path = require('path'); module.exports = function (app) { /** * --------------basic setup----------------------- */ app.use(require('../../node_modules/cookie-parser')()); app.use(require('../../node_modules/express-session')({ secret: 'bittrade secret', saveUninitialized: true, resave: true })); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); };
function(instance, properties, context) { if (instance.data.myData === undefined || instance.data.myData === null) { console.log("No data to download") return; } var link = document.createElement('a'); link.setAttribute('href', instance.data.myData); link.setAttribute('target', "_blank"); link.setAttribute('download', instance.data.filename); link.click(); }
var messageBlinkId; $(document).ready(function() { startTime(); getAppointments(); getDate(); //initCanvas(); canvas = document.getElementById('can'); signaturePad = new SignaturePad(canvas); $('#message').hide(); $('#messageNew').hide(); initMessageShowTap(); changeImage(); $.ajax({ cache: false, url: "/checkUnread", dataType: "json", success: function(data) { if (data == true) { $('#messageNew').show(); messageBlinkId = setInterval(messageBlink, 1500);; } }, error: function (data) { } }); //close new message $('#messageShowClose').bind('tap',function() { $('#messageShow').hide(); $.ajax({ cache: false, url: "/checkUnread", dataType: "json", success: function (data) { if (data == false) { window.clearInterval(messageBlinkId); $('#imgMessageNew').remove(); } }, error: function (data) { } }); }); $('.station').bind('tap',function() { var src=$(this).attr('src'); var myRegexp = /.+\/btn-(.+)\.png$/g; var match = myRegexp.exec(src); var station = match[1]; var area=$(this).parent().parent().text().trim(); var ip; if (area==='BATHROOM'){ ip="192.168.178.31" } else if (area==='LIVINGROOM'){ ip="192.168.178.37" } else { return; } $.ajax('tune?target='+ip+'&station='+station); }); $('#trash').bind('tap',function() { canvas = document.getElementById('can'); ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); $('#message').hide(); }); //canvas save $('#save').bind('tap',function() { canvas = document.getElementById('can'); var dataUrl = canvas.toDataURL(); var filename = Date.now() + '.png'; dataUrl = dataUrl.replace('data:image/png;base64,',''); ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); $.post( "save", { dataUrl: dataUrl, filename: filename} ); $('#message').hide(); $('#messageNew').html('<img id="imgMessageNew" style="cursor:pointer;" height="100" width="100" src="static/img/message.png" />'); initMessageShowTap(); $('#messageNew').show(); messageBlinkId = setInterval(messageBlink, 1500); }); $('.newMsg').bind('tap',function() { $('#message').css({ position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', zIndex: 701, 'background-image': 'url(static/img/paper.png)', 'background-repeat':'no-repeat' }); $('#message').show(); }); $('.boxheader').bind('tap',function() { var area=$(this).text().trim(); var ip; if (area==='BATHROOM'){ ip="192.168.178.31" } else if (area==='LIVINGROOM'){ ip="192.168.178.37" } else { return; } $.ajax('stop?target='+ip); }); }); function initMessageShowTap(){ //show new message $('#imgMessageNew').bind('tap',function() { $('#messageNew').hide(); $('#messageShow').show(); $('#messageShowContent').html($('<img />').attr('src','/getUnread?t='+(new Date()).getTime())); }); } function messageBlink() { $('#messageNew').fadeOut(1500).fadeIn(1500); } function startTime() { var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); m = checkTime(m); s = checkTime(s); document.getElementById('time').innerHTML = h + ":" + m; var t = setTimeout(startTime, 15000); } function checkTime(i) { if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10 return i; } function fadeOut(){ $('#scrollimage').fadeOut(); changeImage(); } function changeImage(){ $('#scrollimage').css('height', ''); $('#scrollimage').css('width', ''); var img = $("<img id='scrollimage' />").attr('src', 'getImage?t='+(new Date()).getTime()) .on('load', function () { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { alert('broken image!'); } else { $('#scrollimage').remove(); $("#scroll").append(img); $('#scrollimage').fadeIn(); var width = $('#scrollimage').height(); var height = $('#scrollimage').width(); if (this.naturalHeight > this.naturalWidth) { $('#scrollimage').css('height', ''); $('#scrollimage').css('width', '100%'); upDown(); } else { $('#scrollimage').css('height', '100%'); $('#scrollimage').css('width', ''); leftRight(); } } }); /*var imgSrc = $('#scrollimage').attr('src'); if (!imgSrc) { $('#scrollimage').attr('src', '1.jpg'); } else { var i = imgSrc.replace(".jpg", ""); i = parseInt(i) + 1; if (i > 2) { i = 1; } $('#scrollimage').attr('src', i + '.jpg'); }*/ } function upDown(){ $('#scroll').animate({ scrollTop: $('#scroll').get(0).scrollHeight }, 12000); $('#scroll').animate({ scrollTop: -$('#scroll').get(0).scrollHeight }, 10000, fadeOut); } function leftRight() { $('#scroll').animate({ scrollLeft: $('#scroll').get(0).scrollWidth }, 12000); $('#scroll').animate({ scrollLeft: -$('#scroll').get(0).scrollWidth }, 10000, fadeOut); } function getDate() { $.ajax({ cache: false, url: "/getDate", dataType: "json", success: function(data) { $("#date").empty(); var formatedText = ""; $.each(data, function (i, item) { formatedText += data[i] + "<br>"; }); $("#date").append(formatedText); }, error: function(data) { console.log("error") $("#date").empty(); $("#date").append("Error fetching date"); } }); var u = setTimeout(getDate, 30000); //5Minutes = 300s } function getAppointments() { $.ajax({ cache: false, url: "/getAppointments", dataType: "json", success: function(data) { console.log("success"); $("#appointments").empty(); var formatedText = ""; var beginDate = ""; $.each(data, function (i, item) { var begin = data[i][0]; var end = data[i][1]; var subject = data[i][2]; var b = begin.split(" "); var bDate = ""; if (beginDate == b[0]) { } else { bDate = "<br><b>"+b[0]+"</b><br><br>"; } beginDate = b[0]; var c = end.split(" "); formatedText += bDate + b[1] + "&nbsp;-&nbsp;" + c[1] + "&nbsp" + subject + "<br>"; }); $("#appointments").append(formatedText); }, error: function(data) { console.log("error") $("#appointments").empty(); $("#appointments").append("Error fetching appointments"); } }); var u = setTimeout(getAppointments, 300000); //5Minutes = 300s }
export const ADD_TO_CART = 'ADD_TO_CART'; export const DElETE_FROM_CART = 'DElETE_FROM_CART'; export const addToCart = product => { return { type: ADD_TO_CART, product: product } } export const deleteFromCart = product => { return { type: DElETE_FROM_CART, product: product } }
function primeFact(n){ let res = []; for(let divisor = 2;divisor<=n;divisor++) { while(n%divisor===0) { res.push(divisor); n/=divisor } } return res; } console.log("Program run successfully"); module.exports = primeFact
"use strict" // jedna funkcija: function putMinElementAtNBeginning(numbers){ var numbers=[3, 5, 1, 2, 6, 2, 9]; for (var i = 0; i < numbers.length-1; i++){ var position = i; for (var j = i; j < numbers.length;j++){ if (numbers[position] > numbers[j]) { position = j; } } var tmp = numbers[i]; numbers[i] = numbers[position]; numbers[position] = tmp; } return numbers; } console.log(putMinElementAtNBeginning([3,5,1,2,6,2,9])); // funkcija u funkciji: function filterNumbers(numbers, shouldIAddTheNumber) { var filteredNumbers=[]; for (var i=0; i< numbers.length; i++) { if (!shouldIAddTheNumber(numbers[i])){ continue; } filteredNumbers[filteredNumbers.length]= numbers[i]; } return filteredNumbers; } function conditionFunction(element){ return (element !=="l" || element ==8); } console.log(filterNumbers("hello", conditionFunction)); // drugi nacin function filterNumbers(numbers, shouldIAddTheNumber) { var filteredNumbers=[]; for (var i=0; i< numbers.length; i++) { if (!shouldIAddTheNumber(numbers[i])){ continue; } filteredNumbers[filteredNumbers.length]= numbers[i]; } return filteredNumbers; } function conditionFunction(element){ return !isNaN(element) && isFinite(element); } console.log(filterNumbers([2, 3, NaN, Infinity, true], conditionFunction)); // treci nacin: function filterNumbers(numbers, shouldIAddTheNumber) { var filteredNumbers=[]; for (var i=0; i< numbers.length; i++) { if (!shouldIAddTheNumber(numbers[i])){ continue; } filteredNumbers[filteredNumbers.length]= numbers[i]; } return filteredNumbers; } function conditionFunction(element){ return (element !==3 && element !==9); } console.log(filterNumbers([3,5,1,2,6,4,9], conditionFunction)); //cetvrti nacin: function transformValues(numbers, transformerFunction) { var transformed=[]; for (var i=0; i< numbers.length; i++) { transformed[transformed.length] = transformerFunction(numbers[i]); } return transformed; } function transformerFunction(element){ return element * 2 + 3; } console.log(transformValues([2,3,4,5], transformerFunction)); // zadatak Write IIFE that replaces the first and the last element of the given array and prints out its elements. //Input array: [4, 5, 11, 9] //Output array: [ 9, 5, 11, 4] function noviNiz (inputArr){ var outputArr=[]; for (i=0; i< inputArr.length; i++){ outputArr[0] = inputArr[inputArr.length-1]; outputArr[inputArr.length-1]= inputArr[0]; outputArr[1] = inputArr[1]; outputArr[2] = inputArr[2]; } return outputArr; } console.log(noviNiz([4, 5, 11, 9])); // zadatak 2 Write IIFE that calculates the surface area of the given rectangle with sides a and b. //Input: 4 5 //Output: 20 function povr(a,b) { return a * b ; } console.log(povr(5,8)); // zadatak 3 Write IIFE that replaces all appearances of the letters m or M with * and returns the number of replacements. // Input: prograMming // Output: progra**ing, 2 function replaceStar(inputStr) { var outputStr='' ; var pos = 0 ; for(var i = 0 ; i < inputStr.length ; i ++ ) { if(inputStr[i] === 'm' || inputStr[i] === 'M') { pos++; outputStr += '*'; }else { outputStr += inputStr[i]; } } return (outputStr + pos); } console.log(replaceStar('prograMming')); // 4. zadatak Write a function with parameters name and surname that returns a function that suggests an email in the form name.surname@gmail.com. // Input: pera peric // Output: pera.peric@gmail.com function mail(name , surname) { var form = name + '.' + surname + '@gmail.com' ; return form ; } console.log(mail('kristina' , 'butkovic')) ; // 5 //Write a function that returns a function that calculates a decimal value of the given octal number. //Input: 034 //Output: 28 function octalNum(arguments1){ return arguments1; } function broj2() { return parseInt(octalNum(), 8); } console.log(octalNum(34)); function broj1 (numbers){ var dec = parseInt(numbers,8); return number; } function broj2(broj1){ return broj1(); } console.log(broj2(54));
import { getSampleData } from '../utils'; export const getData = (length, minHeight, maxHeight) => { return { type: 'GET_DATA', payload: getSampleData(length, minHeight, maxHeight) } } export const selectItem = (index) =>{ return { type: 'SELECT_ITEM', payload: {index} } }
import React from 'react'; import { responsiveContextTypes } from 'rsg-components/Responsive/Provider'; import Inputs from 'rsg-components/Responsive/Inputs'; import Presets from 'rsg-components/Responsive/Presets'; const s = require('./Toolbar.css'); const ResponsiveToolbar = (props, context) => { return ( <div className={s.toolbar}> <Inputs {...context} /> <Presets {...context} /> </div> ); }; ResponsiveToolbar.contextTypes = responsiveContextTypes; export default ResponsiveToolbar;
var rest = require("../http_mods/rest.js"); var conf = require("../util/config.js"); var mocks = require("./mocks.js"); exports.test = function(test) { console.log( rest.resolveTemplate("../data", "users") ); var template = { bool : false, string : "", number : 1, array : [] }; var input = { bool : true, string : "data", number : 2, array : ["one", "two", "three"] }; console.dir("copyBean: " + rest.copyBean(template, input)); console.dir("copyBean: " + rest.copyBean(template, input)); conf.emitter.on('configReady', function() { var response = new mocks.response(); //console.dir(response); rest.doGet(new mocks.request() , response, new mocks.url("/data/users")); //console.log("\n\ndoPost\n\n should 404"); rest.doPost(new mocks.request('{"name":"Paul Hinds", "handle" : "teknopaul"}') , response, new mocks.url("/data/users")); //console.log("\n\ndoPost\n\n should work"); rest.doPost(new mocks.request('{"name":"Paul Hinds", "handle" : "teknopaul"}') , response, new mocks.url("/data/users/Teknopaul")); //console.log("Should 404"); rest.doPost(new mocks.request('{"name":"Paul Hinds", "handle" : "teknopaul"}') , response, new mocks.url("/data/users/Tekno.paul")); //console.log("Should drop the wrong data"); rest.doPost(new mocks.request('{"name":"Bob Jones", "handle" : "bob", "wrong" : true}') , response, new mocks.url("/data/users/Bob")); test.done(); }); };
import React, { Component } from 'react'; import Nav from './Nav.js'; import './App.css'; import {items} from './staticData.js'; import ItemPage from './ItemPage.js'; import CartPage from './CartPage.js'; class App extends Component { constructor(){ super(); this.state = ({ currentTab:'items', arrayItemsCart:[0,2,4,2] }); } addItemToCart = (itemId) =>{ this.setState({ arrayItemsCart : [...this.state.arrayItemsCart,itemId] }); } sustractItemFromCart = (itemId) =>{//esto es una forma de quitar un elemento del array usando inmutabilidad, que al parecer es basico en redux let i = this.state.arrayItemsCart.indexOf(itemId); if(i != -1){ this.setState({ arrayItemsCart: [ ...this.state.arrayItemsCart.slice(0,i), ...this.state.arrayItemsCart.slice(i+1) ] }); } } renderItemsCart = () =>{ let itemCounts = this.state.arrayItemsCart.reduce((itemCounts, itemId) =>{ itemCounts[itemId] = itemCounts[itemId] || 0; //esto lo que hace es que si es undefined le da valor 0 para que no haya que inicializarlo itemCounts[itemId]++; return itemCounts; },{}); let itemsCart = Object.keys(itemCounts).map(itemId => { let item = items.find(item => item.id === parseInt(itemId,10)); //el siguiente return al usar ...item lo que se hace //es que se aņade un campo 'count' al objeto item return { ...item,count:itemCounts[itemId] } }); return (<CartPage items={itemsCart} sustractItemFromCart={this.sustractItemFromCart} isEmpty={itemsCart.length === 0 ? true: false} addItemToCart={this.addItemToCart} />) } renderNav = () =>{ let itemCounts = this.state.arrayItemsCart.reduce((itemCounts, itemId) =>{ itemCounts[itemId] = itemCounts[itemId] || 0; //esto lo que hace es que si es undefined le da valor 0 para que no haya que inicializarlo itemCounts[itemId]++; return itemCounts; },{}); let sumaItems = 0; let sumaPrice = 0; let itemsCart = Object.keys(itemCounts).map(itemId => { let item = items.find(item => item.id === parseInt(itemId,10)); sumaItems = sumaItems + itemCounts[itemId]; sumaPrice = sumaPrice + (itemCounts[itemId]*item.price) }); return ( <Nav selectedTab = {this.state.currentTab} handleClickItems={this.toggleToItems} handleClickCart={this.toggleToCart} totalPrice = {sumaPrice.toFixed(2)} totalNItems= {sumaItems} /> ); } //gestiona link nav toggleToCart = () =>{ this.setState({currentTab:'cart'} ); } //gestiona link nav toggleToItems = () =>{ this.setState({currentTab:'items'}); } render() { let mainContent = ""; if(this.state.currentTab === 'items'){ mainContent = ( <ItemPage items={items} addItemToCart={this.addItemToCart} /> ) }else{ mainContent = this.renderItemsCart(); } return ( <div className="App"> {this.renderNav()} {mainContent} </div> ); } } export default App;
import React from 'react'; import Cart from './screen/Cart'; import Home from './screen/Home'; import Login from './screen/Login'; import Product from './screen/Product'; import ProductList from './screen/ProductList'; import Register from './screen/Register'; function App() { return ( <> <Home /> </> ); } export default App;
import React from "react"; import { Card, CardMedia, withStyles, Typography } from "@material-ui/core"; import Rating from "./Rating"; const styles = () => ({ media: { height: 0, paddingTop: "56.25%" }, overlay: { position: "absolute", top: "550px", left: "540px", color: "black", background: "transparent" }, card: { position: "relative" } }); const HotelData = props => { const { classes } = props; if (props.data.hotelgalleryimages === undefined) { console.log("error"); } else { var imgs = props.data.hotelgalleryimages.map(item => ( <img style={{ border: "1px solid black" }} className="d-block " src={item} alt="First slide" width="200px" height="200px" /> )); } return ( <div> <Card className={classes.card}> <CardMedia className={classes.media} image={props.data.hotelimages} title="Hotels" /> <div className={classes.overlay}> <Typography variant="h2" gutterBottom style={{ fontFamily: "italic" }} > {props.data.hotelname} </Typography> </div> </Card> <br /> <br /> <Typography variant="h5" align="center" gutterBottom style={{ fontFamily: "italic" }} > Welcome to </Typography> <Typography variant="h2" align="center" gutterBottom style={{ fontFamily: "italic" }} > {props.data.hotelname} </Typography> <Typography variant="subtitle1" align="center" gutterBottom style={{ fontSize: "20px", fontFamily: "italic" }} > {props.data.hoteldescription} </Typography> <br /> <Typography variant="h3" align="center" gutterBottom style={{ fontFamily: "italic" }} > Gallery </Typography> <div style={{ textAlign: "center" }} > <div style={{ display: "inline-flex", border: "2px solid black", margin: "20px" }} > {imgs} </div> <br /> <Typography variant="subtitle2" gutterBottom> Give Rating </Typography> <br /> <Rating /> </div> </div> ); }; export default withStyles(styles)(HotelData);
export { default as GlobalStyles } from './GlobalStyles'; export { default as Header } from './Header'; export { default as Home } from './Home'; export { default as Detail } from './Detail'; export { default as Card } from './Card'; export { default as CardList } from './CardList'; export { default as Select } from './Select'; export { default as Search } from './Search'; export { default as Filters } from './Filters'; export { default as LoadPage } from './LoadPage'; export { default as Loader } from './Loader';
const expect = require('expect.js'); const config = require('../src/config.js'); const search = require('../src/search.js'); const appointment = require('../src/appointment.js'); const authenticate = require('../src/authenticate.js'); const _ = require('underscore'); describe('Appointment', function () { this.timeout(10000); describe('Appointment Lifecycle', function () { var sharedState = { customerSessionHref: null, appointmentDetails: null, appointment: null, cancelledAppointment: null, access_token: null }; it('must authenticate', function (done) { authenticate.authenticate(function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.access_token).to.not.be(undefined); sharedState.access_token = result.content.access_token; done(); }) }); it('should be able to authenticate using configured user', function (done) { appointment.authenticate( sharedState.access_token, config.customerUsername, config.customerPassword, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.customer).to.not.be(undefined); expect(result.content.customer).to.be.an('object'); sharedState.customerSessionHref = result.content.href; done(); }) }); it('should be able to search for a service', function (done) { search.byServiceName( sharedState.access_token, 'Blowdry', function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be(undefined); expect(result.content.available_appointments).to.be.an('array'); expect(result.content.available_appointments).to.not.be.empty(); sharedState.appointmentDetails = result.content.available_appointments[1]; done(); }); }); it('Should be able to book the service', function (done) { if (!sharedState.customerSessionHref || !sharedState.appointmentDetails) { done('Inconclusive - earlier tests failed'); return; } appointment.bookAppointment( sharedState.access_token, sharedState.customerSessionHref, sharedState.appointmentDetails, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.href).to.not.be(undefined); sharedState.appointment = result.content.appointments[0]; done(); }); }); it('Should not be able to double-book the time-slot', function (done) { if (!sharedState.customerSessionHref || !sharedState.appointmentDetails || !sharedState.appointment) { done('Inconclusive - earlier tests failed'); return; } appointment.bookAppointment( sharedState.access_token, sharedState.customerSessionHref, sharedState.appointmentDetails, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(409); // Conflict expect(result.content.error_type_code).to.eql('system'); expect(result.content.message).to.eql('Proposed appointment is no longer available'); done(); }); }); it('Should be able to retrieve the same appointment', function (done) { if (!sharedState.customerSessionHref || !sharedState.appointment) { done('Inconclusive - earlier tests failed'); return; } appointment.retrieveAppointments( sharedState.access_token, sharedState.customerSessionHref, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.appointments).to.not.be(undefined); expect(result.content.appointments).to.be.an('array'); expect(result.content.appointments).to.not.be.empty(); var foundAppointment = _.findWhere(result.content.appointments, {href: sharedState.appointment.href}); expect(foundAppointment).to.not.be(undefined); done(); }); }); it('Should be able to cancel the same appointment', function (done) { if (!sharedState.customerSessionHref || !sharedState.appointment) { done('Inconclusive - earlier tests failed'); return; } appointment.cancelAppointment( sharedState.access_token, sharedState.customerSessionHref, sharedState.appointment.href, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); sharedState.cancelledAppointment = sharedState.appointment; done(); }); }); }); });
'use strict' const test = require('ava') const pkg = require('../package') const { capitalizeName, setupDependenciesVersions } = require('../app/helpers') test('capitalizeName', t => { t.is(capitalizeName('project-name'), 'Project Name') }) test('.setupDependenciesVersions', async t => { t.deepEqual(await setupDependenciesVersions(pkg), pkg) })
import { devices } from "node-hid" console.log(devices())
import Layout from '../window/Layout' import Icon from '../Icon' import { useState, useContext } from 'react' import Button from '../Button' import useFormValidation from '../../hooks/useFormValidation' import { contactValidator } from '../../helpers/validate' import { fetchContact } from '../../actions' import { toastContext } from '../../context/toastContext' const INITIAL_VALUE = { name: '', email: '', subject: '', message: '' } // https://www.google.com/search?rlz=1C1GCEU_koKR848KR848&biw=1366&bih=657&tbm=isch&sa=1&ei=WpJjXbSQN9GImAWbhor4Ag&q=window+95+send+mail&oq=window+95+send+mail&gs_l=img.3...69607.72020..72244...0.0..0.159.1658.0j13......0....1..gws-wiz-img.......35i39j0j0i30j0i10i30j0i8i30j0i24.OcYwUrkc8cI&ved=0ahUKEwi0pc6_iaDkAhVRBKYKHRuDAi8Q4dUDCAY&uact=5#imgrc=sknvPiMfnALjaM: const ContactForm = ({ x, y, onClose, title }) => { const { handleBlur, values, handleChange, errors } = useFormValidation( INITIAL_VALUE, contactValidator ) const toastCtx = useContext(toastContext) const sendEmail = async values => { alert(JSON.stringify(values, null, 2)) try { const res = await fetchContact(values) toastCtx.addToast('메일이 정상적으로 전송 되었습니다') toastCtx.addToast( '메일이 전송되지 않았습니다. 다시 한 번 시도해주세요' ) } catch (err) { console.error(err) } } return ( <Layout title={title} x={x} y={y} onClose={onClose} width="355px" height="515px" > <div className="contact__container"> <div className="contact__field"> <div className="field__name flex--col"> <span> 이름 <span className="required">*</span> </span> <input name="name" type="text" value={values.name} onBlur={handleBlur} onChange={handleChange} ></input> <span className="name__error error">{errors.name}</span> </div> <div className="field__email flex--col"> <span> 이메일 <span className="required">*</span> </span> <input name="email" type="text" value={values.email} onBlur={handleBlur} onChange={handleChange} ></input> <span className="name__error error"> {errors.email} </span> </div> <div className="field__subject flex--col"> <span>제목</span> <input name="subject" type="text" value={values.subject} onBlur={handleBlur} onChange={handleChange} ></input> </div> <div className="field__message flex--col"> <span>내용</span> <textarea name="message" rows={12} value={values.message} onBlur={handleBlur} onChange={handleChange} ></textarea> </div> <div className="field__submit"> <Button title="보내기" onClick={() => { if (Object.keys(errors).length === 0) { sendEmail(values) } }} /> </div> </div> </div> </Layout> ) } export default ContactForm
import React from 'react'; import styled from 'styled-components'; import { Link } from 'react-router-dom'; const ItemBody = styled.div` min-width: 75%; max-width: 75%; padding: 0 5px; } @media (min-width: 482px) { min-width: 50%; max-width: 50%; } @media (min-width: 701px) { min-width: 33.33%; max-width: 33.33%; } @media (min-width: 1011px) { min-width: 25%; max-width: 25%; } `; const ItemBodyLarge = styled(Link)` min-width: 75%; max-width: 75%; padding: 0 5px; display: block; text-decoration: none; } @media (min-width: 482px) { min-width: 50%; max-width: 50%; } @media (min-width: 1011px) { min-width: 33.33%; max-width: 33.33%; } `; const carouselItem = ({ children }) => <ItemBody>{children}</ItemBody>; export const CarouselItemWrapper = ({ children, title }) => ( <ItemBodyLarge to={`/${title.toLowerCase().replace(/ /g, '-')}/near-me`}> {children} </ItemBodyLarge> ); export default carouselItem;
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { options: { includePaths: [ // 把 compass-mixins 加到 sass 的 include path 'node_modules/compass-mixins/lib' ], outputStyle: 'compressed', encoding: 'utf-8' }, dist: { // 用 grunt 展開檔案丟給 node-sass // ref: http://gruntjs.com/configuring-tasks#globbing-patterns files: [{ expand: true, cwd: 'sass', src: '{,**/}*.scss', dest: 'stylesheets', ext: '.css' }] } } }); grunt.loadNpmTasks('grunt-sass'); grunt.registerTask('default', ['sass']); };
import TopInfo from "./components/TopInfo"; import TabTitle from "./components/TabTitle"; import TabContent from "./components/TabContent"; import { Redirect } from "react-router-dom"; import { useSelector } from "react-redux"; export default function Profile({ children }) { const { login } = useSelector((state) => state.user); return ( <> {!login ? ( <Redirect to="/" /> ) : ( <main className="homepage" id="main"> <div> <div className="overlay_nav" /> <main className="profile" id="main"> <section> <TopInfo /> <div className="container"> <div className="tab"> <TabTitle /> <TabContent children={children} /> </div> </div> </section> </main> </div> </main> )} </> ); }
/* global QUnit */ "use strict"; require.config({ "baseUrl": "/test", "paths": { // Local "tests" : "tests", "boros" : "/src/boros", // 3rd Party Hosted "jquery" : "//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min", // CDN "modernizr" : "//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min" }, // Define dependencies "shim" : { "boros" : ["jquery"] } }); require([ "jquery", "modernizr", "tests", "boros" ], function ($) { $(function () { QUnit.load(); QUnit.start(); }); });
var mongoose = require('mongoose'); // for working w/ our database var Schema = mongoose.Schema; var IdServicioSchema = new Schema({ id: Number, }); module.exports = IdServicioSchema;//mongoose.model('User', UserSchema);
import React from "react"; import immage from "./11.jpg"; import SideNav from "./SideNav"; import SearchBar from "./SearchBar"; import { Pane, Popover, Button, Icon, Combobox, Image, Avatar, } from "evergreen-ui"; import ContactTable from "./ContactTable"; function Contact() { return ( <div className="dashboard"> <SideNav /> <div> <SearchBar /> <div className="task-layer1"> <div className="task-row1"> <div className="contact-btn"> <h4>Company</h4> <Button width="auto" height={20} appearance="minimal" iconAfter="caret-down" > All </Button> </div> </div> <div> <div className="task-button"> <Popover content={({ close }) => ( <Pane width={300} height={400}> <div className="avatar-contact"> <Avatar src={immage} name="JK " size={100} isSolid="true" /> <h3>Name</h3> <h4>description</h4> </div> <div> <div className="avatar-contact1"> <h4>Email</h4> <input className="popover2" /> </div> <div className="avatar-contact1"> <h4>Company</h4> <input className="popover2" /> </div> <div className="Contact-cr-btn"> <Button onClick={() => alert("congo")} appearance="primary" > Add </Button> <div> <Button onClick={close} appearance="primary"> Cancell </Button> </div> </div> </div> </Pane> )} > <Button appearance="primary" className="task-button"> Add contact </Button> </Popover> </div> </div> </div> <div className="task-content"> <div> <Pane background="ivory"> <ContactTable /> </Pane> </div> </div> </div> </div> ); } export default Contact;
import React, { Component } from 'react' import './App.css' import MyButton from './components/MyButton' import data from './data/dataset.json' import { Grid } from '@material-ui/core' import Result from './components/Result' import ResultPlaceholder from './components/ResultPlaceholder' import Header from './Header' class App extends Component { state = { currentQuantity: 0, } buttonClicked = (event) => { this.setState({ currentQuantity: event.currentTarget.value }) } render() { return ( <div className="App"> <Header /> <Grid container justify='center' direction='column'> <p style={{marginTop: 30}}><strong>Please choose a class!</strong></p> {this.state.currentQuantity !== 0 ? <Result quantity={this.state.currentQuantity} /> : <ResultPlaceholder />} </Grid> <Grid container justify='center' className='scrollable'> {data.map((record, key) => { return <MyButton key={key} buttonName={record['class'] !== 'undefined' ? record['class'] : 'missing'} onClick={this.buttonClicked} value={record['quantity']} /> })} </Grid> </div> ) } } export default App
/**/ const convolutionSearch=require("./convolution").convolutionSearch; const plist=require("./plist"); const normalize=require("ksana-corpus/diacritics").normalize; const enumBigram=function(cor,t1,t2){ var v1=cor.expandVariant(t1); var v2=cor.expandVariant(t2); var out=[]; if (v1==t1) v1=[t1]; if (v2==t2) v2=[t2]; for (var i=0;i<v1.length;i++) { for (var j=0;j<v2.length;j++) { out.push(v1[i]+v2[j]); } } return out; } // 發菩提心 ==> 發菩 提心 2 2 // 菩提心 ==> 菩提 心 2 1 // 因緣所生法 ==> 因緣 所生 法 2 2 1 // 民國五 == 民國 五 2 1 var splitPhrase=function(cor,simplephrase) { const TokenTypes=cor.tokenizer.TokenTypes; const PUNC=TokenTypes.PUNC; const LATIN=TokenTypes.LATIN; const SPACE=TokenTypes.SPACE; var alltokens=cor.get(["inverted","tokens"])||[]; var tokens=cor.tokenizer.tokenize(simplephrase); while (tokens.length&& tokens[0]&&tokens[0][2]==PUNC) { tokens.shift(); } while (tokens.length&& tokens[tokens.length-1]&& tokens[tokens.length-1][2]==PUNC) { tokens.pop(); } for (var i=0;i<tokens.length;i++) { if (tokens[i][2]===LATIN) { tokens[i][0]=normalize(tokens[i][0]).toLowerCase(); } } tokens=tokens.filter(function(tk){return tk[2]!==PUNC && tk[2]!==SPACE}); var loadtokens=[],lengths=[],j=0,lastbigrampos=-1; var putUnigram=function(token){ var variants=cor.expandVariant(token); if (variants instanceof Array) { variants=variants.filter(function(v){ const at=plist.indexOfSorted(alltokens,v); return (at>-1 && alltokens[at]==v); }); if (variants.length==1) variants=variants[0]; } loadtokens.push(variants); lengths.push(1); } while (j+1<tokens.length) { var token=tokens[j][0]; var nexttoken=tokens[j+1][0]; const possiblebigrams=enumBigram(cor,token,nexttoken); const bi=[]; for (var k=0;k<possiblebigrams.length;k++) { var i=plist.indexOfSorted(alltokens,possiblebigrams[k]); if (alltokens[i]===possiblebigrams[k]) { bi.push(possiblebigrams[k]); } } if (bi.length) { bi.length==1?loadtokens.push(bi[0]):loadtokens.push(bi); lengths.push(2); j++; } else { putUnigram(token); } j++; } var totallen=lengths.reduce(function(r,a){return r+a},0); while (totallen<tokens.length) { token=tokens[j][0]; putUnigram(token); j++; totallen++; } return {tokens:loadtokens, lengths: lengths , tokenlength: tokens.length}; } const nativeMergePostings=function(cor,paths,cb){ cor.get(paths,{address:true},function(postingAddress){ //this is sync var postingAddressWithWildcard=[]; for (var i=0;i<postingAddress.length;i++) { postingAddressWithWildcard.push(postingAddress[i]); if (splitted.lengths[i]>1) { postingAddressWithWildcard.push([splitted.lengths[i],0]); //wildcard has blocksize==0 } }; cor.mergePostings(postingAddressWithWildcard,function(r){ cor.cachedPostings[phrase]=r; cb(phrase_term); }); }); } var postingPathFromTokens=function(engine,tokens) { if (typeof tokens=="string") tokens=[tokens]; const alltokens=engine.get(["inverted","tokens"]); var postingid=[]; for (var i=0;i<tokens.length;i++) { const at=plist.indexOfSorted(alltokens,tokens[i]); if (at>-1 && alltokens[at]==tokens[i]) postingid.push(at); } return postingid.map(function(t){return ["inverted","postings",t]}); } const getPostings=function(cor,tokens,cb){ var paths=[]; const out=[]; for (var i=0;i<tokens.length;i++){ const token=tokens[i]; const path=postingPathFromTokens(cor,token); if (path.length==1) { out.push([token,1]); //posting count =1 paths.push(path[0]); } else { //need to merge postings const cached=cor.cachedPostings[token]; if (cached) { out.push([token,cached]); } else { out.push([token,path.length]); //posting count paths=paths.concat(path); } } } cor.get(paths,function(postings){ var now=0,i=0; for (var i=0;i<out.length;i++) { const postingcount=out[i][1]; if (postingcount instanceof Array) { continue;//from cache } const tokenpostings=[]; for (var j=0;j<postingcount;j++) { tokenpostings.push(postings[now]); now++; } const combined=plist.combine(tokenpostings); const key=out[i][0]; if (tokenpostings.length>1) { cor.cachedPostings[key.join(",")]=combined; } out[i][1]=combined; } const outtokens=out.map(function(o){return o[0]}); const outpostings=out.map(function(o){return o[1]}); cb(outtokens,outpostings); }); } const simplePhrase=function(cor,phrase,cb){ const splitted=splitPhrase(cor,phrase.trim()); if (cor.mergePostings) { //native search doesn't support variants var paths=postingPathFromTokens(cor,splitted.tokens); nativeMergePosting(cor,paths,cb); return; } getPostings(cor,splitted.tokens,function(tokens,postings){ var out=postings[0],dis=splitted.lengths[0]; for (var i=1;i<postings.length;i++) { var post=postings[i]; out=plist.pland(out,post,dis); dis+=splitted.lengths[i]; } cor.cachedPostings[phrase]=out; cb({phrase:phrase,postings:out,lengths:splitted.tokenlength}); //fix length }); } //如夢幻泡沫。 const fuzzyPhrase=function(cor,phrase,cb){ //return postings and lengths and score phrase=phrase.replace(/[  ]/g,""); convolutionSearch(cor,phrase,{},function(res){ const matches=res.matches.map(function(a){return a[0]}); const scores=res.matches.map(function(a){return a[1]}); cb({scores:scores,matches:matches,phrasepostings:res.phrasepostings, count:res.matches.length,phrase:phrase,lengths:0,fuzzy:true}); }); } module.exports={simplePhrase:simplePhrase,fuzzyPhrase:fuzzyPhrase}
function popLoginForm () { var loginForm = document.getElementById('login-form') if (loginForm.getAttribute('style').indexOf('display') === -1 || loginForm.getAttribute('style').indexOf('display: initial;') !== -1) { loginForm.setAttribute('style', 'display: none;') } else { loginForm.setAttribute('style', 'display: initial;') } new Popper( document.getElementById('login-btn'), document.getElementById('login-form'), { placement: 'bottom' } ) } if (document.getElementById('login-btn')) document.getElementById('login-btn').onclick = popLoginForm window.onload = function () { var loginForm = document.getElementById('login-form') loginForm.setAttribute('style', 'display: none;') }
import React from "react"; import { joinGroupCall } from "../../utils/webRTC/webRTCGroupCallHandler"; import { useSelector } from "react-redux"; const GroupCallRoomListItem = ({ room }) => { const handleListItemPressed = (room) => { joinGroupCall(room.socketId, room.roomId); }; const { groupCallActive } = useSelector((state) => state.call); return ( <button className="w-40 px-4 border-t-2 border-r-2 border-customBlack flex justify-center items-center bg-customBlue cursor-pointer hover:bg-opacity-40" key={room.id} onClick={() => { handleListItemPressed(room); }} disabled={groupCallActive} > <h3 className="text-xl text-customWhite font-bold">{room.hostname}</h3> </button> ); }; export default GroupCallRoomListItem;
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/chat_list/chat/_float_building_card" ], { "3a80": function(n, t, e) { var a = e("8ef3"); e.n(a).a; }, "7e9f": function(n, t, e) { e.d(t, "b", function() { return a; }), e.d(t, "c", function() { return o; }), e.d(t, "a", function() {}); var a = function() { var n = this; n.$createElement; n._self._c; }, o = []; }, "8e90": function(n, t, e) { e.r(t); var a = e("7e9f"), o = e("b080"); for (var c in o) [ "default" ].indexOf(c) < 0 && function(n) { e.d(t, n, function() { return o[n]; }); }(c); e("3a80"); var i = e("f0c5"), u = Object(i.a)(o.default, a.b, a.c, !1, null, "66e3da28", null, !1, a.a, void 0); t.default = u.exports; }, "8ef3": function(n, t, e) {}, b080: function(n, t, e) { e.r(t); var a = e("e0b1"), o = e.n(a); for (var c in a) [ "default" ].indexOf(c) < 0 && function(n) { e.d(t, n, function() { return a[n]; }); }(c); t.default = o.a; }, e0b1: function(n, t, e) { Object.defineProperty(t, "__esModule", { value: !0 }), t.default = void 0; var a = { props: { building: { type: Object } }, data: function() { return { show: !0 }; }, mounted: function() { var n = this; setTimeout(function() { n.show = !1; }, 1e4); }, methods: { send: function() { this.$emit("send"), this.show = !1; } } }; t.default = a; } } ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/chat_list/chat/_float_building_card-create-component", { "pages/chat_list/chat/_float_building_card-create-component": function(n, t, e) { e("543d").createComponent(e("8e90")); } }, [ [ "pages/chat_list/chat/_float_building_card-create-component" ] ] ]);
import "./featuredInfo.css"; import AllInclusiveOutlinedIcon from '@material-ui/icons/AllInclusiveOutlined'; import AccountCircleOutlinedIcon from '@material-ui/icons/AccountCircleOutlined'; import { useEffect, useState } from 'react'; import TestDataService from "../../../services/tests.service"; import { Link } from "react-router-dom"; export default function FeaturedInfoo() { const [all, setAll] = useState([]); useEffect(() => { retieveAllTests(); }, []); const retieveAllTests = () => { TestDataService.getAll() .then(response => { setAll(response.data) }) .catch(err => { console.log("Error while getting data from database" + err); } ) }; const alltest = all.length; return ( <Link to={"/staff/labassistant/patients"} style={{ color: 'inherit', textDecoration: "none" }}> <div className="featured"> <div className="featuredItem"> <span className="featuredTitle">All Tests</span> <div className="featuredMoneyContainer"> <span className="featuredMoney">{alltest}</span> <span className="featuredMoneyRate"> <AllInclusiveOutlinedIcon className="featuredIcon" /> </span> </div> <span className="featuredSub">All tests in every state</span> </div> <div className="featuredItem"> <span className="featuredTitle">My patients</span> <div className="featuredMoneyContainer"> <span className="featuredMoney">{alltest}</span> <span className="featuredMoneyRate"> <AccountCircleOutlinedIcon className="featuredIcon" /> </span> </div> <span className="featuredSub">All the patients</span> </div> </div> </Link> ); }
import { useState, useEffect } from 'react' import { Block } from '../../components/Block'; import { Button } from '../../components/Button'; import { Counter } from '../../components/Counter'; import './TicTacToe.css'; export function TicTacToe(){ const [tMatrix, setTMatrix] = useState([ [-1, -1, -1], [-1, -1, -1], [-1, -1, -1], ]); const [currentPlayer, setCurrentPlayer] = useState(3); const [winnerName,setWinnerName] = useState(''); const winCombinations = ["00,01,02","00,10,20","00,11,22","10,11,12","20,21,22","02,12,22","01,11,21","02,12,22","20,11,02"]; function reset(){ setTMatrix([ [-1, -1, -1], [-1, -1, -1], [-1, -1, -1], ]); setCurrentPlayer(3); setWinnerName(''); } useEffect(()=>{ detectWinner(); },[tMatrix]) // useEffect(()=>{ // console.log("entered"); // return ()=>{ // console.log("exit"); // } // },[]) function detectWinner(){ let sum; let won = winCombinations.some((combination) =>{ sum = 0; // ["10","11","12"] combination.split(',').forEach((item)=>{ sum = sum + tMatrix[item[0]][item[1]] }); return (sum === 9 || sum ===12) }); if(won){ setWinnerName(sum === 9?'X':sum===12?'O':''); } } function onBlockClick(id){ if(winnerName||tMatrix[parseInt(id/3)][id%3]>-1){ return; } setTMatrix((m)=>{ let temp = [...m]; temp[parseInt(id/3)][id%3] = currentPlayer; return temp; }); setCurrentPlayer((v)=>v===3?4:3); } return ( <div className="t3-container"> <h1>Tic Tac Toe</h1> <div className="game-info"> <h2>Turn for Player <span ></span></h2> <Button text="Reset" onClick={reset} /> </div> <h2> { winnerName && ("Player "+ winnerName+ " Wins") } </h2> <div className="game-container"> <Block value={tMatrix[0][0]} id={0} onBlockClick={onBlockClick} /> <Block value={tMatrix[0][1]} id={1} onBlockClick={onBlockClick} /> <Block value={tMatrix[0][2]} id={2} onBlockClick={onBlockClick} /> <Block value={tMatrix[1][0]} id={3} onBlockClick={onBlockClick} /> <Block value={tMatrix[1][1]} id={4} onBlockClick={onBlockClick} /> <Block value={tMatrix[1][2]} id={5} onBlockClick={onBlockClick} /> <Block value={tMatrix[2][0]} id={6} onBlockClick={onBlockClick} /> <Block value={tMatrix[2][1]} id={7} onBlockClick={onBlockClick} /> <Block value={tMatrix[2][2]} id={8} onBlockClick={onBlockClick} /> </div> </div> ) }
export const COMMON_API = 'COMMON_API';
// Otaku类 抽象概念 function Otaku(name, age){ this.name = name; this.age = age; this.habit = 'Games'; } Otaku.prototype.strenth = 60; Otaku.prototype.sayYourName = function() { console.log('I am ' + this.name); } // new // 1. 返回一个实例{} 拥有Otaku 函数中加的那些属性 // 2. 让我们的实例访问到 Otaku.prototype 中的属性 // new? js 关键字 function objectFactor(fn, ...args){ // 返回新的空的对象 console.log(arguments); var obj = new Object(), Constructor = [].shift.call(arguments); console.log(arguments); Constructor.apply(obj, arguments); // this指向新的对象 // 让Constructor执行 // fn.apply(obj, ...args) obj.__proto__ = Constructor.prototype console.log(obj.__proto__) console.log(obj.prototype) console.log(fn.prototype) console.log(Constructor.prototype) return obj; } // 1. 构造函数 // 2. 其余是构造函数需要的参数 const didi = objectFactor(Otaku,'sasuke',18);
import React, { Component } from 'react'; import { Image } from 'react-native'; import { style } from './style'; import Linear from 'react-native-linear-gradient'; import { Colors } from './../../../app.json'; class Splash extends Component { componentDidMount() { setTimeout(() => { this.props.navigation.replace('Home'); }, 4000); } render() { const { container, logo } = style; return ( <Linear colors={[Colors.red, Colors.mauve, Colors.dark]} style={container}> <Image source={require('./../../assets/logo.png')} style={logo} /> </Linear> ); } } export default Splash;
const path = require('path'); const config = require('../config'); const {getHash, getDirectoryName, callGit} = require('../utils'); const {asyncErrorHandler, repoNotFoundHandler} = require('../handlers'); const execFile = require("util").promisify(require("child_process").execFile); const status = require('../status'); const {params} = config; module.exports = repoNotFoundHandler(asyncErrorHandler(async (req, res) => { const { [params.repositoryId]: repo, [params.commitHash]: commit, } = req.params; const repoPath = path.join(rootDirPath, getDirectoryName(repo)); const hash = await getHash(repoPath, commit, true); if (!hash) { return res.sendStatus(status.notFound); } const diff = await callGit(execFile, ['log', '-p', '--pretty=format:', hash, '-1'], repoPath, true); return res.json({diff}); }));
var searchData= [ ['highscores_60',['highscores',['../group__menu.html#ga4b3d6369d7f9c546acbe8bd725f27292',1,'menu.h']]], ['highscores_2eh_61',['highscores.h',['../highscores_8h.html',1,'']]], ['hm_62',['hm',['../group__makecodes.html#gad7777d60e2b4b4776da8b789605fcf9a',1,'makecodes.h']]], ['hold_63',['HOLD',['../group__mouse.html#ggadc6e5733fc3c22f0a7b2914188c49c90a9cfa27b414cab750fb14ec07cdf5cf6a',1,'mouse.h']]], ['hour_64',['hour',['../struct__l__elemento.html#a26d5bae76d83086900174b266fd2cd82',1,'_l_elemento']]], ['hpont_65',['hpont',['../group__makecodes.html#gae1fa8897ff6089384a1c55b1c90351dd',1,'makecodes.h']]] ];
import Ember from 'ember'; Ember.calculator = Ember.Object.extend({ numbers: [], input: 0, sum: Ember.computed.sum('numbers') }); export default Ember.Route.extend({ model() { return Ember.calculator.create(); }, actions: { addNumber: function(calculator) { calculator.get("numbers").pushObject(Number(calculator.get("input"))); } } });
import { classNameBindings } from '@ember-decorators/component'; import BaseDropDown from 'ember-bootstrap/components/base/bs-dropdown'; @classNameBindings('inNav:nav-item', 'isOpen:show') export default class Dropdown extends BaseDropDown {}
function highlightUsername(message) { var username = $('#username').val(); if ($.trim(username)) { var usernameRegex = new RegExp(username,"gi"); message = message.replace(usernameRegex, function myFunction(match) { return "<span class='username'>" + match + "</span>" }); } return message; } function addLines(data) { $.each(data, function(i, chatline) { $('ul').prepend('<li><span class="username">&lt;' + chatline.username + "&gt;</span> <span class='message'>" + highlightUsername(chatline.message) + "</span>"); }); } function updateTimestamp(data) { if (data[data.length-1]) { $('#since').val(data[data.length-1].timestamp); } } function clearForm() { $('#message').val(''); } function ajaxRequest(data) { var ajaxOptions = { url: '/chat', type: 'POST', data: data }; return $.ajax(ajaxOptions).success(addLines).success(updateTimestamp); } $(function() { $('form').on('submit', function(ev) { ev.preventDefault(); ajaxRequest({ 'username': $('#username').val(), 'message': $('#message').val(), 'since': $('#since').val() }).success(clearForm); }); // uncomment to make app update chats every two seconds setInterval(function() { ajaxRequest( {'since': $('#since').val()} ) }, 2000); });
import React from 'react'; import { NativeSelect, InputLabel, Switch, Slider } from '@material-ui/core'; import { ChromePicker } from 'react-color'; class LedControl extends React.Component { constructor() { super(); this.state = { colorValue: {r: 255, g: 10, b: 10}, style: "", kwargs: { red: 255, green: 10, blue: 10, brightness: 1, speed: 10, reverse: false, animation: "instant", animation_speed: 20, step: 1, }, isLoading: true, error: null } this.effects = { "staticColor": { prettyName: "Static Color", speed: false, reverse: false, animation: true, rgb: true, brightness: true, animation_speed: true, step: false, }, "rainbowCycle": { prettyName: "Rainbow Cycle", speed: true, reverse: true, animation: false, rgb: false, brightness: true, animation_speed: false, step: false, }, "rainbowBreathing": { prettyName: "Rainbow Breathing", speed: true, reverse: true, animation: true, rgb: false, brightness: true, animation_speed: true, step: true, } } this.animations = { "instant": "Instant", "colorWipe": "Color Wipe", "colorWipeTwoSided": "Color Wipe Two Sided" } this.post = this.post.bind(this) this.changeStyle = this.changeStyle.bind(this) this.changeAnimation = this.changeAnimation.bind(this) this.changeBrightness = this.changeBrightness.bind(this) this.changeSpeed = this.changeSpeed.bind(this) this.changeAnimationSpeed = this.changeAnimationSpeed.bind(this) this.changeStep = this.changeStep.bind(this) this.changeReverse = this.changeReverse.bind(this) this.changeColor = this.changeColor.bind(this) this.handleChange = this.handleChange.bind(this) } async componentDidMount() { try { fetch('http://192.168.1.214:5000/get_lights') .then(res => res.json()) .then(data => { console.log(data); this.setState({ style: data.style, kwargs: data.kwargs, isLoading: false }, () => { this.state.colorValue = {r: this.state.kwargs.red, g: this.state.kwargs.green, b: this.state.kwargs.blue} }); }) } catch (error) { this.setState({ error: error.message, isLoading: false }); } } changeStyle(event) { this.setState({ style: event.target.value }, () => { this.post(); }); } changeAnimation(event) { this.setState({ kwargs: { ...this.state.kwargs, animation: event.target.value} }, () => { this.post(); }); } changeBrightness(_, newValue) { this.setState({ kwargs: { ...this.state.kwargs, brightness: newValue} }, () => { this.post(); }); } changeSpeed(_, newValue) { this.setState({ kwargs: { ...this.state.kwargs, speed: newValue} }, () => { this.post(); }); } changeAnimationSpeed(_, newValue) { this.setState({ kwargs: { ...this.state.kwargs, animation_speed: newValue} }, () => { this.post(); }); } changeStep(_, newValue) { this.setState({ kwargs: { ...this.state.kwargs, step: newValue} }, () => { this.post(); }); } changeReverse(event) { this.setState({ kwargs: { ...this.state.kwargs, reverse: event.target.checked} }, () => { this.post(); }); } changeColor(color) { this.setState({ kwargs: { ...this.state.kwargs, red: color.rgb.r, green: color.rgb.g, blue: color.rgb.b} }, () => { this.post(); }); } handleChange(color) { this.setState({ colorValue: color.rgb }) } post() { fetch('http://192.168.1.214:5000/change_lights', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ style: this.state.style, kwargs: this.state.kwargs, }) }).then(response => { console.log(response) }) } renderLed = () => { const { style, kwargs, isLoading, error } = this.state; if (error) { return <div>{error}</div>; } if (isLoading) { return <div>Loading...</div>; } return ( <form> <div class="row row-space"> <div class="col"> <div class="input-group"> <label class="label">Effect</label> <div class="w-100"> <NativeSelect id="select1" value={style} onChange={this.changeStyle}> {Object.keys(this.effects).map(effect => <option value={effect}>{this.effects[effect].prettyName}</option> )} </NativeSelect> </div> </div> </div> </div> {(() => { if (this.effects[style].animation) { return ( <div class="row row-space"> <div class="col"> <div class="input-group"> <label class="label">Animation</label> <div class="w-100"> <NativeSelect id="select2" value={kwargs.animation} onChange={this.changeAnimation}> {Object.keys(this.animations).map(animation => <option value={animation}>{this.animations[animation]}</option> )} </NativeSelect> </div> </div> </div> </div> ) } })()} {(() => { if (this.effects[style].brightness) { return ( <div class="row row-space"> <div class="col"> <div class="mb-1 input-group"> <label class="label">Brightness</label> <div class="w-100"> <Slider onChangeCommitted={this.changeBrightness} defaultValue={kwargs.brightness} aria-labelledby="brightness_slider" step={0.01} min={0} max={1} valueLabelDisplay="auto" /> </div> </div> </div> </div> ) } })()} {(() => { if (this.effects[style].rgb) { return ( <div class="row row-space"> <div class="col"> <div class="input-group"> <label class="label">Color</label> <div class="w-100"> <ChromePicker color={ this.state.colorValue} onChange={ this.handleChange } onChangeComplete={ this.changeColor } /> </div> </div> </div> </div> ) } })()} {(() => { if (this.effects[style].speed) { return ( <div class="row row-space"> <div class="col"> <div class="input-group"> <label class="label">Speed</label> <div class="w-100"> <Slider onChangeCommitted={this.changeSpeed} defaultValue={kwargs.speed} aria-labelledby="speed_slider" step={1} min={0} max={100} valueLabelDisplay="auto" /> </div> </div> </div> </div> ) } })()} {(() => { if (this.effects[style].animation_speed && this.state.kwargs.animation != "instant") { return ( <div class="row row-space"> <div class="col"> <div class="input-group"> <label class="label">Animation Speed</label> <div class="w-100"> <Slider onChangeCommitted={this.changeAnimationSpeed} defaultValue={kwargs.animation_speed} aria-labelledby="animation_speed_slider" step={1} min={0} max={100} valueLabelDisplay="auto" /> </div> </div> </div> </div> ) } })()} {(() => { if (this.effects[style].step) { return ( <div class="row row-space"> <div class="col"> <div class="input-group"> <label class="label">Step</label> <div class="w-100"> <Slider onChangeCommitted={this.changeStep} defaultValue={kwargs.step} aria-labelledby="step_slider" step={1} min={1} max={100} valueLabelDisplay="auto" /> </div> </div> </div> </div> ) } })()} {(() => { if (this.effects[style].reverse) { return ( <div class="row row-space"> <div class="col"> <div class="input-group"> <label class="label">Reverse</label> <div class="w-100"> <Switch checked={kwargs.reverse} onChange={this.changeReverse} color="Primary" /> </div> </div> </div> </div> ) } })()} </form> ); }; render() { return <div>{this.renderLed()}</div>; } } export default LedControl;
#pragma strict // Provides the dragging behavior whereby the assembly is dragged around across all the other surfaces in the scene. // option-drag (alt-drag) copies before dragging. // option-click (alt-click) deletes // click tries goto (and removes gizomo). // It is expected that something is else is taking care of adding and removing the gizmo, and ensuring that nothing is // highlighted before we start (as that will just get confusing during copy). // For example, the assembly's mesh/collider must be on the IgnoreRaycast = 2 layer. // The affordance that this script is attached to should be bit smaller than the assembly bounding box: // 1. This allows there to be no confusion as to whether a strike near the corner is hitting us or a corner affordance, as the corners lie outside our (shrunken) box. // 2. For cubes, when we project from affordance to mounting surface and back, we certainly won't miss an edge. // TODO: // reverse hit for skinny meshes: // Push the selectedHit a bit towards the go center, so that we don't miss the edge on reversal. // var bounds = obj.bounds(); // selectedHit += (bounds.center - selectedHit).normalized * 0.1; class Sticky extends ColorInteractor { // We are used with corner Adjust scripts, which brodcast 'updateAffordance' as they doDragging. private var assemblyObj:Obj; function updateAffordance() { //As other interactors resize assembly during movement, keep affordance at proper size. // WARNING: There is a bug in the Unity-provided CharacterMotor script, such that if it has movingPlatform.enabled, // the following line can cause avatars to go flying around. The AddAdjuster code below is careful to // try to reuse Adjusters, and thus if the floor is adjustable, CharacterMoter will see the "same" moving platform // change radically and treat that as movenent. transform.localScale = assemblyObj.size() * 0.99; } private var transparency:Renderer; // the display of the transparent box is toggleable. function Awake() { highlightColor = makeAlpha(Vector3(0.902, 0.91, 0.847)); // a shade of Facebook split-complement-1 super.Awake(); transparency = transform.Find('display').GetComponent.<Renderer>(); } function OnDestroy() { if (!!assemblyObj) { SetAssemblyLayer(assemblyObj.mesh, originalAssemblyLayer); } super.OnDestroy(); } // Management of the whole gizmo (e.g., six-axis corner affordances with Adjust scripts, too). public static var StickyInstance:Sticky; // Allow just one, globally private var isMaximal = true; function makeMaximal(max:boolean) { yield 1; if (max == isMaximal) return; for (var axis:Transform in transform.parent) { if ((axis == transform) || (axis.name == 'Y')) continue; for (var aff:Transform in axis) { var adj = aff.gameObject.GetComponent.<Adjust>(); var col = adj.affordanceCollider; col.enabled = max; col.GetComponent.<Renderer>().enabled = max; } } isMaximal = max; } private var originalAssemblyLayer = 0; function updateAssembly(assy:Transform) { // We supply our own affordance that is just a bit smaller than the assembly bbox (so that we don't interfere with corner affordances). // So here we turn of the assembly's own collider, and re-enable it OnDestroy and here. if (!!assemblyObj) SetAssemblyLayer(assemblyObj.mesh, originalAssemblyLayer); super.updateAssembly(assy); if (!assy) { // on instantiation without parent assemblyObj = null; } else { assemblyObj = assy.gameObject.GetComponent.<Obj>(); originalAssemblyLayer = SetAssemblyLayer(assemblyObj.mesh, 2); makeMaximal(assemblyObj.kind != 'Plane'); } } function unparentGizmo(assy:Transform):Transform { var gizmo = StickyInstance.transform.parent; gizmo.parent = null; return gizmo; } public static function AddAdjuster(assy:Transform, adjusterPrefab:Transform) { // Add adjusterPrefab as a child of assy. if (AnyMoving) { return; } // Don't mess up an existing drag. var obj = assy.GetComponent.<Obj>(); if (obj.frozen) { return; } var gizmo:Transform; //if (!!StickyInstance) RemoveAdjuster(); // for debugging if (!StickyInstance) { gizmo = Instantiate(adjusterPrefab, assy.transform.position, assy.transform.rotation); StickyInstance = gizmo.Find('StrikeTarget').GetComponent.<Sticky>(); gizmo.name = 'Adjuster'; // I.e., not "Adjuster (clone)" gizmo.parent = assy; AnyActive = true; StickyInstance.isActive = true; } else if (StickyInstance.assembly == assy) { return; } else { var striker = StickyInstance.transform; striker.localScale = Vector3(0.01, 0.01, 0.01); // If a big gizmo gets reparented underneath us, we'll go flying. gizmo = striker.parent; gizmo.parent = assy; // Reparenting maintains global position, so we need to reset these. gizmo.localPosition = Vector3.zero; gizmo.localRotation = Quaternion.identity; } var go = gizmo.gameObject; go.BroadcastMessage('updateAssembly', assy, SendMessageOptions.DontRequireReceiver); go.BroadcastMessage('updateAffordance', null, SendMessageOptions.DontRequireReceiver); // get the size right go.BroadcastMessage('sizeAffordances', obj.scalar(0.0)); } public static function RemoveAdjuster(immediate:boolean) { Debug.Log('RemoveAdjuster instance=' + StickyInstance); if (!StickyInstance) return; if (immediate) { SetAssemblyLayer(StickyInstance.transform.parent.gameObject, 2); // Get the StrikeTarget out of the way SetAssemblyLayer(StickyInstance.assemblyObj.mesh, StickyInstance.originalAssemblyLayer); // now, without waiting until destroy } Destroy(StickyInstance.transform.parent.gameObject); AnyMoving = false; StickyInstance = null; } public static function RemoveAdjuster() { RemoveAdjuster(false); } private static var TransparencyOn = false; function Update() { // handle transparenc and delete. (Note that only one Sticky is present, so this isn't repeated.) if (Input.GetKeyDown(KeyCode.T) && Input.GetKey(KeyCode.LeftControl)) { TransparencyOn = !TransparencyOn; } transparency.enabled = TransparencyOn; if ((Input.GetKeyDown(KeyCode.Delete)|| Input.GetKeyDown(KeyCode.Backspace)) // this adjuster might have been left on an obj that is different than a frozen (no adjuster) selected object. && !!Obj.SelectedObj && !Obj.SelectedObj.frozen) { Obj.SelectedObj.deleteObject(); // which does a save as well. return; } super.Update(); } // The core activities of an Interactor: startDragging, resetCast/doDragging, stopDragging public var pivotPrefab:Transform; private var cursorOffsetToSurface:Vector3 = Vector3.zero; private var lastDragPosition:Vector3; private var firstDragPosition:Vector3; // For debouncing click vs drag; private var rt1:Vector3; private var fwd1:Vector3; private var originalCopied:GameObject; // during a copy drag, this holds the original prototype of the copy. private var draggedOriginalLayer = 0; // of the whole assembly, not just the Obj.mesh var lastSurface:Collider; // Keep track of this during dragging so that we can reparent at end. function startDragging(assembly:Transform, cameraRay:Ray, hit:RaycastHit):Laser { lastSurface = null; var go = assembly.gameObject; var obj = go.GetComponent.<Obj>(); if (!!Input.GetAxis('Fire2')) { // alt/option key // Transfer gizmo to copy. Can't destroy it because it has state (including our own executing code). var gizmo = unparentGizmo(assembly); originalCopied = go; var originalObj = assemblyObj; go = Instantiate(go, assembly.position, assembly.rotation); assembly = go.transform; gizmo.parent = assembly; assembly.parent = originalCopied.transform.parent; assembly.BroadcastMessage('updateAssembly', assembly, SendMessageOptions.DontRequireReceiver); // assemblyObj is side-effected by updateAssembly. assemblyObj.sharedMaterials(obj.sharedMaterials()); assemblyObj.renamePlace(true); // rename if it's a place. obj = assemblyObj; // If we're making a copy, the first dragging movement will always intersect the original object, and // we'll instantly jump out from that surface as we try to mount the copy onto the original. Even if // that's what the user ultimately wants, they still don't wan the jump. So, if we're working with a copy, // don't count the original until the user has finished that first copying drag. // I tried more complicated variants, such as ignoring the original only until we've 'cleared' away // from it, but couldn't make them work. draggedOriginalLayer = SetAssemblyLayer(originalCopied, 2); } else if (!!Input.GetAxis('Fire3')) { // cmd key var select = AvatarSelectComp(); if (!!select) { obj.ExternalPropertyEdit('properties', false); select.StartGizmo(assembly.gameObject); } return null; } var mountingDirection = obj ? assembly.TransformDirection(obj.localMounting) : -assembly.up; // Two Tests: // First we project the hit.point along the mountingDirection until we hit // a surface to slide along. No surface means we give up. // FIXME: the reverse projection, below, will miss for skinny meshes that lie inside the affordance box's original hit.point. // We should re-cast this to the objectCollider, then go towards the center a bit, before projecting down to a surface. var surfaceHit:RaycastHit; var selectedHit = hit.point; // Start with where the user clicked on the affordance. // Any object on any (non-ignored) layer will do. (No layer mask.) if (!Physics.Raycast(selectedHit, mountingDirection, surfaceHit)) { // Should we also check for being too far away? I think we might always want to let the object fall to floor (no matter what height), // but it does seem spooky to let an object slide to a wall across the room (e.g., if we're rotated to make the mountingDirection be sideways). // For now, no distance test. Debug.Log("Nothing under object to slide along."); // FIXME: create some sort of animation that shows that there's nothing under the mounting direction. surfaceHit = hit; } else { // Now the reverse: the surfaceHit.point back to the assembly Obj's collider. var reverseHit:RaycastHit; // But use a point "below" the hit.point (into surface, by depth of object) so we can catch embedded objects. var embeddedPoint = surfaceHit.point + (mountingDirection * obj.size().magnitude); var reverseRay = Ray(embeddedPoint, -mountingDirection); var offset = Vector3.zero; var col = obj.objectCollider(); var isMeshCollider = col.GetType().Name == 'MeshCollider'; var oldConvex = isMeshCollider && (col as MeshCollider).convex; if (isMeshCollider) (col as MeshCollider).convex = true; // so raycast can hit back of plane if (col.Raycast(reverseRay, reverseHit, Mathf.Infinity)) { offset = surfaceHit.point - reverseHit.point; /*Debug.Log('hit10:' + (10 * selectedHit) + '@' + hit.collider + ' surface10:' + (10 * surfaceHit.point) + '@' + surfaceHit.collider + ' reverse10:' + (10 * reverseHit.point) + '@' + reverseHit.collider + ' offset10:' + (10 * offset));*/ // FIXME: For any non-trivial offset, this should be animated. assembly.position += offset; } else { Debug.LogError('** No reverse hit! ** hit:' + surfaceHit.point + ' mounting:' + mountingDirection + ' embedded:' + embeddedPoint); } if (isMeshCollider) (col as MeshCollider).convex = oldConvex; } // Set drag state firstDragPosition = surfaceHit.point; lastDragPosition = firstDragPosition; rt1 = assembly.right; fwd1 = assembly.forward; var contact:Vector3 = Camera.main.WorldToScreenPoint(lastDragPosition); contact.z = 0; cursorOffsetToSurface = contact - Input.mousePosition; // Setup up pivot. var pivot = Instantiate(pivotPrefab, lastDragPosition, assembly.rotation); if (pivot.parent) Debug.LogError('*** FIXME Select:StartDragging Non-null pivot parent ' + pivot.parent); if (pivot.localScale != Vector3(1, 1, 1)) Debug.LogError('*** FIXME Select:StartDragging Non-unity pivot scale ' + pivot.localScale); pivot.parent = assembly.parent; // No need to worry about scale screwing things up, because Obj assemblies always have unitary localScale. assembly.parent = pivot; // During drag, we have to get the whole assembly out of the way, so that we don't intersect with child objects and bounce around. // It's ok that originalAssemblyLayer might already be set for a copy -- the value would be the same anyway. originalAssemblyLayer = SetAssemblyLayer(assembly.gameObject, 2); gameObject.layer = 8; // Get our StrikeTarget out of the way. Don't change children, nor make StrikeTarget stop getting OnMouseEnter/Exit at all. // FIXME: animate laser movement from hit.point to surfaceHit.point. hit.point = surfaceHit.point; // so that Laser.StartInteraction() can do the right thing. return AvatarLaserComp(); } function stopDragging(assembly:Transform) { // StrikeTarget must normally be on the same layer as other objects (Default). Otherwise large but covered StrikeTargets would // soak up DoAdjuster.OnMouseEnter events from the objects that cover it. gameObject.layer = 0; // restore our StrikeTarget to Default layer. SetAssemblyLayer(assembly.gameObject, originalAssemblyLayer); var original = originalCopied; // pun: we're setting the WHOLE original obj, which will RESET it's Obj.mesh to behave normally, even if we've messed with it. if (!!original) SetAssemblyLayer(original, draggedOriginalLayer); originalCopied = null; var newParent = Obj.ColliderGameObject(lastSurface); var pivot = assembly.parent; assembly.parent = (newParent == null) ? pivot.parent : newParent.transform; // Destroy merely schedules destruction. We don't want pivot in the hierarchy (e.g., during saving). pivot.parent = null; Destroy(pivot.gameObject); // Test for movement must be here rather than DoDragging, because we might not receive any DoDragging events. if (Vector3.Distance(firstDragPosition, lastDragPosition) > 0.2) { // real movement, not just a click if (!!original) { Save.AddTabItem(assembly); } assembly.gameObject.GetComponent(Obj).saveScene(!!original ? 'copy' : 'move'); } else if (!!original) { assembly.parent = null; Destroy(assembly.gameObject); // the copy. us. original.GetComponent.<Obj>().deleteObject(); // which does a save as well. } else { AvatarGoto(assembly, true); } } // We cast only against the Default layer (0). E.g., we don't want this to catch the gizmo on the HUD layer (8), nor assembly on IgnoreRaycast(2). function resetCast(hit:RaycastHit[]):boolean { // overridable method to get new hit.point during drag return Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition + cursorOffsetToSurface), hit[0], Mathf.Infinity, (1<<0)); } function doDragging(assembly:Transform, hit:RaycastHit) { var delta = hit.point - lastDragPosition; //Debug.Log('collider:' + hit.collider + ' last10:' + (10 * lastDragPosition) + ' hit10:' + (10 * hit.point) + ' delta10:' + (10 * delta)); lastDragPosition = hit.point; lastSurface = hit.collider; var pivot = assembly.parent; pivot.Translate(delta, Space.World); var norm:Vector3 = HitNormal(hit); var alignedX:boolean = Mathf.Abs(Vector3.Dot(rt1, norm)) > 0.9; var fwd:Vector3 = alignedX ? fwd1 : Vector3.Cross(rt1, norm); pivot.rotation = Quaternion.LookRotation(fwd, norm); } // Utilities public static function SetAssemblyLayer(go:GameObject, layer:int):int { // set or restore IgnoreRaycast of an object with collider, returning old layer //Debug.Log('set ' + go + ' layer from ' + go.layer + ' to ' + layer); var old = go.layer; go.layer = layer; for (var child:Transform in go.transform) { if (child.tag != 'FixedLayer') SetAssemblyLayer(child.gameObject, layer); } return old; } public static function HitNormal(hit:RaycastHit) { // answer normal to the surface at hit.point, for meshes and primitives // Just in case, also make sure the collider also has a renderer material and texture var meshCollider = hit.collider as MeshCollider; //Debug.LogWarning('collider=' + (meshCollider ? meshCollider : 'null') + ' parent=' + (meshCollider ? meshCollider.transform.parent : 'null')); if (meshCollider == null || meshCollider.sharedMesh == null) { // Debug.LogWarning('using hit.normal'); return hit.normal; } var mesh : Mesh = meshCollider.sharedMesh; var normals = mesh.normals; var triangles = mesh.triangles; // Extract local space normals of the triangle we hit var n0 = normals[triangles[hit.triangleIndex * 3 + 0]]; var n1 = normals[triangles[hit.triangleIndex * 3 + 1]]; var n2 = normals[triangles[hit.triangleIndex * 3 + 2]]; // interpolate using the barycentric coordinate of the hitpoint var baryCenter = hit.barycentricCoordinate; // Use barycentric coordinate to interpolate normal var interpolatedNormal = n0 * baryCenter.x + n1 * baryCenter.y + n2 * baryCenter.z; // normalize the interpolated normal interpolatedNormal = interpolatedNormal.normalized; // Transform local space normals to world space var hitTransform : Transform = hit.collider.transform; interpolatedNormal = hitTransform.TransformDirection(interpolatedNormal); //Debug.LogWarning('computing ' + hit.normal + ' baryCenter=' + baryCenter + ' local normal=' + interpolatedNormal); return interpolatedNormal; } }
import React from 'react' import Store from './../todoStore' import TodoItem from './todoItem' import AddTodo from './addTodo' class TodoList extends React.Component { constructor (props) { super(props) // Just this is doing the magic! Store.bind({ paths: { todos: ['todos'] }, to: this }) } render () { let localStore = this.state.store return ( <> <h5>Data displayed here as part of Todo List View</h5> <div class='todoCount'> { localStore.todos.length } </div> { localStore.todos.map((item) => { return ( <TodoItem todo={item} /> ) })} </> ) } } export default TodoList
import React from "react"; import './Education.css'; import logo from './henry-logo.jfif'; export default function Education () { return ( <div className="wrapper"> <h1 style={{marginTop: '5%'}}>EDUCATION </h1> <div className="edu-wrapper"> <div className="henry-pic"> <img className="logo" src={logo} alt="Logo" /> </div> <div className="henry-content"> <h2>Henry</h2> <h3>Full Stack Web Development</h3> <h4>August 2020 - December 2020</h4> <ul className="list"> <li><span>HTML5 | CSS3 | JavaScript | Git</span></li> <li><span>NodeJs | Web servers (Express)</span></li> <li><span>AJAX | Webpack | ReactJS | Redux | React-Redux</span></li> <li><span>SQL | Postgres | MySQL | authentication</span></li> <li><span>Data Structures, algorithms, Big O, Functional VS OOP</span></li> </ul> </div> </div> </div> ) }