text
stringlengths
65
6.05M
lang
stringclasses
8 values
type
stringclasses
2 values
id
stringlengths
64
64
import React from 'react'; import { Helmet } from 'react-helmet'; import Layout from '../components/Layout'; import { useInfiniteQuery } from 'react-query'; import { useParams } from 'react-router-dom'; import { searchProducts } from '../Queries/Queries'; import { useIntl } from 'react-intl'; import SearchRightSide from '../components/Search/SearchRightSide'; import SearchLeftSide from '../components/Search/SearchLeftSide'; import { AnimatePresence, motion } from 'framer-motion'; import SideCartMenu from '../components/SingleProduct/SideCartMenu'; import { scrollTo } from 'scroll-js'; import { DataProvider } from '../contexts/DataContext'; import Loader from 'react-loader-spinner'; import 'react-loader-spinner/dist/loader/css/react-spinner-loader.css'; export default function SearchResults() { const { query } = useParams(); const { formatMessage, locale } = useIntl(); const [brandFilters, setBrandFilters] = React.useState([]); const [sortBy, setSortBy] = React.useState({ value: 'newest', label: formatMessage({ id: 'Newest' }), }); const [resultsPerPage, setResultsPerPage] = React.useState({ label: 30, value: 60, }); // const [filtersApplied, setFiltersApplied] = React.useState(false); const [priceFilters, setPriceFilters] = React.useState(null); const [filters, setFilters] = React.useState([]); const [cartMenuOpen, setCartMenu] = React.useState(false); const { deliveryCountry } = React.useContext(DataProvider); /** * Main Fetch */ const { data, isLoading: productsLoading, isFetching: productsFetching, fetchNextPage, isFetchingNextPage, hasNextPage, } = useInfiniteQuery( [ 'searchProducts', { query, resultsPerPage, priceFilters, brandFilters, sortBy }, ], ({ pageParam }) => searchProducts({ query, resultsPerPage, pageParam, brandFilters, priceFilters, sortBy, }), { retry: true, getNextPageParam: lastPage => { if (lastPage.currentPage < lastPage.lastPage) { return lastPage.currentPage + 1; } else { return undefined; } }, } ); const handleResultPerPageChange = selectedValue => { setResultsPerPage(selectedValue); }; const handleRemoveFilters = filter => { setFilters(prev => { return prev.filter(i => i.value !== filter.value); }); if (filter.type === 'Brand') { setBrandFilters(prev => { return prev.filter(i => i.label !== filter.value); }); } if (filter.type === 'Sort') { setSortBy({ value: 'newest', label: formatMessage({ id: 'Newest' }) }); } if (filter.type === 'Price') { setPriceFilters(null); } }; const handleSubmitFilters = (selectedPrice, selectedBrands) => { setBrandFilters(selectedBrands); setPriceFilters(selectedPrice); scrollTo(window, { top: 50, behavior: 'smooth' }); setFilters(() => { if (selectedPrice && !selectedBrands.length > 0) { //if only price const priceFilter = { type: 'Price', value: `${formatMessage({ id: 'less-than' })} ${selectedPrice} ${ deliveryCountry?.currency.translation[locale].symbol }`, }; return [priceFilter]; } else if (!selectedPrice && selectedBrands.length > 0) { // if only brands const brandsFilters = []; selectedBrands.forEach(brand => brandsFilters.push({ type: 'Brand', value: brand.label }) ); return [...brandsFilters]; } else { const priceFilter = { type: 'Price', value: `${formatMessage({ id: 'less-than' })} ${selectedPrice} ${ deliveryCountry?.currency.translation[locale].symbol }`, }; const brandsFilters = []; selectedBrands.forEach(brand => brandsFilters.push({ type: 'Brand', value: brand.label }) ); return [priceFilter, ...brandsFilters]; } }); }; const handleSortByChange = selectedValue => { if (selectedValue.value === 'newest') { setFilters(prev => { return prev.filter(i => i.type !== 'Sort'); }); setSortBy(selectedValue); return; } setFilters(prev => { let newArr = prev.filter(i => i.type !== 'Sort'); newArr.push({ type: 'Sort', value: selectedValue.label }); return newArr; }); setSortBy(selectedValue); }; return ( <Layout> <Helmet> <title> {formatMessage({ id: 'search-for' })} {query} </title> </Helmet> <AnimatePresence> {cartMenuOpen && ( <SideCartMenu key="side-cart" setSideMenuOpen={setCartMenu} /> )} {cartMenuOpen && ( <motion.div key="sidecart-bg" initial={{ opacity: 0 }} animate={{ opacity: 0.5 }} exit={{ opacity: 0 }} onClick={() => setCartMenu(false)} className="side__addCart-bg" ></motion.div> )} </AnimatePresence> <div className="max-w-default mx-auto p-4 overflow-hidden" style={{ minHeight: 'calc(100vh - 150px)' }} > <div className="search-page__container"> <SearchLeftSide products={data?.pages[0].products} productsLoading={productsLoading} brandFilters={brandFilters} setBrandFilters={setBrandFilters} priceFilters={priceFilters} productsFetching={productsFetching} handleSubmitFilters={handleSubmitFilters} filters={filters} /> <SearchRightSide data={data} productsLoading={productsLoading} sortBy={sortBy} setResultsPerPage={setResultsPerPage} filters={filters} handleRemoveFilters={handleRemoveFilters} handleSortByChange={handleSortByChange} setCartMenuOpen={setCartMenu} resultsPerPage={resultsPerPage} handleResultPerPageChange={handleResultPerPageChange} query={query} /> </div> {data && hasNextPage && ( <div className="flex my-2 justify-center"> <button className="p-2 w-40 text-lg font-semibold flex items-center justify-center rounded bg-main-color text-main-text" onClick={() => { fetchNextPage(); }} > {isFetchingNextPage ? ( <Loader type="ThreeDots" color="#fff" height={27} width={27} visible={true} /> ) : ( formatMessage({ id: 'show-more' }) )} </button> </div> )} </div> </Layout> ); }
JavaScript
CL
c0833c0c313c2d3be8d1ce51820ca9d1f0cf5e5b35b5c100b219a27ab0995bb2
const stylelint = require("stylelint") const _ = require("lodash") const resolvedNestedSelector = require("postcss-resolve-nested-selector") const { ruleMessages, validateOptions, report } = stylelint.utils const rewire = require("rewire") const postcssModulesLocalByDefaultRewired = rewire("postcss-modules-local-by-default") const extractICSS = postcssModulesLocalByDefaultRewired.__get__("extractICSS") const localizeNode = postcssModulesLocalByDefaultRewired.__get__("localizeNode") const ruleName = "css-modules/no-global-scoped-selector" const messages = ruleMessages(ruleName, { rejectedKeyframes: "@keyframes :global(...) is not scoped locally", rejectedSelector: selector => `Selector "${selector}" is not scoped locally (scoped selectors must contain at least one local class or id)`, localizeNodeError: (selector, errorMessage) => `Error in selector "${selector}": ${errorMessage}`, }) module.exports = stylelint.createPlugin(ruleName, (isEnabled, options) => (root, result) => { const validOptions = validateOptions( result, ruleName, { actual: isEnabled }, { actual: options, possible: { fileExtensions: [_.isString] }, optional: true }, ) if (!validOptions) return if ( options && options.fileExtensions && (!root.source || !root.source.input.file || !options.fileExtensions.some(extension => root.source.input.file.endsWith(extension))) ) { return } // START OF CODE ADAPTED FROM postcss-modules-local-by-default const localAliasMap = new Map() const { icssImports } = extractICSS(root, false) Object.keys(icssImports).forEach(key => { Object.keys(icssImports[key]).forEach(prop => { localAliasMap.set(prop, icssImports[key][prop]) }) }) root.walkAtRules(atRule => { if (/keyframes$/i.test(atRule.name)) { const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(atRule.params) if (globalMatch) { report({ ruleName, result, message: messages.rejectedKeyframes, node: atRule, word: atRule.params, }) } } }) root.walkRules(rule => { if (rule.parent && rule.parent.type === "atrule" && /keyframes$/i.test(rule.parent.name)) { // ignore keyframes rules return } if (!rule.nodes.some(({ type }) => ["decl", "atrule"].includes(type))) { // ignore rules without declarations return } const splitRule = rule.toString().split(",") rule.selectors.forEach((selector, selectorIndex) => { if (selector.startsWith("%")) return // ignore SCSS placeholder selectors resolvedNestedSelector(selector, rule).forEach(resolvedSelector => { const clonedRule = rule.clone() clonedRule.selector = resolvedSelector let message try { const context = localizeNode(clonedRule, "pure", localAliasMap) if (context.hasPureGlobals) { message = messages.rejectedSelector(resolvedSelector) } } catch (error) { message = messages.localizeNodeError(resolvedSelector, error.message ? error.message : error) } if (!message) return report({ ruleName, result, message, node: rule, word: splitRule.slice(selectorIndex).join(",").trim(), }) }) }) }) // END OF CODE ADAPTED FROM postcss-modules-local-by-default }) module.exports.ruleName = ruleName module.exports.messages = messages
JavaScript
CL
3ddfaac957de2ecc3d5d37da25255f8725b73ddc1f1cf23c87b177bb3a726083
/* global document, setTimeout, WSE */ /* Copyright (c) 2012, 2013 The WebStory Engine Contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name WebStory Engine nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (out) { "use strict"; out.assets.mixins.displayable.flicker = function (command, args) { var self, duration, bus, stage, times, step, element, fx = out.fx; var isAnimation, fn, iteration, maxOpacity, val1, val2, dur1, dur2; args = args || {}; self = this; duration = command.getAttribute("duration") || 500; times = command.getAttribute("times") || 10; maxOpacity = command.getAttribute("opacity") || 1; element = args.element || document.getElementById(this.cssid); step = duration / times; iteration = 0; if (!element) { this.bus.trigger( "wse.interpreter.warning", { element: command, message: "DOM Element for asset is missing!" } ); return; } if (!(parseInt(element.style.opacity, 10))) { val1 = 0; val2 = maxOpacity; dur1 = step / 3; dur2 = dur1 * 2; } else { val2 = 0; val1 = maxOpacity; dur2 = step / 3; dur1 = dur2 * 2; } bus = args.bus || this.bus; stage = args.stage || this.stage; isAnimation = args.animation === true ? true : false; if (!isAnimation) { self.interpreter.waitCounter += 1; } fn = function () { iteration += 1; fx.transform( function (v) { element.style.opacity = v; }, val1, val2, { duration: dur1, onFinish: function () { fx.transform( function (v) { element.style.opacity = v; }, val2, val1, { duration: dur2, onFinish: function () { if (iteration <= times) { setTimeout(fn, 0); return; } if (!isAnimation) { self.interpreter.waitCounter -= 1; } }, easing: fx.easing.easeInQuad } ); }, easing: fx.easing.easeInQuad } ); }; fn(); bus.trigger("wse.assets.mixins.flicker", this); return { doNext: true }; }; }(WSE));
JavaScript
CL
bea2e7c59905220cac16e17bd4fe293988e613f76f8fb647e953c98dedb0f30c
var phylocanvas; HTMLWidgets.widget({ name: 'radial_phylo', type: 'output', initialize: function(el, width, height) { return { width: el.offsetWidth, height: el.offsetHeight } }, renderValue: function(el, x, instance) { // function to add css to <head> var addCSS = function(css) { var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = "text/css"; if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } head.appendChild(style); }; // if 'canvas_size' is a number (auto-calcuated or user-input) then use it var width; var height; if (typeof(x.canvas_size === 'number') && x.canvas_size%1 === 0) { width = x.canvas_size; height = x.canvas_size; } else { // get width and height of current window width = Math.max(instance.width, instance.height); height = Math.max(instance.width, instance.height); } // if user provides large canvas_size give the svg that width and height if (x.scale === true) { addCSS("svg { width: 100%; height: 100%; }"); } else { addCSS("svg { height: " + width + "px; width: " + height + "px; }"); addCSS("body { overflow: scroll !important; }"); } YUI.add('plot', function(Y) { Y.Plot = { radial: function(width, height, id, o, args) { var data = o.responseXML; var dataObject = { phyloxml: data, fileSource: true }; // set some options of the phylogram Smits.PhyloCanvas.Render.Parameters.Circular.bufferRadius = x.tree_margin; Smits.PhyloCanvas.Render.Parameters.Circular.bufferAngle = parseInt(x.arc); Smits.PhyloCanvas.Render.Parameters.Circular.bufferOuterLabels = 0; Smits.PhyloCanvas.Render.Style.text["font-size"] = parseInt(x.font_size); // make phylogram phylocanvas = new Smits.PhyloCanvas( dataObject, el.id, width, height, 'circular', x.scale // holds true or false ); } }; }); YUI_config = { comboBase: 'https://yui-s.yahooapis.com/combo?' } window.onload = function(){ YUI(YUI_config).use('plot', 'oop', 'json-stringify', 'io-base', 'event', 'event-delegate', function(Y){ var uri = HTMLWidgets.getAttachmentUrl('phyloxml', 'xml'); function complete(id, o, args) { Y.Plot.radial(width, height, id, o, args); init(); //unitip } Y.on('io:complete', complete, Y); var request = Y.io(uri); }); }; // Add function to allow creating elements after other elements // Create legend if (x.legend_colors.length > 0) { var legend = $("<div>", {id: "legend"}); var legend_list = $("<ul>", {id: "legend_list"}); $(legend).insertAfter($("#htmlwidget_container")); $(legend).append(legend_list); // Create list elements for each legend item $.each(x.legend_colors, function(i, item) { $(legend_list).append("<li><span style='background-color: " + x.legend_colors[i] + ";'></span>" + x.legend_values[i] + "</li>"); }); } // Create DL image as PNG link var a = document.createElement('a'); a.href = "#"; a.id = "download_link"; var widget = document.body.children[0]; var img_gray = HTMLWidgets.getAttachmentUrl('images', 'download_sheet_gray'); var download_image = new Image(); $(download_image).attr("src", img_gray); if (this.queryVar("viewer_pane") === "1") { // If widgets shown in RStudio, DL as PNG link tells user to open in browser a.title = "Must view in browser to save as PNG"; } else { // Otherwise create the button hover effects a.title = "Save as PNG"; var img_blue = HTMLWidgets.getAttachmentUrl('images', 'download_sheet_blue'); $(download_image) .mouseover(function() { $(this).attr("src", img_blue); }) .mouseout(function() { $(this).attr("src", img_gray); }) .mousedown(function() { var current_pos = parseInt($(this).css("top")); $(this).css("padding-top", 1 + "px"); }) .bind("mouseup mouseleave", function() { $(this).css("padding-top", 0 + "px"); }); } a.appendChild(download_image); // Insert the image inside the link document.body.insertBefore(a, widget); // Insert the link // Attach click handler to save the image when link clicked a.onclick = function() { $(document.body).append("<canvas id='canvg'></canvas>"); $(document.body).append("<img id='svgimg' src=''>"); // The anchor below allows you to suggest a filename for the image. You // have to download the image through it, by setting the href to the // image src once it's ready and setting the filename in the 'downloaad' // attribute. var download_anchor = document.createElement("a"); // Use Raphael.Export to get the SVG from the phylogram var s = phylocanvas.getSvg(); var c = s.svg; var svg = c.toSVG(); // Use canvg to draw the SVG onto the empty canvas canvg(document.getElementById("canvg"), svg); // Give the canvas a second or two to load, then set the image source setTimeout(function() { //fetch the dataURL from the canvas and set it as src on the image var dataURL = document.getElementById("canvg").toDataURL("image/png"); document.getElementById("svgimg").src = dataURL; }, 1000); // Initiate the download setTimeout(function() { var svgimg = document.getElementById("svgimg"); // Indicate the data is a byte stream so it doesn't open image in browser var img_data_uri = svgimg.src.replace("image/png", "image/octet-stream"); $(download_anchor).attr("download", "phylo.png"); download_anchor.href = img_data_uri; // Fake a mouse click on our anchor to initiate the download if (document.createEvent) { var e = document.createEvent("MouseEvents"); e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); download_anchor.dispatchEvent(e); } else if (download_anchor.fireEvent) { download_anchor.fireEvent("onclick"); } }, 1000); }; }, // Returns the value of a GET variable // From: github.com/rstudio/dygraphs/blob/master/inst/htmlwidgets/dygraphs.js queryVar: function(name) { return decodeURI(window.location.search.replace( new RegExp("^(?:.*[&\\?]" + encodeURI(name).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1")); }, resize: function(el, width, height, instance) { } });
JavaScript
CL
6e117ccfe848f9cb1bf6e508f8ff0a74e2ccc5e3c8fc2002083e7fbfd56ed2a6
import React, { Component } from "react"; import { Route } from "react-router"; import { Layout } from "./components/Layout"; import Home from "./components/Home"; import "bootstrap/dist/css/bootstrap.min.css"; import "./custom.css"; import "mapbox-gl/dist/mapbox-gl.css"; import "./index.css"; import Cart from "./components/CartV2/Cart"; import Products from "./components/CartV2/Products"; import Stores from "./components/Stores"; import Profile from "./components/Profile/Profile"; import OrdesHistory from "./components/Profile/OrdersHistory"; import ProfileSettings from "./components/Profile/ProfileSettings"; import Pending from "./components/Profile/Pending"; import Register from "./components/Register"; class App extends Component { static displayName = App.name; render() { return ( <Layout> <Route exact path="/" component={Home} /> <Route exact path="/register" component={Register} /> <Route exact path="/Profile" component={Profile} /> <Route exact path="/:id/Product" component={Products} /> <Route exact path="/Stores" component={Stores} /> <Route exact path="/Cart" component={Cart} /> <Route exact path="/OrdesHistory" component={OrdesHistory} /> <Route exact path="/Settings" component={ProfileSettings} /> <Route exact path="/Pending" component={Pending} /> </Layout> ); } } export default App;
JavaScript
CL
4d08879b68c774576f5997f65207e9dc4c1f4df753bf054c1703a9f40780d40c
/** * @author: yate * @description: 封装axios方法 */ import axios from 'axios'; import { baseUrl } from '../api/env'; axios.defaults.baseURL = baseUrl; axios.defaults.headers.common['Authorization'] = ''; // 添加请求时拦截器 axios.interceptors.request.use(function(config) { return config; }, function(error) { console.log(error); return Promise.reject(error); }); // 添加响应时拦截器 axios.interceptors.response.use(function(response) { const res = response.data; return res; }, function(error) { console.log(error); return Promise.reject(error); }); export default { getByParam, postByParam, putByParam, patchByParam, deleteByParam }; /** * get 请求 * @param {[type]} url 请求接口地址 * @param {[type]} params 请求参数 * @return {[type]} Promise */ function getByParam (url, config) { return new Promise(function(resolve, reject) { axios.get(url, config).then(function(res) { resolve(res.data); }).catch(function(err) { reject(err); }); }); } /** * post 请求 * @param {[type]} url 请求接口地址 * @param {[type]} params 发送的数据 * @return {[type]} Promise */ function postByParam (url, data, config) { return new Promise(function(resolve, reject) { const defaultConfig = { transformRequest: [ function(requestData, headers) { headers['Content-Type'] = 'application/json'; return JSON.stringify(requestData); } ] }; axios.post(url, data, (config || defaultConfig)).then(function(res) { resolve(res.data); }).catch(function(err) { reject(err); }); }); } /** * put 请求 * @description 调用一次与连续调用多次是等价的,已经被用来表示对资源进行整体覆盖 * @param {[type]} url 请求接口地址 * @param {[type]} params 发送的数据 * @return {[type]} Promise */ function putByParam (url, data, config) { return new Promise(function(resolve, reject) { const defaultConfig = { transformRequest: [ function(requestData, headers) { headers['Content-Type'] = 'application/json'; return JSON.stringify(requestData); } ] }; axios.put(url, data, config || defaultConfig).then(function(res) { resolve(res.data); }).catch(function(err) { reject(err); }); }); } /** * patch 请求 * @description patch 用于对资源进行部分修改,连续多个的相同请求会产生不同的效果 * @param {[type]} url 请求接口地址 * @param {[type]} params 发送的数据 * @return {[type]} Promise */ function patchByParam (url, data, config) { return new Promise(function(resolve, reject) { const defaultConfig = { transformRequest: [ function(requestData, headers) { headers['Content-Type'] = 'application/json'; return JSON.stringify(requestData); } ] }; axios.patch(url, data, config || defaultConfig).then(function(res) { resolve(res.data); }).catch(function(err) { reject(err); }); }); } /** * delete 请求 * @description 用于删除指定的资源。 * @param {[type]} url 请求接口地址 * @param {[type]} params 发送的数据 * @return {[type]} Promise */ function deleteByParam (url, config) { return new Promise(function(resolve, reject) { axios.delete(url, config).then(function(res) { resolve(res.data); }).catch(function(err) { reject(err); }); }); }
JavaScript
CL
191c947133d34a43d60a3c189cd536eee44e92cf1a00178ba00665b685d250b3
/** * @fileOverview Playlist views. * There are two main views, a list of all playlists, and a detailed view * of a single playlist. Exactly one of these two views is always present. * It would be desirable if there was a 1:1 correspondance between models and * views but this was considered not necessary for this simple application: * A PlaylistSet is rendered by a PlaylistSetView. * A Playlist model is rendered by a PlaylistView, TitleView, DescriptionView, * Player, SearchWidget, and MyTracksView. * Player and SearchWidget do not use a model-view pattern. * PlalistView, TitleView, and DescriptionView install notification callbacks in * a Playlist, but each callback is set by only one of them. (This simplistic * notification design allows to install only a single notification callback per * type which is sufficient for this application.) */ /** * The main view attached to rootElement, either a list of all playlists or a * playlist view. * @type {?PlaylistSetView|PlaylistView} */ mainView = null; /** * Displays a list of all playlists, and lets the user add and delete playlists * and switch to a playlist. * @constructor * @param {PlaylistSet} playlists The playlists to display. */ function PlaylistSetView(playlists) { /** @type{PlaylistSet} */ this.playlists = playlists; var element = document.getElementById('my-playlists'); /* Make it visible. */ element.style.display = ''; /** * The root DOM element of this view. * @type {Element} */ this.element = element; this.renderPlaylists(); playlists.onChange = bind(this, this.renderPlaylists); /* * Button to create a new playlist, appends it to playlists, and switches to a * view of this playlist. */ var add = document.getElementById('new-playlist'); add.onclick = bind(this, function() { this.remove(); var playlist = new Playlist(myPlaylists.uniqueTitle()); myPlaylists.addPlaylist(playlist); mainView = new PlaylistView(playlist); }); element.appendChild(add); }; // Detaches this view from the DOM. PlaylistSetView.prototype.remove = function() { this.element.style.display = 'none'; document.getElementById('playlist-set').innerHTML = ''; }; PlaylistSetView.prototype.renderPlaylists = function() { var set = document.getElementById('playlist-set'); set.innerHTML = ''; for (index in this.playlists.playlists) { var playlist = this.playlists.playlists[index]; var e = this.renderPlaylist(playlist, this.playlists); set.appendChild(e); } }; /** * Renders a playlist in the lists of playlists. * @param {Playlist} playlist * @return {Object} The DOM element containing the playlist. */ PlaylistSetView.prototype.renderPlaylist = function(playlist) { var element = document.createElement('div'); element.innerHTML = playlist.title; // Switch to a view of this playlist. element.onclick = bind(this, function() { this.remove(); mainView = new PlaylistView(playlist); }); return element; }; /** * A detailed view of a single playlist. * The user can change the title and description, add tracks, remove tracks, * move tracks, and play the tracks. * @param {Playlist} playlist The playlist model. */ function PlaylistView(playlist) { /** @type {Playlist} */ this.playlist = playlist; var div = document.getElementById('playlist'); /* Make it visible. */ div.style.display = ''; /** * The root DOM element of the view. * @type {Object} */ this.div = div; /* Installs notification callbacks in the playlist model. */ playlist.onAddTrack = bind(this, function(track) { this.addTrack(track); }); playlist.onDeleteTrack = bind(this, function(track) { this.deleteTrack(track); }); playlist.onMoveTrack = bind(this, function(track, target) { this.moveTrack(track, target); }); playlist.onChange = this.onChange; /* * Switch back to the main view when the playlist is deleted, for example * by a history undo. */ myPlaylists.onDeletePlaylist = bind(this, function(playlist) { if (playlist == this.playlist) { this.remove(); mainView = new PlaylistSetView(myPlaylists); } }); /* Back button which switches to the view of all playlists. */ var back = document.getElementById('my-playlists-button'); back.onclick = bind(this, function() { this.remove(); mainView = new PlaylistSetView(myPlaylists); }); /* Player widget */ this.player = new Player(playlist); /* Lets the user delete the playlist. */ var deleter = document.getElementById('delete-playlist'); deleter.onclick = bind(this, function() { myPlaylists.deletePlaylist(playlist); }); this.title = new TitleView(playlist, div); this.description = new DescriptionView(playlist, div); /* Render the tracks. */ this.tracksElement = document.getElementById('tracks'); this.tracks = []; for (var idx in playlist.tracks) { var track = this.renderTrack(playlist.tracks[idx]); this.tracksElement.appendChild(track); this.tracks.push(track); } /* Lets the user search and add public tracks. */ var search = new SearchWidget(playlist); /* Lets the user add his own private tracks. */ this.myTracksView = new MyTracksView(playlist); }; /* Hides the view. */ PlaylistView.prototype.remove = function() { this.player.remove(); this.myTracksView.remove(); this.div.style.display = 'none'; this.tracksElement.innerHTML = ''; /* Uninstall notification callbacks. */ this.playlist.onAddTrack = null; this.playlist.onDeleteTrack = null; this.playlist.onMoveTrack = null; myPlaylists.onDeletePlaylist = null; }; /** Renders a track. * Moving of tracks is implemented with HTML5 drag & drop. * @param {Object} track SoundCloud track. * @return {Element} The DOM element rendering the track. */ PlaylistView.prototype.renderTrack = function(track) { var element = document.createElement('div'); PlaylistView.fillTrack(element, track); element.className = 'track'; element.draggable = true; element.ondragstart = function(event) { var index = NodeIndex(event.target); event.dataTransfer.setData("index", String(index)); } this.div.ondragover = function(event) { var target = event.target; if (event.target.className == 'track' || event.target.parentNode.className == 'track') { event.preventDefault(); } }; this.div.ondrop = bind(this, function(event) { var target = event.target; if (target.className != 'track') { target = target.parentNode; } if (target.className = 'track') { event.preventDefault(); var index = event.dataTransfer.getData("index"); var target = NodeIndex(target); this.playlist.moveTrack(index, target); } }); /* Button to delete the track. */ var x = document.createElement('button'); x.innerHTML = 'Delete'; x.onclick = bind(this, function() { this.playlist.deleteTrack(track); }); element.appendChild(x); return element; }; /** * Fills a track with data. * This is a property of PlaylistView so that it can also be called from the * SearchWidget. * @param {Element} element The DOM element. * @param {Object} track SoundCloud track. */ PlaylistView.fillTrack = function(element, track) { var user = document.createElement('span'); user.className = 'user'; user.style.display = 'inline-block'; user.appendChild(document.createTextNode(track.user.username)); element.appendChild(user); var title = document.createElement('span'); title.className = 'title'; title.appendChild(document.createTextNode(track.title)); element.appendChild(title); }; /** * Adds a track to the view. * @param {Object} track SoundCloud track. */ PlaylistView.prototype.addTrack = function(track) { var element = this.renderTrack(track); this.tracksElement.appendChild(element); this.tracks.push(element); } /** * Delets a track. * @param {number} index The index of the track to delete. */ PlaylistView.prototype.deleteTrack = function(index) { this.tracksElement.removeChild(this.tracks[index]); this.tracks.splice(index, 1); } /** * Moves a track to a new position. * @param {number} index The index of the track before the move. * @param {number} target The index of the track after the move. */ PlaylistView.prototype.moveTrack = function(index, target) { /* Note that the order of these calls is important. */ var newTrack = this.tracksElement.removeChild(this.tracks[index]); this.tracks.splice(index, 1); if (target < this.tracks.length) { this.tracksElement.insertBefore(newTrack, this.tracks[target]); } else { this.tracksElement.appendChild(newTrack); } this.tracks.splice(target, 0, newTrack); }; /** * Utility to locate a node in its parent's children. * @param {Object} node The child node. * @return {number} The index of the node in the list of its parent's children. */ function NodeIndex(node) { var parent = node.parentNode; var index; for (index = 0; index < parent.childNodes.length; ++index) { if (parent.childNodes[index] == node) { return index; } } }; /** * Renders a playlist title, and allows the user edit it. * Editing is possibly by clicking on the title which is not perfectly * discoverable (it is hinted by a hover style). It might be better to add an edit * button. * @constructor * @param {Playlist} playlist * @param {Object} parent The parent DOM element to which the view is added. */ function TitleView(playlist, parent) { /** @type {Playlist} */ this.playlist = playlist; playlist.onTitleChange = bind(this, this.update); var element = document.getElementById('title'); /** * The root DOM element of this view. * @type {object} */ this.element = element; element.style.display = ''; this.update(); element.onclick = bind(this, TitleView.prototype.edit); }; /* Updates the rendered title text. */ TitleView.prototype.update = function() { this.element.innerHTML = this.playlist.title; /* Also sets the text in the edit form. */ document.getElementById('title-input').setAttribute('value', this.playlist.title); }; /** * Lets the user edit the title. Switches to an input form. * This UI is not very intuitive since editing is only possible by clicking * on the title, and it does not quite behave like a form (there is no cancel * button, and the title is changed also whenever the input element looses * focus. The idea is that it should behave more like an editable text field * than like a web form. */ TitleView.prototype.edit = function() { var div = this.element; div.style.display = 'none'; var form = document.getElementById('title-form'); form.style.display = 'inline'; var text = document.getElementById('title-input'); text.setAttribute('value', this.playlist.title); text.focus(); if (this.playlist.title) { text.select(); } form.onsubmit = bind(this, TitleView.prototype.change); text.onblur = bind(this, TitleView.prototype.change); this.form = form; } TitleView.prototype.change = function(event) { event.preventDefault(); var title = document.getElementById('title-input').value; this.playlist.setTitle(title); document.getElementById('title-form').style.display = 'none'; this.element.style.display = ''; return false; }; /** * Renders a playlist description, and lets the user edit it. * Although the user can input multiple lines of text, line breaks are ignored * when rendering. * Like for titles, editing is possibly by clicking on the description, which is * not perfectly discoverable (it is hinted by a hover style). It might be * better to add an edit button. * @param {Playlist} playlist * @param {Object} parent Parent DOM element. */ function DescriptionView(playlist, parent) { this.playlist = playlist; this.element = document.getElementById('description'); this.update(); this.playlist.onDescriptionChange = bind(this, this.update); this.element.onclick = bind(this, this.edit); }; /* Updates the rendered description. */ DescriptionView.prototype.update = function() { this.element.innerHTML = this.playlist.description || 'Add description'; if (!this.playlist.description) { this.element.className = 'gray'; } else { this.element.className = ''; } }; /* Switches to an edit form of the description. */ DescriptionView.prototype.edit = function() { this.element.style.display = 'none'; var form = document.getElementById('description-form'); form.style.display = ''; var text = document.getElementById('description-textarea'); text.innerHTML = ''; text.value = this.playlist.description; text.select(); text.focus(); form.onsubmit = bind(this, this.change); text.onblur = bind(this, this.change); } /* Called when the user has input a description. Updates the model and switches * back to the normal description rendering. */ DescriptionView.prototype.change = function(event) { event.preventDefault(); var description = document.getElementById('description-textarea').value; this.playlist.setDescription(description); document.getElementById('description-form').style.display = 'none'; this.element.style.display = ''; return false; }; /** * A view of the user's private tracks. Since private tracks are not surfaced * in search, we show a list of the user's private tracks. We only show his or * her private tracks to keep the list shorter. * @constructor * @param {Playlist} playlist The playlist to which tracks can be added. */ var MyTracksView = function(playlist) { this.playlist = playlist; /* * Installs a callback to be notified if the user authenticates and private * tracks become available. */ MyTracks.onChange = bind(this, this.render); this.render(); }; /** * Renders the private tracks, if there are any. */ MyTracksView.prototype.render = function() { var element = document.getElementById('my-tracks-div'); var tracks = MyTracks.tracks; if (tracks.length == 0) { element.style.display = 'none'; return; } element.style.display = ''; for (var i in tracks) { var track = tracks[i]; this.renderTrack(track); } }; /** * Renders a track, and lets the user add it to the playlist. * @param {Object} track SoundCloud track. */ MyTracksView.prototype.renderTrack = function(track) { var result = document.createElement('div'); result.className = 'my-track'; PlaylistView.fillTrack(result, track); var add = document.createElement('button'); add.innerHTML = 'Add'; add.onclick = bind(this, function() { this.playlist.addTrack(track); }); result.appendChild(add); document.getElementById('my-tracks').appendChild(result); }; /** * Removes the tracks UI from the DOM, and resets the notification callback. */ MyTracksView.prototype.remove = function() { document.getElementById('my-tracks-div').style.display = 'none'; document.getElementById('my-tracks').innerHTML = ''; MyTracks.onChange = null; };
JavaScript
CL
87ce26e445e75f6ee328b09be0272b4e4570b427aff9bc53aa0c8164b6c48db7
/* * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of fiware-iotagent-lib * * fiware-iotagent-lib is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * fiware-iotagent-lib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with fiware-iotagent-lib. * If not, seehttp://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ 'use strict'; var logger = require('fiware-node-logger'), errors = require('../errors'), restUtils = require('./restUtils'), groupService = require('./groupService'), async = require('async'), apply = async.apply, revalidator = require('revalidator'), templateGroup = require('../templates/deviceGroup.json'), configurationHandler, context = { op: 'IoTAgentNGSI.GroupServer' }, mandatoryHeaders = [ 'fiware-service', 'fiware-servicepath' ], mandatoryParameters = [ 'resource', 'apikey' ]; /** * Generates a middleware that checks the request body against the given revalidator template. * * @param {Object} template Loaded JSON Scheam Template. * @return {Function} Express middleware that checks the validity of the body. */ function checkBody(template) { return function bodyMiddleware(req, res, next) { var errorList = revalidator.validate(req.body, template); if (errorList.valid) { next(); } else { logger.debug(context, 'Errors found validating request: %j', errorList); next(new errors.WrongSyntax('Errors found validating request.')); } }; } /** * Apply the handler for configuration updates if there is any. * * @param {Object} newConfiguration New configuration that is being loaded. */ function applyConfigurationHandler(newConfiguration, callback) { if (configurationHandler && newConfiguration) { if (newConfiguration.services) { async.map(newConfiguration.services, configurationHandler, callback); } else { configurationHandler(newConfiguration, callback); } } else { callback(); } } /** * Handle the device group creation requests, adding the header information to the device group body. * * @param {Object} req Incoming request. * @param {Object} res Outgoing response. * @param {Function} next Invokes the next middleware in the chain. */ function handleCreateDeviceGroup(req, res, next) { /*jshint sub:true */ for (var i = 0; i < req.body.services.length; i++) { req.body.services[i].service = req.headers['fiware-service']; req.body.services[i].subservice = req.headers['fiware-servicepath']; req.body.services[i].internalAttributes = req.body.services[i]['internal_attributes']; } async.series([ apply(groupService.create, req.body), apply(applyConfigurationHandler, req.body) ], function(error) { if (error) { next(error); } else { res.status(200).send({}); } }); } /** * Handle GET requests for device groups. Two kind of requests kind arrive: those with the wildcard servicepath ('/*') * and requests for a specific subservice. The former ones are considered service listings, and an array of all the * subservices is returned. For the latter, the description of the specific subservice is returned instead. * * @param {Object} req Incoming request. * @param {Object} res Outgoing response. * @param {Function} next Invokes the next middleware in the chain. */ function handleListDeviceGroups(req, res, next) { if (req.headers['fiware-servicepath'] === '/*') { groupService.list(function(error, groupList) { if (error) { next(error); } else { res.status(200).send({ count: groupList.length, services: groupList }); } }); } else { groupService.find(req.headers['fiware-service'], req.headers['fiware-servicepath'], function(error, group) { if (error) { next(error); } else { res.status(200).send(group); } }); } } /** * Handle a request for modifications of device groups. * * @param {Object} req Incoming request. * @param {Object} res Outgoing response. * @param {Function} next Invokes the next middleware in the chain. */ function handleModifyDeviceGroups(req, res, next) { async.series([ apply(groupService.update, req.headers['fiware-service'], req.headers['fiware-servicepath'], req.query.resource, req.query.apikey, req.body), apply(applyConfigurationHandler, req.body) ], function(error) { if (error) { next(error); } else { res.status(200).send({}); } }); } /** * Handle a request for the removal of a device group. * * @param {Object} req Incoming request. * @param {Object} res Outgoing response. * @param {Function} next Invokes the next middleware in the chain. */ function handleDeleteDeviceGroups(req, res, next) { groupService.remove( req.headers['fiware-service'], req.headers['fiware-servicepath'], req.query.resource, req.query.apikey, function(error) { if (error) { next(error); } else { res.status(200).send({}); } }); } /** * Load the routes related to device provisioning in the Express App. * * @param {Object} router Express request router object. */ function loadContextRoutes(router, name) { router.post('/iot/agents/' + name + '/services', restUtils.checkRequestAttributes('headers', mandatoryHeaders), checkBody(templateGroup), handleCreateDeviceGroup); router.get('/iot/agents/' + name + '/services', restUtils.checkRequestAttributes('headers', mandatoryHeaders), handleListDeviceGroups); router.put('/iot/agents/' + name + '/services', restUtils.checkRequestAttributes('headers', mandatoryHeaders), restUtils.checkRequestAttributes('query', mandatoryParameters), handleModifyDeviceGroups); router.delete('/iot/agents/' + name + '/services', restUtils.checkRequestAttributes('headers', mandatoryHeaders), restUtils.checkRequestAttributes('query', mandatoryParameters), handleDeleteDeviceGroups); } function setConfigurationHandler(newHandler) { configurationHandler = newHandler; } exports.loadContextRoutes = loadContextRoutes; exports.setConfigurationHandler = setConfigurationHandler;
JavaScript
CL
9ad0d9c6d35820a8f5c4a9f20cdf9c2cf506fdff44cc8f12116446f3a0957d9d
// Copyright 2019 New Relic Corporation. All rights reserved. // SPDX-License-Identifier: Apache-2.0 import React from 'react'; import { Map, CircleMarker, TileLayer } from 'react-leaflet'; import { Spinner, Grid, GridItem, PlatformStateContext, NerdletStateContext, NerdGraphQuery } from 'nr1'; import { ENTITY_QUERY, getMarkerColor } from './util'; import NrqlFactory from './nrql-factory'; import DetailsPanel from './details-panel'; import { NerdGraphError, EmptyState } from '@newrelic/nr1-community'; export default class PageViewMap extends React.Component { constructor(props) { super(props); this.state = { detailsOpen: false, openedFacet: null, mapCenter: [10.5731, -7.5898], zoom: 3 }; this.togglePageViewDetails = this.togglePageViewDetails.bind(this); } togglePageViewDetails = (facet, center) => { if (facet) { this.setState({ detailsOpen: true, openedFacet: facet, mapCenter: center }); } else { // debugger; this.setState({ detailsOpen: false, openedFacet: null }); } }; updateZoom = zoom => { this.setState({ zoom: zoom }); }; render() { const { detailsOpen, mapCenter, openedFacet } = this.state; return ( <PlatformStateContext.Consumer> {platformUrlState => ( <NerdletStateContext.Consumer> {nerdletUrlState => ( <NerdGraphQuery query={ENTITY_QUERY} variables={{ entityGuid: nerdletUrlState.entityGuid }} fetchPolicyType={NerdGraphQuery.FETCH_POLICY_TYPE.NO_CACHE} > {({ loading, error, data }) => { if (loading) { return <Spinner fillContainer />; } if (error) { return <NerdGraphError error={error} />; } // console.debug(data); const nrqlFactory = NrqlFactory.getFactory(data); const { accountId, servingApmApplicationId, applicationId } = data.actor.entity; const appId = servingApmApplicationId || applicationId; const { entity } = data.actor; const { apdexTarget } = data.actor.entity.settings || 0.5; // return "Hello"; return appId ? ( <NerdGraphQuery query={nrqlFactory.getMapDataGraphQL({ appId, entity, accountId, platformUrlState })} > {({ loading, error, data }) => { if (loading) { return <Spinner fillContainer />; } if (error) { return <NerdGraphError error={error} />; } // console.debug(data); const { results } = data.actor.account.mapData; return ( <Grid spacingType={[ Grid.SPACING_TYPE.NONE, Grid.SPACING_TYPE.NONE ]} > <GridItem columnSpan={detailsOpen ? 8 : 12}> <Map className="containerMap" style={{ height: '99vh' }} center={mapCenter} zoom={this.state.zoom} zoomControl onZoomEnd={e => { this.updateZoom(e.target._zoom); }} ref={ref => { this.mapRef = ref; }} > <TileLayer attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> {results.map((pt, i) => { const center = [pt.lat, pt.lng]; return ( <CircleMarker key={`circle-${i}`} center={center} color={getMarkerColor(pt.y, apdexTarget)} radius={Math.log(pt.x) * 3} onClick={() => { this.togglePageViewDetails(pt, center); }} /> ); })} </Map> </GridItem> {openedFacet && ( <GridItem columnSpan={4}> <DetailsPanel appId={appId} entity={entity} nrqlFactory={nrqlFactory} accountId={accountId} openedFacet={openedFacet} platformUrlState={platformUrlState} togglePageViewDetails={ this.togglePageViewDetails } /> </GridItem> )} </Grid> ); }} </NerdGraphQuery> ) : ( <EmptyState heading="No location data is available for this application" desription={`${entity.name} does not have PageView events with an associated appId or this application hasn't been granted access to that data.`} /> ); }} </NerdGraphQuery> )} </NerdletStateContext.Consumer> )} </PlatformStateContext.Consumer> ); } }
JavaScript
CL
05cb3ce71bd49d5ec6fa1ad0e9ad729c55d17fcb82e5286140614ec586c78950
/** * [Lube.Places] * * @date [2016] * @revision [0.1] * @author [Tim Vermaelen] * @type [module] */ // global function required to re-instantiate function asyncGoogleMaps() { } /** * @function $ : jQuery * @function google : Google * @namespace ns : namespace GiveADay */ window.Lube = (function ($, google, ns) { // 1. ECMA-262/5 'use strict'; // 2. CONFIGURATION var cfg = { cache: { container: '[data-class="places"]' }, classes: {}, data: {}, events: { change: 'change', focus: 'focus', placeChanged: 'place_changed', status: 'status' }, formData: { street_number: 'short_name', // 0. huisnummer route: 'long_name', // 1. straat sublocality_level_1: 'long_name', // 2. gemeente locality: 'long_name', // 3. stad administrative_area_level_2: 'short_name', // 4. stad administrative_area_level_1: 'short_name', // 5. provincie country: 'short_name', // 6. land postal_code: 'short_name' // 7. postcode }, scripts: { maps: '//maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&key=AIzaSyAO58KawXmkqBDsYkZ0JB-8KIBSFRcm-tk&callback=asyncGoogleMaps' } }; // 3. CONSTRUCTOR ns.Places = function (options) { this.settings = $.extend(true, {}, cfg, options); this.init(); }; // 4. PROTOTYPE OBJECT ns.Places.prototype = { version: 0.1, init: function () { var self = this; this.cacheItems(); if (this.containers.length) { this.getApi(function () { google = window.google || {}; self.bindEvents(); }); } }, cacheItems: function () { var settings = this.settings, cache = settings.cache; this.containers = $(cache.container); this.coords = undefined; this.placeSearch = undefined; this.autocomplete = undefined; }, getApi: function (cb) { var settings = this.settings, scripts = settings.scripts; if (!google) { $.getScript(scripts.maps) .done(cb) .fail(function (jqxhr, obj, exception) { console.warn('Google Maps - failed to load script: ' + exception); } ); } }, bindEvents: function () { var self = this, settings = this.settings, events = settings.events; this.containers.on(events.focus, function () { self.autocomplete = self.autocomplete || new google.maps.places.Autocomplete(this, { types: ['geocode'] }); self.coords = self.coords || new ns.Geolocation(function (data) { var position = new google.maps.LatLng(parseFloat(data.latitude), parseFloat(data.longitude)); self.autocomplete.setBounds(new google.maps.LatLngBounds(position, position)); google.maps.event.addListener(self.autocomplete, events.placeChanged, function () { self.setFormData(); }); }); }); }, getAddressComponentValue: function (place, id) { var settings = this.settings, formData = settings.formData, i = 0, addressComponent, addressFormat, val = ''; for (; i < place.address_components.length; i++) { addressComponent = place.address_components[i]; addressFormat = addressComponent.types[0] === id && formData[id]; val = addressFormat ? addressComponent[addressFormat] : val; } return val; }, setFormData: function () { var settings = this.settings, events = settings.events, formData = settings.formData, place = this.autocomplete.getPlace(), location = place.geometry.location, id, val, inpComponent, inpComponentObj, inpComponentOptions; $('#latitude').val(location.lat()); $('#longitude').val(location.lng()); for (id in formData) { if (formData.hasOwnProperty(id)) { inpComponent = $('#' + id); inpComponentObj = inpComponent.get(0); val = this.getAddressComponentValue(place, id); if (inpComponent.length && val) { switch (inpComponentObj.type) { case 'select-one': inpComponentOptions = $(inpComponentObj.options); inpComponentOptions.prop({ selected: false }); inpComponentOptions.filter('[value="' + val + '"]').prop({ selected: true }); break; default: inpComponent.prop({ disabled: false }); inpComponent.val(val); break; } inpComponent.trigger(events.change); } } } } }; // 5. NAMESPACE return ns; }(window.jQuery, window.google, window.Lube || {}));
JavaScript
CL
7855dad7232ab6a08d26d94ff0f56a82a204d2eb15e43e53aaf038ce6ab9389e
import React, { Component } from 'react'; import { I18nextProvider } from 'react-i18next'; import * as PropTypes from 'prop-types'; import { MuiThemeProvider } from '@material-ui/core'; import { ApolloProvider } from 'react-apollo'; import SearchProvider from './containers/SearchProvider'; import { Search } from './containers/Search'; import theme from './theme'; import i18n from './i18n'; import { getApolloClient } from './client'; import NavBar from './containers/NavBar'; export class MultiModalComponent extends Component { static propTypes = { uri : PropTypes.string, onResultClick: PropTypes.func, }; static defaultProps = { uri : 'https://api-test.trompamusic.eu', onResultClick: () => true, }; constructor(props) { super(props); this.client = getApolloClient(this.props.uri); } render() { return ( <ApolloProvider client={this.client}> <MuiThemeProvider theme={theme}> <I18nextProvider i18n={i18n}> <SearchProvider client={this.client}> <NavBar /> <Search onResultClick={this.props.onResultClick} /> </SearchProvider> </I18nextProvider> </MuiThemeProvider> </ApolloProvider> ); } }
JavaScript
CL
f5533f482489b2b45dd54f2b4f216f9b7ec704bc4b224a0960acc214612c5657
// Exercise 1 // 1. Create an object called shape that has a type property and a // getType method. var shape = { type: "", getType: function() { return this.type; } }; // 2. Define a Trangle constructor function whose prototype is // shape. Objects created with Triangle should have three own // properties: a, b and c representing the sides of a triange. function Triangle(a, b, c) { this.type = "triangle"; this.a = a; this.b = b; this.c = c; } Triangle.prototype = shape; // 3. Add a new method to the prototype called getPerimeter. Triangle.prototype.getPerimeter = function() { return this.a + this.b + this.c; } // Note, normally this is done for you because a function's // prototype object will have a constructor property pointing // to the function. However, in this case, because we set it // manually, we lost that constructor reference. Triangle.prototype.constructor = Triangle;
JavaScript
CL
728661ac1fb994b8cab6a03bd7d73e1566be4898842fd3f1cb096ab9582b6d3d
/* 👋 Hi! This file was autogenerated by tslint-to-eslint-config. https://github.com/typescript-eslint/tslint-to-eslint-config It represents the closest reasonable ESLint configuration to this project's original TSLint configuration. We recommend eventually switching this configuration to extend from the recommended rulesets in typescript-eslint. https://github.com/typescript-eslint/tslint-to-eslint-config/blob/master/docs/FAQs.md Happy linting! 💖 */ module.exports = { env: { es6: true, }, extends: [ /** * Turns off all rules that are unnecessary or might conflict with Prettier. */ 'prettier', /** * Turns off all TypeScript rules that are unnecessary or might conflict with Prettier. */ 'prettier/@typescript-eslint', /** * Adds React-related rules. */ 'plugin:react/recommended', /** * Adds React hooks-related rules. */ 'plugin:react-hooks/recommended', ], /** * An ESLint parser which leverages TypeScript ESTree to allow for ESLint to lint TypeScript source code. */ parser: '@typescript-eslint/parser', parserOptions: { project: 'tsconfig.json', sourceType: 'module', ecmaFeatures: { jsx: true, }, }, plugins: ['@typescript-eslint', 'import', 'jsdoc', '@babel'], rules: { /** * Require that member overloads be consecutive */ '@typescript-eslint/adjacent-overload-signatures': 'error', /** * Disallows awaiting a value that is not a Thenable */ '@typescript-eslint/await-thenable': 'error', /** * Bans specific types from being used */ '@typescript-eslint/ban-types': [ 'error', { types: { Boolean: 'Avoid using the `Boolean` type. Did you mean `boolean`?', Symbol: 'Avoid using the `Boolean` type. Did you mean `symbol`?', Number: 'Avoid using the `Number` type. Did you mean `number`?', String: 'Avoid using the `String` type. Did you mean `string`?', Object: 'Avoid using the `Object` type. Did you mean `object`?', Function: 'Avoid using the `Function` type. Prefer a specific function type, like `() => void`.', /* * Allow use of '{}' - we use it to define React components with no properties */ '{}': false, }, }, ], /** * Enforces consistent usage of type assertions */ '@typescript-eslint/consistent-type-assertions': ['error', {assertionStyle: 'as'}], /** * Enforce dot notation whenever possible */ '@typescript-eslint/dot-notation': 'error', /** * Disallow empty functions */ '@typescript-eslint/no-empty-function': 'error', /** * Forbids the use of classes as namespaces */ '@typescript-eslint/no-extraneous-class': 'error', /** * Requires Promise-like values to be handled appropriately */ '@typescript-eslint/no-floating-promises': 'error', /** * Disallow iterating over an array with a for-in loop */ '@typescript-eslint/no-for-in-array': 'error', /** * Enforce valid definition of `new` and `constructor` */ '@typescript-eslint/no-misused-new': 'error', /** * Disallow the use of parameter properties in class constructors */ '@typescript-eslint/no-parameter-properties': 'error', /** * Disallow aliasing this */ '@typescript-eslint/no-this-alias': 'error', /** * Warns if a type assertion does not change the type of an expression */ '@typescript-eslint/no-unnecessary-type-assertion': 'error', /** * Disallow unused expressions */ '@typescript-eslint/no-unused-expressions': [ 'error', { allowShortCircuit: true, }, ], /** * Prefer a `for-of` loop over a standard `for` loop if the index is only used to access the array being iterated */ '@typescript-eslint/prefer-for-of': 'error', /** * Use function types instead of interfaces with call signatures */ '@typescript-eslint/prefer-function-type': 'error', /** * Require the use of the `namespace` keyword instead of the `module` keyword to declare custom TypeScript modules */ '@typescript-eslint/prefer-namespace-keyword': 'error', /** * Requires that private members are marked as `readonly` if they're never modified outside of the constructor */ '@typescript-eslint/prefer-readonly': 'error', /** * Requires any function or method that returns a Promise to be marked async */ '@typescript-eslint/promise-function-async': 'error', /** * When adding two variables, operands must both be of type number or of type string */ '@typescript-eslint/restrict-plus-operands': 'error', /** * Sets preference level for triple slash directives versus ES6-style import declarations */ '@typescript-eslint/triple-slash-reference': [ 'error', { path: 'always', types: 'prefer-import', lib: 'always', }, ], /** * Enforces unbound methods are called with their expected scope */ '@typescript-eslint/unbound-method': 'error', /** * Warns for any two overloads that could be unified into one by using a union or an optional/rest parameter */ '@typescript-eslint/unified-signatures': 'error', /** * Prevents conditionals where the type is always truthy or always falsy */ '@typescript-eslint/no-unnecessary-condition': ['error', {allowConstantLoopConditions: true}], /** * */ 'prefer-arrow-callback': ['error', {allowNamedFunctions: true}], /** * Ensures `super()` is called in derived class constructors */ 'constructor-super': 'error', /** * Require === and !== */ eqeqeq: ['error', 'smart'], /** * Blacklist certain identifiers to prevent them being used * "There are only two hard things in Computer Science: cache invalidation and naming things." — Phil Karlton */ 'id-blacklist': [ 'error', 'any', 'Number', 'number', 'String', 'string', 'Boolean', 'boolean', 'Undefined', 'undefined', ], /** * Require identifiers to match a specified regular expression */ 'id-match': 'error', /** * Report imported names marked with @deprecated documentation tag */ 'import/no-deprecated': 'error', /** * Forbid the use of extraneous packages */ 'import/no-extraneous-dependencies': [ 'error', { devDependencies: ['**/__tests__/**/*', '**/__story__/**/*', '**/fixtures/**/*'], optionalDependencies: false, }, ], /** * Reports invalid alignment of JSDoc block asterisks. */ 'jsdoc/check-alignment': 'error', /** * Reports invalid padding inside JSDoc blocks. */ 'jsdoc/check-indentation': 'error', /** * Enforces a consistent padding of the block description. */ 'jsdoc/newline-after-description': 'error', /** * This rule reports types being used on @param or @returns. */ 'jsdoc/no-types': 'error', /** * The use of bitwise operators in JavaScript is very rare and often & or | is simply a mistyped && or ||, which will lead to unexpected behavior. */ 'no-bitwise': 'error', /** * Disallow assignment operators in conditional statements */ 'no-cond-assign': 'error', /** * Disallow console.log */ 'no-console': [ 'error', { allow: [ 'debug', 'info', 'dirxml', 'warn', 'error', 'time', 'timeEnd', 'timeLog', 'trace', 'assert', 'clear', 'count', 'countReset', 'group', 'groupCollapsed', 'groupEnd', 'table', 'Console', 'markTimeline', 'profile', 'profileEnd', 'timeline', 'timelineEnd', 'timeStamp', 'context', ], }, ], /** * Disallow the use of debugger */ 'no-debugger': 'error', /** * Rule to disallow a duplicate case label */ 'no-duplicate-case': 'error', /** * Disallow duplicate imports */ 'no-duplicate-imports': 'error', /** * Disallow empty destructuring patterns */ 'no-empty': 'error', /** * Disallow eval() */ 'no-eval': 'error', /** * Disallow Case Statement Fallthrough */ 'no-fallthrough': 'error', /** * Disallow this keywords outside of classes or class-like objects. * * We use class fields in our class components, which is an ES proposal. * Eslint generates false positives for no-invalid-this in this case - * we need to use the babel plugin, which checks them correctly. */ 'no-invalid-this': 'off', '@babel/no-invalid-this': 'error', /** * Disallow Primitive Wrapper Instances */ 'no-new-wrappers': 'error', /** * Disallow variable redeclaration */ 'no-redeclare': 'error', /** * Disallow specific imports */ 'no-restricted-imports': [ 'error', 'lodash', 'date-fns', '@material-ui/core', '@material-ui/styles', '@material-ui/icons', ], /** * Disallow Use of the Comma Operator */ 'no-sequences': 'error', /** * Disallow Shadowing of Restricted Names */ 'no-shadow': 'off', '@typescript-eslint/no-shadow': 'error', /** * Disallow sparse arrays */ 'no-sparse-arrays': 'error', /** * Disallow template literal placeholder syntax in regular strings */ 'no-template-curly-in-string': 'error', /** * Disallow Initializing to undefined */ 'no-undef-init': 'error', /** * Disallow control flow statements in finally blocks */ 'no-unsafe-finally': 'error', /** * Require let or const instead of var */ 'no-var': 'error', /** * Enforce variables to be declared either separately in functions */ 'one-var': ['error', 'never'], /** * Suggest using of const declaration for variables that are never modified after declared */ 'prefer-const': 'error', /** * Require Radix Parameter */ radix: 'error', /** * Require calls to isNaN() when checking for NaN */ 'use-isnan': 'error', // React-specific rule overrides /** * We use TypeScript - we don't use dynamic prop type checks */ 'react/prop-types': 'off', /** * We use anonymous functions for components - having displayNames would be good, * but we don't want to change the entire code base */ 'react/display-name': 'off', /** * Enable ' in unescaped entities - it's safe and escaping it makes adding copy harder */ 'react/no-unescaped-entities': [ 'error', { forbid: ['>', '}', '"'], }, ], /** * Make exhaustive deps mandatory */ 'react-hooks/exhaustive-deps': 'error', }, };
JavaScript
CL
1b762b1954761a106ab46efd3e6ef247ff70df828a751fd8b3711aa8fe6125f5
import React, { PureComponent } from "react"; // @material-ui/core components import withStyles from "@material-ui/core/styles/withStyles"; // @material-ui/icons import AddAlert from "@material-ui/icons/AddAlert"; // core components import GridItem from "components/Grid/GridItem.jsx"; import GridContainer from "components/Grid/GridContainer.jsx"; import CustomInput from "components/CustomInput/CustomInput.jsx"; import Button from "components/CustomButtons/Button.jsx"; import Card from "components/Card/Card.jsx"; import CardHeader from "components/Card/CardHeader.jsx"; import CardBody from "components/Card/CardBody.jsx"; import CardFooter from "components/Card/CardFooter.jsx"; import Snackbar from "components/Snackbar/Snackbar.jsx"; const woodLotJSON = require('build-contracts/WoodManager.json'); const MyContract = window.web3.eth.contract(woodLotJSON.abi); const myContractInstance = MyContract.at( Object.keys(woodLotJSON.networks).map( key => woodLotJSON.networks[key].address )[0] ); const styles = { cardCategoryWhite: { color: "rgba(255,255,255,.62)", margin: "0", fontSize: "14px", marginTop: "0", marginBottom: "0" }, cardTitleWhite: { color: "#FFFFFF", marginTop: "0px", minHeight: "auto", fontWeight: "300", fontFamily: "'Roboto', 'Helvetica', 'Arial', sans-serif", marginBottom: "3px", textDecoration: "none" } }; class ProductNew extends PureComponent { constructor(props) { super(props); this.state = { madeira: "", quantidade: "", data: new Date(), alerta: false, nomeFazenda: "" }; } handleChange = event => { this.setState({ [event.target.id]: event.target.value }); }; handleSubmit = event => { event.preventDefault(); const { madeira, quantidade, nomeFazenda } = this.state; myContractInstance.addWoodLot( madeira, quantidade.toString(), nomeFazenda, { from: window.acc }, (err, res) => { if (!err) { this.setState({ alerta: true }, () => { setTimeout(() => { this.props.history.goBack(); }, 1000); }); } else { this.props.history.goBack(); } } ); }; render() { const { classes } = this.props; const { madeira, quantidade, nomeFazenda } = this.state; return ( <div> <GridContainer> <form style={{ display: "contents" }}> <GridItem xs={12} sm={12} md={8}> <Card> <CardHeader color="primary"> <h4 className={classes.cardTitleWhite}>Cadastrar Lote</h4> <p className={classes.cardCategoryWhite}>Informe os dados</p> </CardHeader> <CardBody> <GridContainer> <GridItem xs={12} sm={12} md={12}> <CustomInput labelText="Madeira" id="madeira" value={madeira} onChange={this.handleChange} formControlProps={{ fullWidth: true }} /> </GridItem> </GridContainer> <GridContainer> <GridItem xs={12} sm={12} md={12}> <CustomInput labelText="Qunatidade Produzida (m3)" id="quantidade" value={quantidade} onChange={this.handleChange} formControlProps={{ fullWidth: true }} /> </GridItem> </GridContainer> <GridContainer> <GridItem xs={12} sm={12} md={12}> <CustomInput labelText="Nome da Fazenda" id="nomeFazenda" value={nomeFazenda} onChange={this.handleChange} formControlProps={{ fullWidth: true }} /> </GridItem> </GridContainer> </CardBody> <CardFooter> <Button onClick={this.handleSubmit} color="primary"> Salvar </Button> <Button onClick={() => this.props.history.goBack()}> Cancelar </Button> </CardFooter> </Card> </GridItem> </form> </GridContainer> <Snackbar place="tc" color="info" icon={AddAlert} message="Produto salvo com sucesso!" open={this.state.alerta} closeNotification={() => this.setState({ alerta: false })} close /> </div> ); } } export default withStyles(styles)(ProductNew);
JavaScript
CL
3e6d48cb3575c5a75888706c857b9382d7d9725fdfbbf9b9a2b96ce6d710361a
var fs = require( 'fs' ), path = require( 'path' ), rimraf = require( 'rimraf' ), chai = require( 'chai' ), expect = chai.expect, sinon = require( 'sinon' ), JSONStore = require( '..' ), STORE_PATH = path.join( __dirname, 'temp' ); chai.use( require( 'sinon-chai' ) ); function readJSON( file ) { return JSON.parse( fs.readFileSync( file, 'utf8' ) ); } describe( 'Asynchronous usage', function() { var jsonStore; before( function() { jsonStore = JSONStore( STORE_PATH ); } ); after( function( done ) { rimraf( STORE_PATH, done ); } ); it( 'should allow valid filenames', function( done ) { ( function( names ) { var count = 0; names.forEach( function( name ) { jsonStore.set( name, { hello: 'world' }, function( err ) { expect( err ).to.not.exist; count++; if ( count === names.length ) done(); } ); } ); } )( [ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', 'abc def', 'abc[def]', 'abc(def)', 'abc-def', 'abc_def', 'abc.def', 'abc,def' ] ); } ); it( 'should not allow invalid filenames', function( done ) { ( function( names ) { var count = 0; names.forEach( function( name ) { jsonStore.set( name, { hello: 'world' }, function( err ) { expect( err ).to.exist; expect( err.message ).to.equal( 'Invalid Key' ); count++; if ( count === names.length ) done(); } ); } ); } )( [ 'slash/not/allowed', 'backslash\\not\\allowed', 'specials\rnot\nallowed', 'not-alphanumeric-é-not-allowed', 'double-quote-"-not-allowed', 'single-quote-\'-not-allowed' ] ); } ); it( 'should fail when trying to retrieve a nonexistent object', function( done ) { jsonStore.get( 'nonexistent_object', function( err ) { expect( err ).to.exist.and.be.instanceof( Error ).and.have.property( 'code', 'ENOENT' ); done(); } ); } ); it( 'should save a valid JSON object to disk', function( done ) { var myObject = { hello: 'world', foo: [ 'bar', 'baz' ] }; jsonStore.set( 'my_object', myObject, function( err ) { expect( err ).to.not.exist; expect( fs.existsSync( path.join( STORE_PATH, 'my_object.json' ) ) ).to.be.true; expect( readJSON( path.join( STORE_PATH, 'my_object.json' ) ) ).to.deep.equal( myObject ); delete myObject.hello; jsonStore.set( 'my_object', myObject, function( err ) { expect( err ).to.not.exist; expect( readJSON( path.join( STORE_PATH, 'my_object.json' ) ) ).to.deep.equal( myObject ); done(); } ); } ); } ); it( 'should save and retrieve a valid JSON object from the disk', function( done ) { var myObject = { hello: 'world', foo: [ 'bar', 'baz' ] }; jsonStore.set( 'my_object_to_retrieve', myObject, function( err ) { expect( err ).to.not.exist; jsonStore.get( 'my_object_to_retrieve', function( err, myObjectFromStore ) { expect( err ).to.not.exist; expect( myObjectFromStore ).to.deep.equal( myObject ); done(); } ); } ); } ); it( 'should be able to list all JSON objects inside the store', function( done ) { jsonStore.keys( function( err, keys ) { expect( err ).to.not.exist; expect( keys ).to.be.an.array; done(); } ); } ); it( 'should save and delete a valid JSON object from the disk', function( done ) { var myObject = { hello: 'world', foo: [ 'bar', 'baz' ] }; jsonStore.set( 'my_object', myObject, function( err ) { expect( err ).to.not.exist; jsonStore.remove( 'my_object', function( err ) { expect( err ).to.not.exist; expect( fs.existsSync( path.join( STORE_PATH, 'my_object.json' ) ) ).to.be.false; done(); } ); } ); } ); } );
JavaScript
CL
57f8e7364f77e5d5f17057d0b27a3e2a603fae1d891f82eaee8fe20e65060cfc
import {queryHistoryOrder,queryAddressZones,queryAddressBuildings,queryAddressUnits,queryBySearch, queryMessage,sendMessage,queryInvoice,addInvoiceInfo,FormInfo,queryByDateSearch,queryList,returnMoney} from '../services/histories'; export default { namespace: 'histories', state: { data: { list: [], pagination: {}, }, dataInfo: [], zonesData:[], buildingsData:[], unitsData:[], }, effects: { *fetch({ payload, callback }, { call, put }) { const response = yield call(queryHistoryOrder, payload); const result = { list: response.data.rows, pagination: { total: response.data.total, page_size: response.data.page_size, current: response.data.current, }, }; yield put({ type: 'show', payload: result, }); if (callback) callback(result); }, // 查询小区 *fetchByZones({ payload ,callback}, { call, put }) { const response = yield call(queryAddressZones,payload); yield put({ type: 'showZones', payload: response, }); if (callback) callback(response); }, // 根据小区查楼号 *fetchByBuildings({ payload ,callback}, { call, put }) { const response = yield call(queryAddressBuildings,payload); yield put({ type: 'showBuildings', payload: response, }); if (callback) callback(response); }, // 根据楼号查房间号 *fetchByUnits({ payload ,callback}, { call, put }) { const response = yield call(queryAddressUnits,payload); yield put({ type: 'showUnits', payload: response, }); if (callback) callback(response); }, // 级联查询列表 *fetchList({ payload ,callback}, { call, put }) { const response = yield call(queryList,payload); const result = { list: response.data.rows, pagination: { total: response.data.total, page_size: response.data.page_size, current: response.data.current, }, }; yield put({ type: 'show', payload: result, }); if (callback) callback(result); }, // 根据业主姓名,房号,手机号进行查询 *fetchBySearch({ payload ,callback}, { call, put }) { const response = yield call(queryBySearch,payload); const result = { list: response.data.rows, pagination: { total: response.data.total, page_size: response.data.page_size, current: response.data.current, }, }; yield put({ type: 'show', payload: result, }); if (callback) callback(result); }, // 根据日期进行查询 *fetchByDate({ payload ,callback}, { call, put }) { const response = yield call(queryByDateSearch,payload); const result = { list: response.data.rows, pagination: { total: response.data.total, page_size: response.data.page_size, current: response.data.current, }, }; yield put({ type: 'show', payload: result, }); if (callback) callback(result); }, // 根据手机号查询短信内容 *fetchByPhone({ payload ,callback}, { call, put }) { const response = yield call(queryMessage,payload); yield put({ type: 'show', payload: response, }); if (callback) callback(response); }, // 短信Info *getMessageInfo({ payload: { id }, callback }, { call, put }) { let response = yield call(FormInfo,id); yield put({ type: 'saveInfo', payload: response, }); if (callback) callback(response); }, // 发票Info *getInvoiceInfo({ payload, callback }, { call, put }) { const response = yield call(queryInvoice, payload); yield put({ type: 'invoiceInfo', payload: response, }); if (callback) callback(response); }, // 发短信 *sendByPhone({ payload ,callback}, { call}) { const response = yield call(sendMessage,payload); if (callback) callback(response); }, // 退款 *refundButton({ payload,callback}, { call }) { const response = yield call(returnMoney,payload); if (callback) callback(response); }, // 查询发票信息 *fetchByList({ payload ,callback}, { call, put }) { const response = yield call(queryInvoice,payload); yield put({ type: 'show', payload: response, }); if (callback) callback(response); }, // 申请发票 *applicationInvoice({ payload, callback }, { call}) { const response = yield call(addInvoiceInfo, payload); if (callback) callback(response); }, }, reducers: { // 接受服务器数据返回 show(state, action) { return { ...state, data: action.payload, }; }, // 小区 showZones(state, action) { return { ...state, zonesData: action.payload, }; }, // 楼栋 showBuildings(state, action) { return { ...state, buildingsData: action.payload, }; }, // 房号 showUnits(state, action) { return { ...state, unitsData: action.payload, }; }, pageShow(state, action) { return { ...state, data: action.payload, }; }, saveInfo(state, action){ return { ...state, dataInfo: action.payload.data, } }, showSearch(state,action){ return{ ...state, data:action.payload, } }, invoiceInfo(state, action){ return { ...state, dataInfo: action.payload, } }, }, };
JavaScript
CL
13a50af6cd24888bec3d71f1fba9f617fefd71f2beecd1996d43ba9c542d3ff5
'use strict'; var find = require('101/find'); var Api = require('models/api.js'); var errorPage = require('models/error-page.js'); var logger = require('middlewares/logger')(__filename).log; /** * Middleware to check if the container is running * @param {object} req - Request Object * Requires both targetNaviEntryInstance && targetShortHash to exist * @param {object} res - Response Object * @param {function} next - Next method */ module.exports.middleware = function checkContainerStatusMiddleware(req, res, next) { var log = logger.child({ tx: true, req: req, method: 'check-container-status', targetInstance: req.targetNaviEntryInstance }); log.info('called'); if (!req.targetNaviEntryInstance) { log.trace('No targetNaviEntryInstance skipping'); return next(); } var reqUrl = Api.getTargetUrl(req.parsedReqUrl, req.targetNaviEntryInstance); log = log.child({targetHost: reqUrl}); if (req.targetNaviEntryInstance.dockRemoved) { req.targetHost = errorPage.generateErrorUrl('dock_removed', { elasticUrl: reqUrl, shortHash: module.exports._getTargetShortHash(req) }); log.trace('Dock is migrating'); return next(); } if (!req.targetNaviEntryInstance.running) { req.targetHost = errorPage.generateErrorUrl('not_running', { elasticUrl: reqUrl, shortHash: module.exports._getTargetShortHash(req) }); log.trace('Container is not running'); return next(); } log.trace('set target host'); req.targetHost = reqUrl; next(); }; /** * Get the short hash for the targetNaviEntry * @param {object} req Request Object * @returns {String} Shorthash of the instance * @private */ module.exports._getTargetShortHash = function _getShortHash(req) { var log = logger.child({ tx: true, req: req, method: '_getTargetShortHash'}); log.info('called'); var branchName = req.targetNaviEntryInstance.branch; var targetShortHash = find(Object.keys(req.naviEntry.directUrls), function (key) { return req.naviEntry.directUrls[key].branch == branchName; }); log.trace({ targetShortHash: targetShortHash },'Returning target shortHash'); return targetShortHash; };
JavaScript
CL
826853dd04a4b5fec700b38aad7f321083a723a440ca265555f8db14b8f26c72
'use strict'; const post = require( './external-request/post' ); const fs = require( 'fs' ); const url = require( 'url' ); const compose = require( 'async/compose' ); const asyncify = require( 'asyncify' ); const fromArray = require( 'tessa-common/lib/stream/from-array' ); const apply = require( 'tessa-common/lib/stream/apply' ); const FormData = require( 'form-data' ); const http = require( 'http' ); const path = require( 'path' ); const sendRequest = require( './external-request/send-request' ); function uploadColumnMap( columnMap ){ /** * * @param {object} chunkMetaData is the information regarding the chunked data to send, * @param {object} requestContext is the information relating the request being made * @param {string} _ the encoding * @param {function} next the callback. */ function transform( spreadsheetContainerResponse, _, next ){ compose( postColumnMap, getColumnMapURL.bind( null, spreadsheetContainerResponse._links.self.href ) )( ( err, res )=>{ process.nextTick( next.bind( null, null, res ) ); } ); function postColumnMap( columnMapURL, columnMapPayload, next ){ const options = url.parse( columnMapURL ); options.method = 'post'; options.headers = { 'Content-Type': 'application/json', 'Content-Length': columnMapPayload.length }; sendRequest( options, columnMapPayload, ( err, res )=>{ process.nextTick( next.bind( null, null, res ) ); } ); } function getColumnMapURL( spreadsheetDataURL, next ){ const options = url.parse( spreadsheetDataURL ); options.method = 'get'; sendRequest( options, null, ( err, res )=>{ process.nextTick( next.bind( null, null, res._links.next.href, columnMap ) ); } ); } } return require( 'stream' ).Transform( { objectMode: true, transform, flush: require( 'tessa-common/lib/stream/util/just-flush' ) } ); } module.exports = uploadColumnMap;
JavaScript
CL
d2c2dc00f986b56168541d78ac69bc69e70927493a70b3f7e74d5166b2c74517
import React from 'react'; import ReactDOM from 'react-dom'; import { HashRouter, Route, Switch } from 'react-router-dom'; import { Provider } from 'react-redux'; import { Container } from 'reactstrap'; import RequireAuth from './components/RequireAuth'; import store from './reducers'; import App from './components/App'; import StartupScreen from './screens/StartupScreen'; import DashboardScreen from './screens/DashboardScreen'; import ProfileScreen from './screens/ProfileScreen'; ReactDOM.render( <Provider store={store}> <HashRouter> <App> <Switch> <Route path="/profile" component={RequireAuth(ProfileScreen)} /> <Route path="/dashboard" component={RequireAuth(DashboardScreen)} /> <Route exact path="/" component={StartupScreen} /> </Switch> </App> </HashRouter> </Provider>, document.getElementById('root') );
JavaScript
CL
aa974001a2645654a93561f4c43499df5819b39bc9f8ea9e50fcf71354921f4b
// This model was generated by Lumber. However, you remain in control of your models. // Learn how here: https://docs.forestadmin.com/documentation/v/v6/reference-guide/models/enrich-your-models module.exports = (sequelize, DataTypes) => { const { Sequelize } = sequelize; // This section contains the fields of your model, mapped to your table's columns. // Learn more here: https://docs.forestadmin.com/documentation/v/v6/reference-guide/models/enrich-your-models#declaring-a-new-field-in-a-model const Company = sequelize.define('company', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: Sequelize.literal('uuid_generate_v4()'), }, active: { type: DataTypes.BOOLEAN, defaultValue: Sequelize.literal('true'), }, createdAt: { type: DataTypes.DATE, defaultValue: Sequelize.literal('now()'), }, updatedAt: { type: DataTypes.DATE, defaultValue: Sequelize.literal('now()'), }, name: { type: DataTypes.STRING, }, deliverooId: { type: DataTypes.STRING, }, email: { type: DataTypes.STRING, allowNull: false, validate: { notNull: { msg: 'Please enter an email.' } } }, phone: { type: DataTypes.STRING, }, countryDiallingCode: { type: DataTypes.STRING, }, countryIsoAlpha3: { type: DataTypes.STRING, }, }, { tableName: 'company', underscored: true, schema: process.env.DATABASE_SCHEMA, }); // This section contains the relationships for this model. See: https://docs.forestadmin.com/documentation/v/v6/reference-guide/relationships#adding-relationships. Company.associate = (models) => { Company.belongsTo(models.address, { foreignKey: { name: 'addressIdKey', field: 'address_id', }, as: 'address', }); Company.hasMany(models.location, { foreignKey: { name: 'companyIdKey', field: 'company_id', }, as: 'locations', }); Company.hasMany(models.user, { foreignKey: { name: 'companyIdKey', field: 'company_id', }, as: 'users', }); }; return Company; };
JavaScript
CL
f3dee9ad7db4428a0164906d272febe9bb70b632115e7ebeb7280eca141dc023
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); // const SpritesmithPlugin = require('webpack-spritesmith'); // Path // const APP_PATH = __dirname.match('(.*)skin.*')[1]; // const TMPL_PATH = path.resolve(APP_PATH, 'app/design/frontend/PlumTree/ba_mb/template'); module.exports = { entry: { vendor:[ 'vue', 'vuex', 'fastclick' ], app: path.join(__dirname, 'src/main'), // head: path.join(__dirname, 'src/component/headComponet'), head: path.join(__dirname, 'src/component/headOutput/headComponet'), login: path.join(__dirname, 'src/component/loginOutput/login'), register: path.join(__dirname, 'src/component/registerOutput/register'), registerEm: path.join(__dirname, 'src/component/registerOutput/registerEm'), bindphone: path.join(__dirname, 'src/component/registerLoginExtraOutput/bindPhone'), findpsw: path.join(__dirname, 'src/component/registerLoginExtraOutput/findPsw'), findpsw2: path.join(__dirname, 'src/component/registerLoginExtraOutput/findPsw2'), resetPsw: path.join(__dirname, 'src/component/registerLoginExtraOutput/resetPsw'), userCenter: path.join(__dirname, 'src/component/userCenter/userCenter'), changePsw: path.join(__dirname, 'src/component/userCenter_changePswOutput/changePassword'), help: path.join(__dirname, 'src/component/userCenter/help') }, output: { path: path.join(__dirname, '/dist/'), // publicPath: '/dist/', publicPath: '/src/', filename: '[name].js' }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { 'scss': 'vue-style-loader!css-loader!sass-loader', 'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax' } } }, { test: /\.js$/, loader: 'babel-loader', exclude: /(node_modules)/, options: { presets: ['env'], plugins: ['syntax-dynamic-import'] } }, { test: /\.scss$/, use: [ 'style-loader', 'css-loader','postcss-loader', 'sass-loader'] }, { test: /\.(png|jpe?g|eot|svg|ttf|gif|woff2?)$/, loader: 'url-loader', options: { limit: 8192, name: '/assets/img/[name].[ext]' } } ], }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js' }, modules: ["node_modules", "spritesmith-generated"] }, devServer: { historyApiFallback: true, noInfo: true }, performance: { hints: false }, devtool: '#eval-source-map', plugins: [ new webpack.optimize.CommonsChunkPlugin({ names:'vendor', filename:'vue.fastclick.js', minChunks: function (module) { // 通过npm 安装到node_modules目录的库 return module.context && module.context.indexOf("node_modules") !== -1; } }), new ExtractTextPlugin({ filename: '/assets/css/[name]_[chunkhash].css' }), new HtmlWebpackPlugin({ template: './src/dev-pages/register.html', filename: '_register.html', chunks:['register','head'], chunksSortMode: function (a, b) {//控制js加载顺序 ['register','head'] if (a.names[0] > b.names[0]) { return 1; } if (a.names[0] < b.names[0]) { return -1; } return 0; }, title:'手机注册', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/registerEm.html', filename: '_registerEm.html', chunks:['registerEm','head'], chunksSortMode: function (a, b) {//控制js加载顺序 ['register','head'] if (a.names[0] > b.names[0]) { return 1; } if (a.names[0] < b.names[0]) { return -1; } return 0; }, title:'邮箱注册', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/bindphone.html', filename: '_bindphone.html', chunks:['bindphone','head'], title:'绑定手机号', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/login.html', filename: '_login.html', chunks:['login','head'], title:'登录', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/findpsw.html', filename: '_findpsw.html', chunks:['findpsw','head'], title:'找回密码', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/findpsw2.html', filename: '_findpsw2.html', chunks:['findpsw2','head'], title:'找回密码2', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/resetpsw.html', filename: '_resetpsw.html', chunks:['resetPsw','head'], title:'重设密码', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/userCenter_changePsw.html', filename: '_userCenter_changePsw.html', chunks:['changePsw','head'], title:'修改密码', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/userCenter.html', filename: '_userCenter.html', chunks:['userCenter','head'], title:'用户中心首页', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/userCenter_help.html', filename: '_userCenter_help.html', chunks:['help','head'], title:'帮助中心', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/userCenter_setting.html', filename: '_userCenter_setting.html', chunks:['help','head'], title:'用户设置', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/userCenter_security.html', filename: '_userCenter_security.html', chunks:['help','head'], title:'安全中心', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/order_waiting.html', filename: '_order_waiting.html', chunks:['help','head'], title:'待付款', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/order_send.html', filename: '_order_send.html', chunks:['help','head'], title:'已发货', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/order_pay.html', filename: '_order_pay.html', chunks:['help','head'], title:'已付款', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/browsing.html', filename: '_browsing.html', chunks:['help','head'], title:'浏览足迹', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/collection.html', filename: '_collection.html', chunks:['help','head'], title:'收藏夹', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/coupon.html', filename: '_coupon.html', chunks:['help','head'], title:'优惠券-已使用', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/coupon2.html', filename: '_coupon2.html', chunks:['help','head'], title:'优惠券-未使用', hash: false }), new HtmlWebpackPlugin({ template: './src/dev-pages/myorder.html', filename: '_myorder.html', chunks:['help','head'], title:'优惠券-未使用', hash: false }) ] }
JavaScript
CL
4216c56890f5fa94fbe4a293811ef80d5a86bf6ceda3ca317022bf29f29a95f7
"use strict"; /** * generate an artificial dataset * column description follows visualizations * with additional values (see respective type-classes) * some are shared: * * - if "isarray" is set, "multitude" gives the count of columns for that binding * default: 2 * * param * * columns | Object | column description; see generators and vizdescriptions * settings | Object | additional settings * settings.rowmode | Enum | determines the mode how to generator measurements inside the rows * | 'groups' | for each combination of dimensions all measures are created * | 'hierarchies' | for each combination of dimensions one measure is created * | 'random' | a random combination of values from all columns is created * | 'timeseries' | for each combination of dimensions a timeseries of measures is created * settings.rowcount | Number | number of rows created; used only for rowmode='random' * * * notes * * - make sure the measurement columns contain enough values * to satisfy all relevant dimension combinations * - measurement columns will be reset per time column value change * * */ define( ['basic/Constants', 'basic/types/Dataset', 'store/data', 'testing/generator/NumericColumn', 'testing/generator/SemanticColumn', 'testing/generator/TimeColumn', 'basic/types/Null', ], function( Constants, Dataset, Datastore, NumericColumn, SemanticColumn, TimeColumn, NullType ){ /** * actual function */ return async function createDataset( def ) { // create generator classes const generators = []; let pos = 0; // column position for( let i=0; i<def.columns.length; i++ ) { // shortcut const d = def.columns[i]; // select column generator const generatorPool = []; switch( d.datatype ) { case Constants.DATATYPE.NUMERIC: case Constants.VIZDATATYPE.QUANTITATIVE: generatorPool.push( NumericColumn ); break; case Constants.DATATYPE.SEMANTIC: case Constants.VIZDATATYPE.CATEGORICAL: generatorPool.push( SemanticColumn ); break; case Constants.DATATYPE.TIME: case Constants.VIZDATATYPE.TIME: generatorPool.push( TimeColumn ); break; default: // combined datatypes: collect all options if( (d.datatype & Constants.VIZDATATYPE.CATEGORICAL) == Constants.VIZDATATYPE.CATEGORICAL ) { generatorPool.push( SemanticColumn ); } if( (d.datatype & Constants.VIZDATATYPE.QUANTITATIVE) == Constants.VIZDATATYPE.QUANTITATIVE ) { generatorPool.push( NumericColumn ); } if( (d.datatype & Constants.VIZDATATYPE.TIME) == Constants.VIZDATATYPE.TIME ) { generatorPool.push( TimeColumn ); } } // an empty pool should not occur if( generatorPool.length < 1 ) { throw Error( 'Unknown datatype: ' + d.datatype ); } // single vs multiple binding-columns if( d.isarray ) { // multiple: add a sufficient number of generators at random const multitude = d.multitude || 2; for( let i=0; i<multitude; i++ ) { const gen = generatorPool[ Math.floor( Math.random() * generatorPool.length ) ]; generators.push( new gen( pos, d ) ); pos += 1; } } else { // single: add generator generators.push( new generatorPool[ Math.floor( Math.random() * generatorPool.length ) ]( pos, d ) ); pos += 1; } } /* XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Metadata XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ // set dataset-wide metadata const meta = { columns: generators.map( g => g.meta ) }; /* XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Data XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ // select row generator scheme let createRow = createRowTimeseries; if( ('settings' in def) && def.settings && ('rowmode' in def.settings)) { switch( def.settings.rowmode.toLowerCase() ) { case 'hierarchy': createRow = createRowHierarchy; break; case 'group': createRow = createRowGroup; break; case 'random': createRow = createRowRandom; break; case 'timeseries': createRow = createRowTimeseries; break; } } // init all generators generators.forEach( g => g.init() ); // split generators in dimensions and measurements const dimGens = generators.map( (g) => (g.role == Constants.ROLE.DIM) ? g : null ), measGens = generators.map( (g) => (g.role == Constants.ROLE.MEAS) ? g : null ); // collect row data const data = generators.map( g => [] ); for( let row of createRow( dimGens, measGens, 0, def ) ) { // copy to data object's column oriented structure for( let i=0; i<row.length; i++ ) { data[i].push( row[i] ); } } /* XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Finalize XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ // create the dataset object const ds = new Dataset( meta, data ); // debug: print the created dataset // showData( ds.getDataRows(), def ); // insert into datastore const id = Datastore.addDataset( ds ); return id; }; /** * helper function to display the created dataset */ function showData( d, def ) { console.log( `Mode: ${def.settings.rowmode}`); console.log( '------------------------------- DATA -----------------------------' ) for( let row of d ) { console.log( row.join( '\t' ) ); } console.log( '------------------------------------------------------------------' ) } /* XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Row Creators XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ /** * generator function to create the subsequent rows * timeseries edition */ function* createRowTimeseries( dimGens, measGens, index ) { // if we are beyond all dimension generators if( index >= dimGens.length ) { // create values from all measurement generators const res = []; for( let generator of measGens ) { if( generator ) { res[ generator.getPos() ] = generator.getValue(); } } // return as a single result yield res; return; } // shortcut const generator = dimGens[ index ]; // skip measurement generators for now if( !generator ) { yield* createRowTimeseries( dimGens, measGens, index+1 ); return; } // if this is a non Categorical column, init all measurements anew if( (generator instanceof TimeColumn) || (generator instanceof NumericColumn) ) { measGens.forEach( g => g ? g.init() : '' ); } // reset the generator generator.reset(); // get the values // traverse all values from this generator for( let curValue of generator.getValues() ) { // traverse the next level of generators for( let subVal of createRowTimeseries( dimGens, measGens, index+1 ) ){ // insert the current value subVal[ generator.getPos() ] = curValue; // output yield subVal; } } } /** * generator function to create the subsequent rows * hierarchies edition */ function* createRowHierarchy( dimGens, measGens, index ) { // if we are beyond all dimension generators if( index >= dimGens.length ) { // create values from all measurement generators const res = []; for( let generator of measGens ) { if( generator ) { // init the generator anew // TODO can probably be optimized generator.init(); // insert the value res[ generator.getPos() ] = generator.getValue(); } } // return as a single result yield res; return; } // shortcut const generator = dimGens[ index ]; // skip measurement generators for now if( !generator ) { yield* createRowHierarchy( dimGens, measGens, index+1 ); return; } // reset the generator generator.reset(); // get the values // traverse all values from this generator for( let curValue of generator.getValues() ) { // traverse the next level of generators for( let subVal of createRowHierarchy( dimGens, measGens, index+1 ) ){ // insert the current value subVal[ generator.getPos() ] = curValue; // output yield subVal; } } } /** * generator function to create the subsequent rows * group edition */ function* createRowGroup( dimGens, measGens, index ) { // end the recursion if( index >= dimGens.length ) { yield []; return; } // shortcut const generator = dimGens[ index ] || measGens[ index ]; // reset the generator generator.init(); // get the values // traverse all values from this generator for( let curValue of generator.getValues() ) { // traverse the next level of generators for( let subVal of createRowGroup( dimGens, measGens, index+1 ) ){ // insert the current value subVal[ generator.getPos() ] = curValue; // output yield subVal; } } } /** * generator function to create the subsequent rows * group edition */ function* createRowRandom( dimGens, measGens, index, def ) { // default values def.settings = Object.assign({ rowcount: 10, }, def.settings ); // we may need a null value const nullInstance = NullType(); // should null values be included? const missingThreshold = def.settings && ('missing' in def.settings) ? def.settings.missing : 0; // collect getter functions const getter = dimGens.map( (gen,i) => { // get the generator gen = dimGens[i] || measGens[i]; // provide an accessor if( gen instanceof SemanticColumn ) { // semantic columns return (function(gen){ // pool of values const pool = [ ... gen.getValues() ]; return function(){ if( Math.random() < missingThreshold ) { return nullInstance; } else { return pool[ Math.floor( Math.random() * pool.length ) ]; } }; })( gen ); } else { // numeric/time columns return (function(gen){ return function(){ if( Math.random() < missingThreshold ) { return nullInstance; } else { return gen.getRandomValue(); } }; })( gen ); } }); for( let i=0; i<def.settings.rowcount; i++ ) { yield getter.map( g => g() ); } } });
JavaScript
CL
0da2250e3975a7d4e187d2457fc802ca5cb6e5f2ee816e67d0d5826978e6fbf7
import React from 'react'; import PropTypes from 'prop-types'; /* eslint-disable import/no-named-as-default */ import Dropdown from '../Dropdown'; import IntegrationPicker from '../IntegrationPicker'; /* eslint-enable import/no-named-as-default */ import { integrationPropType } from '../propTypes'; import './IntegrationManual.scss'; const IntegrationManual = ({ site, integration, integrations, handleNewParams, }) => ( <div className="integration-manual"> <h2 className="integration-manual__title"> {'Integration manual for '} <img src={integration.logo} className="integration-manual__logo" alt={integration.name} /> <Dropdown placeholder="switch" closeDropdownAction="onChange" className="integration-manual__integration-dropdown" > <IntegrationPicker onChange={handleNewParams} integrations={integrations} key="integrationPicker" /> </Dropdown> </h2> <div className="integration-manual__steps"> {/* eslint-disable react/no-array-index-key */ integration.manual.steps.map((step, i) => ( <div key={i} className="integration-manual__step"> <div className="integration-manual__step__title"> <span className="integration-manual__step__num"> {`Step ${i + 1}`} </span> - {step.title} </div> <div className="integration-manual__step__body"> {step.body(site.key, site.url)} </div> </div> )) /* eslint-enable react/no-array-index-key */ } </div> </div> ); IntegrationManual.propTypes = { site: PropTypes.shape({ key: PropTypes.string.isRequired, url: PropTypes.string.isRequired, }).isRequired, integration: integrationPropType.isRequired, integrations: PropTypes.arrayOf(integrationPropType).isRequired, handleNewParams: PropTypes.func.isRequired, }; export default IntegrationManual;
JavaScript
CL
2ebfefd024ebf47aa82eb9816c1707e87ee058c34a69ba4ef23d461d7e436578
/* * * Configs for the server * */ // Container for all the environments var environments = {}; // Debug configuration environments.debug = { 'envName': 'debug', 'httpPort': 8080, 'httpsPort': 8081, 'hashSecret': 'thisIsASecret' }; // Production configuration environments.production = { 'envName': 'production', 'httpPort': 80, 'httpsPort': 443, 'hashSecret': 'zjfbe654wgj7i4g' }; // Determine requested in command line environment var currentEnvironment = typeof(process.env.NODE_ENV) == 'string' ? process.env.NODE_ENV.toLowerCase() : ''; // Take chosen environment from the object or take default one var environmentToExport = typeof(environments[currentEnvironment]) == 'object' ? environments[currentEnvironment] : environments.debug; // Export the module module.exports = environmentToExport;
JavaScript
CL
6b742bcf78b6beb62f61e02177b478ad089ffd19431ca923e6395bef7b9cd120
import React from "react"; // @material-ui/core components import { makeStyles } from "@material-ui/core/styles"; import InputAdornment from "@material-ui/core/InputAdornment"; import Icon from "@material-ui/core/Icon"; // @material-ui/icons import People from "@material-ui/icons/People"; import Favorite from "@material-ui/icons/Favorite"; import Email from "@material-ui/icons/Email"; import CheckCircle from "@material-ui/icons/CheckCircle"; import IconButton from "@material-ui/core/IconButton"; import Visibility from "@material-ui/icons/Visibility"; import VisibilityOff from "@material-ui/icons/VisibilityOff"; // core components import Header from "components/Header/Header.js"; import HeaderLinks from "components/Header/HeaderLinks.js"; import Footer from "components/Footer/Footer.js"; import GridContainer from "components/Grid/GridContainer.js"; import GridItem from "components/Grid/GridItem.js"; import Button from "components/CustomButtons/Button.js"; import Card from "components/Card/Card.js"; import CardBody from "components/Card/CardBody.js"; import CardFooter from "components/Card/CardFooter.js"; import CustomInput from "components/CustomInput/CustomInput.js"; //jss import styles from "assets/jss/material-kit-react/views/loginPage.js"; import image from "assets/img/bg8.jpg"; import { get, postJSON } from "axiosSetting.js"; import useForm from "react-hook-form"; const useStyles = makeStyles(styles); // eslint-disable-next-line no-useless-escape const emailREG = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; const codeREG = /^[0-9]{6}$/; const defalutCodeText = "发送验证码"; const initialState = { nickname: "", email: "", code: "", password: "", repeatPassword: "", codeText: defalutCodeText, codeButtonDisabled: false, showPassword: false, showRepeatPassword: false }; const registerReducer = (state, action) => { console.log(JSON.stringify(state)); console.log(JSON.stringify(action)); const { type, payload } = action; switch (type) { case "INPUT_CHANGE": return { ...state, [payload.key]: payload.value }; case "TOGGLE_BUTTON": return { ...state, [payload.key]: !state[payload.key] }; case "CODE_TEXT_CHANGE": return { ...state, codeButtonDisabled: payload === defalutCodeText ? false : true, codeText: payload }; default: return state; } }; export default function RegisterPage(props) { const [cardAnimaton, setCardAnimation] = React.useState("cardHidden"); setTimeout(function() { setCardAnimation(""); }, 700); const classes = useStyles(); const { ...rest } = props; const [state, dispatch] = React.useReducer(registerReducer, initialState); const { register, handleSubmit, errors } = useForm({ mode: "onBlur" }); //处理input框onChange事件 const handleChange = key => e => { dispatch({ type: "INPUT_CHANGE", payload: { key: key, value: e.target.value } }); }; //处理toggle类型的button的onClick事件 const handleToggle = key => () => { dispatch({ type: "TOGGLE_BUTTON", payload: { key: key } }); }; //注册 const handleRegister = async () => { const { nickname, password, email, code } = state; const body = { nickname: nickname, email: email, code: code, password: password }; let res = await postJSON("/api/user/register", body); if (res && res.code === 0) rest.history.push("/login"); }; //发送验证码请求,倒计时1分钟 const handleSendCode = () => { if (errors.email) return; get("/api/user/sendCode", { email: state.email }); let countdown = 60; const text = "s 重新发送"; const timer = setInterval(() => { if (countdown > 0) { dispatch({ type: "CODE_TEXT_CHANGE", payload: countdown + text }); countdown--; } else { clearInterval(timer); dispatch({ type: "CODE_TEXT_CHANGE", payload: defalutCodeText }); } }, 1000); }; //检查email是否被注册,为什么发送了3次,可能react-hook-form问题,onBlur重复检测有点问题 const handleCheckEmail = async value => { let isRegistered = true; let res = await get("/api/user/check", { email: value }); console.log(res); if (res && res.code === 0) isRegistered = false; return !isRegistered || "邮箱已被注册"; }; const handleCheckPassword = value => { if (/^\d+$/.test(value)) return "不能为纯数字"; if (/^[A-Za-z]+$/.test(value)) return "不能为纯字母"; return /^[A-Za-z0-9]+$/.test(value); }; const handleCheckRepeatPassword = value => { let password = state.password || ""; return value === password || "两次密码不一致"; }; return ( <div> <Header absolute color="transparent" brand="MeetHere" rightLinks={<HeaderLinks />} {...rest} /> <div className={classes.pageHeader} style={{ backgroundImage: "url(" + image + ")", backgroundSize: "cover", backgroundPosition: "top center" }} > <div className={classes.container}> <GridContainer justify="center"> <GridItem xs={12} sm={12} md={4}> <Card className={classes[cardAnimaton]}> <form className={classes.form} onSubmit={handleSubmit(handleRegister)} > <CardBody> <h2 className={classes.cardTitle}>用户注册</h2> <CustomInput labelText="昵称" id="nickname" formControlProps={{ fullWidth: true }} error={!!errors.nickname} inputProps={{ type: "text", placeholder: "用户昵称(不超过20位)", name: "nickname", inputRef: register({ required: "不能为空", maxLength: { value: 20, message: "昵称太长" } }), startAdornment: ( <InputAdornment position="start"> <People className={classes.inputIconsColor} /> </InputAdornment> ), onChange: handleChange("nickname") }} helperText={errors.nickname && errors.nickname.message} //配合inputRef的register /> <CustomInput labelText="电子邮箱" id="email" formControlProps={{ fullWidth: true }} error={!!errors.email} inputProps={{ type: "text", placeholder: "电子邮箱", name: "email", inputRef: register({ required: "不能为空", pattern: { value: emailREG, message: "邮件格式不合法" }, validate: handleCheckEmail }), startAdornment: ( <InputAdornment position="start"> <Email className={classes.inputIconsColor} /> </InputAdornment> ), onChange: handleChange("email") }} helperText={errors.email && errors.email.message} /> <CustomInput labelText="验证码" id="code" formControlProps={{ fullWidth: true }} error={!!errors.code} inputProps={{ type: "text", placeholder: "6位数字验证码", name: "code", inputRef: register({ required: "不能为空", pattern: { value: codeREG, message: "验证码格式不合法" } }), startAdornment: ( <InputAdornment position="start"> <CheckCircle className={classes.inputIconsColor} /> </InputAdornment> ), endAdornment: ( <InputAdornment position="end"> <Button className={classes.sendCode} type="submit" color="primary" onClick={handleSendCode} disabled={state.codeButtonDisabled} > {state.codeText} </Button> </InputAdornment> ), onChange: handleChange("code") }} helperText={errors.code && errors.code.message} //配合inputRef的register /> <CustomInput labelText="密码" id="pass" formControlProps={{ fullWidth: true }} error={!!errors.password} inputProps={{ type: state.showPassword ? "text" : "password", placeholder: "密码(6-16位数字和字母组合)", name: "password", inputRef: register({ required: "不能为空", minLength: { value: 6, message: "密码太短" }, maxLength: { value: 16, message: "密码太长" }, validate: handleCheckPassword }), startAdornment: ( <InputAdornment position="start"> <Icon className={classes.inputIconsColor}> lock_outline </Icon> </InputAdornment> ), endAdornment: ( <InputAdornment position="end"> <IconButton aria-label="toggle password visibility" onClick={handleToggle("showPassword")} > {state.showPassword ? ( <Visibility /> ) : ( <VisibilityOff /> )} </IconButton> </InputAdornment> ), autoComplete: "off", onChange: handleChange("password") }} helperText={errors.password && errors.password.message} //配合inputRef的register /> <CustomInput labelText="重复密码" id="repeat-pass" formControlProps={{ fullWidth: true }} error={!!errors.repeatPassword} inputProps={{ type: state.showRepeatPassword ? "text" : "password", placeholder: "重复密码", name: "repeatPassword", inputRef: register({ required: "不能为空", validate: handleCheckRepeatPassword }), startAdornment: ( <InputAdornment position="start"> <Icon className={classes.inputIconsColor}> lock_outline </Icon> </InputAdornment> ), endAdornment: ( <InputAdornment position="end"> <IconButton aria-label="toggle password visibility" onClick={handleToggle("showRepeatPassword")} > {state.showRepeatPassword ? ( <Visibility /> ) : ( <VisibilityOff /> )} </IconButton> </InputAdornment> ), autoComplete: "off", onChange: handleChange("repeatPassword") }} helperText={ errors.repeatPassword && errors.repeatPassword.message } //配合inputRef的register /> </CardBody> <CardFooter className={classes.cardFooter}> <Button type="submit" color="primary" round> <Favorite /> 注册 </Button> </CardFooter> </form> </Card> </GridItem> </GridContainer> </div> <Footer whiteFont /> </div> </div> ); }
JavaScript
CL
9f2d0495655122748c881d03b3fb19fe4b1157ceddf03fbab481fab003c4e485
import React from 'react'; import { shallow } from 'enzyme'; import { chai } from 'meteor/practicalmeteor:chai'; import { ReadyPromptComponent } from './ready-prompt.component'; describe('Component: ReadyPromptComponent', () => { describe('when not connected to room', () => { describe('when first user in the room', () => { it('should attempt to join room stream directly', () => { const company = { name: 'cheese', href: 'test' }; const el = shallow(<ReadyPromptComponent />); chai.assert(false); }); }); describe('when not first user in the room', () => { it('should not attempt to join room stream right away', () => { const company = { name: 'cheese', href: 'test' }; const el = shallow(<ReadyPromptComponent />); chai.assert(false); }); describe('when tapping join button', () => { it('should attempt to join room stream', () => { chai.assert(false); }); }); describe('when tapping root element', () => { it('should initiate onTouchTap from props', () => { chai.assert(false); }); }); }); }); describe('when connected to room', () => { it('should not show a loading screen or join option', () => { chai.assert(false); }); }); });
JavaScript
CL
a528fe481a9ef2ee198bb77b6157f8acbfe28ffe0a3565994dafe9695b0a10b3
var fs = require('fs'); var path = require('path'); var _ = require('underscore'); var utils = require("../helpers/http-helpers"); var getHandler = require("../web/get-handler"); /* * You will need to reuse the same paths many times over in the course of this sprint. * Consider using the `paths` object below to store frequently used file paths. This way, * if you move any files, you'll only need to change your code in one place! Feel free to * customize it in any way you wish. */ exports.paths = { 'siteAssets' : path.join(__dirname, '../web/public'), 'archivedSites' : path.join(__dirname, '../archives/sites'), 'list' : path.join(__dirname, '../archives/sites.txt') }; // Used for stubbing paths for jasmine tests, do not modify exports.initialize = function(pathsObj){ _.each(pathsObj, function(path, type) { exports.paths[type] = path; }); }; // The following function names are provided to you to suggest how you might // modularize your code. Keep it clean! //step 1 exports.requestAddUrl = function(res, url){ exports.accessList(res, url); }; exports.accessList = function(res, url){ fs.readFile(exports.paths.list, function(err, data){ var allSites = data.toString(); if(!exports.isUrlInList(url, allSites)){ exports.addUrlToList(res, url); getHandler.serveAssets(res, utils.fullURL('loading.html'), 302); }else{ exports.accessArchive(res, url); } }); }; exports.isUrlInList = function(url, list){ return list.search(url) !== -1; }; exports.addUrlToList = function(res, url){ fs.appendFile(exports.paths.list, url + '\n', function(err){ if(err){ console.log(err); }else{ console.log(url + ' is added to sites.txt'); } }); }; exports.accessArchive = function(res, url){ var targetArchive = exports.paths.archivedSites + '/' + url; fs.exists(targetArchive, function(exists){ if(exists){ getHandler.serveAssets(res, targetArchive, 302); }else{ getHandler.serveAssets(res, utils.fullURL('loading.html'), 302); } }); }; exports.saveToArchive = function(url, data){ fs.writeFile(exports.paths.archivedSites + '/' + url, data, function(err){ if(err){ console.log(err); } }); };
JavaScript
CL
3ff437120e429931f71e1a63af897954cd09cadb50da83faf2bed50f5bf96441
import React from "react"; import { createStore, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import reduxPromise from "redux-promise"; import rootReducer from "./reducers"; import { Provider } from "react-redux"; import { composeWithDevTools } from "redux-devtools-extension"; import PropTypes from "prop-types"; const middleware = [thunk, reduxPromise]; const Root = ({ children, initialState = {} }) => { const store = createStore( rootReducer, initialState, composeWithDevTools(applyMiddleware(...middleware)) ); return <Provider store={store}>{children}</Provider>; }; Root.propTypes = { children: PropTypes.object.isRequired, initialState: PropTypes.object }; export default Root;
JavaScript
CL
827476e622eb410bbdd157d03a2fddc5da3e6c034de8683afd0af310d153fb46
// Include our config file that defines port # var config = require('./config/config.json'); var express = require('express'); const path = require('path'); // parses post data and lets you access it from req.body.<nameofparam> var bodyParser = require('body-parser') // instantiate an app server. var app = express(); // MIDDLEWARE app.use( bodyParser.json() ); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); //ROUTES var InsertRouter = require('./controllers/InsertController.js'); var FindAllRouter = require('./controllers/FindAllController.js'); // handles get requests to <domain>/ app.get("/", function (req, res) { res.render("index"); }); // handles post requests to <domain>/ app.post("/", InsertRouter.insert); // After inserting records, go to <domain>/requets to see all requests! app.get("/requests", FindAllRouter.find); // listens for http requests on our Port defined in config.json app.listen(config.PORT, function() { console.log("listening on port: " + config.PORT); });
JavaScript
CL
edd3ba8d6a53095d28af557170876b3063feea992620484186258b60e5df886d
const log = require('./lib/Log').getLogger(`server[${process.pid}]`) const path = require('path') const getIPAddress = require('./lib/getIPAddress') const http = require('http') const fs = require('fs') const { promisify } = require('util') const parseCookie = require('./lib/parseCookie') const jwtVerify = require('jsonwebtoken').verify const Koa = require('koa') const koaBody = require('koa-body') const koaFavicon = require('koa-favicon') const koaLogger = require('koa-logger') const koaMount = require('koa-mount') const koaRange = require('koa-range') const koaStatic = require('koa-static') const Prefs = require('./Prefs') const libraryRouter = require('./Library/router') const mediaRouter = require('./Media/router') const prefsRouter = require('./Prefs/router') const roomsRouter = require('./Rooms/router') const userRouter = require('./User/router') const SocketIO = require('socket.io') const socketActions = require('./socket') const IPC = require('./lib/IPCBridge') const IPCLibraryActions = require('./Library/ipc') const IPCMediaActions = require('./Media/ipc') const { SERVER_WORKER_STATUS, SERVER_WORKER_ERROR, } = require('../shared/actionTypes') async function serverWorker ({ env, startScanner, stopScanner }) { const jwtKey = await Prefs.getJwtKey() const app = new Koa() // server error handler app.on('error', (err, ctx) => { if (err.code === 'EPIPE') { // these are common since browsers make multiple requests for media files log.verbose(err.message) return } // silence 4xx response "errors" (koa-logger should show these anyway) if (ctx.response && ctx.response.status.toString().startsWith('4')) { return } if (err.stack) log.error(err.stack) else log.error(err) }) // middleware error handler app.use(async (ctx, next) => { try { await next() } catch (err) { ctx.status = err.status || 500 ctx.body = err.message ctx.app.emit('error', err, ctx) } }) // http request/response logging app.use(koaLogger((str, args) => (args.length === 6 && args[3] >= 500) ? log.error(str) : log.verbose(str))) app.use(koaFavicon(path.join(env.KF_SERVER_PATH_ASSETS, 'favicon.ico'))) app.use(koaRange) app.use(koaBody({ multipart: true })) // all http requests app.use(async (ctx, next) => { ctx.io = io ctx.jwtKey = jwtKey ctx.startScanner = startScanner ctx.stopScanner = stopScanner // verify jwt try { const { kfToken } = parseCookie(ctx.request.header.cookie) ctx.user = jwtVerify(kfToken, jwtKey) } catch (err) { ctx.user = { userId: null, username: null, name: null, isAdmin: false, roomId: null, } } await next() }) // http api (koa-router) endpoints app.use(libraryRouter.routes()) app.use(mediaRouter.routes()) app.use(prefsRouter.routes()) app.use(roomsRouter.routes()) app.use(userRouter.routes()) // @todo these could be read dynamically from src/routes // but should probably wait for react-router upgrade? const rewriteRoutes = ['account', 'library', 'queue', 'player'] const indexFile = path.join(env.KF_SERVER_PATH_WEBROOT, 'index.html') if (env.NODE_ENV === 'development') { log.info('Enabling webpack dev and HMR middleware') const webpack = require('webpack') const webpackConfig = require('../config/webpack.config') const compiler = webpack(webpackConfig) const koaWebpack = require('koa-webpack') koaWebpack({ compiler }) .then((middleware) => { // webpack-dev-middleware and webpack-hot-client app.use(middleware) // serve /assets since webpack-dev-server is unaware of this folder app.use(koaMount('/assets', koaStatic(env.KF_SERVER_PATH_ASSETS))) // "rewrite" top level SPA routes to index.html app.use(async (ctx, next) => { const route = ctx.request.path.substring(1).split('/')[0] if (!rewriteRoutes.includes(route)) return next() ctx.body = await new Promise(function (resolve, reject) { compiler.outputFileSystem.readFile(indexFile, (err, result) => { if (err) { return reject(err) } return resolve(result) }) }) ctx.set('content-type', 'text/html') ctx.status = 200 }) }) } else { // production mode // serve build folder as webroot app.use(koaStatic(env.KF_SERVER_PATH_WEBROOT)) app.use(koaMount('/assets', koaStatic(env.KF_SERVER_PATH_ASSETS))) // "rewrite" top level SPA routes to index.html const readFile = promisify(fs.readFile) app.use(async (ctx, next) => { const route = ctx.request.path.substring(1).split('/')[0] if (!rewriteRoutes.includes(route)) return next() ctx.body = await readFile(indexFile) ctx.set('content-type', 'text/html') ctx.status = 200 }) } // end if // create http server const server = http.createServer(app.callback()) // http server error handler server.on('error', function (err) { log.error(err) process.emit('serverWorker', { type: SERVER_WORKER_ERROR, error: err.message, }) // not much we can do without a working server process.exit(1) }) // create socket.io server and attach handlers const io = SocketIO(server, { serveClient: false }) socketActions(io, jwtKey) // attach IPC action handlers IPC.use(IPCLibraryActions(io)) IPC.use(IPCMediaActions(io)) log.info(`Starting web server (host=${env.KF_SERVER_HOST}; port=${env.KF_SERVER_PORT})`) // success callback in 3rd arg server.listen(env.KF_SERVER_PORT, env.KF_SERVER_HOST, () => { const port = server.address().port const url = `http://${getIPAddress()}` + (port === 80 ? '' : ':' + port) log.info(`Web server running at ${url}`) process.emit('serverWorker', { type: SERVER_WORKER_STATUS, payload: { url }, }) }) } module.exports = serverWorker
JavaScript
CL
98425c325a55cbe36405475edf505d6696f1d8aba4ab845661adf321d13aad2a
/** * Given a starting string and a list of insertions to make to make to that string, * find the count of the most frequent character minus the least frequent after * applying the list of insertions ten times. * */ const partOne = (input) => { let [template, rules] = parseInputString(input); let letterCounts = polymerCounts(template, rules, 10); return mostLeastFrequentDiff(letterCounts); } /** * Find the counts of each character after applying the rules to the template iterations times * * A start of NNCB and a rule of 'NN -> C' with an iteration of 1 will result in a string of 'NCNCB' * * This works by keeping a map of pairs => count, which is replaced each iteration, and a map of characters => count which isn't * * @param {array} template array of characters for the initial string * @param {array} rules array of rules of the form [ SS, S] where SS is a pair of characters and S is the character to insert between them * @param {*} iterations how many times to apply the ruleset * @returns Map of letter => times it appears */ const polymerCounts = (template, rules, iterations) => { let polymer = new Map(); let letterCounts = new Map(); increaseMapCounter(letterCounts, template[0], 1); for (let i = 1; i < template.length; i++) { increaseMapCounter(polymer, template[i-1] + template[i], 1); increaseMapCounter(letterCounts, template[i], 1); } for (let step = 0; step < iterations; step++ ) { let newPolymer = new Map(); rules.forEach(rule => { let match = rule[0]; let insert = rule[1]; let currentCount = polymer.get(match) ?? 0; increaseMapCounter(newPolymer, match[0] + insert, currentCount); increaseMapCounter(newPolymer, insert + match[1] , currentCount); increaseMapCounter(letterCounts, insert, currentCount); }) polymer = newPolymer; } return letterCounts; } /** * Given a map of counts, find the difference of the highest and lowest count * @param {Map} map any key to numeric value * @returns int */ const mostLeastFrequentDiff = (map) => { let mostFrequent = Math.max(...Array.from(map.values())); let leastFrequent = Math.min(...Array.from(map.values())); return mostFrequent - leastFrequent; } /** * Increase the value of the map.key by additionalCount * @param {Map} map * @param {*} key * @param {int} additionalCount */ const increaseMapCounter = (map, key, additionalCount) => { let existingCount = map.get(key) ?? 0; map.set(key, existingCount + additionalCount); } /** * Given a starting string and a list of insertions to make to make to that string, * find the count of the most frequent character minus the least frequent after * applying the list of insertions forty times. */ const partTwo = (input) => { let [template, rules] = parseInputString(input); let letterCounts = polymerCounts(template, rules, 40); return mostLeastFrequentDiff(letterCounts); } const parseInputString = (input) => { let [start, unparsedRules] = input.split("\n\n"); start = start.split(''); let rules = unparsedRules.split("\n").map( rule => rule.split(' -> ')); return [start, rules] } module.exports = {partOne, partTwo};
JavaScript
CL
9c2e0ca15a8578cb8bd87a0686f4063b434ae827b00fb697e459d242c05769fb
'use strict' //dependencies const gulp = require('gulp'); const del = require('del'); const util = require('gulp-util'); const zip = require('gulp-zip'); const minimist = require('minimist'); const rename = require('gulp-rename'); const exec = require('child_process').exec; const replace = require('gulp-replace'); const merge = require('merge-stream'); const cleancss = require('gulp-clean-css'); const concat = require('gulp-concat'); const babel = require('gulp-babel'); const uglify = require('gulp-uglify'); const download = require('gulp-download'); let timestamp = Math.round(Date.now() / 1000); gulp.task('default', ['cachebust', 'zip']); //clean dynamiclly generated files gulp.task('clean', () => { return del(['dist', 'src/_site', 'src/css/_vendor', 'src/css/fonts', 'src/js/_vendor', 'src/css/vendor.min.css', 'src/js/vendor.min.js']); }); //make a zip file for distribution and backup gulp.task('zip', ['build'], () => { let fszip = gulp.src('dist/_site/**') .pipe(zip(`v${timestamp}.zip`)) .pipe(gulp.dest('dist/_site/files')); return fszip; }); //jekyll build the site gulp.task('build', ['scripts'], (cb) => { exec(['jekyll b --source src --destination dist/_site'], function(err, stdout, stderr) { console.log(stdout); console.log(stderr); cb(err); }); }); //compile stylesheet gulp.task('styles', ['libs'], () => { let vendor = gulp.src(['src/css/_vendor/*.css']) .pipe(cleancss()) .pipe(concat('vendor.min.css')) .pipe(gulp.dest('src/css')); return vendor; }); //compile javascript gulp.task('scripts', ['styles'], () => { let vendor = gulp.src(['src/js/_vendor/*.js']) .pipe(uglify()) .pipe(concat('vendor.min.js')) .pipe(gulp.dest('src/js')); let main = gulp.src(['src/js/_main.js']) .pipe(babel({ presets: ['es2015'] })) .pipe(uglify()) .pipe(rename('main.min.js')) .pipe(gulp.dest('src/js')); return merge(vendor, main); }); gulp.task('libs', ['clean'], () => { //catfw let catfwcss = gulp.src('src/assets/catfw.min.css') .pipe(gulp.dest('src/css/_vendor/')); let catfwfonts = gulp.src(['src/assets/fonts/catif.ttf', 'src/assets/fonts/catif.woff', 'src/assets/fonts/catif.eot', 'src/assets/fonts/catif.svg']) .pipe(gulp.dest('src/css/fonts')); let catfwjs = gulp.src('src/assets/catfw.min.js') .pipe(gulp.dest('src/js/_vendor/')); //jquery let jquery = download('https://code.jquery.com/jquery-3.1.0.min.js') .pipe(gulp.dest('src/js/_vendor/')); let svg4everybody = download('https://raw.githubusercontent.com/jonathantneal/svg4everybody/master/dist/svg4everybody.min.js') .pipe(gulp.dest('src/js/_vendor/')); return merge(catfwcss, catfwjs, jquery, svg4everybody); }); //add timestamp to static assets to bust cache //not the best solution, will use MD5 later gulp.task('cachebust', ['build'], () => { let fscachebust = gulp.src(['dist/_site/**/*.html', 'dist/_site/**/*.md', 'dist/_site/**/*.markdown']) .pipe(replace(/@@hash/g, timestamp)) .pipe(gulp.dest('dist/_site')) return fscachebust; }); //compress images gulp.task('imagemin', () => { gulp.src(['src/images/*', '_ux/*.{png,jpeg,svg}']) .pipe(imagemin()) .pipe(gulp.dest('src/images')); });
JavaScript
CL
96d0b80663102e4732577367103118e94e70d806f8251e5bedc84dd07fe6a542
import React from 'react'; import ReactDOM from 'react-dom'; import { Card, CardHeader } from 'material-ui/Card'; import Field from './verify_key_fields_component'; import ArrowDownIcon from 'material-ui/svg-icons/hardware/keyboard-arrow-down'; import { Translate } from 'react-redux-i18n'; import _ from 'lodash'; class VerifyKeyDocument extends React.Component { constructor(props) { super(props); this.state = { inputHeight: 'calc(100vh - 196px)' }; } componentDidMount() { let nodeStyle = null; if (this.refs['input-zone']) { nodeStyle = ReactDOM.findDOMNode(this.refs['input-zone']); } if (nodeStyle) { this.setState({ inputHeight: window.innerHeight - nodeStyle.getBoundingClientRect().top - 20 }); } } shouldComponentUpdate(nextProps) { return !_.isEqual(this.props, nextProps); } render() { const { action_onBlurField, action_onFocusField, action_onKeyPressFocus, action_onModifyFieldValue, action_onSelectRecord, data_document = [], data_final = [{}], error_document, field_definitions, focus_details, is_empty_state, primary1Color, accent1Color } = this.props; const { inputHeight } = this.state; const { focus_record = 0 } = focus_details; const record_final = data_final[focus_record] || {}; const record_document = data_document[focus_record] || {}; const error_record = error_document[focus_record] || {}; return ( <div style={{ height: 'calc(100vh - 130px)', overflowY: 'hidden', overflowX: 'hidden' }} > <CardHeader subtitle={ <Translate value="productions.verify_key.verified_total" completed_amount={record_final.total_different || 0} fields_amount={record_final.total_fields || 0} /> } subtitleColor={ record_final.total_different === record_final.total_fields ? primary1Color : accent1Color } title={`Record ${focus_record + 1}/${data_document.length}`} /> <div ref={'input-zone'} className="special_scroll" style={{ height: inputHeight, overflowY: 'auto', overflowX: 'hidden' }} > {field_definitions && field_definitions.length > 0 && field_definitions.map((v, i) => { return ( <Field action_onBlurField={action_onBlurField} action_onFocusField={action_onFocusField} action_onKeyPressFocus={action_onKeyPressFocus} action_onModifyFieldValue={action_onModifyFieldValue} field={v} field_value={record_document[v.name] || {}} final_value={record_final[v.name] || ''} field_error={error_record[v.name] || ''} is_disabled={is_empty_state} is_focus={ focus_details.focus_field_name === v.name && !is_empty_state } key={`${v.name}-${i}`} record_index={focus_record} /> ); })} {data_document && data_document.map((record, index) => { if (index === parseInt(focus_record, 10)) { return null; } return ( <Card key={`record-${index}`} onExpandChange={() => { action_onSelectRecord(index); }} > <CardHeader key={`record-${index}-unselect`} actAsExpander={true} closeIcon={<ArrowDownIcon />} openIcon={<ArrowDownIcon />} showExpandableButton={true} subtitleColor={ data_final[index].total_different === data_final[index].total_fields ? primary1Color : accent1Color } subtitle={ <Translate value="productions.verify_key.verified_total" completed_amount={ data_final[index].total_different || 0 } fields_amount={data_final[index].total_fields || 0} /> } title={`Record ${index + 1}`} /> </Card> ); })} {!is_empty_state && ( <div style={{ display: 'inlineBlock', height: 'calc(80vh)', position: 'relative', width: '100%' }} /> )} </div> </div> ); } } export default VerifyKeyDocument;
JavaScript
CL
135667005a0def9de9d6bea64cc93e0c29b61d64fba48f57f8861b16ec61cfe0
import React from 'react' export default function Terms () { return ( <div className="article"> <section> <p>UpBlockchain User Agreement (hereinafter referred to as “Agreement”) is a contract between you (“user” and collectively with others using the platform “users”) and Up Blockchain Technology Limited (https://upblockchain.io) (the Site) (“we”, “us”, “our”, and “UpBlockchain”). Terms of this Agreement affect your legal rights and obligations. If you do not agree to this Agreement, do not access or use any of our services (“UpBlockchain Services”).</p> <p>In the event of any violation of the Agreement, we reserve the right to suspend or terminate your access to UpBlockchain Services. We may also file a suspicious transaction report (“STR”) if we know or have reasons to believe that the user, user’s funds or assets, or transactions conducted or attempted by the user may involve potential money laundering or terrorist financing related criminal activity, regardless of the amount involved. For any user who is suspected of violating relevant laws and regulations, UpBlockchain has the right to freeze the user’s accounts and all assets, and transfer them to relevant government authorities as required by law.</p> <p>UpBlockchain reserves the right to change or modify the terms and conditions contained in this Agreement, including but not limited to any policy or guideline of the Site, at any time and at its sole and absloute discretion. This Agreement may be updated regularly and corresponding notices of changes will be given to users. Any changes or modifications will take effect immediately thereafter. The Agreement, as revised, updated or amended, will then replace the previous version upon being published on the Site. Users may access to the latest version of the Agreement at any time.</p> </section> <section> <h3>I. Contents and Release of the Agreement</h3> <p>1.1. The contents of this Agreement include its main body, schedules, appendices and/or annexures and all valid amendments, supplements, and announcements that UpBlockchain has released or may release from time to time, all of which constitute an integral part of this Agreement and shall have the same legal effect as the Agreement. Except as otherwise officially stated, all UpBlockchain Services are bound by the terms of this Agreement.</p> <p>1.2. You should carefully read all the contents of the Agreement before using UpBlockchain Services. If you have any questions regarding this Agreement or the use of the Site, please contact UpBlockchain directly by sending an email at terms@upblockchain.org Regardless of whether you have read the Agreement, by using any services made available through the UpBlockchain website at https://upblockchain.io, the UpBlockchain API, and/or any associated UpBlockchain-hosted websites or mobile applications (collectively the “Site”), you agree to be bound by this Agreement. You do not have the right to claim that the Agreement is invalid or require revocation because you have not read this Agreement or you have not received any response from UpBlockchain to your consultation. </p> <p>1.3. You are committed to accept and comply with this Agreement. UpBlockchain reserves the right to change or modify the terms and conditions contained in this Agreement. We will provide notices of these changes by posting official announcements at https://upblockchain.io. We will not inform users individually. Any changes or modifications will take effect immediately upon being published on the Site. These changes will apply at that instant to all the current and subsequent uses of the Site. If you do not agree with such changes or modifications, you should stop using UpBlockchain Services immediately. Your continued use of this Site acts as acceptance of the last revised Agreement with its updated changes and modifications.</p> </section> <section> <h3>II. Account</h3> <h4>2.1. Eligibility and Prohibition of Using our Services</h4> <p>​By accessing or using UpBlockchain Services, you represent and warrant that you have full capacity for civil rights and civil conduct. The users can be natural persons, legal entities or other organizations. You also represent and warrant that you are not on any terrorist organizations and terrorist activities personnel lists, such as the United Nations Security Council terrorist organizations and terrorist activities personnel list, nor restricted or prohibited from engaging in any type of trading platforms by the People’s Bank Of China (PBOC), as well as other administrative law enforcement agencies. If you do not have the above qualifications, you and your guardian shall bear all the consequences arising therefrom, and UpBlockchain reserves the rights to cancel or permanently suspend your account and claim against you and your guardian.</p> <h4>2.2. The Purpose of Using UpBlockchain Services</h4> <p>You represent and warrant that your use of UpBlockchain Services is not for the purpose of conducting any illegal or criminal activities nor for the purpose of breaching or disordering UpBlockchain’s digital assets transactions.</p> <h4>2.3. Wallet Security</h4> <p>​You are responsible for the custody and confidentiality of your digital assets wallet password, and you are responsible for all activities (including but not limited to information disclosure, posting, online click consent or submission of various requests) that occur under that login and password.</p> <h4>You agree to:</h4> <p>(1) Immediately notify UpBlockchain if any person has unauthorized use of your personal digital wallet or any other breach of confidentiality, and accept all risks of unauthorized access.</p> <p>(2) Ensure that you strictly comply with the Site/service security, certification, transactions, deposit, withdrawal mechanism or process.</p> <p>(3) Make sure you leave the Site/service in the correct way at the end of each trading period. As a decentralized exchange, UpBlockchain shall not and will not be liable for any loss whatsoever arising from your failure to comply with this Section. It is reasonable for you to understand that UpBlockchain takes action on your request but is not responsible for any consequences (including but not limited to any loss) that you have incurred before taking action.</p> </section> <section> <h3>III. UpBlockchain Services</h3> <h4>3.1. Our Services</h4> <p>UpBlockchain provides an online decentralized Ethereum-based tokens trading platform for users to conduct trading. We offer users with a convenient way to trade ETH and many ERC-20 tokens. https://upblockchain.io as the platform provider is not a buyer or seller in these trades. By using the Upblockchain Services, users can create trading orders, inquire blockchain asset price and trading information, conclude the transaction, and make a deal on the Site. UpBlockchain may make other ancillary services available to Users to facilitate the exchange of tokens like lending, limit orders, and stop orders. You are welcome to attend all events and activities organized by us, as well as to use other information and technical services. Our services do not provide users with the ability to trade one form of legal tender for another form of legal tender.</p> <h4>3.2. Rules and Acceptable Use</h4> <p>3.2.1. When accessing or using UpBlockchain Services, you acknowledge and consent that it is your sole responsibility to comply with applicable laws and regulations, UpBlockchain’s terms and agreements, and other relevant provisions. You agree that you will not violate any law, contract, intellectual property or other third-party right or commit a tort and that you are solely responsible for your conduct and for reporting and paying any taxes arising from your use of the Services. You acknowledge that your use of UpBlockchain will not endanger national security or disclose state secrets. You shall not violate the national community and the legitimate rights and interests of citizens. For any legal consequences caused by your violation of the terms and commitments, UpBlockchain assumes no responsibility and you shall ensure that UpBlockchain will not bear any losses.</p> <p>​ You understand and consent that if UpBlockchain suspects you or others of using your information in furtherance of illegal activity, UpBlockchain may be required to provide your information to government agencies as required by law.</p> <p>3.2.2. You agree you will not use the UpBlockchain Services in any manner that could interfere with, disrupt, negatively affect or inhibit other users from fully enjoying UpBlockchain Services, or that could damage, disable, overburden or impair the functioning of UpBlockchain Services in any manner. If a dispute happens between you and another user(s) when using the UpBlockchain Services, UpBlockchain has the right to make a judgment in its sole discretion. </p> <p>3.2.3. You agree that you will not copy, transmit, distribute, sell, resell, license, de-compile, reverse engineer, disassemble, modify, publish, participate in the transfer or sale of, create derivative works from, perform, display, incorporate into another website, or in any other way exploit any of the content or any other part of the UpBlockchain Services or any derivative works thereof, in whole or in part for commercial or non-commercial purposes. Without limiting the foregoing, you will not frame or display the Site or its contents as part of other web site or any other work of authorship without the prior written permission of UpBlockchain. In addition, you will not use any devices, software, callable routines, web crawler, scraper or other automated means or interface not provided by us to access and intervene our Services or to extract data. It is also prohibited for you to take any action that imposes an unreasonable or disproportionately large load on our infrastructure, or detrimentally interfere with, intercept, or expropriate any system, data, or information.</p> <p>3.2.4. You acknowledge and consent that UpBlockchain has the right to determine whether you have violated any of these terms in the Agreement, in our sole discretion. We may terminate your access to the UpBlockchain Services based our sole discretion, immediately and without prior notice. If UpBlockchain suspects your use of the UpBlockchain Services involves illegal activity according to law or any regulatory terms, we have the right to publicize the detail of your violations, as well as the measures adopted by us.</p> <p>3.2.5. UpBlockchain reserves the right to determine whether your use of the UpBlockchain Services (include any direct and indirect effects that may have happened as the result of your previous action), has violated any terms of the Agreement. You agree to indemnify, defend and hold UpBlockchain , its affiliates and service providers, and each of their respective officers, directors, agents, employees, and representatives, harmless from any claim or demand (including attorneys’ fees and costs and any fines, fees or penalties imposed by any regulatory authority) arising out of or related to: (a) your breach of the terms of this Agreement, (b) your use of the UpBlockchain Services, or (c) your violation of any law, rule, or regulation, or the rights of any third party.</p> <p>3.3. Change of Service, Suspension, Termination - When special circumstances arise, UpBlockchain reserves the rights to revise the contents of UpBlockchain Services and may suspend or terminate the UpBlockchain Services so provided.</p> <p>3.3.1. Change of Service - We reserve the right to revise the contents of UpBlockchain Services and other policies and announcements published by UpBlockchain, at any time and in our sole discretion. We will update our Agreement regularly and provide notice of these changes on https://upblockchain.io. Any changes or modifications will be effective immediately when the revision is posted. Your continued use of this Site acts as your acceptance of such changes or modifications. If you do not agree to the terms in effect when you access or use the Site, you must stop using the Site and all UpBlockchain Services. We encourage you to review the Agreement frequently to ensure you understand the terms and conditions that apply to your access to, and use of, the UpBlockchain Services.</p> <p>3.3.2. Suspension and Termination - UpBlockchain reserves the right to terminate all UpBlockchain Services in accordance with this Agreement. This Agreement will expire when all UpBlockchain Services are terminated. After the expiration of this Agreement, UpBlockchain is no longer obligated to deliver any processed or unprocessed information or the user(s) or any other third parties. You also have no right to request UpBlockchain to provide any services or to fulfill any obligations. If you breach any of the terms, you will continue to be held responsible and accountable after the Agreement expires.</p> </section> <section> <h3>IV. Trading Rules</h3> <p>You acknowledge and agree that by accessing and using UpBlockchain Services, you comply with all terms mentioned in the Agreement when making any transactions or orders, including but not limited to review exchange information; make deposits and withdrawals; submit an order; check transactions, and cancel an order. You also agree to follow UpBlockchain’s digital asset trading rules:</p> <p>4.1 Browsing transaction information: When you browse the digital asset transaction information on UpBlockchain, you should carefully read all the contents contained in the transaction information before trading, including but not limited to the digital asset price, commission and fees.</p> <p>4.2 Transfer and Approve: you understand and agree that although UpBlockchain does not charge any transfer or approve fees, it is your responsibility to cover the gas fee (Ethereum network fee). This is for the cost of executing transactions on the Ethereum network. These transaction fees will be deducted from your wallet.</p> <p>4.3. Transaction records: You can view your corresponding transaction records in your trading history.</p> </section> <section> <h3>V. User Rights and Licences</h3> <p>UpBlockchain grants you a limited, non-exclusive, non-transferable licence, subject to the terms of this Agreement, to access and use the UpBlockchain website and the UpBlockchain Services, solely for approved purposes as permitted by UpBlockchain. Any other use of the UpBlockchain Services or any contents therein is expressly prohibited. All other rights in the Site or its contents are reserved by us. You agree you will not copy, transmit, distribute, sell, licence, reverse engineer, modify, publish, or participate in the transfer or sale of, create derivative works from, or in any other way exploit any of the UpBlockchain’s contents.</p> <p>5.1 You have the right to obtain the blockchain asset information from UpBlockchain. UpBlockchain and its users may provide third party contents on the Site. UpBlockchain does not control, endorse, or adopt any third party contents and makes no representation or warranties of any kind regarding the third party contents, including but not limited to its accuracy or completeness. You acknowledge and consent that UpBlockchain is not responsible or liable in any manner for any third party contents and undertakes no responsibility to update or review any third party contents. You acknowledge and consent that your use of such third party contents is at your own risk. Your business dealings or correspondence with, or participation in promotions of, any third parties, and any terms, conditions, warranties, or representations associated with such dealings or promotions, are solely between you and such third parties. We are not responsible or liable for any loss or damage of any sort incurred as the result of any such dealings or promotions or as the result of the presence of such third party contents on the Site.</p> <p>5.2. If you encounter any technical difficulty on our platform, you can submit a ticket in the Help Center under “Support”. Our customer service team will assist you as soon as possible. Please understand that it might take some time to solve your problem. For other personal reasons due to improper use, we will not guarantee to help you recover your assets.</p> <p>5.3. Unless otherwise specified, UpBlockchain shall not guarantee the accuracy, completeness, reliability of any contents, including but not limited to, advertising from the Site in any manner from the UpBlockchain is not responsible for any products, services, information or materials purchased or obtained by the user according to the content information on this website. The user bears the risk of using the content of this website.</p> <p>5.4 You have the right to make comments and suggestions in regard to UpBlockchain services, and UpBlockchain will take your suggestions into serious consideration. If your feedback is involved with violent words, insulting verbal abuse, rumors, and defamation, once discovered, UpBlockchain has the right to clarify the relevant false text and we retain the right to further pursue legal action.</p> <p>5.5 You may not use the trademarks, emblems and service marks contained in this website in any way without the prior written consent of UpBlockchain, and you may not copy, reproduce, and store the information and materials contained in UpBlockchain in the retrieval system, Transmit, distribute or carry out other infringement. Please strictly abide by the relevant laws and regulations, do not publish any illegal content on UpBlockchain.</p> <p>5.6. A third party authorized by UpBlockchain or a third party that you agree with UpBlockchain shall have the right to accept your dispute with another user for any transaction based on your irrevocable authorization and to have sole discretion to determine the facts relating to the dispute, and then make a decision to deal with, including but not limited to adjust the transaction status of the relevant order, direct the third party to pay the company or customer service will be all or part of the payment to the transaction party or both. You should make up for the loss of UpBlockchain and its affiliates, otherwise, UpBlockchain and its affiliates reserve the rights to directly offset your interest in other contracts and to continue to recover. You understand and agree that a third party authorized by UpBlockchain or a third party that you agree to with UpBlockchain is not a judicial authority and can only identify the evidence as an ordinary person, or a third party authorized by UpBlockchain or UpBlockchain or you agree with UpBlockchain third party to the dispute is entirely based on your irrevocable mediation, it cannot guarantee that the outcome of the dispute in line with your expectations, nor on the dispute mediation conclusions bear any responsibility.</p> </section> <section> <h3>VI. Limitation of Liability and Disclaimer</h3> <p>You acknowledge and consent that you agree not to hold UpBlockchain accountable for any related losses resulted from the following circumstances (including but not limited to), whether or not such loss or damage can be reasonably foreseen by UpBlockchain and whether or not UpBlockchain has previously been advised of the possibility of such loss or damage:</p> <p>6.1. UpBlockchain suspects your transaction relates to a prohibited use as stated in the terms pf this Agreement.</p> <p>6.2. UpBlockchain suspects your transaction involves money laundering, terrorist financing, fraud, or any other type of crime.</p> <p>6.3. Your misunderstanding of UpBlockchain Services.</p> <p>6.4. UpBlockchain, as an “online service provider”, does not guarantee that the information and the UpBlockchain Services can fully meet the needs of users. UpBlockchain does not assume legal liability for errors, insults, defamation, omission, obscenity, pornography, or blasphemy that our users may encounter while using UpBlockchain Services.</p> <p>6.4.1. Based on the special nature of the Internet, UpBlockchain does not guarantee that the UpBlockchain Services will not be interrupted, and the timeliness of the UpBlockchain Services and the security thereof are also not guaranteed, and UpBlockchain does not bear the responsibility which is not caused by us.</p> <p>6.4.2. UpBlockchain may provide some links to other sites. These links are only for your convenience and learning purposes, UpBlockchain does not guarantee the authenticity, effectiveness, legitimacy of such sites.</p> <p>6.4.3. UpBlockchain strives to enable users to securely access and use our Site; however, we do not guarantee that the Site or its servers are free of viruses or other potentially harmful factors. Hence, the user should use the industry’s recognized software to check and kill any virus in the files downloaded from UpBlockchain.</p> <p>6.5. UpBlockchain is not responsible for any damage incurred during your transaction, including but not limited to profit or loss on your business activities, business interruption, loss due to the market violation, data loss, loss of reputation or goodwill.</p> <p>6.6. UpBlockchain shall not be liable for (a) any inaccuracy, error, delay in, or omission of (i) any information, or (ii) the transmission or delivery of information; or (b) any loss or damage arising from any event beyond our reasonable control, including but not limited to flood, extraordinary weather conditions, earthquake, or other act of God, fire, war, insurrection, riot, labor dispute, accident, action of government, communications, power failure, or equipment or software malfunction, or any other cause beyond our reasonable control.</p> <p>6.7. All UpBlockchain announcements and notifications will be delivered through a formal page announcement on https://upblockchain.org or https://upblockchain.io. UpBlockchain assumes no legal responsibility for any winning, discount activities or information which are delivered not by above channels.</p> <p>6.8. UpBlockchain aims to ensure that the platform operates 7*24 hours. But we cannot guarantee the DDoS attack, the server vendor to suspend the service, the network provider to suspend service or other force majeure events and other unknown reasons which may cause the Site cannot be accessed, the trading hall cannot be a single order, withdrawal orders, pending orders have not been a normal transaction, recharge to mention a long time not credited to the account and so on. For the above reasons resulting in loss of user assets, UpBlockchain does not assume any responsibility.</p> <p>6.9. The guarantees and undertakings of UpBlockchain as set forth in this Agreement are the sole warranties and representations made by UpBlockchain in respect of the services provided by this Agreement. All such warranties and representations represent the commitment and warranty of UpBlockchain itself and do not guarantee that any third party will comply with the warranties and undertakings in this Agreement. UpBlockchain does not waive any rights not covered by this Agreement to the extent that the law applies to UpBlockchain, which reserves the rights to waive or cancel the liability of UpBlockchain damage.</p> </section> </div> ) }
JavaScript
CL
f27047c2897fea88f857a3a281672dda3308d44dac52d079d7c9465fc6a3f727
import React from 'react'; import PropTypes from 'prop-types'; import './styles.css'; import { Grid, TableFilterRow, TableHeaderRow, VirtualTable } from '@devexpress/dx-react-grid-material-ui'; import { FilteringState, IntegratedFiltering, IntegratedSorting, SortingState } from '@devexpress/dx-react-grid'; import Paper from '@material-ui/core/Paper'; import BodyCell from './components/BodyCell'; import settings from './tableSettings'; import data from './data'; /** * Компонент-класс TableCondition для выполнения отображения таблицы с информацией о трубе */ export default class TableCondition extends React.Component { static defaultProps = {}; static propTypes = { pipeNumber: PropTypes.number.isRequired, }; /** * Конструктор компонента с переопределением пропсов и стейтом. * @param props */ constructor(props) { super(props); this.state = { ...settings, rows: [], }; } componentDidMount() { this.setState({ rows: data[this.props.pipeNumber - 1], }); } componentDidUpdate(prevProps, prevState, snapshot) { if (prevProps.pipeNumber !== this.props.pipeNumber) { this.setState({ rows: data[this.props.pipeNumber - 1], }); } } render() { const { rows, columns } = this.state; return ( <div className="table-wrapper"> <Paper> <Grid rows={rows} columns={columns} > <FilteringState/> <SortingState defaultSorting={[{ columnName: 'min_thickness', direction: 'asc' }]} /> <IntegratedSorting/> <IntegratedFiltering/> <VirtualTable cellComponent={BodyCell}/> <TableFilterRow/> <TableHeaderRow showSortingControls/> </Grid> </Paper> </div> ); } }
JavaScript
CL
4f35d761fac3b25f381ed9dd01ea60fbba46669df4b5ea0691712d377fcddc27
/* eslint-disable no-unused-vars,no-trailing-spaces */ /** * Created by viktor on 7/7/17. */ // ======================================================== // Import Packages // ======================================================== import React, { Component } from 'react' import PropTypes from 'prop-types' import { View, Text, TextInput, Alert, Dimensions, KeyboardAvoidingView, Keyboard, ScrollView, Image, ActivityIndicator, TouchableOpacity, TouchableHighlight } from 'react-native' import CustomNav from '../../Containers/Common/CustomNav' import {reduxForm, Field} from 'redux-form' import { connect } from 'react-redux' import {FORM_TYPES} from '../../Config/contants' import styles from '../../Themes/ApplicationStyles' import {AUTH_ENTITIES} from '../../Utility/Mapper/Auth' import {COMMON_ENTITIES, DEVICE_LOGICAL_RESOLUTION} from '../../Utility/Mapper/Common' import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view' import LWTextInput from '../Utility/LWFormInput' import ProcessingIndicator from '../Utility/ProcessingIndicator' import {validateEmail, validatePassword, validatePasswordSchema} from '../../Utility/Transforms/Validator' import _ from 'lodash' import { Icon } from 'react-native-elements' import Colors from '../../Themes/Colors' import Fonts from '../../Themes/Fonts' import GravityCapsule from '../Utility/GravityCapsule' import { USER_ENTITIES } from '../../Utility/Mapper/User' // ======================================================== // Utility // ======================================================== const form = reduxForm({ form: FORM_TYPES.AUTH, destroyOnUnmount: false, enableReinitialize: true }) // ======================================================== // Core Component // ======================================================== class Login extends Component { // -------------------------------------------------------- // Lifecycle methods constructor (props) { super(props) this.state = { showPassword: false, _emailError: false, _passwordError: false, _emailErrorMessage: null, _passwordErrorMessage: null, passwordSchema: undefined, showIcons: false } const {height, width} = Dimensions.get('window') const isIPhoneX = height === DEVICE_LOGICAL_RESOLUTION.IPHONE_DEVICE_X.height && width === DEVICE_LOGICAL_RESOLUTION.IPHONE_DEVICE_X.width this.isX = isIPhoneX } // -------------------------------------------------------- // Action handlers componentWillMount () { this.props.initialize() } componentWillUnmount () { this.props.destroy() } togglePasswordVisibility () { this.setState(prevstate => { return {showPassword: !prevstate.showPassword} }) } hideError () { const {handleLocalAction, localActions} = this.props handleLocalAction({type: localActions.HIDE_ERROR}) } markError (inputType, error, message) { switch (inputType) { case AUTH_ENTITIES.EMAIL: this.setState({_emailError: error, _emailErrorMessage: message}) break case AUTH_ENTITIES.PASSWORD: this.setState({_passwordError: error, _passwordErrorMessage: message}) break default: this.setState({ _emailError: false, _passwordError: false }) } } markPasswordSchema (val) { let schema = validatePasswordSchema(val) this.setState({passwordSchema: schema}) } validate (type, val) { switch (type) { case AUTH_ENTITIES.EMAIL: if (validateEmail(val)) { this.markError(AUTH_ENTITIES.EMAIL, true, 'Enter valid Email Address.') return 'Correct Email Needed' } else { this.markError(AUTH_ENTITIES.EMAIL, false, null) return undefined } case AUTH_ENTITIES.PASSWORD: this.markPasswordSchema(val) let passwordError = validatePassword(val) if (passwordError) { this.markError(AUTH_ENTITIES.PASSWORD, true, passwordError) return 'MIN 6 Char pass needed' } else { this.markError(AUTH_ENTITIES.PASSWORD, false, null) return undefined } } } navigateToNext (data) { const {localActions, handleLocalAction, handleSubmit, navigator, isProcessing, type} = this.props if (type !== AUTH_ENTITIES.LOGIN && /\s/.test(data[AUTH_ENTITIES.PASSWORD])) { Alert.alert('Signup Error', 'Password did not confirm with policy: \nPassword must not contain space') return } let email = data && data[AUTH_ENTITIES.EMAIL] && data[AUTH_ENTITIES.EMAIL].toLowerCase() handleLocalAction({ type: type, [AUTH_ENTITIES.EMAIL]: email, [AUTH_ENTITIES.PASSWORD]: data[AUTH_ENTITIES.PASSWORD], [COMMON_ENTITIES.NAVIGATOR]: navigator }) } navigateToForgotPassword () { const {localActions, handleLocalAction, navigator} = this.props handleLocalAction({ type: localActions.FORGOT_PASSWORD, [COMMON_ENTITIES.NAVIGATOR]: navigator }) } clearField (field) { const {localActions, handleLocalAction, navigator} = this.props handleLocalAction({ type: localActions.REMOVE_VALUE, form: FORM_TYPES.AUTH, field: field, value: '' }) } // -------------------------------------------------------- // Child Components renderFormContainer () { const {handleSubmit, type, showEmailError, showPasswordError} = this.props const {_emailError, _passwordError, _passwordErrorMessage, showIcons} = this.state let emailError = (showEmailError && _emailError) ? 'Please enter valid email address' : undefined let passwordError = (showPasswordError && _passwordError) ? _passwordErrorMessage : undefined return ( <View style={{flex: 1, justifyContent: 'flex-start'}}> <View style={styles.screen.textInput.parentContainerStyle}> <Field name={AUTH_ENTITIES.EMAIL} isLabel label='Email' whiteBackground accessible accessibilityLabel={'Email'} accessibilityRole={'keyboardkey'} returnKeyType='next' onSubmitEditing={() => this.password.getRenderedComponent().refs.password.focus()} autoCapitalize='none' component={LWTextInput} showIcon={showEmailError} iconName={emailError ? 'clear' : 'done'} iconCallback={() => emailError && this.clearField(AUTH_ENTITIES.EMAIL)} iconColor={emailError ? Colors.switchOff : Colors.appColor} iconSize={18} placeholderText='Email' keyboardType='email-address' validate={val => this.validate(AUTH_ENTITIES.EMAIL, val)} isError={this.state._emailError} extraTextStyle={{fontSize: (this.state.showPassword) ? 16 : 15}} extraStyle={{borderColor: emailError ? Colors.switchOff : Colors.appColor}} maxLength={39} /> </View> { (emailError) && <Text style={{ fontFamily: Fonts.type.book, color: Colors.switchOff, fontSize: 11, marginHorizontal: 15, marginBottom: 10, marginTop: -10 }}> {emailError} </Text> } <View style={{...styles.screen.textInput.parentContainerStyle, marginTop: 10}}> <Field name={AUTH_ENTITIES.PASSWORD} isLabel label='Password' whiteBackground accessible accessibilityLabel={'password'} accessibilityRole={'keyboardkey'} returnKeyType='done' ref={(el) => { this.password = el }} refField='password' withRef component={LWTextInput} showIcon={showPasswordError} iconName={passwordError ? 'clear' : 'done'} iconCallback={() => passwordError && this.clearField(AUTH_ENTITIES.PASSWORD)} iconColor={passwordError ? Colors.switchOff : Colors.appColor} iconSize={18} secureTextEntry={!this.state.showPassword} placeholderText='Password' validate={val => this.validate(AUTH_ENTITIES.PASSWORD, val)} isError={this.state._passwordError} extraTextStyle={{fontSize: (this.state.showPassword) ? 16 : 15}} extraStyle={{borderColor: passwordError ? Colors.switchOff : Colors.appColor}} /> </View> { (passwordError) && <Text style={{ fontFamily: Fonts.type.book, color: Colors.switchOff, fontSize: 11, marginHorizontal: 15, marginTop: -10 }}> {passwordError} </Text> } <View style={{ marginTop: 20, marginBottom: 23 }}> {this.renderNextButton()} </View> </View> ) } renderNextButton () { const {handleSubmit, type, isProcessing} = this.props const isX = this.isX || false return ( <View> <TouchableHighlight underlayColor={Colors.buttonYellowUnderlay} accessible accessibilityLabel={'Continue'} accessibilityRole={'button'} disabled={isProcessing} style={{ ...styles.bottomNavigator.containerStyle // shadowOpacity: 0.15, // shadowRadius: 10, // shadowOffset: {height: 10, width: 0} }} onPress={_.debounce(_.bind(handleSubmit(data => this.navigateToNext(data)), this), 500, {'leading': true, 'trailing': false})}> <Text style={styles.bottomNavigator.textStyle}>Continue</Text> </TouchableHighlight> <TouchableOpacity activeOpacity={1} accessible accessibilityLabel={'Forgot your password?'} accessibilityRole={'button'} onPress={() => this.navigateToForgotPassword()}> <Text style={{...styles.text.title, marginTop: 20, color: Colors.fontGray, textDecorationLine: 'underline'}}>Forgot your password?</Text> </TouchableOpacity> </View> ) } renderHeading () { return ( <View style={{...styles.screen.h2.containerStyle}}> <Text style={{ fontFamily: Fonts.type.bold, color: '#FFF', fontSize: 22, alignSelf: 'center', marginBottom: 20 }}> Hey there! </Text> <Text style={{ fontFamily: Fonts.type.book, color: '#FFF', fontSize: 18, textAlign: 'center', marginHorizontal: 20 }}> Investing for kids starts with you so your email address please? </Text> </View> ) } // -------------------------------------------------------- // Core render method render () { const {errorObj, isProcessing, type, navigator} = this.props if (errorObj) { Alert.alert(errorObj.code, errorObj.message, [ {text: 'OK', onPress: () => this.hideError()} ], { cancelable: false } ) } return ( <View style={{...styles.screen.containers.root, backgroundColor: '#FFF'}}> <CustomNav navigator={navigator} gradientBackdrop leftButtonPresent customIcon={<Icon name='ios-close' type='ionicon' containerStyle={{left: 10}} color={Colors.white} size={40} />} title={'Log in'} titlePresent /> <ProcessingIndicator isProcessing={isProcessing} /> <KeyboardAwareScrollView contentContainerStyle={{ ...styles.screen.containers.keyboard }} resetScrollToCoords={{ x: 0, y: 0 }} extraScrollHeight={100} showsVerticalScrollIndicator={false} keyboardDismissMode='interactive' keyboardShouldPersistTaps='handled'> <View style={{ flex: 1, paddingHorizontal: 20 }}> {this.renderHeading()} {this.renderFormContainer()} </View> </KeyboardAwareScrollView> </View> ) } } Login.propTypes = { // used for handling local actions, comes from container directly handleLocalAction: PropTypes.func.isRequired, // used for mapping local action types, comes from container directly localActions: PropTypes.object.isRequired, // used for navigation, comes via react-native-navigation navigator: PropTypes.object.isRequired, isProcessing: PropTypes.bool.isRequired, showPasswordError: PropTypes.bool, showEmailError: PropTypes.bool, // type of authentication 'Login' or 'SignUp' type: PropTypes.string.isRequired, // heading as per signup/login heading: PropTypes.string.isRequired } // ======================================================== // Export // ======================================================== const Screen = connect()(form(Login)) export default Screen
JavaScript
CL
5c33a5c28f619666832a495714238d2fa19b3f935e784d6ef3c48659e7985229
/** * TODO: Write real documentation. */ /** * Truncate a block of text to a designated number of characters or words, returning the split result as an array. * Default behaviour is to split the text at 25 characters, breaking words if need be. * * @param {String} Text to operate on. * @param {Object} Options for fine-tuning the truncation result. Possible options are: * - by: {Enum} Whether to measure text based on word or character limit (Values: "char" or "word"). * - limit: {Number} Maximum number of words/characters permitted before breaking. * - cutoff: {Mixed} Decides where and if to break a word to meet the character limit. * - I'll finish this off later, probably... */ function truncate(string){ if(arguments.length < 2 || !string) return [string || ""]; /** Default arguments. */ var args = { limit: 25, by: "char", cutoff: "break", trim: true }; /** If passed a number as our second argument, simply set the limit parameter. */ if("number" === typeof arguments[1]) args.limit = arguments[1]; /** Otherwise, simply merge our supplied arguments into our defaults. */ else for(var i in arguments[1]) args[i] = arguments[1][i]; /** Lowercase our string-typed arguments for easier comparison. */ args.by = args.by.toLowerCase(); args.cutoff = "string" === typeof args.cutoff ? args.cutoff.toLowerCase() : +(args.cutoff); /** Trim leading/trailing whitespace from our string */ if(args.trim) string = string.replace(/(^\s+|\s+$)/g, ""); /** Truncating based on word count. */ if("word" === args.by){ var words = string.split(/\s+/); if(words.length <= args.limit) return [string]; return [ words.slice(0, args.limit).join(" "), words.slice(args.limit).join(" ") ]; } /** Truncating based on character count (default behaviour). */ else{ if(string.length < args.limit) return [string]; /** Break text mid-word; or, the character at the cutoff point is whitespace anyway. */ if(!args.cutoff || "break" === args.cutoff || /\s/.test(string[args.limit])) return [ string.substring(0, args.limit), string.substring(args.limit) ]; /** Some word-preservation behaviour is in order, so let's dig a little closer into the string's contents. */ var before = string.substring(0, args.limit), after = string.substring(args.limit), lastStart = before.match(/(\s*)(\S+)$/), lastEnd = after.match(/^\S+/); /** Always include the last word in the untruncated half of the string. */ if("after" === args.cutoff) return [ string.substring(0, before.length + lastEnd[0].length), string.substring( before.length + lastEnd[0].length) ]; /** Never include the final word in the untruncated result. */ else if("before" === args.cutoff) return [ string.substring(0, before.length - lastStart[0].length), string.substring( before.length - lastStart[0].length) ]; /** Otherwise, use an arbitrary threshold point to determine where the threshold should lie. */ else{ var lastWord = lastStart[2] + lastEnd; /** If supplied a floating point number, interpret it as a percentage of the affected word's length. */ if(args.cutoff > 0 && args.cutoff < 1) args.cutoff = Math.round(lastWord.length * args.cutoff); /** Word's cutoff length is still less than the desired truncation limit. Include the word in the first half. */ if(args.limit > (before.length - lastStart[2].length)+args.cutoff) return [ string.substring(0, before.length - lastStart[0].length), string.substring( before.length - lastStart[0].length) ]; /** Otherwise, do the opposite of what the above comment just said. */ return [ string.substring(0, before.length + lastEnd[0].length), string.substring( before.length + lastEnd[0].length) ]; } } return [string]; }
JavaScript
CL
e6a5581e93adb09112e05416ebdb23ec0f600cc214eac7468d80d1f3fe1067ff
export default { route: { dashboard: 'Dashboard', introduction: 'Introduzione', documentation: 'Documentazione', guide: 'Guida', permission: 'Permessi', pagePermission: 'Pagina Permessi', directivePermission: 'Permessi di Autorizzazione', icons: 'Icone', components: 'Componenti', componentIndex: 'Introduzione', tinymce: 'Tinymce', markdown: 'Contrassegna', jsonEditor: 'JSON Editor', dndList: 'Lista Dnd', splitPane: 'Pannello Diviso', avatarUpload: 'Caricamento Avatar', dropzone: 'Zona di rilascio', sticky: 'Attacca', countTo: 'Contare fino a', componentMixin: 'Mixin', backToTop: 'Torna in cima', dragDialog: 'Trascina dialogo', dragSelect: 'Trascina Seleziona', dragKanban: 'Trascina Kanban', charts: 'Grafici', keyboardChart: 'Grafico Tastiera', lineChart: 'Grafico a linee', mixChart: 'Mix Grafico', example: 'Esempio', nested: 'Percorsi Annidati', menu1: 'Menu 1', 'menu1-1': 'Menu 1-1', 'menu1-2': 'Menu 1-2', 'menu1-2-1': 'Menu 1-2-1', 'menu1-2-2': 'Menu 1-2-2', 'menu1-3': 'Menu 1-3', menu2: 'Menu 2', Table: 'Tabella', dynamicTable: 'Tabella dinamica', dragTable: 'Trascina tabella', inlineEditTable: 'Modifica in linea', complexTable: 'Tabella Complessa', treeTable: 'Tabella ad Albero', customTreeTable: 'Tabella ad albero personalizzata', tab: 'Tab', form: 'Modulo', createArticle: 'Crea Articolo', editArticle: 'Modifica Articolo', articleList: 'Elenco articoli', errorPages: 'Pagine di errore', page401: '401', page404: '404', errorLog: 'Registro errori', excel: 'Excel', exportExcel: 'Esporta Excel', selectExcel: 'Esporta selezionati', uploadExcel: 'Carica Excell', zip: 'Zip', exportZip: 'Esporta Zip', theme: 'Tema', clipboardDemo: 'Appunti', i18n: 'I18n', externalLink: 'Link Esterno' }, navbar: { logOut: 'Disconnettersi', dashboard: 'Dashboard', github: 'Github', screenfull: 'Schermo intero', theme: 'Tema', size: 'Dimensione globale' }, login: { title: 'Modulo di accesso', logIn: 'Accesso', username: 'Nome Utente', password: 'Password', any: 'qualsiasi', thirdparty: 'Oppure connettiti con', thirdpartyTips: 'Non può essere simulato a livello locale, quindi si prega di combinare la propria simulazione bussiness !!!' }, documentation: { documentation: 'Documentazione', github: 'Github Repository' }, permission: { roles: 'I tuoi ruoli', switchRoles: 'Scambia ruoli', tips: 'In alcuni casi non è opportuno utilizzare l' autorizzazione-v, come il componente-ab dell' elemento o la colonna el-table e altri casi dom di rendering asincroni che possono essere raggiunti solo impostando manualmente v-if. ' }, guide: { description: 'La pagina della guida è utile per alcune persone che sono entrate nel progetto per la prima volta. È possibile presentare brevemente le funzionalità del progetto. La demo si basa su ', button: 'Mostra guida' }, components: { documentation: 'Documentazione', tinymceTips: 'L' editor Rich Text è una parte fondamentale del sistema di gestione, ma allo stesso tempo è un luogo con molti problemi. Nel processo di selezione di testi ricchi, ho anche fatto molte deviazioni. Vengono utilizzati sostanzialmente gli editor di rich text comuni sul mercato e infine Tinymce ha scelto. Consulta la documentazione per confronti e presentazioni più dettagliati dell' editor Rich Text.', dropzoneTips: 'Perché la mia azienda ha esigenze particolari e deve caricare immagini su qiniu, quindi invece di una terza parte, ho scelto di incapsularla da solo. È molto semplice, puoi vedere il codice di dettaglio in @ / components / Dropzone.', stickyTips: 'Quando la pagina viene fatta scorrere nella posizione preselezionata, sarà attaccata in alto.', backToTopTips1: 'Quando la pagina viene fatta scorrere nella posizione specificata, il pulsante Torna in alto appare nell' angolo in basso a destra ', backToTopTips2: 'Puoi personalizzare lo stile del pulsante, mostrare / nascondere, altezza dell'aspetto, altezza del ritorno. Se è necessario un prompt di testo, è possibile utilizzare gli elementi element-ui el-tooltip esternamente', imageUploadTips: 'Dal momento che stavo usando solo la versione vue @ 1, e al momento non è compatibile con mockjs, l'ho modificato da solo, e se hai intenzione di usarlo, è meglio usare la versione ufficiale.', }, table: { dynamicTips1: 'Intestazione fissa, ordinata per ordine di intestazione', dynamicTips2: 'Intestazione non fissa, ordinata per ordine di clic', dragTips1: 'Ordine predefinito', dragTips2: 'Ordine dopo il trascinamento', title: 'Titolo', importance: 'Importanza', type: 'Tipo', remark: 'Osservazione', search: 'Cerca', add: 'Aggiungi', export: 'Esporta', reviewer: 'recensore', id: 'ID', date: 'Data', author: 'Autore', readings: 'Letture', status: 'Stato', actions: 'Azioni', edit: 'Modifica', publish: 'Pubblica', draft: 'Bozza', delete: 'Elimina', cancel: 'Cancella', confirm: 'Conferma' }, errorLog: { tips: 'Fare clic sull'icona del bug nell'angolo in alto a destra', description: 'Ora il sistema di gestione è sostanzialmente la forma della spa, migliora l'esperienza dell'utente, ma aumenta anche la possibilità di problemi di pagina, una piccola negligenza può portare all'intero deadlock della pagina. Fortunatamente Vue fornisce un modo per rilevare le eccezioni di gestione, in cui è possibile gestire errori o segnalare eccezioni.', documentation: 'Introduzione del documento' }, excel: { export: 'Esporta', selectedExport: 'Esporta elementi selezionati', placeholder: 'Inserisci il nome del file (elenco Excel predefinito)' }, zip: { export: 'Export', placeholder: 'Inserisci il nome del file (file predefinito)' }, pdf: { tips: 'Qui usiamo window.print () per implementare la funzione di download di pdf.' }, theme: { change: 'Cambia Tema', documentation: 'Documentazione sul Tema', tips: 'Tips: È diverso dalla scelta del tema sulla barra di navigazione: due diversi metodi di skinning, ognuno con diversi scenari applicativi. Fare riferimento alla documentazione per i dettagli.' }, tagsView: { refresh: 'Refresh', close: 'Chiudi', closeOthers: 'Chiudi gli Altri', closeAll: 'Chiudi Tutto' } }
JavaScript
CL
770769a9ac9d4ca082bb62fa5cdc6f62965b78a69898cb882dc7d69b486ef99e
import { createWizard, destroyWizard, setWizardModel, changeWizardStep } from '../wizard'; describe('(Actions) HalcyonWizard', function () { describe('createWizard', function () { it('Should be a function.', function () { expect(createWizard).to.be.a('function'); }); it('Should return an action object.', function () { const action = createWizard(); expect(action).to.be.an('object'); expect(action.type).to.be.a('string'); expect(action.payload).to.be.an('object'); }); it('Should specify an action type of "HALCYON_WIZARD_CREATE".', function () { const action = createWizard(); expect(action.type).to.equal('HALCYON_WIZARD_CREATE'); }); it('Should set the first argument as the payload\'s "instance" property.', function () { const instance = {}; const action = createWizard(instance); expect(action.payload.instance).to.equal(instance); }); it('Should set the second argument as the payload\'s "model" property.', function () { const model = {}; const action = createWizard(null, model); expect(action.payload.model).to.equal(model); }); }); describe('destroyWizard', function () { it('Should be a function.', function () { expect(destroyWizard).to.be.a('function'); }); it('Should return an action object.', function () { const action = destroyWizard(); expect(action).to.be.an('object'); expect(action.type).to.be.a('string'); expect(action.payload).to.be.an('object'); }); it('Should specify an action type of "HALCYON_WIZARD_DESTROY".', function () { expect(destroyWizard().type).to.equal('HALCYON_WIZARD_DESTROY'); }); it('Should set the first argument as the payload\'s "instance" property.', function () { const instance = {}; const action = destroyWizard(instance); expect(action.payload.instance).to.equal(instance); }); }); describe('setWizardModel', function () { it('Should be a function.', function () { expect(setWizardModel).to.be.a('function'); }); it('Should return an action object.', function () { const action = setWizardModel(); expect(action).to.be.an('object'); expect(action.type).to.be.a('string'); expect(action.payload).to.be.an('object'); }); it('Should specify an action type of "HALCYON_WIZARD_SET_MODEL".', function () { expect(setWizardModel().type).to.equal('HALCYON_WIZARD_SET_MODEL'); }); it('Should set the first argument as the payload\'s "instance" property.', function () { const instance = {}; const action = setWizardModel(instance); expect(action.payload.instance).to.equal(instance); }); it('Should set the second argument as the payload\'s "model" property.', function () { const model = {}; expect(setWizardModel(null, model).payload.model).to.equal(model); }); }); describe('changeWizardStep', function () { it('Should be a function.', function () { expect(changeWizardStep).to.be.a('function'); }); it('Should return an action object.', function () { const action = changeWizardStep(); expect(action).to.be.an('object'); expect(action.type).to.be.a('string'); expect(action.payload).to.be.an('object'); }); it('Should specify an action type of "HALCYON_WIZARD_STEP_CHANGE".', function () { expect(changeWizardStep().type).to.equal('HALCYON_WIZARD_STEP_CHANGE'); }); it('Should set the first argument as the payload\'s "instance" property.', function () { const instance = {}; const action = changeWizardStep(instance); expect(action.payload.instance).to.equal(instance); }); it('Should set the second argument as the payload\'s "index" property.', function () { expect(changeWizardStep(null, 0).payload.index).to.equal(0); expect(changeWizardStep(null, 2).payload.index).to.equal(2); }); }); });
JavaScript
CL
c83430a3e552ea58b8cffaa5e47a51a0fafcc8fea074a40b7803815013d6d21a
import React from "react" import Layout from "../components/global/layout" import SEO from "../components/global/seo" import Section from "../components/shared/section" import Wrap from "../components/shared/wrap" import Banner from "../components/shared/banner" import MinistryImage from "../components/assets/ministryImage" import Container from "../components/shared/container" import ContentCard from "../components/cards/contentCard" const MinistryPage = () => ( <Layout> <SEO title="Ministry" /> <Section> <Banner title="Ministry" subtitle='"Philippians 4:13 (KJV) “I can do all things through Christ which strengtheneth me.”' /> <Container className="ministry-hero"> <Wrap> <Container className="intro"> <MinistryImage /> <ContentCard className="overlap"> <p> I am a non-denominational Christian and strongly believe a relationship with God is far greater than simply having a religion in the world we live and die in together. Understand this, I am far from perfect. I am still a sinner but I am a saved sinner and simply a creation just as everyone and everything else. Furthermore, I don’t claim to be better than any creation; I am just different. </p> </ContentCard> </Container> <ContentCard className="description"> <p> Contemporarily, I currently attend Center of Hope Bible Fellowship under the leadership of Pastor Rory Tate and First Lady Nicole Tate as a musician and youth leader. God has given me a role to use my gifts effectively and efficiently by playing instruments and teaching about life through Biblical principles inside and outside a variety of churches across Northeast Ohio. </p> <p> I have had a strong and positive impact on many people’s lives with my words and actions with the help of the Prodigious God and creations. That being stated, I will continue to play drums and complete speaking engagements inside and outside of churches across Northeast Ohio until God calls and chooses me to transition. I strongly believe it is not the work of my own but the creations in and around my life. But most of all, the power in which God has put in me to do for His glory. And if He can do it with me and for me, He can do the same with others and for others. </p> </ContentCard> </Wrap> </Container> </Section> <Section className="testimony"> <Banner title="Invitation to the Lifeboat" /> <Container className="lifeboat"> <Wrap> <Container className="card-container left"> <ContentCard> <p> The world that was created by God that we live in today is as if we were living on the Titanic. The Titanic was once flowing on water smoothly just as the world once was. However, the Titanic began to sink slowly, and just like the Titanic sinking, the world is slowly sinking. In uncertain times, creations created by the Almighty Creator must know that tomorrow is never promised. Therefore, the sad truth to every living creation is death being guaranteed while living on this planet. However, after death on this planet, there is another life that creations can choose to live in. That life is either eternity in Heaven or eternity in Hell. </p> </ContentCard> </Container> <Container className="card-container right"> <ContentCard> <p> That all being stated, it sounds as if it’s good news and bad news at the same time in which it is. Although the world is changing positively and negatively like it’s supposed to, there is a lifeboat. And that lifeboat is Jesus Christ (Yeshua) The Messiah. God the Father sent His only begotten Son in human form to be born, receiving the Holy Spirit, live a life by example, die, and rise again with all power in His hands so that we might have life and have it abundantly. </p> </ContentCard> </Container> <Container className="card-container left"> <ContentCard> <p> According to John 14:6 (KJV), it says, “Jesus saith unto him, I am the way, the truth, and the life: no man cometh unto the Father, but by me.” God sent His only begotten Son to give His creations life. As it states in John 3:16 (CEV), “God loved the people of this world so much that he gave his only Son, so that everyone who has faith in him will have eternal life and never really die.” Jesus also states in John 10:10 (NKJV), “The thief does not come except to steal, and to kill, and to destroy. I have come that they may have life, and that they may have it more abundantly.” Praise God! </p> </ContentCard> </Container> <Container className="card-container right"> <ContentCard> <p> To be in the lifeboat and to stay in it, all you have to do is have faith and follow what Romans 10:9-11 (NLT) says, “If you openly declare that Jesus is Lord and believe in your heart that God raised him from the dead, you will be saved. For it is by believing in your heart that you are made right with God, and it is by openly declaring your faith that you are saved. As the scriptures tell us, “Anyone who trusts in him will never be disgraced.’” God has given His creations free will. Therefore, nothing is forced on us. I’ve thought, seen, and heard what He’s done in my life and around my life in the past, present, and future. The choice is the creations but time isn’t on the creations side. The creations must know that God loves us and wants the best for us while we’re living on this planet and after we’re removed from this planet. According to Proverbs 3:5-6 (KJV) it says, “Trust in the Lord with all thine heart; and lean not unto thine own understanding. In all thy ways acknowledge him, and he shall direct thy paths.” God is the answer. Therefore, after reading this on my website, what will the choice be? </p> </ContentCard> </Container> </Wrap> </Container> <Wrap> <ContentCard className="footnote"> <p>Much love and blessings to all.</p> </ContentCard> </Wrap> </Section> </Layout> ) export default MinistryPage
JavaScript
CL
a96478af7e465b3b7eeae753f4a1739989dd9658be3793c283ce79f068ada050
/*! ***************************************************************************** Copyright (c) 2014 Artifact Health, LLC. All rights reserved. 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. ***************************************************************************** */ 'use strict'; var concat = require("dts-concat").concat; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('dts_concat', 'Combines TypeScript .d.ts files into a single .d.ts file for distributing CommonJS modules.', function() { var done = this.async(); concat(this.options(), done); }); }
JavaScript
CL
8fd420baf6aaf3f844d4f97830da22ea488fb5a4bfd56ed19f52040977e1df22
(global["webpackJsonp"] = global["webpackJsonp"] || []).push([["pages/agent/reporder/reporder"],{ /***/ 81: /*!*********************************************************************************************!*\ !*** E:/HBuilderProjects/MotorOrder/main.js?{"page":"pages%2Fagent%2Freporder%2Freporder"} ***! \*********************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(createPage) {__webpack_require__(/*! uni-pages */ 4); var _vue = _interopRequireDefault(__webpack_require__(/*! vue */ 2)); var _reporder = _interopRequireDefault(__webpack_require__(/*! ./pages/agent/reporder/reporder.vue */ 82));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };} createPage(_reporder.default); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@dcloudio/uni-mp-weixin/dist/index.js */ 1)["createPage"])) /***/ }), /***/ 82: /*!************************************************************************!*\ !*** E:/HBuilderProjects/MotorOrder/pages/agent/reporder/reporder.vue ***! \************************************************************************/ /*! no static exports found */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _reporder_vue_vue_type_template_id_6ace6b0c___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./reporder.vue?vue&type=template&id=6ace6b0c& */ 83); /* harmony import */ var _reporder_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./reporder.vue?vue&type=script&lang=js& */ 85); /* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _reporder_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _reporder_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); /* harmony import */ var _reporder_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./reporder.vue?vue&type=style&index=0&lang=css& */ 88); /* harmony import */ var _D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/runtime/componentNormalizer.js */ 10); var renderjs /* normalize component */ var component = Object(_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__["default"])( _reporder_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"], _reporder_vue_vue_type_template_id_6ace6b0c___WEBPACK_IMPORTED_MODULE_0__["render"], _reporder_vue_vue_type_template_id_6ace6b0c___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"], false, null, null, null, false, _reporder_vue_vue_type_template_id_6ace6b0c___WEBPACK_IMPORTED_MODULE_0__["components"], renderjs ) component.options.__file = "E:/HBuilderProjects/MotorOrder/pages/agent/reporder/reporder.vue" /* harmony default export */ __webpack_exports__["default"] = (component.exports); /***/ }), /***/ 83: /*!*******************************************************************************************************!*\ !*** E:/HBuilderProjects/MotorOrder/pages/agent/reporder/reporder.vue?vue&type=template&id=6ace6b0c& ***! \*******************************************************************************************************/ /*! exports provided: render, staticRenderFns, recyclableRender, components */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_template_id_6ace6b0c___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--16-0!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/template.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-uni-app-loader/page-meta.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!./reporder.vue?vue&type=template&id=6ace6b0c& */ 84); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_template_id_6ace6b0c___WEBPACK_IMPORTED_MODULE_0__["render"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_template_id_6ace6b0c___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "recyclableRender", function() { return _D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_template_id_6ace6b0c___WEBPACK_IMPORTED_MODULE_0__["recyclableRender"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "components", function() { return _D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_template_id_6ace6b0c___WEBPACK_IMPORTED_MODULE_0__["components"]; }); /***/ }), /***/ 84: /*!*******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--16-0!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/template.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-uni-app-loader/page-meta.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!E:/HBuilderProjects/MotorOrder/pages/agent/reporder/reporder.vue?vue&type=template&id=6ace6b0c& ***! \*******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! exports provided: render, staticRenderFns, recyclableRender, components */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "recyclableRender", function() { return recyclableRender; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "components", function() { return components; }); var components = { uniPopup: function() { return __webpack_require__.e(/*! import() | components/uni-popup/uni-popup */ "components/uni-popup/uni-popup").then(__webpack_require__.bind(null, /*! @/components/uni-popup/uni-popup.vue */ 506)) }, uniSegmentedControl: function() { return __webpack_require__.e(/*! import() | components/uni-segmented-control/uni-segmented-control */ "components/uni-segmented-control/uni-segmented-control").then(__webpack_require__.bind(null, /*! @/components/uni-segmented-control/uni-segmented-control.vue */ 542)) }, uniIcons: function() { return Promise.all(/*! import() | components/uni-icons/uni-icons */[__webpack_require__.e("common/vendor"), __webpack_require__.e("components/uni-icons/uni-icons")]).then(__webpack_require__.bind(null, /*! @/components/uni-icons/uni-icons.vue */ 442)) }, uniLoadMore: function() { return __webpack_require__.e(/*! import() | components/uni-load-more/uni-load-more */ "components/uni-load-more/uni-load-more").then(__webpack_require__.bind(null, /*! @/components/uni-load-more/uni-load-more.vue */ 499)) } } var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h var l1 = _vm.__map(_vm.orderList, function(items, index) { var l0 = _vm.__map(items.item, function(list, __i0__) { var m0 = parseInt(list.currentprice) return { $orig: _vm.__get_orig(list), m0: m0 } }) return { $orig: _vm.__get_orig(items), l0: l0 } }) _vm.$mp.data = Object.assign( {}, { $root: { l1: l1 } } ) } var recyclableRender = false var staticRenderFns = [] render._withStripped = true /***/ }), /***/ 85: /*!*************************************************************************************************!*\ !*** E:/HBuilderProjects/MotorOrder/pages/agent/reporder/reporder.vue?vue&type=script&lang=js& ***! \*************************************************************************************************/ /*! no static exports found */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _D_360_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!./node_modules/babel-loader/lib!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--12-1!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/script.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!./reporder.vue?vue&type=script&lang=js& */ 86); /* harmony import */ var _D_360_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_D_360_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__); /* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _D_360_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _D_360_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__)); /* harmony default export */ __webpack_exports__["default"] = (_D_360_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0___default.a); /***/ }), /***/ 86: /*!********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/babel-loader/lib!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--12-1!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/script.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!E:/HBuilderProjects/MotorOrder/pages/agent/reporder/reporder.vue?vue&type=script&lang=js& ***! \********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(uni) {Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0; var _jwweixin = _interopRequireDefault(__webpack_require__(/*! @/common/js/jwweixin.js */ 87));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };} // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // var uniSegmentedControl = function uniSegmentedControl() {__webpack_require__.e(/*! require.ensure | components/uni-segmented-control/uni-segmented-control */ "components/uni-segmented-control/uni-segmented-control").then((function () {return resolve(__webpack_require__(/*! @/components/uni-segmented-control/uni-segmented-control.vue */ 542));}).bind(null, __webpack_require__)).catch(__webpack_require__.oe);};var uniLoadMore = function uniLoadMore() {__webpack_require__.e(/*! require.ensure | components/uni-load-more/uni-load-more */ "components/uni-load-more/uni-load-more").then((function () {return resolve(__webpack_require__(/*! @/components/uni-load-more/uni-load-more.vue */ 499));}).bind(null, __webpack_require__)).catch(__webpack_require__.oe);};var uniPopup = function uniPopup() {__webpack_require__.e(/*! require.ensure | components/uni-popup/uni-popup */ "components/uni-popup/uni-popup").then((function () {return resolve(__webpack_require__(/*! @/components/uni-popup/uni-popup.vue */ 506));}).bind(null, __webpack_require__)).catch(__webpack_require__.oe);};var uniIcons = function uniIcons() {Promise.all(/*! require.ensure | components/uni-icons/uni-icons */[__webpack_require__.e("common/vendor"), __webpack_require__.e("components/uni-icons/uni-icons")]).then((function () {return resolve(__webpack_require__(/*! @/components/uni-icons/uni-icons.vue */ 442));}).bind(null, __webpack_require__)).catch(__webpack_require__.oe);};var _default = { components: { uniSegmentedControl: uniSegmentedControl, uniLoadMore: uniLoadMore, uniPopup: uniPopup, uniIcons: uniIcons }, data: function data() {return { userInfo: {}, //用户信息 orderList: [], //订单列表 state: [0, 1, 2, -1], //待接单/已发货/已收货/已取消 p: 1, total: 0, pageSize: 10, pageCount: '', status: 'more', tabItems: ['待接单', '已发货', '已收货', '已取消'], tabIndex: 0, badge: [0, 0, 0, 0], marginTop: '', timer: null, engineCode: 'A', isShow: false, s_id: '', search: { nickname: '', tel: '', code: 'A' } };}, onLoad: function onLoad(options) {console.log(parseInt(options.id)); //读取存储数据 var this_ = this;this_.tabIndex = parseInt(options.id) == -1 ? 3 : parseInt(options.id);this_.wxInit();uni.getStorage({ key: 'userInfo', success: function success(res) {this_.userInfo = res.data[0];this_.getOrderList();this_.orderQty(); //获取数字 //每隔5秒刷新 this_.timer = setInterval(function () {this_.orderQty(); //获取数字 }, 5000);} });}, onUnload: function onUnload() {var this_ = this;if (this_.timer) {clearInterval(this_.timer);this_.timer = null;}}, mounted: function mounted() {this.marginTop = this.$refs.tabitem.$el.getBoundingClientRect().height;}, //上拉加载 onReachBottom: function onReachBottom() {if (this.p < this.pageCount) {this.p++;this.status = 'loading';this.getOrderList();} else {this.status = 'noMore';}}, methods: { allShow: function allShow() {this.getOrderList();}, showChange: function showChange(e) {this.getOrderList();}, searchDo: function searchDo() {console.log(this.tabIndex);this.getOrderList();this.$refs.popup.close();this.clearSearchData();this.orderList = [];}, closeDialogShow: function closeDialogShow() {this.$refs.popup.close();this.clearSearchData();}, clearSearchData: function clearSearchData() {this.search.nickname = '';this.search.tel = '';this.search.code = 'A';}, openDialogShow: function openDialogShow() {this.$refs.popup.open();}, tel: function tel(phoneNum) {uni.makePhoneCall({ phoneNumber: phoneNum //仅为示例 });}, //tab切换 onClickTab: function onClickTab(e) {console.log(e);var this_ = this;if (this_.tabIndex !== e.currentIndex) {this_.p = 1;this_.tabIndex = e.currentIndex;this_.getOrderList();}}, //微信 wxInit: function wxInit() {var this_ = this;var _data = { url: 'http://tiangang.htqp.com.cn:2345/' }; // 获取微信签名 this_.$http.httpTokenRequest({ url: 'JsSdkUiPackage', method: 'POST', data: _data }). then(function (res) { //请求成功 this_.wxConfig(res.data.Timestamp, res.data.NonceStr, res.data.Signature, res.data.AppId); }, function (error) { console.log(error); }); }, wxConfig: function wxConfig(_timestamp, _nonceStr, _signature, _appId) { _jwweixin.default.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: _appId, // 必填,公众号的唯一标识 timestamp: _timestamp, // 必填,生成签名的时间戳 nonceStr: _nonceStr, // 必填,生成签名的随机串 signature: _signature, // 必填,签名,见附录1 jsApiList: ['scanQRCode'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); }, //获取订单列表 getOrderList: function getOrderList() { uni.showLoading(); var this_ = this; this_.$http.httpTokenRequest({ url: this_.$api.CustOrderList + '?c_id=' + '&c_ma001=' + this_.userInfo.c_ma001 + '&state=' + this_.state[this_.tabIndex] + '&nickname=' + this.search.nickname + '&tel=' + this.search.tel + '&code=' + this.search.code + '&m_id=' + this_.userInfo.c_m_id + '&pageindex=' + this_.p + '&pagesize=' + this_.pageSize, method: 'GET', data: {} }). then(function (res) { //请求成功 uni.hideLoading(); console.log(res.data); for (var i = 0; i < res.data.rows.length; i++) { this_.$set(res.data.rows[i], 'priceTotal', 0); var _item = res.data.rows[i].item; for (var m = 0; m < _item.length; m++) { res.data.rows[i].priceTotal += _item[m].i_qty * _item[m].currentprice; } } if (this_.p > 1) { this_.orderList = this_.orderList.concat(res.data.rows); } else { this_.orderList = res.data.rows; } if (0 <= res.data.total < this_.pageSize) { this_.status = 'noMore'; } else { this_.status = 'more'; } this_.papeTotal(res.data.total); }, function (error) { console.log(error); }); }, //获取修理厂列表头部红点数量 orderQty: function orderQty() { var this_ = this; this_.$http.httpTokenRequest({ url: this_.$api.CustNewOrderQty + '?c_ma001=' + this_.userInfo.c_ma001 + '&m_id=' + this_.userInfo.c_m_id + '&c_id=', method: 'GET', data: {} }). then(function (res) { for (var i = 0; i < res.data.length; i++) { if (res.data[i].s_state_no == 0) { this_.badge[0] = res.data[i].qty; } else if (res.data[i].s_state_no == 1) { this_.badge[1] = res.data[i].qty; } else if (res.data[i].s_state_no == 2) { this_.badge[2] = res.data[i].qty; } else if (res.data[i].s_state_no == -1) { this_.badge[3] = res.data[i].qty; } } this_.$set(this_.badge, true); }, function (error) { console.log(error); }); }, proDetail: function proDetail(list) { var this_ = this; list.item = []; this_.$http.httpTokenRequest({ url: this_.$api.CustOrderItem + '?s_id=' + list.s_id, method: 'GET', data: {} }). then(function (res) { //请求成功 list.item = res.data; }, function (error) { console.log(error); }); }, //扫码出库 scanOut: function scanOut(list) { var this_ = this; if (list.item.length > 0) { _jwweixin.default.ready(function () { _jwweixin.default.scanQRCode({ needResult: 1, scanType: ["qrCode", "barCode"], success: function success(res) { var urlName = res.resultStr; var engineCode = urlName.split("?")[1].split("=")[1]; uni.showLoading(); this_.$http.httpTokenRequest({ url: this_.$api.MotorBind + '?s_id=' + list.s_id, method: 'POST', data: { code: engineCode, ma002: this_.userInfo.c_ma002, level: this_.userInfo.c_level, m_id: this_.userInfo.c_m_id } }). then(function (res) { //请求成功 uni.hideLoading(); if (res.data.State) { this_.proDetail(list); } uni.showModal({ title: '温馨提示', content: res.data.Message, success: function success(res) { // if (res.confirm) { // console.log('用户点击确定'); // } else if (res.cancel) { // console.log('用户点击取消'); // } } }); }, function (error) { uni.showModal({ title: '温馨提示', content: "扫描出库失败" }); uni.hideLoading(); }); }, error: function error(res) { alert("失败:" + JSON.stringify(res)); } }); }); } else { this_.proDetail(item, 'refresh'); } }, handleOut: function handleOut(item) { this.isShow = true; this.s_id = item.s_id; }, cancelDo: function cancelDo() { this.isShow = false; }, handleOutDo: function handleOutDo(item) { var this_ = this; this_.$http.httpTokenRequest({ url: this_.$api.MotorBind + '?s_id=' + this.s_id, method: 'POST', data: { code: this.engineCode, ma002: this_.userInfo.c_ma002, level: this_.userInfo.c_level, m_id: this_.userInfo.c_m_id } }). then(function (res) { //请求成功 uni.hideLoading(); if (res.data.State) { this_.proDetail(list); } uni.showModal({ title: '温馨提示', content: res.data.Message, success: function success(res) { // if (res.confirm) { // console.log('用户点击确定'); // } else if (res.cancel) { // console.log('用户点击取消'); // } } }); }, function (error) { uni.hideLoading(); alert("扫描出库失败"); console.log(error); }); }, // scanOut(item) { // let this_ = this; // if (item.detail.length > 0) { // wx.ready(function() { // wx.scanQRCode({ // needResult: 1, // scanType: ["qrCode", "barCode"], // success: function(res) { // //获取url中engineCode // //alert(res.resultStr); // let urlName = res.resultStr; // if (urlName.split("?").length > 1) { // let paraArr = urlName.split("?")[1].split("&"); // let engineCode = ''; // for (var i = 0; i < paraArr.length; i++) { // if (paraArr[i].split("=")[0] == 'engineCode') { // engineCode = paraArr[i].split("=")[1]; // } // } // } // //判断明细中是否含有code相同的 // let isHas = false; // /*for(var j=0;j<item.detail.length;j++){ // let codeArr = item.detail[j].code.split(","); // for(var z=0;z<codeArr.length;z++){ // if(codeArr[z] == engineCode){ // isHas = true; // } // } // }*/ // if(isHas){ // alert("该发动机已扫码"); // }else{ // uni.showLoading(); // this_.$http.httpTokenRequest({ // url:this_.$api.MotorBind + '?s_id=' + item.s_id, // method:'POST', // data:{code:engineCode}, // }).then(res => { // //请求成功 // uni.hideLoading(); // if(res.data.Sate){ // this_.proDetail(item,'refresh'); // } // alert(res.data.Message); // },error => { // uni.hideLoading(); // alert("扫描出库失败"); // console.log(error); // }); // } // }, // error: function(res) { // alert("失败"); // console.log("失败"); // console.log(res); // } // }); // }); // } else { // this_.proDetail(item, 'refresh'); // } // }, //确认发货 orderOk: function orderOk(list, index) { var this_ = this; uni.showLoading(); this_.$http.httpTokenRequest({ url: this_.$api.CustSendOrder + '?s_id=' + list.s_id, method: 'GET', data: {} }). then(function (res) { uni.hideLoading(); if (res.data.State) { uni.showModal({ title: '温馨提示', content: res.data.Message, success: function success(res) { if (res.confirm) { this_.confirmOrder(list.s_c_id, list.s_id, list.s_code, list.c_tel, list.s_c_nickname, index); } else if (res.cancel) { //console.log('用户点击取消'); } } }); } else { uni.showToast({ icon: 'none', title: "未扫描绑定发动机识别码,请先扫描出库", duration: 1500 }); } }, function (error) { console.log(error); }); }, //确认发货接口 confirmOrder: function confirmOrder(s_c_id, s_id, s_code, s_tel, s_c_nickname, index) { var this_ = this; uni.showLoading(); this_.$http.httpTokenRequest({ url: this_.$api.CustSendOrder + '?ma001=' + this_.userInfo.c_ma001 + '&m_id=' + this_.userInfo.c_m_id, method: 'POST', data: { c_id: s_c_id, c_tel: this_.userInfo.c_tel, c_nickname: this_.userInfo.c_nickname, s_id: s_id, s_code: s_code, s_tel: s_tel, s_c_nickname: s_c_nickname } }). then(function (res) { uni.hideLoading(); if (res.data.State) { this_.orderList.splice(index, 1); } uni.showToast({ icon: 'none', title: res.data.Message, duration: 1500 }); }, function (error) { console.log(error); }); }, //获取总页数 papeTotal: function papeTotal(rowCount) { var this_ = this; if (rowCount != null && rowCount != "") { if (rowCount % this_.pageSize == 0) { this_.pageCount = parseInt(rowCount / this_.pageSize); } else { this_.pageCount = parseInt(rowCount / this_.pageSize) + 1; } } else { return 0; } }, //删除发动机号 delCode: function delCode(item, _delCode, index) { var this_ = this; if (this_.tabIndex == 0) { uni.showModal({ title: '温馨提示', content: '确定要删除该发动机号吗?', success: function success(res) { if (res.confirm) { this_.$http.httpTokenRequest({ url: this_.$api.MotorClear, method: 'POST', data: { s_id: item.i_s_id, i_code: _delCode } }). then(function (res) { if (res.data.State) { this_.$refs[index][0].$el.innerHTML = ''; } uni.showToast({ icon: 'none', title: res.data.Message, duration: 1500 }); }, function (error) { console.log(error); }); } else if (res.cancel) { //console.log('用户点击取消'); } } }); } }, //取消订单 orderCancel: function orderCancel(list, index) { var this_ = this; uni.showModal({ title: '温馨提示', content: '是否取消?', success: function success(res) { if (res.confirm) { uni.showLoading(); this_.$http.httpTokenRequest({ url: this_.$api.CustCancelOrder + '?s_c_id=' + list.s_c_id, method: 'POST', data: { "c_nickname": list.c_nickname, "c_tel": list.s_tel, "s_id": list.s_id, "s_code": list.s_code } }). then(function (res) { uni.hideLoading(); if (res.data.State) { this_.orderList.splice(index, 1); } uni.showToast({ icon: 'none', title: res.data.Message, duration: 1500 }); }, function (error) { console.log(error); }); } else if (res.cancel) { //console.log('用户点击取消'); } } }); } } };exports.default = _default; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@dcloudio/uni-mp-weixin/dist/index.js */ 1)["default"])) /***/ }), /***/ 88: /*!*********************************************************************************************************!*\ !*** E:/HBuilderProjects/MotorOrder/pages/agent/reporder/reporder.vue?vue&type=style&index=0&lang=css& ***! \*********************************************************************************************************/ /*! no static exports found */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _D_360_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_D_360_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_6_oneOf_1_1_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_2_D_360_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!./node_modules/mini-css-extract-plugin/dist/loader.js??ref--6-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-1-1!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--6-oneOf-1-2!./node_modules/postcss-loader/src??ref--6-oneOf-1-3!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!./reporder.vue?vue&type=style&index=0&lang=css& */ 89); /* harmony import */ var _D_360_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_D_360_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_6_oneOf_1_1_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_2_D_360_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_D_360_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_D_360_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_6_oneOf_1_1_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_2_D_360_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__); /* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _D_360_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_D_360_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_6_oneOf_1_1_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_2_D_360_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _D_360_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_D_360_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_6_oneOf_1_1_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_2_D_360_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__)); /* harmony default export */ __webpack_exports__["default"] = (_D_360_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_D_360_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_6_oneOf_1_1_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_2_D_360_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_D_360_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_reporder_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0___default.a); /***/ }), /***/ 89: /*!*************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/mini-css-extract-plugin/dist/loader.js??ref--6-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-1-1!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--6-oneOf-1-2!./node_modules/postcss-loader/src??ref--6-oneOf-1-3!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!E:/HBuilderProjects/MotorOrder/pages/agent/reporder/reporder.vue?vue&type=style&index=0&lang=css& ***! \*************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin if(false) { var cssReload; } /***/ }) },[[81,"common/runtime","common/vendor"]]]); //# sourceMappingURL=../../../../.sourcemap/mp-weixin/pages/agent/reporder/reporder.js.map
JavaScript
CL
fd1ebaff18d0178f1f9688b5266904ce21395a23f940a6ea32990b5141a4d127
 var client; $(document).ready(async function () { const msalConfig = { auth: { clientId: "51d7c325-0c70-4896-8e8d-140eba1f9d2e", // Client Id of the registered application redirectUri: "http://localhost:56802/", }, cache: { cacheLocation: "sessionStorage", // This configures where your cache will be stored storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge forceRefresh: false } }; const graphScopes = ["user.read", "Notes.Create", "Notes.Read", "Notes.ReadWrite"]; // An array of graph scopes const msalApplication = new Msal.UserAgentApplication(msalConfig); const options = new MicrosoftGraph.MSALAuthenticationProviderOptions(graphScopes); const authProvider = new MicrosoftGraph.ImplicitMSALAuthenticationProvider(msalApplication, options); const providerOptions = { authProvider, // An instance created from previous step }; const Client = MicrosoftGraph.Client; client = Client.initWithMiddleware(providerOptions); try { userDetails = await client.api("/me").get(); console.log(userDetails); $("#username").html(userDetails.displayName); if (callBack) { callBack(); } } catch (error) { throw error; } });
JavaScript
CL
f534dc0467fdebc3b7fa2c010e15b94842b992527abda37e5e635b3afc139f3b
import { STATICDATA_LOADING, STATICDATA_LOAD, STATICDATA_ERROR_DB, STATICDATA_NO_OP, } from './constants' import { staticdataRD } from './reducer' const PAYLOAD = { beliefs: '', strengths: '', lifeDescriptions: '' } const INITIAL_STATE = { isLoading: true, isError: false, errorMessage: '', beliefs: [], relationships: [], strengths: [], lifeDescriptors: [], } describe('static data reducer', () => { it('returns passed in state by default', () => { expect(staticdataRD(PAYLOAD, {})).toEqual(PAYLOAD) }) it('returns initial state when no state is passed in', () => { expect(staticdataRD(undefined, {})).toEqual(INITIAL_STATE) }) it('returns initial state on STATICDATA_LOADING', () => { expect(staticdataRD(undefined, { type: STATICDATA_LOADING })).toEqual(INITIAL_STATE) }) it('sets isLoading to false and sets beliefs, strengths, lifeDescriptions to payload on STATICDATA_LOAD', () => { expect(staticdataRD(undefined, { type: STATICDATA_LOAD, payload: PAYLOAD })).toEqual({ ...INITIAL_STATE, ...PAYLOAD, isLoading: false }) }) it('sets isError to true, isLoading to false, errorMessage to payload on STATICDATA_ERROR_DB', () => { expect(staticdataRD(undefined, { type: STATICDATA_ERROR_DB, payload: PAYLOAD })).toEqual({ ...INITIAL_STATE, isLoading: false, isError: true, errorMessage: PAYLOAD }) }) it('returns passed in state on STATICDATA_NO_OP', () => { expect(staticdataRD(PAYLOAD, { type: STATICDATA_NO_OP })).toEqual(PAYLOAD) }) })
JavaScript
CL
1a1ae71738c78cbd383906307336636ba630970643201cfd21894bfef51b58c2
const uuid4 = require('uuid/v4'); module.exports = { // // This function writes multiple inventory into inlfe system - stub to simulate a unique id back from inlife system // writeInlifeAssets: function(enhancedBssItems) {}, // // This function writes single inventory into inlfe system // writeInlifeAsset: function(enhancedBssItem) { // do not care about the stub response as long as it has a unique id // TODO correct this format let response = { sys_id: uuid4() }; return response; }, // // This function writes single inventory relationship into inlfe system // writeInlifeAssetRelationship: function(enhancedBssItem) {} }
JavaScript
CL
8419736f57f78794c9bbd190b0245eed84420ce1e6af3e29da792af84046ff14
/** * Copyright 2017 dialog LLC <info@dlg.im> * @flow */ import '!style!css!./photoswipe.css'; import type { PhotoSwipeItem, PhotoSwipeOptions } from 'photoswipe'; import React, { Component } from 'react'; import cx from 'classnames'; import PhotoSwipe from 'photoswipe'; import PhotoSwipeUI from 'photoswipe/src/js/ui/photoswipe-ui-default'; import Icon from '../Icon/Icon'; import styles from './Lightbox.css'; export type Props = { className?: string, startIndex: number, items: PhotoSwipeItem[], options: $Shape<PhotoSwipeOptions>, onClose: () => any }; export type State = { current: ?PhotoSwipeItem }; class Lightbox extends Component { props: Props; state: State; container: ?HTMLElement; photoSwipe: ?PhotoSwipe; constructor(props: Props) { super(props); this.state = { current: props.items[props.startIndex] }; } componentDidMount(): void { if (this.container) { const photoSwipe = new PhotoSwipe(this.container, PhotoSwipeUI, this.props.items, { ...this.props.options, index: this.props.startIndex, history: false, closeOnScroll: false, // UI options shareEl: false }); photoSwipe.listen('close', this.handleClose); photoSwipe.listen('afterChange', this.handleIndexChange); photoSwipe.init(); this.photoSwipe = photoSwipe; } } shouldComponentUpdate(nextProps: Props, nextState: State): boolean { return nextState.current !== this.state.current; } componentWillUnmount(): void { if (this.photoSwipe) { try { this.photoSwipe.close(); } catch (e) { // do nothing } this.photoSwipe = null; } } handleIndexChange = () => { if (this.photoSwipe) { this.setState({ current: this.photoSwipe.currItem }); } }; handleClose = (): void => { this.photoSwipe = null; this.props.onClose(); }; setContainer = (container: HTMLElement): void => { this.container = container; }; renderDownload(): ?React.Element<any> { const { current } = this.state; if (!current) { return null; } return ( <a className={styles.buttonDownload} href={current.src} download={current.src}> <Icon glyph="file_download" className={styles.icon} /> </a> ); } render(): React.Element<any> { const className = cx('pswp', styles.container, this.props.className); return ( <div ref={this.setContainer} className={className} tabIndex="-1" role="dialog" aria-hidden="true" > <div className={cx('pswp__bg', styles.background)} /> <div className={cx('pswp__scroll-wrap', styles.scroll)}> <div className={cx('pswp__container', styles.wrapper)}> <div className={cx('pswp__item', styles.item)} /> <div className={cx('pswp__item', styles.item)} /> <div className={cx('pswp__item', styles.item)} /> </div> <div className="pswp__ui pswp__ui--hidden"> <div className={cx('pswp__top-bar', styles.toolbar)}> <div className="pswp__counter" /> <button className="pswp__button pswp__button--close" title="Close (Esc)" /> <button className="pswp__button pswp__button--share" title="Share" /> <button className="pswp__button pswp__button--fs" title="Toggle fullscreen" /> {this.renderDownload()} <button className="pswp__button pswp__button--zoom" title="Zoom in/out" /> <div className="pswp__preloader"> <div className="pswp__preloader__icn"> <div className="pswp__preloader__cut"> <div className="pswp__preloader__donut" /> </div> </div> </div> </div> <div className="pswp__share-modal pswp__share-modal--hidden pswp__single-tap" > <div className="pswp__share-tooltip" /> </div> <button className="pswp__button pswp__button--arrow--left" title="Previous (arrow left)" /> <button className="pswp__button pswp__button--arrow--right" title="Next (arrow right)" /> <div className="pswp__caption"> <div className="pswp__caption__center" /> </div> </div> </div> </div> ); } } export default Lightbox;
JavaScript
CL
a565c097c9a60384161c7b0bcdc2fbeb478795020cb5bdc669ba4816020e4b2e
!function(exports) { var inputSectionElem; var resultSectionElem; var chartTypeSelect; var btnSend; var divParams; var sharedSecretInput; var jsonResultInput; var urlResultInput; var chartImg; const HOST = document.location.origin; const URLS = { 'line': HOST + '/charts/line', 'bar': HOST + '/charts/bar', 'pie': HOST + '/charts/pie', 'polarArea': HOST + '/charts/polarArea', 'doughnut': HOST + '/charts/doughnut' }; var initHTMLElements = function initHTMLElements() { inputSectionElem = document.getElementById('inputs'); chartTypeSelect = inputSectionElem.querySelector('#chartType'); btnSend = inputSectionElem.querySelector('#sendParams'); divParams = inputSectionElem.querySelectorAll('div.chartInputs'); sharedSecretInput = inputSectionElem.querySelector('#sharedSecret'); resultSectionElem = document.getElementById('result'); jsonResultInput = resultSectionElem.querySelector('#jsonResult'); urlResultInput = resultSectionElem.querySelector('#urlResult'); chartImg = resultSectionElem.querySelector('#chartImg'); chartTypeSelect.value = 'line'; onSelectChange({target:{value:'line'}}); }; var setResultsVisibility = function setResultsVisibility(visible) { resultSectionElem.dataset.status = visible ? 'visible' : 'hidden'; }; var onInputChange = function onInputChange(evt) { setResultsVisibility(false); }; var onSelectChange = function onSelectChange(evt) { setResultsVisibility(false); if (!evt.target.value) { return; } var chartType = evt.target.value; for (var i = 0, l = divParams.length; i < l; i++) { var domNode = divParams[i]; domNode.style.display = domNode.id === chartType ? 'inline' : 'none'; } }; var getInputValues = function getInputValues(domElems) { var result = {}; for (var i = 0, l = domElems.length; i < l; i++) { var elem = domElems[i]; var name = elem.name; if (name === 'sharedSecret') { continue; } var value = elem.value; if (value !== '') { if (elem.class === 'json') { result[name] = JSON.parse(value); } else { result[name] = value; } } } return result; }; var composeJSON = function composeJSON(chartType) { var genericFieldsDOM = inputSectionElem.querySelectorAll('div#genericParameters input'); var genericValues = getInputValues(genericFieldsDOM); var inputsFieldsDOM = inputSectionElem.querySelectorAll('div#' + chartType + ' input'); var especificValues = getInputValues(inputsFieldsDOM); return Object.assign({}, genericValues, especificValues); }; var loadImg = function loadImg() { var params = composeJSON(chartTypeSelect.value); var sharedSecret = sharedSecretInput.value; var paramsStringified = JSON.stringify(params); jsonResultInput.value = paramsStringified; setResultsVisibility(true); var encodedParams = btoa(paramsStringified); if (sharedSecret) { var auth = cryptoUtils.then(cu => cu.doImportKey(cu.str2bin(sharedSecret)). then(cu.doHMAC.bind(cu, cu.str2bin(encodedParams))). then(cu.bin2hex). then(function(auth) { let src = URLS[chartTypeSelect.value] + '?param=' + encodedParams + '&auth=' + auth; chartImg.src = src; urlResultInput.value = src; return src; })); } else { let src = URLS[chartTypeSelect.value] + '?param=' + encodedParams; urlResultInput.value = src; chartImg.src = src; } }; var addHandlers = function addHandlers() { var setHandler = function setHandle(arrElem, handler) { for (var i = 0, l = arrElem.length; i < l; i++) { var elem = arrElem[i]; elem.addEventListener('keyup', handler); } }; chartTypeSelect.addEventListener('change', onSelectChange); btnSend.addEventListener('click', loadImg); var genericFieldsDOM = inputSectionElem.querySelectorAll('div#genericParameters input'); setHandler(genericFieldsDOM, onInputChange); var chartTypes = Object.keys(URLS); for (var i = 0, l = chartTypes.length; i < l; i++) { var inputsFieldsDOM = inputSectionElem.querySelectorAll('div#' + chartTypes[i] + ' input'); setHandler(inputsFieldsDOM, onInputChange); } }; var init = function init() { initHTMLElements(); addHandlers(); }; init(); }(this);
JavaScript
CL
8e6f4b953d791bee5002882386388a30ebc68ac9c474ef3f01941d51d2057d88
const gulp = require('gulp'); const browserSync = require('browser-sync'); browserSync.create('PGR2015'); const serve = require('./gulp_tasks/serve'), ts = require('./gulp_tasks/ts'), clean = require('./gulp_tasks/clean'), html = require('./gulp_tasks/html'), scss = require('./gulp_tasks/scss'), build = require('./gulp_tasks/build'), test = require('./gulp_tasks/test'); gulp.task('clean:tmp', clean('.tmp')); gulp.task('clean:dist', clean('dist')); gulp.task('serve', ['ts:serve', 'html:serve', 'scss:serve'], serve); gulp.task('ts:serve', ['clean:tmp'], ts); gulp.task('ts-watch:serve', ts); gulp.task('html:serve', ['clean:tmp'], html); gulp.task('html-watch:serve', html); gulp.task('scss:serve', ['clean:tmp'], scss); gulp.task('scss-watch:serve', scss); gulp.task('build-webpack', ['clean:dist'], build.webpack); gulp.task('build-inject', ['clean:dist', 'build-webpack'], build.inject); gulp.task('build-scripts', ['clean:dist', 'build-inject'], build.scripts); gulp.task('build-styles', ['clean:dist'], build.styles); gulp.task('build', ['clean:dist', 'build-webpack', 'build-inject', 'build-scripts', 'build-styles']); gulp.task('test-inject', test.inject); gulp.task('test-run', ['test-inject'], test.run); gulp.task('test', ['test-run']);
JavaScript
CL
ab9102faecbaaef4f7213d141cffdb819d267ee1f2849e9936efe713041ae0b7
const PdfManager = require('src/manager/PdfManager/PdfManager'), InquirerManager = require('src/manager/InquirerManager/InquirerManager'), fileManager = require('src/manager/FileManager'), config = require('config'), genExec = require('src/utils/genExec'), KafedraPage = require('src/page/KafedraPage'), EbmuMPage = require('src/page/EbmuMPage'); class ManualRunner { run() { const task = function*() { const pdfManager = new PdfManager('file'), inquirerManager = new InquirerManager('manual'), ebmuMPage = new EbmuMPage(); let pdfFiles = yield pdfManager.getPdfs(); for(let pdfFile of pdfFiles) { let answers = yield inquirerManager.getInquirerResult(), {kafedra, authors, title, type, year} = answers, absManualsPath = config.projectDir+kafedra.getManualsUrl(), index = fileManager.getNextIndex(absManualsPath, '.pdf'), kafedraPage = new KafedraPage(kafedra), pdfUrl = kafedra.getManualsUrl()+`/${index}.pdf`, manualProps = {authors, title, pdfUrl, type, year}; fileManager.moveToProject(pdfFile, kafedra.getManualsUrl(), index+'.pdf'); kafedraPage.addManual(manualProps); ebmuMPage.incrementManualsCounter(); } }; return genExec(task()); } } module.exports = ManualRunner;
JavaScript
CL
b57c7cce2c2818c03729101bfad27c3b20977ac6f760661b375054fceb379d70
webpackJsonp([7],{"+hz4":function(t,a,e){"use strict";a.a={name:"Talk",props:["talk","descFlex"],computed:{images:function(){return Array.isArray(this.talk.img)?this.talk.img:[this.talk.img]},id:function(){return this.talk.author.toLowerCase().split(" ").join("-")}},mounted:function(){this.id===this.$route.query.focus&&this.$refs.talk.focus()}}},"2mQT":function(t,a,e){"use strict";function i(t){e("9CeH")}var o=e("+hz4"),n=e("k1dV"),s=e("VU/8"),r=i,l=s(o.a,n.a,!1,r,"data-v-4dd8688c",null);a.a=l.exports},"3+Hb":function(t,a,e){"use strict";var i=e("2mQT");a.a={head:{title:"VueConf US 2018 | Workshops"},components:{Talk:i.a},data:function(){return{evanWorkshop:{type:"talk",img:"/img/evan.jpg",topic:"Advanced Features from the Ground Up",author:"Evan You",social:[{github:"https://github.com/yyx990803",twitter:"https://twitter.com/youyuxi"}],authorInfo:"Vue.js Author",description:"We often reach for existing libraries when dealing with advanced app features such as routing, state management, form validation and i18n, and a lot of times the implementations behind these libraries can be a black box. \n\n In this workshop we are going to build simple versions of such libraries from the ground up using basic Vue features. \n\n This will help you better understand the nature of these problems and how to better leverage Vue’s reactivity system to come up with elegant solutions."},blakeWorkshop:{type:"talk",img:"/img/blake.jpg",topic:"Application state with Vuex",author:"Blake Newman",social:[{github:"https://github.com/blake-newman",twitter:"https://twitter.com/blakenewman"}],authorInfo:"Software Engineer at Attest\nVue Core Team"},sarahWorkshop:{type:"talk",img:"/img/sarah.jpg",topic:"Animated Interfaces with Vue.js",author:"Sarah Drasner",social:[{github:"https://github.com/sdras",twitter:"https://twitter.com/sarah_edo"}],authorInfo:"Senior Cloud Developer Advocate at Microsoft\nVue Core Team"},chrisWorkshop:{type:"talk",img:"/img/chris.jpg",topic:"Vue.js Fundamentals",author:"Chris Fritz",social:[{github:"https://github.com/chrisvfritz",twitter:"https://twitter.com/chrisvfritz"}],authorInfo:"Consultant\nVue Core Team",description:"This full-day, hands-on workshop will get you coding a Vue.js application in no time! Vue.js is easy to get started with, and easy to build on! This workshop is lead by a member of the core Vue.js team."}}}}},"9CeH":function(t,a,e){var i=e("oeIv");"string"==typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);e("rjj0")("198a16ee",i,!0)},BaXI:function(t,a,e){"use strict";var i=function(){var t=this,a=t.$createElement,e=t._self._c||a;return e("div",{staticClass:"container"},[e("div",{staticClass:"container__inner post-section"},[e("h1",{staticClass:"agenda__header"},[t._v("Workshops")]),t._m(0),e("div",{staticClass:"agenda"},[e("talk",{attrs:{talk:t.evanWorkshop,"desc-flex":7}}),e("talk",{attrs:{talk:t.chrisWorkshop,"desc-flex":7}}),e("talk",{attrs:{talk:t.sarahWorkshop,"desc-flex":7}},[e("p",[t._v("In one day of training, attendees will go from knowing nothing (or very little) about animating in Vue to creating complex effects in performant and visually stunning patterns. The web is more than a document reader, and Vue has unique offerings that make animations not only possible, but possible to do in an organized and state-managed manner.")]),e("p",[t._v("What we'll go over is included but not limited to:")]),e("ul",[e("li",[t._v("Working with SVG within Vue components")]),e("li",[t._v("Creating custom directives for animation")]),e("li",[t._v("Using in-out modes to create effective and reusable component composition")]),e("li",[t._v("Using Vue <transition> hooks for external javascript libraries")]),e("li",[t._v("Interpolating state for data visualization with watchers")]),e("li",[t._v("Integration of animation with routers for page transition")])])]),e("talk",{attrs:{talk:t.blakeWorkshop,"desc-flex":7}},[e("p",[t._v("As an application grows, you will notice that components will share common code and state. Eventually as the application grows it can become more important to manage this state carefully, to improve maintainability, predictability and application flow.")]),e("p",[t._v("Vuex, is inspired by elm. It is not only a "),e("strong",[t._v("library")]),t._v(" but a "),e("strong",[t._v("state management pattern")]),t._v(". Introducing these patterns, improves the overall application flow and creates a centralised state. However, it is easy to go overboard with state managment; thus we will look at a full range of best practices to ensure you can make the most of Vuex.")]),e("p",[t._v("Schedule:")]),e("ul",[e("li",[t._v("What is Vuex?")]),e("li",[t._v("Looking at state management patterns")]),e("li",[t._v("Determining application state from local state")]),e("li",[t._v("Using "),e("strong",[t._v("Actions")]),t._v(", "),e("strong",[t._v("Mutations")]),t._v(" and "),e("strong",[t._v("Getters")])]),e("li",[t._v("Modularising a store")]),e("li",[t._v("Composing actions (Promises and Async/Await)")]),e("li",[t._v("Avoiding common pitfalls")])])])],1)])])},o=[function(){var t=this,a=t.$createElement,e=t._self._c||a;return e("p",{staticClass:"subheader__description"},[e("strong",[t._v("Monday March 26")]),e("br"),t._v("Workshops and conference tickets are sold separately.")])}],n={render:i,staticRenderFns:o};a.a=n},BbVY:function(t,a,e){"use strict";function i(t){e("eWR8")}Object.defineProperty(a,"__esModule",{value:!0});var o=e("3+Hb"),n=e("BaXI"),s=e("VU/8"),r=i,l=s(o.a,n.a,!1,r,"data-v-cc1294de",null);a.default=l.exports},eWR8:function(t,a,e){var i=e("zjJu");"string"==typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);e("rjj0")("5c0c4b82",i,!0)},k1dV:function(t,a,e){"use strict";var i=function(){var t=this,a=t.$createElement,e=t._self._c||a;return e("div",{staticClass:"talk__container"},[e("div",{ref:"talk",staticClass:"talk",attrs:{id:t.id,tabindex:"0"}},[e("div",{staticClass:"talk__image-container"},[e("div",{staticClass:"talk__images"},t._l(t.images,function(a){return e("img",{staticClass:"talk__image",attrs:{src:a,alt:t.talk.author}})})),e("div",{staticClass:"talk__author"},[t._v(t._s(t.talk.author))]),e("div",{staticClass:"talk__author-info"},[t._v(t._s(t.talk.authorInfo))]),e("div",{staticClass:"talk__social__container"},t._l(t.talk.social,function(a){return e("div",{staticClass:"talk__social"},[a.github?e("a",{staticClass:"icon icon--github",attrs:{href:a.github,target:"_blank"}}):t._e(),a.gitlab?e("a",{staticClass:"icon icon--gitlab",attrs:{href:a.gitlab,target:"_blank"}}):t._e(),a.twitter?e("a",{staticClass:"icon icon--twitter",attrs:{href:a.twitter,target:"_blank"}}):t._e()])}))]),e("div",{staticClass:"talk__description",style:{flex:t.descFlex}},[e("h2",{staticClass:"talk__topic"},[t._v(t._s(t.talk.topic))]),t._t("default",[e("p",[t._v(t._s(t.talk.description))])]),e("div",{staticClass:"center"},[t._t("ticket")],2)],2)])])},o=[],n={render:i,staticRenderFns:o};a.a=n},oeIv:function(t,a,e){a=t.exports=e("FZ+f")(!1),a.push([t.i,".talk__container[data-v-4dd8688c]{margin-bottom:40px}.talk[data-v-4dd8688c]{display:-webkit-box;display:-ms-flexbox;display:flex;padding:40px 10px;margin-bottom:20px;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-ms-flex-pack:distribute;justify-content:space-around;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;background:#fff;border-radius:5px;text-align:left;-webkit-box-shadow:0 15px 35px rgba(50,50,93,.03),0 5px 15px rgba(0,0,0,.06);box-shadow:0 15px 35px rgba(50,50,93,.03),0 5px 15px rgba(0,0,0,.06);cursor:pointer;-webkit-transition:all .15s ease;transition:all .15s ease;cursor:auto}.talk[data-v-4dd8688c]:hover{-webkit-box-shadow:0 15px 35px rgba(50,50,93,.07),0 5px 15px rgba(0,0,0,.1);box-shadow:0 15px 35px rgba(50,50,93,.07),0 5px 15px rgba(0,0,0,.1)}@media only screen and (min-width:640px){.talk[data-v-4dd8688c]{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row;padding:40px}}.talk[data-v-4dd8688c]:focus{outline:none}.talk__description[data-v-4dd8688c]{-webkit-box-flex:5;-ms-flex:5;flex:5;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start;height:100%;white-space:pre-line;padding:0 15px}.talk__description li[data-v-4dd8688c],.talk__description p[data-v-4dd8688c],.talk__description ul[data-v-4dd8688c]{font-size:18px}.talk__description ul[data-v-4dd8688c]{margin:0;padding-left:30px}.talk__image-container[data-v-4dd8688c]{-webkit-box-flex:3;-ms-flex:3;flex:3;-webkit-box-orient:vertical;-ms-flex-direction:column;flex-direction:column;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between}.talk__image-container[data-v-4dd8688c],.talk__images[data-v-4dd8688c]{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-direction:normal}.talk__images[data-v-4dd8688c]{-webkit-box-orient:horizontal;-ms-flex-direction:row;flex-direction:row}.talk__image[data-v-4dd8688c]{display:block;margin:0 -10px;height:70px;width:70px;border-radius:50%;padding-bottom:10px}@media only screen and (min-width:640px){.talk__image[data-v-4dd8688c]{height:150px;width:150px}}.talk__social__container[data-v-4dd8688c]{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row}.talk__social[data-v-4dd8688c]{margin:10px 20px 0}.talk__social .icon[data-v-4dd8688c]:not(:last-child){padding-right:10px}.talk__topic[data-v-4dd8688c]{color:#3bb881;margin:15px;text-align:center}@media only screen and (min-width:640px){.talk__topic[data-v-4dd8688c]{margin:5px 0 0;text-align:left}}.talk__author[data-v-4dd8688c]{font-weight:600;font-size:20px;padding-bottom:5px}@media only screen and (min-width:640px){.talk__author[data-v-4dd8688c]{font-size:24px}}.talk__author-info[data-v-4dd8688c]{text-align:center;word-break:break-word;white-space:pre-line}.center[data-v-4dd8688c]{margin-top:30px}.button[data-v-4dd8688c]{text-transform:uppercase;font-size:16px;font-weight:400}",""])},zjJu:function(t,a,e){a=t.exports=e("FZ+f")(!1),a.push([t.i,".agenda__card[data-v-cc1294de]{height:100px;width:100%}.agenda__header[data-v-cc1294de]{margin-bottom:20px}.subheader__description[data-v-cc1294de]{margin:0 0 80px}",""])}}); //# sourceMappingURL=workshops.86b8fdb66a80c9de07a6.js.map
JavaScript
CL
f072fb3390c964c448db7b762cf543fc1577a9150427ab927fd77778bb53509b
/** Vagner Machado QCID 23651127 This is my implementation of the RFC865 Quote of the Day Protocol for TCP connection. * This Node JS server listens for a connection on port 3014 * Once a connection is established, a short message is sent out the connection. * Any data receives is disregarded. * The connection is closed by the server after sending the message. */ "use strict" const net = require("net"); const port = 3014; //I was going to add this quote array as a separate file but then you'd need it in you directory for it to work, so I just kept it here. const quotes = ["Act as if what you do makes a difference. It does.\r\n-William James", "Success is not final, failure is not fatal: it is the courage to continue that counts.\r\n-Winston Churchill", "Never bend your head. Always hold it high. Look the world straight in the eye.\r\n-Hellen Keller", "What you get by achieving your goals is not as important as what you become by achieving your goals.\r\n-Zig Ziglar", "Believe you can and you're halfway there.\r\n-Theodore Roosevelt", "I can't change the direction of the wind, but I can adjust my sails to always reach my destination.\r\n-Jimmy Dean", "If you believe in yourself, with a tiny pinch of magic all your dreams can come true!\r\n-Sponge Bob" ]; //variable to hold random number representing the index in quote array let quoteNumber; //create a server const server = net.createServer(); //handles the server throwing an error const connectionError = function (err) { console.log(err.message, " was thrown by server."); }; //handles a connection to the QOTD server const connectionListener = function(socket) { //callback for end of connection by client const connectionEnd = function () { console.log("Client disconnected."); }; //callback for client error const connectionError = function (err) { console.log(err.message, "thrown by the socket", socket.remotePort); }; //socket event listeners socket.on("end", connectionEnd); socket.on("error", connectionError); console.log("Client connected on remote port ", socket.remotePort); //quoteNumber = Math.floor(Math.random() * 7); //optional for a new quote per connection //to use the line above, comment out the following two lines of uncommented code below. //randomize a quote so it is the same quote for the same day, based on current date let date = new Date(); quoteNumber = ((date.getDate() + date.getUTCFullYear() + date.getMonth() + 1)% 7); console.log("Sending quote at quote array position ", quoteNumber, "and ending connection."); socket.end(quotes[quoteNumber]); }; //handles the binding of the server const connectionStart = function () { console.log("Server bound, listening on port", port); }; //server event listeners server.on("error", connectionError); server.on("connection", connectionListener); server.on("listening", connectionStart); //start listening on the socket 3014 server.listen(port);
JavaScript
CL
085b30e7010b136dd36a485763aec25bcaff718b4744b81a918d2059b3e52475
/** * @file * * ### Responsibilities * - create global variable SOURCEONLY that is only true for 'unminified' code * * @author Daniel Lamb <dlamb.open.source@gmail.com> */ /*jshint unused: false*/ /** @define {boolean} SOURCEONLY is used to exclude sections of code that should not be included in production code such as debugging logic or exporting private methods and state for unit testing. These sections are stripped by specifying --define SOURCEONLY=false to the JSCompiler. */ var SOURCEONLY = true;
JavaScript
CL
7da62712a0e47483c1a0f6d7fc6004de5cc9d9c8543431ecf691e3458d5377ce
/* * 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. */ var app = { // Application Constructor initialize: function() { document.addEventListener('deviceready', this.onDeviceReady.bind(this), false); document.getElementById('btntomarfoto').addEventListener("click",takephoto); document.getElementById('btnestado').addEventListener("click",ShowBatteryStatus); document.getElementById('wifi').addEventListener("click",checkConnection); document.getElementById('btndevice').addEventListener("click",version); }, // deviceready Event Handler // // Bind any cordova events here. Common events are: // 'pause', 'resume', etc. onDeviceReady: function() { this.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); } }; app.initialize(); function takephoto(){ navigator.camera.getPicture(onSuccess, onFail, { quality: 25, destinationType: Camera.DestinationType.DATA_URL }); } function onSuccess(imageData) { var image = document.getElementById('img'); image.src = "data:image/jpeg;base64," + imageData; } function onFail(message) { alert('Failed because: ' + message); } function vibrar() { navigator.vibrate(1000); } function ShowBatteryStatus(){ window.addEventListener("batterystatus", onBatteryStatus, false); } function onBatteryStatus(status) { alert("Nivel Bateria: " + status.level + " Cargando:" + status.isPlugged); } function version(){ alert("UUID:"+device.uuid +"\n"+"Plataforma:"+device.platform +"\n"+"Version SO:"+device.version+"\n"+"Modelo:"+device.model+"\n"+"Fabricante:"+device.manufacturer); } function checkConnection() { var networkState = navigator.connection.type; var states = {}; states[Connection.UNKNOWN] = 'Unknown connection'; states[Connection.ETHERNET] = 'Ethernet connection'; states[Connection.WIFI] = 'WiFi connection'; states[Connection.CELL_2G] = 'Cell 2G connection'; states[Connection.CELL_3G] = 'Cell 3G connection'; states[Connection.CELL_4G] = 'Cell 4G connection'; states[Connection.CELL] = 'Cell generic connection'; states[Connection.NONE] = 'No network connection'; alert('Tipo de Conexion: ' + states[networkState]); }
JavaScript
CL
c54232bb78a4bfcabae4160a2f36cad9509a02a5a43147f44fb7dcfe2df41239
System.config({ "bundles": { "admin.js": [ "app/admin.js", "github:eonasdan/bootstrap-datetimepicker@0.0.10.js", "github:eonasdan/bootstrap-datetimepicker@0.0.10/build/js/bootstrap-datetimepicker.min.js" ], "main.js": [ "app/main.js", "feature/clipboardButtons/main.js", "feature/codeSidebar/main.js", "feature/filterableList/attributeMatcher.js", "feature/filterableList/filter.js", "feature/filterableList/filterableList.js", "feature/filterableList/getUrlFilter.js", "feature/filterableList/main.js", "feature/formWidgets/main.js", "feature/gotoTop/main.js", "feature/hide-show-guide/main.js", "feature/hide-show-guide/storage.js", "feature/homepage/main.js", "feature/infoPopups/main.js", "feature/map/main.js", "feature/mobileSupport/main.js", "feature/navMenu/main.js", "feature/platformDownloads/main.js", "feature/prettify/main.js", "feature/search/SearchController.js", "feature/search/main.js", "feature/searchFacets/filterForm.js", "feature/searchFacets/main.js", "feature/stsImport/main.js", "feature/switchSidebar/main.js", "feature/timeAgo/main.js", "github:abpetkov/switchery@0.8.2/dist/switchery.min.js", "github:jspm/nodelibs-process@0.1.2.js", "github:jspm/nodelibs-process@0.1.2/index.js", "github:rmm5t/jquery-timeago@1.5.3.js", "github:rmm5t/jquery-timeago@1.5.3/jquery.timeago.js", "github:tcollard/google-code-prettify@1.0.4/bin/prettify.min.js", "github:twbs/bootstrap@2.3.2/js/bootstrap-collapse.js", "github:twbs/bootstrap@2.3.2/js/bootstrap-tooltip.js", "npm:clipboard@1.5.12.js", "npm:clipboard@1.5.12/lib/clipboard-action.js", "npm:clipboard@1.5.12/lib/clipboard.js", "npm:closest@0.0.1.js", "npm:closest@0.0.1/index.js", "npm:delegate@3.0.1.js", "npm:delegate@3.0.1/src/delegate.js", "npm:good-listener@1.1.7.js", "npm:good-listener@1.1.7/src/is.js", "npm:good-listener@1.1.7/src/listen.js", "npm:jquery@1.12.4.js", "npm:jquery@1.12.4/dist/jquery.js", "npm:matches-selector@0.0.1.js", "npm:matches-selector@0.0.1/index.js", "npm:most@0.2.4.js", "npm:most@0.2.4/Stream.js", "npm:most@0.2.4/async.js", "npm:most@0.2.4/most.js", "npm:process@0.11.5.js", "npm:process@0.11.5/browser.js", "npm:select@1.0.6.js", "npm:select@1.0.6/src/select.js", "npm:tiny-emitter@1.1.0.js", "npm:tiny-emitter@1.1.0/index.js", "platform/os.js" ], "maps.js": [ "app/maps.js", "npm:gmaps@0.4.24.js", "npm:gmaps@0.4.24/gmaps.js" ], "pages/projects/show.js": [ "app/pages/projects/show.js", "github:jspm/nodelibs-process@0.1.2.js", "github:jspm/nodelibs-process@0.1.2/index.js", "github:twbs/bootstrap@2.3.2/js/bootstrap-tab.js", "npm:jquery@1.12.4.js", "npm:jquery@1.12.4/dist/jquery.js", "npm:process@0.11.5.js", "npm:process@0.11.5/browser.js" ] }, "defaultJSExtensions": true, "map": { "FortAwesome/font-awesome": "github:FortAwesome/font-awesome@3.2.1", "bootstrap": "github:twbs/bootstrap@2.3.2", "clipboard": "npm:clipboard@1.5.12", "eonasdan/bootstrap-datetimepicker": "github:eonasdan/bootstrap-datetimepicker@0.0.10", "font-awesome": "github:FortAwesome/font-awesome@3.2.1", "github:jspm/nodelibs-assert@0.1.0": { "assert": "npm:assert@1.4.1" }, "github:jspm/nodelibs-buffer@0.1.0": { "buffer": "npm:buffer@3.6.0" }, "github:jspm/nodelibs-process@0.1.2": { "process": "npm:process@0.11.5" }, "github:jspm/nodelibs-util@0.1.0": { "util": "npm:util@0.10.3" }, "github:jspm/nodelibs-vm@0.1.0": { "vm-browserify": "npm:vm-browserify@0.0.4" }, "gmaps": "npm:gmaps@0.4.24", "google-code-prettify": "github:tcollard/google-code-prettify@1.0.4", "jquery": "npm:jquery@1.12.4", "jquery-timeago": "github:rmm5t/jquery-timeago@1.5.3", "most": "npm:most@0.2.4", "npm:assert@1.4.1": { "assert": "github:jspm/nodelibs-assert@0.1.0", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2", "util": "npm:util@0.10.3" }, "npm:buffer@3.6.0": { "base64-js": "npm:base64-js@0.0.8", "child_process": "github:jspm/nodelibs-child_process@0.1.0", "fs": "github:jspm/nodelibs-fs@0.1.2", "ieee754": "npm:ieee754@1.1.6", "isarray": "npm:isarray@1.0.0", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:clipboard@1.5.12": { "good-listener": "npm:good-listener@1.1.7", "select": "npm:select@1.0.6", "tiny-emitter": "npm:tiny-emitter@1.1.0" }, "npm:closest@0.0.1": { "matches-selector": "npm:matches-selector@0.0.1" }, "npm:delegate@3.0.1": { "closest": "npm:closest@0.0.1" }, "npm:good-listener@1.1.7": { "delegate": "npm:delegate@3.0.1" }, "npm:inherits@2.0.1": { "util": "github:jspm/nodelibs-util@0.1.0" }, "npm:jquery@1.12.4": { "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:most@0.2.4": { "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:process@0.11.5": { "assert": "github:jspm/nodelibs-assert@0.1.0", "fs": "github:jspm/nodelibs-fs@0.1.2", "vm": "github:jspm/nodelibs-vm@0.1.0" }, "npm:util@0.10.3": { "inherits": "npm:inherits@2.0.1", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:vm-browserify@0.0.4": { "indexof": "npm:indexof@0.0.1" }, "switchery": "github:abpetkov/switchery@0.8.2", "traceur": "github:jmcriffey/bower-traceur@0.0.93", "traceur-runtime": "github:jmcriffey/bower-traceur-runtime@0.0.93" }, "paths": { "github:*": "jspm_packages/github/*", "npm:*": "jspm_packages/npm/*" }, "transpiler": "traceur" });
JavaScript
CL
32124d5783bd4f24d80b6fa99bd1d1f0024c6f72e30eda5f6b2e72c28d50df75
const app = require("express")(); const bodyParser = require("body-parser"); const multer = require("multer"); const server = require("http").Server(app); const io = require("socket.io")(server); const fs = require("fs"); const path = require("path"); const yargs = require("yargs") .option("pluginsDestDir", { default: "./.plugins/" }) .option("loadPluginsDir", { default: null }) .option("deploymentFilesDest", { default: "/tmp/" }) .option("port", { alias: "p", default: 8000 }).argv; const chalk = require("chalk"); const { exec, spawn } = require("child_process"); const yaml = require("js-yaml"); const EventEmitter = require("events"); const neo4j = require("neo4j-driver").v1; const Kafka = require("node-rdkafka"); const template = require("swig"); const guid = require("uuid/v4"); template.setDefaults({ cache: false }); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); const networkConfig = { kafka: { host: process.env.KAFKA_HOST || "0.0.0.0" }, neo4j: { host: process.env.NEO4J_HOST || "0.0.0.0" }, mongodb: { host: process.env.MONGO_HOST || "0.0.0.0" }, vault: { host: process.env.VAULT_HOSt || "0.0.0.0" }, kube: { host: process.env.KUBERNETES_HOST || "0.0.0.0" }, registry: { host: process.env.REGISTRY_HOST || "0.0.0.0" } }; const defaultPorts = { kafka: "9092", neo4j: "7687", mongodb: "27017", registry: "5000" }; app.post("/config/:app", (req, res) => { const { body, params } = req; const { app } = params; networkConfig[app] = body; res.send("Configuration received"); console.log( chalk.yellow(`Network config updated for '${app}': ${JSON.stringify(body)}`) ); }); const pluginsDestPath = path.resolve(yargs.pluginsDestDir); const KUBECTL_BIN = process.env.KUBECTL_BIN || "kubectl"; function createPluginsDir(cb) { fs.mkdir(pluginsDestPath, 0o755, function(err) { if (err) { if (err.code == "EEXIST") { console.log(chalk.green("Plugins folder already created")); cb(null); } // ignore the error if the folder already exists else { cb(err); console.error( chalk.red( "Impossible to create plugins dir", chalk.red(err.toString()) ) ); } // something else went wrong } else { console.log(chalk.green("Plugins folder created at " + pluginsDestPath)); cb(null); } // successfully created folder }); } const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, pluginsDestPath); }, filename: function(req, file, cb) { if (req.body.pluginName) cb(null, req.body.pluginName); else cb(new Error("Wrong pluginName field")); } }); const upload = multer({ storage }); function isValidPluginName(pluginName) { return pluginName.split("").reduce((red, c) => { if (red === true) return /^[A-Z]|[a-z]|\-|\.$/.test(pluginName); else return red; }, true); } const pluginList = { list: {}, addPlugin(pluginName, commands) { this.list = { ...this.list, [pluginName]: { commands } }; this.emitter.emit("new plugin", { plugins: this.list }); }, getCommands() { return Object.keys(this.list).reduce( (red, pluginName) => [...red, ...this.list[pluginName].commands], [] ); }, emitter: new EventEmitter() }; function loadPlugin(pluginPath, pluginName) { return new Promise((resolve, reject) => { const configPath = path.join(pluginPath, "features", "cli", "config.yml"); try { const pluginConfig = yaml.safeLoad( fs.readFileSync(`${configPath}`, "utf8") ); pluginList.addPlugin( pluginName, pluginConfig.map(c => ({ ...c, ["kubernetes-file"]: path.join( pluginPath, "features", "deployments", c["kubernetes-file"] ) })) ); console.log(chalk.cyan(`Loaded plugin ${pluginName}`)); resolve(); } catch (e) { console.log( chalk.red("Impossible to read CLI config: "), chalk.red(e.toString()) ); reject("Impossible to load CLI config at " + configPath); } }); } if (yargs.loadPluginsDir != null) { const resolvedPath = path.resolve(process.cwd(), yargs.loadPluginsDir); fs.readdir(resolvedPath, (err, files) => { if (err) { console.log( "Impossible to read default plugins directory:\n", chalk.red(err.toString()) ); } else { files.forEach(file => { const dirPath = path.join(resolvedPath, file); fs.stat(dirPath, (err, stats) => { if (err) { console.log( `Impossible to read plugin directory ${dirPath}:\n`, chalk.red(err.toString()) ); } else { if (stats.isDirectory()) { loadPlugin(dirPath, file).then(() => {}, () => {}); } else { console.log(chalk.red(`Path ${dirPath} is not a directory`)); } } }); }); } }); } app.post("/plugins/load", upload.single("plugin"), (req, res) => { const pluginName = req.body.pluginName; const pluginPath = req.file.path; const unzippedPluginPath = path.join( pluginsDestPath, pluginName.replace(/\.[^/.]+$/, "") ); if (isValidPluginName(pluginName)) { exec( `rm -rf ${unzippedPluginPath} && unzip ${pluginPath} -d ${unzippedPluginPath}`, (err, stdout, stderr) => { if (err) { console.log( chalk.red(`Failed to unzip ${pluginPath} at ${unzippedPluginPath}`) ); console.log(chalk.red(err.toString())); res.status(500); res.end(); } else { console.log( chalk.cyan(`Unzipped ${pluginName} at ${unzippedPluginPath}`) ); loadPlugin(unzippedPluginPath, pluginName).then( () => { res.send("Ok"); }, err => { res.status(500); res.send(err); } ); } } ); } else { res.status(500); res.write("Invalid plugin name => " + pluginName); res.end(); } }); app.get("/visu", (req, res) => { const driver = neo4j.driver( `bolt://${networkConfig.neo4j.host}:${defaultPorts.neo4j}`, neo4j.auth.basic("neo4j", "neo4j") ); const session = driver.session(); session.run("MATCH (a)-[r]-(b) RETURN *").then(result => { session.close(); driver.close(); res.send(result.records); }); }); function createSocketCLIUpdater(socket) { return function updater() { socket.emit("cli-config", { commands: pluginList.getCommands() }); }; } function getDeploymentFileFromCommand(command) { return new Promise((resolve, reject) => { const foundCommand = pluginList .getCommands() .find(c => c.configuration === command); if (foundCommand) resolve(foundCommand["kubernetes-file"]); else reject("Deployment file not found"); }); } function compileTemplate(filePath, args) { return new Promise((resolve, reject) => { const deploymentFile = filePath; console.log(chalk.cyan(`Compiling file template ${deploymentFile}`)); const renderedContent = template.renderFile(deploymentFile, { ...args, mongodb_host: networkConfig.mongodb.host, mongodb_port: defaultPorts.mongodb, neo4j_host: networkConfig.neo4j.host, neo4j_port: defaultPorts.neo4j, kafka_host: networkConfig.kafka.host, kafka_port: defaultPorts.kafka, registry_host: networkConfig.registry.host, registry_port: defaultPorts.registry, uuid: guid() }); console.log(renderedContent); const renderedFileName = `compiled-template-${guid()}`; const renderedFilePath = path.join( yargs.deploymentFilesDest, renderedFileName ); console.log(chalk.cyan(`Writing rendered file to ${renderedFilePath}`)); const renderedFile = fs.writeFile( renderedFilePath, renderedContent, err => { if (err) { console.log( chalk.red( `Impossible to write file ${renderedFilePath}: ${err.toString()}` ) ); reject(err.toString()); } else { console.log(chalk.green(`Deployment file ready !`)); resolve(renderedFilePath); } } ); }); } function deployOnKubernetes(deploymentFilePath, socket) { return new Promise((resolve, reject) => { const command = `${KUBECTL_BIN} create -f ${deploymentFilePath}`; console.log(chalk.cyan(`Executing: ${chalk.yellow(command)} ...`)); const kubectl = spawn(KUBECTL_BIN, ["create", "-f", deploymentFilePath]); kubectl.stdout.on("data", data => { socket.emit("log", { topic: "Kubectl", time: new Date(), stream: "stdout", message: data, source: "Kubectl" }); console.log(`${chalk.cyan("[*]")} ${chalk.yellow(data)}`); }); kubectl.stderr.on("data", data => { socket.emit("log", { topic: "Kubectl", time: new Date(), stream: "stderr", message: data, source: "Kubectl" }); console.log(`${chalk.cyan("[*]")} ${chalk.yellow(data)}`); }); kubectl.on("error", err => { socket.emit("log", { topic: "Kubectl", time: new Date(), stream: "stderr", message: err, source: "Kubectl" }); console.log(chalk.red(err)); reject(err); }); kubectl.on("exit", code => { socket.emit("log", { topic: "Kubectl", time: new Date(), stream: "stdout", message: `Kubectl has exited with code: ${code}`, source: "Kubectl" }); if (code === 0) { console.log(chalk.green("Kubectl finished.")); resolve(); } else { console.log(chalk.red("Kubectl couldn't create.")); reject("Kubectl has failed to run correctly"); } }); }); } function runCommand(command, args, socket) { return getDeploymentFileFromCommand(command) .then(filePath => compileTemplate(filePath, args)) .then(deploymentFilePath => deployOnKubernetes(deploymentFilePath, socket)); } createPluginsDir(err => { if (err == null) { server.listen(yargs.port); console.log(chalk.green(`Listening on port ${yargs.port}...`)); io.on("connection", function(socket) { console.log( chalk.cyan(`Connected to client at ${socket.conn.remoteAddress}`) ); const updateCLI = createSocketCLIUpdater(socket); updateCLI(); const kafkaConsumer = new Kafka.KafkaConsumer({ "group.id": socket.id, "metadata.broker.list": `${networkConfig.kafka.host}:${ defaultPorts.kafka }` }); kafkaConsumer.on("event.error", err => { console.log( chalk.red( `Error in Kafka connection for socket id: ${socket.id} (${ err.stack })` ) ); socket.emit("log", { topic: "Kafka", time: new Date(), stream: "stderr", message: `Cannot connect to Kafka to collect logs (${err.stack})`, source: "Satellite" }); }); kafkaConsumer.connect(); kafkaConsumer.on("ready", () => { kafkaConsumer.subscribe(["kube-logs", "log"]); kafkaConsumer.consume(); console.log( chalk.cyan(`Connected to Kafka for socket id: ${socket.id}`) ); socket.emit("log", { topic: "Kafka", time: new Date(), stream: "stdout", message: "Connected to Kafka via the satellite master", source: "Satellite" }); }); kafkaConsumer.on("data", data => { const value = JSON.parse(data.value.toString()); if (data.topic === "log" && value.source.includes("/var/log/juju/")) { socket.emit("log", { topic: data.topic, time: value["@timestamp"], stream: "stdout", message: value.message, source: value.source.replace("/var/log/juju/", "") }); } else if (data.topic === "kube-logs") { const msg = JSON.parse(value.message); socket.emit("log", { topic: data.topic, time: msg.time, stream: msg.stream, message: msg.log.replace(/\n/g, ""), source: value.source.match(/\/var\/log\/containers\/([^_]*)_/)[1] }); } }); pluginList.emitter.on("new plugin", updateCLI); socket.on("command", function(data) { console.log( chalk.cyan( `Received command "${chalk.yellow( data.type )}" with args ${JSON.stringify(data.args)}` ) ); runCommand(data.type, data.args, socket) .then(() => socket.emit("log", { topic: "Master", time: new Date(), stream: "stdout", message: "Command launched", source: "Satellite" }) ) .catch(err => { console.log(chalk.red(err.toString())); return socket.emit("log", { topic: "Master", time: new Date(), stream: "stderr", message: `Impossible to the run command: ${err.toString()}`, source: "Satellite" }); }); }); const driver = neo4j.driver( `bolt://${networkConfig.neo4j.host}:${defaultPorts.neo4j.port}`, neo4j.auth.basic("neo4j", "test") ); socket.on("meta-profile-create", ({ name }) => { const session = driver.session(); session .run( "MERGE (mp:MetaProfil { name: $name }) ON CREATE SET mp.name = $name RETURN mp", { name } ) .then(() => { socket.emit("log", { time: new Date(), message: "Meta profile successfully created", source: "Satellite" }); session.close(); }) .catch(err => { socket.emit("log", { time: new Date(), stream: "stderr", message: `Impossible to create meta profile: ${err.toString()}`, source: "Satellite" }); session.close(); }); }); socket.on("meta-profile-search", ({ name }) => { const session = driver.session(); session .run( `MATCH (mp:MetaProfil) WHERE mp.name CONTAINS $name RETURN mp.name`, { name } ) .then(result => { socket.emit("log", { time: new Date(), message: `Results: ${result.records .map(node => `- ${node.get("mp.name")}`) .join("\n")} `, source: "Satellite" }); session.close(); }) .catch(err => { socket.emit("log", { time: new Date(), stream: "stderr", message: `Impossible to search meta profile: ${err.toString()}`, source: "Satellite" }); session.close(); }); }); socket.on("meta-profile-link", ({ name, accountType, targetString }) => { const session = driver.session(); session .run( `MATCH (mp:MetaProfil { name: $name }) MATCH (target) WHERE $accountType IN labels(target) AND ANY (property in keys(target) WHERE target[property] = $targetString) MERGE (mp)-[r:HAS_ACCOUNT]->(target) RETURN mp`, { name, accountType, targetString } ) .then(() => { socket.emit("log", { time: new Date(), message: "Meta profile successfully linked", source: "Satellite" }); session.close(); }) .catch(err => { socket.emit("log", { time: new Date(), stream: "stderr", message: `Impossible to link meta profile: ${err.toString()}`, source: "Satellite" }); session.close(); }); }); socket.on("meta-profile-remove", ({ name }) => { const session = driver.session(); session .run("MATCH (mp:MetaProfil { name: $name }) DETACH DELETE mp", { name }) .then(() => { socket.emit("log", { time: new Date(), message: "Meta profile successfully removed", source: "Satellite" }); session.close(); }) .catch(err => { socket.emit("log", { time: new Date(), stream: "stderr", message: `Impossible to remove meta profile: ${err.toString()}`, source: "Satellite" }); session.close(); }); }); socket.on("kubectl", ({ args }) => { const kubectl = spawn(KUBECTL_BIN, args.args); kubectl.stdout.on("data", data => socket.emit("log", { topic: "Master", time: new Date(), stream: "stdout", message: data, source: "Kubectl" }) ); kubectl.stderr.on("data", data => socket.emit("log", { topic: "Master", time: new Date(), stream: "stderr", message: data, source: "Kubectl" }) ); kubectl.on("error", error => socket.emit("log", { topic: "Master", time: new Date(), stream: "stdout", message: `Kubectl error: ${error}`, source: "Kubectl" }) ); return kubectl.on("exit", code => socket.emit("log", { topic: "Master", time: new Date(), stream: "stdout", message: `Kubectl exit with code: ${code}`, source: "Kubectl" }) ); }); socket.on("disconnect", function() { pluginList.emitter.removeListener("new plugin", updateCLI); console.log( chalk.yellow( `Disconnected from client at ${socket.conn.remoteAddress}` ) ); io.emit("user disconnected"); kafkaConsumer.disconnect(); driver.close(); }); }); } });
JavaScript
CL
ffefac17e46fded27c9f7d0a18062bfb848ef28a2e9584d821beca50eb0bdb14
const express = require('express'); const path = require('path'); const session = require('express-session'); const bodyParser = require('body-parser'); const {DATABASE_URL, PORT} = require('./config/config'); const app = express(); // connection to database const mongoose = require('mongoose'); const mongoDB = 'mongodb://username:password@ds155097.mlab.com:55097/readerslog-db'; mongoose.connect(mongoDB, { useNewUrlParser: true }); mongoose.Promise = global.Promise; const db = mongoose.connection; db.on('error', console.error.bind(console, 'MongoDB connection error')); //load routes const books = require('./routes/books'); //middleware for the bodyparser app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) app.use(express.json()); //static folder app.use(express.static(path.join(__dirname, 'public'))); // main page load app.get('/', (req, res) => { res.sendFile(__dirname + "/views/books/about.html"); console.log('rendered page successfully'); }); // use the routes set up in 'routes' folder app.use('/books', books); app.use('*', function (req, res) { res.status(404).json({ message: 'Not Found' }); }); let server; // starts the server function runServer(databaseUrl = DATABASE_URL, port = PORT) { return new Promise((resolve, reject) => { mongoose.connect(databaseUrl, err => { if(err) { return reject(err); } server = app.listen(port, () => { console.log(`server running on port ${port}`); resolve(); }) .on("error", err => { mongoose.disconnect(); reject(err); }); }); }); } // closes the server function closeServer() { return mongoose.disconnect().then(() => { return new Promise((resolve, reject) => { console.log("closing server"); server.close(err => { if (err) { return reject(err); } resolve(); }); }); }); } if (require.main === module) { runServer(DATABASE_URL).catch(err => console.error(err)); }; module.exports = { runServer, app, closeServer };
JavaScript
CL
3aace0ff981d58b51350763a5632a9e526b4817c7c09b0ea0195c4fdba9294d5
import _ from 'lodash'; import React, { Component } from 'react'; import { reduxForm, Field } from 'redux-form'; import { Link } from 'react-router-dom'; import Card, { CardContent } from 'material-ui/Card'; import Button from 'material-ui/Button'; import Typography from 'material-ui/Typography'; import responseFormFields from './responseFormFields'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import Table, { TableBody, TableCell, TableHead, TableRow } from 'material-ui/Table'; import Paper from 'material-ui/Paper'; import Radio from 'material-ui/Radio'; import green from 'material-ui/colors/green'; import { Checkbox, RadioGroup } from 'redux-form-material-ui'; const styles = theme => ({ root: { width: '100%', marginTop: theme.spacing.unit * 3, overflowX: 'auto', color: green[600], '&$checked': { color: green[500] } }, card: { minWidth: 275 }, title: { marginBottom: 16, fontSize: 14 }, pos: { marginBottom: 12 }, table: { minWidth: 700 }, tableCell: { textAlign: 'center' }, checked: {}, size: { width: 40, height: 40 }, sizeIcon: { fontSize: 20 }, button: { margin: theme.spacing.unit } }); class ResponseForm extends Component { handleChange = event => { this.setState({ selectedValue: event.target.value }); }; renderFields() { return _.map(responseFormFields, ({ label, minValue, maxValue }) => { return ( <TableRow key={label}> <TableCell>{label}</TableCell> <TableCell> <Field name={label} component={RadioGroup}> <Radio name={label} value="0" label="0" /> </Field> </TableCell> <TableCell> <Field name={label} component={RadioGroup}> <Radio value="1" label="1" /> </Field> </TableCell> <TableCell> <Field name={label} component={RadioGroup}> <Radio value="2" label="2" /> </Field> </TableCell> <TableCell> <Field name={label} component={RadioGroup}> <Radio value="3" label="3" /> </Field> </TableCell> <TableCell> <Field name={label} component={RadioGroup}> <Radio value="4" label="4" /> </Field> </TableCell> <TableCell> <Field name={label} component={RadioGroup}> <Radio value="5" label="5" /> </Field> </TableCell> <TableCell> <span>|</span>{' '} </TableCell> <TableCell> <Field name={'IMP,' + label} component={Checkbox} /> </TableCell> </TableRow> ); }); } renderHeadings(headingArray) { return headingArray.map((item, i) => { return ( <TableCell key={`${i}-${item}`} className={this.props.classes.tableCell} > {item} </TableCell> ); }); } renderDate() { return new Date().toLocaleDateString(); } render() { return ( <div style={{ marginTop: '2%' }}> <Card className={this.props.classes.card}> <CardContent> <Typography className={this.props.classes.title} color="textSecondary" > {this.renderDate()} </Typography> <Typography variant="headline" component="h2"> SINO-NASAL OUTCOME TEST (SNOT-22) </Typography> <Typography color="textSecondary" variant="caption"> SNOT-20 Copyright &copy; 1996 by Jay F. Piccirillo, M.D., Washington University School of Medicine, St. Louis, Missouri. </Typography> <Typography className={this.props.classes.pos} color="textSecondary" variant="caption" > SNOT-22 Developed from modification of SNOT-20 by National Comparative Audit of Surgery for Nasal Polyposis and Rhinosinusitis Royal College of Surgeons of England. </Typography> <Typography component="p"> Below you will find a list of symptoms and social/emotional consequences of your rhinosinusitis. We would like to know more about these problems and would appreciate your answering the following questions to the best of your ability. There are no right or wrong answers, and only you can provide us with this information. Please rate your problems as they have been over the past two weeks. Thank you for your participation. Do not hesitate to ask for assistance if necessary. </Typography> </CardContent> </Card> <form onSubmit={this.props.handleSubmit(this.props.onResponseSubmit)}> <Paper className={this.props.classes.root}> <Table className={this.props.classes.table}> <TableHead> <TableRow> <TableCell>Problem</TableCell> {this.renderHeadings([ 'No Problem', 'Very Mild Problem', 'Very Mild Problem', 'Moderate Problem', 'Severe Problem', 'Problem as bad as it can be', '|', '5 Most Important Items' ])} </TableRow> </TableHead> <TableBody>{this.renderFields()}</TableBody> </Table> </Paper> <div style={{ textAlign: 'center' }}> <Button type="submit" variant="raised" color="secondary" component={Link} to="/dashboard" className={this.props.classes.button} > Cancel </Button> <Button type="submit" variant="raised" color="primary" className={this.props.classes.button} > Submit Response </Button> </div> </form> </div> ); } } ResponseForm.propTypes = { classes: PropTypes.object.isRequired }; function validate(values) { const errors = {}; _.each(responseFormFields, ({ label }) => { if (!values[label]) { errors[label] = `Missing response for - ${label}`; } }); return errors; } export default reduxForm({ validate, form: 'responseForm' })(withStyles(styles)(ResponseForm));
JavaScript
CL
ae6d02f6e325783aa7f116381a9b933f63348620b1d2a9c67ab81e63aaa1ed5d
define(function (require, exports, module) { /************************************************ 字符串工具 *********************************************************/ /** * 数字格式化 每三位一个逗号 * @num 数字 * @poNum 小数点位数 */ function numFmtCmapo(num, point) { point = (point == null || point === "" || typeof(point) === "undefined") ? 0 : point; return (num.toFixed(point) + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,'); } /** * 数字累加效果 * @param node 容器 * @param num 目标数字 * @param deci 小数点位数 * @constructor * 依赖countUp.js */ function NumAnimate(node, num, text, deci) { this.node = node; this.num = num; this.text = text; this.deci = deci; } NumAnimate.prototype = { constructor: NumAnimate, init: function () { if (this.deci == undefined) { this.deci = 0; } var options = { useEasing: true, useGrouping: true, separator: ',', decimal: '.', }; new (require("countUp"))(this.node, 0, this.num, this.text, this.deci, 2.6, options).start(); } }; /** * UUID * @param len UUID长度 */ var UUID = function (len) { return new UUID.prototype.init(len); }; UUID.prototype = { constructor: UUID, /** * 字符 */ chars: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''), /** * 初始化 */ init: function (len) { this.len = len || 32; this.uuid = []; }, /** * 生成UUID */ getUUID: function () { var _self = this; for (var i = 0; i < _self.len; i++) _self.uuid.push(_self.chars[0 | parseInt(Math.random() * 32)]); return _self.uuid.join(""); } }; UUID.prototype.init.prototype = UUID.prototype; /** * 数字 转 中文 */ var Number_Cover = function (number) { return new Number_Cover.prototype.init(number); }; Number_Cover.prototype = { constructor: Number_Cover, /** * 相关参数 */ ary0: ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"], ary1: ["", "十", "百", "千"], ary2: ["", "万", "亿", "兆"], /** * 初始化 */ init: function (number) { this.number = (((number + "").split("")).reverse()).join(""); }, /** * 转换 */ cover_through: function () { var _self = this; if (isNaN(Number(_self.number))) { console.error(_self.number + "不是一个数字"); return; } var zero = "" var newary = "" var i4 = -1 for (var i = 0; i < _self.number.length; i++) { if (i % 4 == 0) { //首先判断万级单位,每隔四个字符就让万级单位数组索引号递增 i4++; newary = _self.ary2[i4] + newary; //将万级单位存入该字符的读法中去,它肯定是放在当前字符读法的末尾,所以首先将它叠加入$r中, zero = ""; //在万级单位位置的“0”肯定是不用的读的,所以设置零的读法为空 } //关于0的处理与判断。 if (_self.number[i] == '0') { //如果读出的字符是“0”,执行如下判断这个“0”是否读作“零” switch (i % 4) { case 0: break; //如果位置索引能被4整除,表示它所处位置是万级单位位置,这个位置的0的读法在前面就已经设置好了,所以这里直接跳过 case 1: case 2: case 3: if (_self.number[i - 1] != '0') { zero = "零" } ; //如果不被4整除,那么都执行这段判断代码:如果它的下一位数字(针对当前字符串来说是上一个字符,因为之前执行了反转)也是0,那么跳过,否则读作“零” break; } newary = zero + newary; zero = ''; } else { //如果不是“0” newary = _self.ary0[parseInt(_self.number[i])] + _self.ary1[i % 4] + newary; //就将该当字符转换成数值型,并作为数组ary0的索引号,以得到与之对应的中文读法,其后再跟上它的的一级单位(空、十、百还是千)最后再加上前面已存入的读法内容。 } } if (newary.indexOf("零") == 0) { newary = newary.substr(1) }//处理前面的0 return newary; } }; Number_Cover.prototype.init.prototype = Number_Cover.prototype; /** * 随机数生成 * @param scope 范围 * @param point 小数点位数 * @return {*} * @constructor */ var Random = function (scope, point) { if (isNaN(Number(scope))) { return 0; } return Number((Math.random() * Number(scope)).toFixed((point || 0))); } module.exports = { numFmtCmapo: numFmtCmapo, NumAnimate: NumAnimate, UUID: UUID, Number_Cover: Number_Cover, Random: Random } });
JavaScript
CL
f6a1b8207b1a39c1752af8c99fac55671e16699d9a9475239244b035699dc29f
/******************************************************************************* * * Copyright (c) 2011, 2016 OpenWorm. * http://openworm.org * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT * * Contributors: * OpenWorm - http://openworm.org/people.html * * 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. *******************************************************************************/ define(function (require) { var link = document.createElement("link"); link.type = "text/css"; link.rel = "stylesheet"; link.href = "geppetto/js/components/dev/form/Form.css"; document.getElementsByTagName("head")[0].appendChild(link); var React = require('react'); var reactJsonSchemaForm = require('./react-jsonschema-form'); var Form = reactJsonSchemaForm.default; var uiSchema ={}; var formComponent = React.createClass({ render: function(){ return ( <Form id={this.props.id} className="geppettoForm" schema={this.props.schema} formData={this.props.formData} uiSchema={uiSchema} onChange={this.props.changeHandler} onSubmit={this.props.submitHandler} onError={this.props.errorHandler} /> ); } }); return formComponent; });
JavaScript
CL
0435027eee71117e8c6e5ca53795ae11e4936900f02f98a091a3cab9f49557a9
#! /usr/bin/env node /** * Mastodon statistics bot * Copyright (c) 2019 Maxime Launois * * 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. */ // This is the cron job that runs every minute. // It should reply to every mention to @mastostats that includes a command // Load Mastostats let bot = require(__dirname + '/../bot.js'); let mentionCount = {}; // Fetch mentions bot.mastodon.mentions().then((result) => { for (let mention of result) { if (mention) { let ignore = false; // Did we already process this mention? for (let processed of bot.data.processedMentions) { if (processed == mention.id) { ignore = true; break; // already processed! } } if (mention.account.bot) { // No processing from bots! Prevent result scraping // This block is definitive and cannot be reverted. bot.mastodon.block(mention.account.id); continue; } else if (!mention.status || ignore) { // Mention to ignore or with no status continue; } // Log that an user mentioned @mastostats let commands = bot.mastodon.sanitizeMention(mention.status.content); mentionCount[mention.account.acct] = (mentionCount[mention.account.acct] || 0) + commands.length; if (mentionCount[mention.account.acct] > 5) { // 5 requests within one minute: probably an attempt to flood the server // Block temporary, lasts three hours and is removed by bot/cron/3hours.js // Note: only (at most) the first four requests are answered bot.mastodon.block(mention.account.id); bot.data.blockedAccounts.push(mention.account.id); bot.data.commit(); console.log(`Blocking account ${mention.account.id}...`); continue; } // Process each command in the list for (let cmd of commands) { console.log(`Processing mention ${mention.id}...`); bot.mastodon.processCommand(cmd, mention.account, mention.status); } } } }).catch((err) => { // A fatal error occurred; log to stderr console.error(err); });
JavaScript
CL
10391aeb427f6888054dd14ad6ecf5e97e63a6654ea36666b4c45d46c683139a
import { Link } from 'react-router-dom'; import { useHistory } from 'react-router'; import { useForm } from 'react-hook-form'; import { authFetchApi } from '../../../../util/fetchApi'; import { useAuth } from '../../../../contexts/AuthContext'; import { useNotification } from '../../../../contexts/NotificationContext'; import { Form, FormGroup, FieldLabel, TextInput, ErrorMessage, } from '../../../Form'; import { Image } from '../EPPStyles'; import Button from '../../../Button'; const EditProfileForm = ({ user }) => { const { addError, addSuccess } = useNotification(); const auth = useAuth(); const history = useHistory(); const { register, handleSubmit, formState: { errors }, } = useForm({ defaultValues: { avatar: user.avatar, name: user.name, location: user.location ?? '', facebook: user.social?.facebook ?? '', instagram: user.social?.instagram ?? '', }, }); const submit = async data => { const newData = { ...data, avatar: data.avatar ?? 'https://shop247-backend.herokuapp.com/defaultprofile.webp', }; try { await authFetchApi( `/users/${auth.user.uid}`, { method: 'PATCH', body: JSON.stringify(newData), }, auth.user ); addSuccess('Profile Updated'); history.push('/profile'); } catch (err) { addError('An Error Occurred'); history.push('/profile'); } }; return ( <Form onSubmit={handleSubmit(submit)}> <h3> Change Account Details </h3> <Image src={user.avatar} alt='profilepic' /> <FormGroup> <FieldLabel htmlFor='avatar'>Profile Picture URL:</FieldLabel> <TextInput type='text' id='avatar' {...register('avatar')} /> </FormGroup> <FormGroup> <FieldLabel htmlFor='name'>User Name:</FieldLabel> <TextInput type='text' id='name' {...register('name', { required: 'Username is required' })} /> <ErrorMessage>{errors.name?.message}</ErrorMessage> </FormGroup> <FormGroup> <FieldLabel>Location:</FieldLabel> <TextInput type='text' id='location' {...register('location')} /> </FormGroup> <FormGroup> <FieldLabel htmlFor='socials'>Social Links:</FieldLabel> <br /> <FormGroup> <FieldLabel htmlFor='facebook'>Facebook:</FieldLabel> <TextInput type='text' id='facebook' {...register('facebook')} /> </FormGroup> <br /> <FormGroup> <FieldLabel htmlFor='instagram'>Instagram:</FieldLabel> <TextInput type='text' id='instagram' {...register('instagram')} /> </FormGroup> </FormGroup> <Button type='submit' solid> Submit </Button> <Button> <Link to={`/profile`}>Back</Link> </Button> </Form> ); }; export default EditProfileForm;
JavaScript
CL
cddbc0ab9a471a71d45800889dffa2a1a34c6ecc541605ea83966d711085eb30
/** * @notes - This class is a builder - It help us to return a format of pagination meta data { currentPage, currentSize, totalPage, totalRecord } - We need to add content when we construct by of() method */ export class PageableMeta { currentPage; currentSize; totalPage; totalRecord; static builder() { return new PageableMeta(); } /** * @notes This method will automatically collect page and size from requestFormation * @param {import('../requestFormation').RequestFormation} query * @returns {PageableMeta} */ appendRequestFormation(query) { const queryContent = query.translate(); this.currentPage = queryContent.pagination.page; this.currentSize = queryContent.pagination.size; return this; } /** * @notes Apply total record which helping to navigate to the final page * @param {number} total * @returns {PageableMeta} */ appendTotalRecord(total) { this.totalRecord = total; return this; } /** * @notes We finalize builder by build method * @returns {{totalPage: number, currentPage, totalRecord, currentSize}} */ build() { return { currentPage: this.currentPage, currentSize: this.currentSize, totalPage: Math.floor(this.totalRecord / this.currentSize) + 1, totalRecord: this.totalRecord }; } }
JavaScript
CL
1c0a484efd581ceeebec8a7f2b3f841fcf1e460dc7798cd0ff54616d1ff6d0cd
'use strict' const Analyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin const MemoryFS = require('memory-fs') const gzipSize = require('gzip-size') const webpack = require('webpack') const Babili = require('babili-webpack-plugin') const path = require('path') function promisify (callback) { return new Promise((resolve, reject) => { callback((err, result) => { if (err) { reject(err) } else { resolve(result) } }) }) } function getConfig (files, opts) { const config = { entry: files, output: { filename: 'bundle.js' }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }) ] } if (opts.minifier === 'babili') { config.plugins.push(new Babili()) } else { config.plugins.push(new webpack.optimize.UglifyJsPlugin({ sourceMap: false, mangle: { screw_ie8: true }, compress: { screw_ie8: true }, compressor: { warnings: false }, output: { comments: false } })) } if (opts.analyzer) { config.plugins.push(new Analyzer({ openAnalyzer: opts.analyzer === 'server', analyzerMode: opts.analyzer, defaultSizes: 'gzip' })) } return config } function runWebpack (config) { return promisify(done => { const compiler = webpack(config) compiler.outputFileSystem = new MemoryFS() compiler.run(done) }) } /** * Return size of project files with all dependencies and after UglifyJS * and gzip. * * @param {string|string[]} files Files to get size. * @param {object} [opts] Extra options. * @param {"server"|"static"|false} [opts.analyzer] Show package content * in browser. * @param {"uglifyjs"|"babili"} [opts.minifier="uglifyjs"] Minifier. * * @return {Promise} Promise with size of files * * @example * const getSize = require('size-limit') * * const index = path.join(__dirname, 'index.js') * const extra = path.join(__dirname, 'extra.js') * * getSize([index, extra]).then(size => { * if (size > 1 * 1024 * 1024) { * console.error('Project become bigger than 1MB') * } * }) */ function getSize (files, opts) { if (typeof files === 'string') files = [files] if (!opts) opts = { } return runWebpack(getConfig(files, opts)).then(stats => { if (stats.hasErrors()) { throw new Error(stats.toString('errors-only')) } const out = stats.compilation.outputOptions const file = path.join(out.path, out.filename) const fs = stats.compilation.compiler.outputFileSystem return promisify(done => fs.readFile(file, 'utf8', done)) }).then(content => { return promisify(done => gzipSize(content, done)) }).then(size => { return size - 293 }) } module.exports = getSize
JavaScript
CL
c67a88e6b93263445cf6b009616bd54759fafc3a2086c3eefb2a7dc917e0941f
(self["webpackChunkbingo"] = self["webpackChunkbingo"] || []).push([["vendors-node_modules_core-js_modules_es_array_concat_js-node_modules_core-js_modules_es_array-c3b762"],{ /***/ "./node_modules/core-js/internals/array-method-has-species-support.js": /*!****************************************************************************!*\ !*** ./node_modules/core-js/internals/array-method-has-species-support.js ***! \****************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var fails = __webpack_require__(/*! ../internals/fails */ "./node_modules/core-js/internals/fails.js"); var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "./node_modules/core-js/internals/well-known-symbol.js"); var V8_VERSION = __webpack_require__(/*! ../internals/engine-v8-version */ "./node_modules/core-js/internals/engine-v8-version.js"); var SPECIES = wellKnownSymbol('species'); module.exports = function (METHOD_NAME) { // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/677 return V8_VERSION >= 51 || !fails(function () { var array = []; var constructor = array.constructor = {}; constructor[SPECIES] = function () { return { foo: 1 }; }; return array[METHOD_NAME](Boolean).foo !== 1; }); }; /***/ }), /***/ "./node_modules/core-js/internals/array-method-is-strict.js": /*!******************************************************************!*\ !*** ./node_modules/core-js/internals/array-method-is-strict.js ***! \******************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var fails = __webpack_require__(/*! ../internals/fails */ "./node_modules/core-js/internals/fails.js"); module.exports = function (METHOD_NAME, argument) { var method = [][METHOD_NAME]; return !!method && fails(function () { // eslint-disable-next-line no-useless-call,no-throw-literal -- required for testing method.call(null, argument || function () { throw 1; }, 1); }); }; /***/ }), /***/ "./node_modules/core-js/internals/create-property.js": /*!***********************************************************!*\ !*** ./node_modules/core-js/internals/create-property.js ***! \***********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var toPrimitive = __webpack_require__(/*! ../internals/to-primitive */ "./node_modules/core-js/internals/to-primitive.js"); var definePropertyModule = __webpack_require__(/*! ../internals/object-define-property */ "./node_modules/core-js/internals/object-define-property.js"); var createPropertyDescriptor = __webpack_require__(/*! ../internals/create-property-descriptor */ "./node_modules/core-js/internals/create-property-descriptor.js"); module.exports = function (object, key, value) { var propertyKey = toPrimitive(key); if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value)); else object[propertyKey] = value; }; /***/ }), /***/ "./node_modules/core-js/internals/get-substitution.js": /*!************************************************************!*\ !*** ./node_modules/core-js/internals/get-substitution.js ***! \************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var toObject = __webpack_require__(/*! ../internals/to-object */ "./node_modules/core-js/internals/to-object.js"); var floor = Math.floor; var replace = ''.replace; var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d{1,2}|<[^>]*>)/g; var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d{1,2})/g; // https://tc39.es/ecma262/#sec-getsubstitution module.exports = function (matched, str, position, captures, namedCaptures, replacement) { var tailPos = position + matched.length; var m = captures.length; var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED; if (namedCaptures !== undefined) { namedCaptures = toObject(namedCaptures); symbols = SUBSTITUTION_SYMBOLS; } return replace.call(replacement, symbols, function (match, ch) { var capture; switch (ch.charAt(0)) { case '$': return '$'; case '&': return matched; case '`': return str.slice(0, position); case "'": return str.slice(tailPos); case '<': capture = namedCaptures[ch.slice(1, -1)]; break; default: // \d\d? var n = +ch; if (n === 0) return match; if (n > m) { var f = floor(n / 10); if (f === 0) return match; if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1); return match; } capture = captures[n - 1]; } return capture === undefined ? '' : capture; }); }; /***/ }), /***/ "./node_modules/core-js/modules/es.array.concat.js": /*!*********************************************************!*\ !*** ./node_modules/core-js/modules/es.array.concat.js ***! \*********************************************************/ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(/*! ../internals/export */ "./node_modules/core-js/internals/export.js"); var fails = __webpack_require__(/*! ../internals/fails */ "./node_modules/core-js/internals/fails.js"); var isArray = __webpack_require__(/*! ../internals/is-array */ "./node_modules/core-js/internals/is-array.js"); var isObject = __webpack_require__(/*! ../internals/is-object */ "./node_modules/core-js/internals/is-object.js"); var toObject = __webpack_require__(/*! ../internals/to-object */ "./node_modules/core-js/internals/to-object.js"); var toLength = __webpack_require__(/*! ../internals/to-length */ "./node_modules/core-js/internals/to-length.js"); var createProperty = __webpack_require__(/*! ../internals/create-property */ "./node_modules/core-js/internals/create-property.js"); var arraySpeciesCreate = __webpack_require__(/*! ../internals/array-species-create */ "./node_modules/core-js/internals/array-species-create.js"); var arrayMethodHasSpeciesSupport = __webpack_require__(/*! ../internals/array-method-has-species-support */ "./node_modules/core-js/internals/array-method-has-species-support.js"); var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "./node_modules/core-js/internals/well-known-symbol.js"); var V8_VERSION = __webpack_require__(/*! ../internals/engine-v8-version */ "./node_modules/core-js/internals/engine-v8-version.js"); var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable'); var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/679 var IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION >= 51 || !fails(function () { var array = []; array[IS_CONCAT_SPREADABLE] = false; return array.concat()[0] !== array; }); var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat'); var isConcatSpreadable = function (O) { if (!isObject(O)) return false; var spreadable = O[IS_CONCAT_SPREADABLE]; return spreadable !== undefined ? !!spreadable : isArray(O); }; var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; // `Array.prototype.concat` method // https://tc39.es/ecma262/#sec-array.prototype.concat // with adding support of @@isConcatSpreadable and @@species $({ target: 'Array', proto: true, forced: FORCED }, { // eslint-disable-next-line no-unused-vars -- required for `.length` concat: function concat(arg) { var O = toObject(this); var A = arraySpeciesCreate(O, 0); var n = 0; var i, k, length, len, E; for (i = -1, length = arguments.length; i < length; i++) { E = i === -1 ? O : arguments[i]; if (isConcatSpreadable(E)) { len = toLength(E.length); if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]); } else { if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); createProperty(A, n++, E); } } A.length = n; return A; } }); /***/ }), /***/ "./node_modules/core-js/modules/es.array.find.js": /*!*******************************************************!*\ !*** ./node_modules/core-js/modules/es.array.find.js ***! \*******************************************************/ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(/*! ../internals/export */ "./node_modules/core-js/internals/export.js"); var $find = __webpack_require__(/*! ../internals/array-iteration */ "./node_modules/core-js/internals/array-iteration.js").find; var addToUnscopables = __webpack_require__(/*! ../internals/add-to-unscopables */ "./node_modules/core-js/internals/add-to-unscopables.js"); var FIND = 'find'; var SKIPS_HOLES = true; // Shouldn't skip holes if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; }); // `Array.prototype.find` method // https://tc39.es/ecma262/#sec-array.prototype.find $({ target: 'Array', proto: true, forced: SKIPS_HOLES }, { find: function find(callbackfn /* , that = undefined */) { return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables addToUnscopables(FIND); /***/ }), /***/ "./node_modules/core-js/modules/es.array.index-of.js": /*!***********************************************************!*\ !*** ./node_modules/core-js/modules/es.array.index-of.js ***! \***********************************************************/ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* eslint-disable es/no-array-prototype-indexof -- required for testing */ var $ = __webpack_require__(/*! ../internals/export */ "./node_modules/core-js/internals/export.js"); var $indexOf = __webpack_require__(/*! ../internals/array-includes */ "./node_modules/core-js/internals/array-includes.js").indexOf; var arrayMethodIsStrict = __webpack_require__(/*! ../internals/array-method-is-strict */ "./node_modules/core-js/internals/array-method-is-strict.js"); var nativeIndexOf = [].indexOf; var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [1].indexOf(1, -0) < 0; var STRICT_METHOD = arrayMethodIsStrict('indexOf'); // `Array.prototype.indexOf` method // https://tc39.es/ecma262/#sec-array.prototype.indexof $({ target: 'Array', proto: true, forced: NEGATIVE_ZERO || !STRICT_METHOD }, { indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { return NEGATIVE_ZERO // convert -0 to +0 ? nativeIndexOf.apply(this, arguments) || 0 : $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined); } }); /***/ }), /***/ "./node_modules/core-js/modules/es.array.join.js": /*!*******************************************************!*\ !*** ./node_modules/core-js/modules/es.array.join.js ***! \*******************************************************/ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(/*! ../internals/export */ "./node_modules/core-js/internals/export.js"); var IndexedObject = __webpack_require__(/*! ../internals/indexed-object */ "./node_modules/core-js/internals/indexed-object.js"); var toIndexedObject = __webpack_require__(/*! ../internals/to-indexed-object */ "./node_modules/core-js/internals/to-indexed-object.js"); var arrayMethodIsStrict = __webpack_require__(/*! ../internals/array-method-is-strict */ "./node_modules/core-js/internals/array-method-is-strict.js"); var nativeJoin = [].join; var ES3_STRINGS = IndexedObject != Object; var STRICT_METHOD = arrayMethodIsStrict('join', ','); // `Array.prototype.join` method // https://tc39.es/ecma262/#sec-array.prototype.join $({ target: 'Array', proto: true, forced: ES3_STRINGS || !STRICT_METHOD }, { join: function join(separator) { return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator); } }); /***/ }), /***/ "./node_modules/core-js/modules/es.array.map.js": /*!******************************************************!*\ !*** ./node_modules/core-js/modules/es.array.map.js ***! \******************************************************/ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(/*! ../internals/export */ "./node_modules/core-js/internals/export.js"); var $map = __webpack_require__(/*! ../internals/array-iteration */ "./node_modules/core-js/internals/array-iteration.js").map; var arrayMethodHasSpeciesSupport = __webpack_require__(/*! ../internals/array-method-has-species-support */ "./node_modules/core-js/internals/array-method-has-species-support.js"); var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('map'); // `Array.prototype.map` method // https://tc39.es/ecma262/#sec-array.prototype.map // with adding support of @@species $({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, { map: function map(callbackfn /* , thisArg */) { return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); /***/ }), /***/ "./node_modules/core-js/modules/es.string.replace.js": /*!***********************************************************!*\ !*** ./node_modules/core-js/modules/es.string.replace.js ***! \***********************************************************/ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var fixRegExpWellKnownSymbolLogic = __webpack_require__(/*! ../internals/fix-regexp-well-known-symbol-logic */ "./node_modules/core-js/internals/fix-regexp-well-known-symbol-logic.js"); var anObject = __webpack_require__(/*! ../internals/an-object */ "./node_modules/core-js/internals/an-object.js"); var toLength = __webpack_require__(/*! ../internals/to-length */ "./node_modules/core-js/internals/to-length.js"); var toInteger = __webpack_require__(/*! ../internals/to-integer */ "./node_modules/core-js/internals/to-integer.js"); var requireObjectCoercible = __webpack_require__(/*! ../internals/require-object-coercible */ "./node_modules/core-js/internals/require-object-coercible.js"); var advanceStringIndex = __webpack_require__(/*! ../internals/advance-string-index */ "./node_modules/core-js/internals/advance-string-index.js"); var getSubstitution = __webpack_require__(/*! ../internals/get-substitution */ "./node_modules/core-js/internals/get-substitution.js"); var regExpExec = __webpack_require__(/*! ../internals/regexp-exec-abstract */ "./node_modules/core-js/internals/regexp-exec-abstract.js"); var max = Math.max; var min = Math.min; var maybeToString = function (it) { return it === undefined ? it : String(it); }; // @@replace logic fixRegExpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative, reason) { var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = reason.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE; var REPLACE_KEEPS_$0 = reason.REPLACE_KEEPS_$0; var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0'; return [ // `String.prototype.replace` method // https://tc39.es/ecma262/#sec-string.prototype.replace function replace(searchValue, replaceValue) { var O = requireObjectCoercible(this); var replacer = searchValue == undefined ? undefined : searchValue[REPLACE]; return replacer !== undefined ? replacer.call(searchValue, O, replaceValue) : nativeReplace.call(String(O), searchValue, replaceValue); }, // `RegExp.prototype[@@replace]` method // https://tc39.es/ecma262/#sec-regexp.prototype-@@replace function (regexp, replaceValue) { if ( (!REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE && REPLACE_KEEPS_$0) || (typeof replaceValue === 'string' && replaceValue.indexOf(UNSAFE_SUBSTITUTE) === -1) ) { var res = maybeCallNative(nativeReplace, regexp, this, replaceValue); if (res.done) return res.value; } var rx = anObject(regexp); var S = String(this); var functionalReplace = typeof replaceValue === 'function'; if (!functionalReplace) replaceValue = String(replaceValue); var global = rx.global; if (global) { var fullUnicode = rx.unicode; rx.lastIndex = 0; } var results = []; while (true) { var result = regExpExec(rx, S); if (result === null) break; results.push(result); if (!global) break; var matchStr = String(result[0]); if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); } var accumulatedResult = ''; var nextSourcePosition = 0; for (var i = 0; i < results.length; i++) { result = results[i]; var matched = String(result[0]); var position = max(min(toInteger(result.index), S.length), 0); var captures = []; // NOTE: This is equivalent to // captures = result.slice(1).map(maybeToString) // but for some reason `nativeSlice.call(result, 1, result.length)` (called in // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it. for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j])); var namedCaptures = result.groups; if (functionalReplace) { var replacerArgs = [matched].concat(captures, position, S); if (namedCaptures !== undefined) replacerArgs.push(namedCaptures); var replacement = String(replaceValue.apply(undefined, replacerArgs)); } else { replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue); } if (position >= nextSourcePosition) { accumulatedResult += S.slice(nextSourcePosition, position) + replacement; nextSourcePosition = position + matched.length; } } return accumulatedResult + S.slice(nextSourcePosition); } ]; }); /***/ }) }]); //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly9iaW5nby8uL25vZGVfbW9kdWxlcy9jb3JlLWpzL2ludGVybmFscy9hcnJheS1tZXRob2QtaGFzLXNwZWNpZXMtc3VwcG9ydC5qcyIsIndlYnBhY2s6Ly9iaW5nby8uL25vZGVfbW9kdWxlcy9jb3JlLWpzL2ludGVybmFscy9hcnJheS1tZXRob2QtaXMtc3RyaWN0LmpzIiwid2VicGFjazovL2JpbmdvLy4vbm9kZV9tb2R1bGVzL2NvcmUtanMvaW50ZXJuYWxzL2NyZWF0ZS1wcm9wZXJ0eS5qcyIsIndlYnBhY2s6Ly9iaW5nby8uL25vZGVfbW9kdWxlcy9jb3JlLWpzL2ludGVybmFscy9nZXQtc3Vic3RpdHV0aW9uLmpzIiwid2VicGFjazovL2JpbmdvLy4vbm9kZV9tb2R1bGVzL2NvcmUtanMvbW9kdWxlcy9lcy5hcnJheS5jb25jYXQuanMiLCJ3ZWJwYWNrOi8vYmluZ28vLi9ub2RlX21vZHVsZXMvY29yZS1qcy9tb2R1bGVzL2VzLmFycmF5LmZpbmQuanMiLCJ3ZWJwYWNrOi8vYmluZ28vLi9ub2RlX21vZHVsZXMvY29yZS1qcy9tb2R1bGVzL2VzLmFycmF5LmluZGV4LW9mLmpzIiwid2VicGFjazovL2JpbmdvLy4vbm9kZV9tb2R1bGVzL2NvcmUtanMvbW9kdWxlcy9lcy5hcnJheS5qb2luLmpzIiwid2VicGFjazovL2JpbmdvLy4vbm9kZV9tb2R1bGVzL2NvcmUtanMvbW9kdWxlcy9lcy5hcnJheS5tYXAuanMiLCJ3ZWJwYWNrOi8vYmluZ28vLi9ub2RlX21vZHVsZXMvY29yZS1qcy9tb2R1bGVzL2VzLnN0cmluZy5yZXBsYWNlLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7O0FBQUEsWUFBWSxtQkFBTyxDQUFDLHFFQUFvQjtBQUN4QyxzQkFBc0IsbUJBQU8sQ0FBQyw2RkFBZ0M7QUFDOUQsaUJBQWlCLG1CQUFPLENBQUMsNkZBQWdDOztBQUV6RDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsY0FBYztBQUNkO0FBQ0E7QUFDQSxHQUFHO0FBQ0g7Ozs7Ozs7Ozs7OztBQ2xCYTtBQUNiLFlBQVksbUJBQU8sQ0FBQyxxRUFBb0I7O0FBRXhDO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsK0NBQStDLFNBQVMsRUFBRTtBQUMxRCxHQUFHO0FBQ0g7Ozs7Ozs7Ozs7OztBQ1RhO0FBQ2Isa0JBQWtCLG1CQUFPLENBQUMsbUZBQTJCO0FBQ3JELDJCQUEyQixtQkFBTyxDQUFDLHVHQUFxQztBQUN4RSwrQkFBK0IsbUJBQU8sQ0FBQywrR0FBeUM7O0FBRWhGO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Ozs7Ozs7Ozs7O0FDVEEsZUFBZSxtQkFBTyxDQUFDLDZFQUF3Qjs7QUFFL0M7QUFDQTtBQUNBLHlDQUF5QyxJQUFJO0FBQzdDLGtEQUFrRCxJQUFJOztBQUV0RDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEdBQUc7QUFDSDs7Ozs7Ozs7Ozs7O0FDdkNhO0FBQ2IsUUFBUSxtQkFBTyxDQUFDLHVFQUFxQjtBQUNyQyxZQUFZLG1CQUFPLENBQUMscUVBQW9CO0FBQ3hDLGNBQWMsbUJBQU8sQ0FBQywyRUFBdUI7QUFDN0MsZUFBZSxtQkFBTyxDQUFDLDZFQUF3QjtBQUMvQyxlQUFlLG1CQUFPLENBQUMsNkVBQXdCO0FBQy9DLGVBQWUsbUJBQU8sQ0FBQyw2RUFBd0I7QUFDL0MscUJBQXFCLG1CQUFPLENBQUMseUZBQThCO0FBQzNELHlCQUF5QixtQkFBTyxDQUFDLG1HQUFtQztBQUNwRSxtQ0FBbUMsbUJBQU8sQ0FBQywySEFBK0M7QUFDMUYsc0JBQXNCLG1CQUFPLENBQUMsNkZBQWdDO0FBQzlELGlCQUFpQixtQkFBTyxDQUFDLDZGQUFnQzs7QUFFekQ7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsQ0FBQzs7QUFFRDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBLEdBQUcsK0NBQStDO0FBQ2xEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLDJDQUEyQyxZQUFZO0FBQ3ZEO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsbUJBQW1CLFNBQVM7QUFDNUIsT0FBTztBQUNQO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsQ0FBQzs7Ozs7Ozs7Ozs7O0FDNURZO0FBQ2IsUUFBUSxtQkFBTyxDQUFDLHVFQUFxQjtBQUNyQyxZQUFZLG1IQUE0QztBQUN4RCx1QkFBdUIsbUJBQU8sQ0FBQywrRkFBaUM7O0FBRWhFO0FBQ0E7O0FBRUE7QUFDQSw0Q0FBNEMscUJBQXFCLEVBQUU7O0FBRW5FO0FBQ0E7QUFDQSxHQUFHLG9EQUFvRDtBQUN2RDtBQUNBO0FBQ0E7QUFDQSxDQUFDOztBQUVEO0FBQ0E7Ozs7Ozs7Ozs7OztBQ3BCYTtBQUNiO0FBQ0EsUUFBUSxtQkFBTyxDQUFDLHVFQUFxQjtBQUNyQyxlQUFlLG9IQUE4QztBQUM3RCwwQkFBMEIsbUJBQU8sQ0FBQyx1R0FBcUM7O0FBRXZFOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBLEdBQUcsd0VBQXdFO0FBQzNFO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLENBQUM7Ozs7Ozs7Ozs7OztBQ3BCWTtBQUNiLFFBQVEsbUJBQU8sQ0FBQyx1RUFBcUI7QUFDckMsb0JBQW9CLG1CQUFPLENBQUMsdUZBQTZCO0FBQ3pELHNCQUFzQixtQkFBTyxDQUFDLDZGQUFnQztBQUM5RCwwQkFBMEIsbUJBQU8sQ0FBQyx1R0FBcUM7O0FBRXZFOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBLEdBQUcsc0VBQXNFO0FBQ3pFO0FBQ0E7QUFDQTtBQUNBLENBQUM7Ozs7Ozs7Ozs7OztBQ2pCWTtBQUNiLFFBQVEsbUJBQU8sQ0FBQyx1RUFBcUI7QUFDckMsV0FBVyxrSEFBMkM7QUFDdEQsbUNBQW1DLG1CQUFPLENBQUMsMkhBQStDOztBQUUxRjs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxHQUFHLDZEQUE2RDtBQUNoRTtBQUNBO0FBQ0E7QUFDQSxDQUFDOzs7Ozs7Ozs7Ozs7QUNkWTtBQUNiLG9DQUFvQyxtQkFBTyxDQUFDLCtIQUFpRDtBQUM3RixlQUFlLG1CQUFPLENBQUMsNkVBQXdCO0FBQy9DLGVBQWUsbUJBQU8sQ0FBQyw2RUFBd0I7QUFDL0MsZ0JBQWdCLG1CQUFPLENBQUMsK0VBQXlCO0FBQ2pELDZCQUE2QixtQkFBTyxDQUFDLDJHQUF1QztBQUM1RSx5QkFBeUIsbUJBQU8sQ0FBQyxtR0FBbUM7QUFDcEUsc0JBQXNCLG1CQUFPLENBQUMsMkZBQStCO0FBQzdELGlCQUFpQixtQkFBTyxDQUFDLG1HQUFtQzs7QUFFNUQ7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxLQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EscUJBQXFCLG9CQUFvQjtBQUN6Qzs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsdUJBQXVCLG1CQUFtQjtBQUMxQztBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsU0FBUztBQUNUO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsQ0FBQyIsImZpbGUiOiJ2ZW5kb3JzLW5vZGVfbW9kdWxlc19jb3JlLWpzX21vZHVsZXNfZXNfYXJyYXlfY29uY2F0X2pzLW5vZGVfbW9kdWxlc19jb3JlLWpzX21vZHVsZXNfZXNfYXJyYXktYzNiNzYyLmpzIiwic291cmNlc0NvbnRlbnQiOlsidmFyIGZhaWxzID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL2ZhaWxzJyk7XG52YXIgd2VsbEtub3duU3ltYm9sID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL3dlbGwta25vd24tc3ltYm9sJyk7XG52YXIgVjhfVkVSU0lPTiA9IHJlcXVpcmUoJy4uL2ludGVybmFscy9lbmdpbmUtdjgtdmVyc2lvbicpO1xuXG52YXIgU1BFQ0lFUyA9IHdlbGxLbm93blN5bWJvbCgnc3BlY2llcycpO1xuXG5tb2R1bGUuZXhwb3J0cyA9IGZ1bmN0aW9uIChNRVRIT0RfTkFNRSkge1xuICAvLyBXZSBjYW4ndCB1c2UgdGhpcyBmZWF0dXJlIGRldGVjdGlvbiBpbiBWOCBzaW5jZSBpdCBjYXVzZXNcbiAgLy8gZGVvcHRpbWl6YXRpb24gYW5kIHNlcmlvdXMgcGVyZm9ybWFuY2UgZGVncmFkYXRpb25cbiAgLy8gaHR0cHM6Ly9naXRodWIuY29tL3psb2lyb2NrL2NvcmUtanMvaXNzdWVzLzY3N1xuICByZXR1cm4gVjhfVkVSU0lPTiA+PSA1MSB8fCAhZmFpbHMoZnVuY3Rpb24gKCkge1xuICAgIHZhciBhcnJheSA9IFtdO1xuICAgIHZhciBjb25zdHJ1Y3RvciA9IGFycmF5LmNvbnN0cnVjdG9yID0ge307XG4gICAgY29uc3RydWN0b3JbU1BFQ0lFU10gPSBmdW5jdGlvbiAoKSB7XG4gICAgICByZXR1cm4geyBmb286IDEgfTtcbiAgICB9O1xuICAgIHJldHVybiBhcnJheVtNRVRIT0RfTkFNRV0oQm9vbGVhbikuZm9vICE9PSAxO1xuICB9KTtcbn07XG4iLCIndXNlIHN0cmljdCc7XG52YXIgZmFpbHMgPSByZXF1aXJlKCcuLi9pbnRlcm5hbHMvZmFpbHMnKTtcblxubW9kdWxlLmV4cG9ydHMgPSBmdW5jdGlvbiAoTUVUSE9EX05BTUUsIGFyZ3VtZW50KSB7XG4gIHZhciBtZXRob2QgPSBbXVtNRVRIT0RfTkFNRV07XG4gIHJldHVybiAhIW1ldGhvZCAmJiBmYWlscyhmdW5jdGlvbiAoKSB7XG4gICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIG5vLXVzZWxlc3MtY2FsbCxuby10aHJvdy1saXRlcmFsIC0tIHJlcXVpcmVkIGZvciB0ZXN0aW5nXG4gICAgbWV0aG9kLmNhbGwobnVsbCwgYXJndW1lbnQgfHwgZnVuY3Rpb24gKCkgeyB0aHJvdyAxOyB9LCAxKTtcbiAgfSk7XG59O1xuIiwiJ3VzZSBzdHJpY3QnO1xudmFyIHRvUHJpbWl0aXZlID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL3RvLXByaW1pdGl2ZScpO1xudmFyIGRlZmluZVByb3BlcnR5TW9kdWxlID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL29iamVjdC1kZWZpbmUtcHJvcGVydHknKTtcbnZhciBjcmVhdGVQcm9wZXJ0eURlc2NyaXB0b3IgPSByZXF1aXJlKCcuLi9pbnRlcm5hbHMvY3JlYXRlLXByb3BlcnR5LWRlc2NyaXB0b3InKTtcblxubW9kdWxlLmV4cG9ydHMgPSBmdW5jdGlvbiAob2JqZWN0LCBrZXksIHZhbHVlKSB7XG4gIHZhciBwcm9wZXJ0eUtleSA9IHRvUHJpbWl0aXZlKGtleSk7XG4gIGlmIChwcm9wZXJ0eUtleSBpbiBvYmplY3QpIGRlZmluZVByb3BlcnR5TW9kdWxlLmYob2JqZWN0LCBwcm9wZXJ0eUtleSwgY3JlYXRlUHJvcGVydHlEZXNjcmlwdG9yKDAsIHZhbHVlKSk7XG4gIGVsc2Ugb2JqZWN0W3Byb3BlcnR5S2V5XSA9IHZhbHVlO1xufTtcbiIsInZhciB0b09iamVjdCA9IHJlcXVpcmUoJy4uL2ludGVybmFscy90by1vYmplY3QnKTtcblxudmFyIGZsb29yID0gTWF0aC5mbG9vcjtcbnZhciByZXBsYWNlID0gJycucmVwbGFjZTtcbnZhciBTVUJTVElUVVRJT05fU1lNQk9MUyA9IC9cXCQoWyQmJ2BdfFxcZHsxLDJ9fDxbXj5dKj4pL2c7XG52YXIgU1VCU1RJVFVUSU9OX1NZTUJPTFNfTk9fTkFNRUQgPSAvXFwkKFskJidgXXxcXGR7MSwyfSkvZztcblxuLy8gaHR0cHM6Ly90YzM5LmVzL2VjbWEyNjIvI3NlYy1nZXRzdWJzdGl0dXRpb25cbm1vZHVsZS5leHBvcnRzID0gZnVuY3Rpb24gKG1hdGNoZWQsIHN0ciwgcG9zaXRpb24sIGNhcHR1cmVzLCBuYW1lZENhcHR1cmVzLCByZXBsYWNlbWVudCkge1xuICB2YXIgdGFpbFBvcyA9IHBvc2l0aW9uICsgbWF0Y2hlZC5sZW5ndGg7XG4gIHZhciBtID0gY2FwdHVyZXMubGVuZ3RoO1xuICB2YXIgc3ltYm9scyA9IFNVQlNUSVRVVElPTl9TWU1CT0xTX05PX05BTUVEO1xuICBpZiAobmFtZWRDYXB0dXJlcyAhPT0gdW5kZWZpbmVkKSB7XG4gICAgbmFtZWRDYXB0dXJlcyA9IHRvT2JqZWN0KG5hbWVkQ2FwdHVyZXMpO1xuICAgIHN5bWJvbHMgPSBTVUJTVElUVVRJT05fU1lNQk9MUztcbiAgfVxuICByZXR1cm4gcmVwbGFjZS5jYWxsKHJlcGxhY2VtZW50LCBzeW1ib2xzLCBmdW5jdGlvbiAobWF0Y2gsIGNoKSB7XG4gICAgdmFyIGNhcHR1cmU7XG4gICAgc3dpdGNoIChjaC5jaGFyQXQoMCkpIHtcbiAgICAgIGNhc2UgJyQnOiByZXR1cm4gJyQnO1xuICAgICAgY2FzZSAnJic6IHJldHVybiBtYXRjaGVkO1xuICAgICAgY2FzZSAnYCc6IHJldHVybiBzdHIuc2xpY2UoMCwgcG9zaXRpb24pO1xuICAgICAgY2FzZSBcIidcIjogcmV0dXJuIHN0ci5zbGljZSh0YWlsUG9zKTtcbiAgICAgIGNhc2UgJzwnOlxuICAgICAgICBjYXB0dXJlID0gbmFtZWRDYXB0dXJlc1tjaC5zbGljZSgxLCAtMSldO1xuICAgICAgICBicmVhaztcbiAgICAgIGRlZmF1bHQ6IC8vIFxcZFxcZD9cbiAgICAgICAgdmFyIG4gPSArY2g7XG4gICAgICAgIGlmIChuID09PSAwKSByZXR1cm4gbWF0Y2g7XG4gICAgICAgIGlmIChuID4gbSkge1xuICAgICAgICAgIHZhciBmID0gZmxvb3IobiAvIDEwKTtcbiAgICAgICAgICBpZiAoZiA9PT0gMCkgcmV0dXJuIG1hdGNoO1xuICAgICAgICAgIGlmIChmIDw9IG0pIHJldHVybiBjYXB0dXJlc1tmIC0gMV0gPT09IHVuZGVmaW5lZCA/IGNoLmNoYXJBdCgxKSA6IGNhcHR1cmVzW2YgLSAxXSArIGNoLmNoYXJBdCgxKTtcbiAgICAgICAgICByZXR1cm4gbWF0Y2g7XG4gICAgICAgIH1cbiAgICAgICAgY2FwdHVyZSA9IGNhcHR1cmVzW24gLSAxXTtcbiAgICB9XG4gICAgcmV0dXJuIGNhcHR1cmUgPT09IHVuZGVmaW5lZCA/ICcnIDogY2FwdHVyZTtcbiAgfSk7XG59O1xuIiwiJ3VzZSBzdHJpY3QnO1xudmFyICQgPSByZXF1aXJlKCcuLi9pbnRlcm5hbHMvZXhwb3J0Jyk7XG52YXIgZmFpbHMgPSByZXF1aXJlKCcuLi9pbnRlcm5hbHMvZmFpbHMnKTtcbnZhciBpc0FycmF5ID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL2lzLWFycmF5Jyk7XG52YXIgaXNPYmplY3QgPSByZXF1aXJlKCcuLi9pbnRlcm5hbHMvaXMtb2JqZWN0Jyk7XG52YXIgdG9PYmplY3QgPSByZXF1aXJlKCcuLi9pbnRlcm5hbHMvdG8tb2JqZWN0Jyk7XG52YXIgdG9MZW5ndGggPSByZXF1aXJlKCcuLi9pbnRlcm5hbHMvdG8tbGVuZ3RoJyk7XG52YXIgY3JlYXRlUHJvcGVydHkgPSByZXF1aXJlKCcuLi9pbnRlcm5hbHMvY3JlYXRlLXByb3BlcnR5Jyk7XG52YXIgYXJyYXlTcGVjaWVzQ3JlYXRlID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL2FycmF5LXNwZWNpZXMtY3JlYXRlJyk7XG52YXIgYXJyYXlNZXRob2RIYXNTcGVjaWVzU3VwcG9ydCA9IHJlcXVpcmUoJy4uL2ludGVybmFscy9hcnJheS1tZXRob2QtaGFzLXNwZWNpZXMtc3VwcG9ydCcpO1xudmFyIHdlbGxLbm93blN5bWJvbCA9IHJlcXVpcmUoJy4uL2ludGVybmFscy93ZWxsLWtub3duLXN5bWJvbCcpO1xudmFyIFY4X1ZFUlNJT04gPSByZXF1aXJlKCcuLi9pbnRlcm5hbHMvZW5naW5lLXY4LXZlcnNpb24nKTtcblxudmFyIElTX0NPTkNBVF9TUFJFQURBQkxFID0gd2VsbEtub3duU3ltYm9sKCdpc0NvbmNhdFNwcmVhZGFibGUnKTtcbnZhciBNQVhfU0FGRV9JTlRFR0VSID0gMHgxRkZGRkZGRkZGRkZGRjtcbnZhciBNQVhJTVVNX0FMTE9XRURfSU5ERVhfRVhDRUVERUQgPSAnTWF4aW11bSBhbGxvd2VkIGluZGV4IGV4Y2VlZGVkJztcblxuLy8gV2UgY2FuJ3QgdXNlIHRoaXMgZmVhdHVyZSBkZXRlY3Rpb24gaW4gVjggc2luY2UgaXQgY2F1c2VzXG4vLyBkZW9wdGltaXphdGlvbiBhbmQgc2VyaW91cyBwZXJmb3JtYW5jZSBkZWdyYWRhdGlvblxuLy8gaHR0cHM6Ly9naXRodWIuY29tL3psb2lyb2NrL2NvcmUtanMvaXNzdWVzLzY3OVxudmFyIElTX0NPTkNBVF9TUFJFQURBQkxFX1NVUFBPUlQgPSBWOF9WRVJTSU9OID49IDUxIHx8ICFmYWlscyhmdW5jdGlvbiAoKSB7XG4gIHZhciBhcnJheSA9IFtdO1xuICBhcnJheVtJU19DT05DQVRfU1BSRUFEQUJMRV0gPSBmYWxzZTtcbiAgcmV0dXJuIGFycmF5LmNvbmNhdCgpWzBdICE9PSBhcnJheTtcbn0pO1xuXG52YXIgU1BFQ0lFU19TVVBQT1JUID0gYXJyYXlNZXRob2RIYXNTcGVjaWVzU3VwcG9ydCgnY29uY2F0Jyk7XG5cbnZhciBpc0NvbmNhdFNwcmVhZGFibGUgPSBmdW5jdGlvbiAoTykge1xuICBpZiAoIWlzT2JqZWN0KE8pKSByZXR1cm4gZmFsc2U7XG4gIHZhciBzcHJlYWRhYmxlID0gT1tJU19DT05DQVRfU1BSRUFEQUJMRV07XG4gIHJldHVybiBzcHJlYWRhYmxlICE9PSB1bmRlZmluZWQgPyAhIXNwcmVhZGFibGUgOiBpc0FycmF5KE8pO1xufTtcblxudmFyIEZPUkNFRCA9ICFJU19DT05DQVRfU1BSRUFEQUJMRV9TVVBQT1JUIHx8ICFTUEVDSUVTX1NVUFBPUlQ7XG5cbi8vIGBBcnJheS5wcm90b3R5cGUuY29uY2F0YCBtZXRob2Rcbi8vIGh0dHBzOi8vdGMzOS5lcy9lY21hMjYyLyNzZWMtYXJyYXkucHJvdG90eXBlLmNvbmNhdFxuLy8gd2l0aCBhZGRpbmcgc3VwcG9ydCBvZiBAQGlzQ29uY2F0U3ByZWFkYWJsZSBhbmQgQEBzcGVjaWVzXG4kKHsgdGFyZ2V0OiAnQXJyYXknLCBwcm90bzogdHJ1ZSwgZm9yY2VkOiBGT1JDRUQgfSwge1xuICAvLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgbm8tdW51c2VkLXZhcnMgLS0gcmVxdWlyZWQgZm9yIGAubGVuZ3RoYFxuICBjb25jYXQ6IGZ1bmN0aW9uIGNvbmNhdChhcmcpIHtcbiAgICB2YXIgTyA9IHRvT2JqZWN0KHRoaXMpO1xuICAgIHZhciBBID0gYXJyYXlTcGVjaWVzQ3JlYXRlKE8sIDApO1xuICAgIHZhciBuID0gMDtcbiAgICB2YXIgaSwgaywgbGVuZ3RoLCBsZW4sIEU7XG4gICAgZm9yIChpID0gLTEsIGxlbmd0aCA9IGFyZ3VtZW50cy5sZW5ndGg7IGkgPCBsZW5ndGg7IGkrKykge1xuICAgICAgRSA9IGkgPT09IC0xID8gTyA6IGFyZ3VtZW50c1tpXTtcbiAgICAgIGlmIChpc0NvbmNhdFNwcmVhZGFibGUoRSkpIHtcbiAgICAgICAgbGVuID0gdG9MZW5ndGgoRS5sZW5ndGgpO1xuICAgICAgICBpZiAobiArIGxlbiA+IE1BWF9TQUZFX0lOVEVHRVIpIHRocm93IFR5cGVFcnJvcihNQVhJTVVNX0FMTE9XRURfSU5ERVhfRVhDRUVERUQpO1xuICAgICAgICBmb3IgKGsgPSAwOyBrIDwgbGVuOyBrKyssIG4rKykgaWYgKGsgaW4gRSkgY3JlYXRlUHJvcGVydHkoQSwgbiwgRVtrXSk7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBpZiAobiA+PSBNQVhfU0FGRV9JTlRFR0VSKSB0aHJvdyBUeXBlRXJyb3IoTUFYSU1VTV9BTExPV0VEX0lOREVYX0VYQ0VFREVEKTtcbiAgICAgICAgY3JlYXRlUHJvcGVydHkoQSwgbisrLCBFKTtcbiAgICAgIH1cbiAgICB9XG4gICAgQS5sZW5ndGggPSBuO1xuICAgIHJldHVybiBBO1xuICB9XG59KTtcbiIsIid1c2Ugc3RyaWN0JztcbnZhciAkID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL2V4cG9ydCcpO1xudmFyICRmaW5kID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL2FycmF5LWl0ZXJhdGlvbicpLmZpbmQ7XG52YXIgYWRkVG9VbnNjb3BhYmxlcyA9IHJlcXVpcmUoJy4uL2ludGVybmFscy9hZGQtdG8tdW5zY29wYWJsZXMnKTtcblxudmFyIEZJTkQgPSAnZmluZCc7XG52YXIgU0tJUFNfSE9MRVMgPSB0cnVlO1xuXG4vLyBTaG91bGRuJ3Qgc2tpcCBob2xlc1xuaWYgKEZJTkQgaW4gW10pIEFycmF5KDEpW0ZJTkRdKGZ1bmN0aW9uICgpIHsgU0tJUFNfSE9MRVMgPSBmYWxzZTsgfSk7XG5cbi8vIGBBcnJheS5wcm90b3R5cGUuZmluZGAgbWV0aG9kXG4vLyBodHRwczovL3RjMzkuZXMvZWNtYTI2Mi8jc2VjLWFycmF5LnByb3RvdHlwZS5maW5kXG4kKHsgdGFyZ2V0OiAnQXJyYXknLCBwcm90bzogdHJ1ZSwgZm9yY2VkOiBTS0lQU19IT0xFUyB9LCB7XG4gIGZpbmQ6IGZ1bmN0aW9uIGZpbmQoY2FsbGJhY2tmbiAvKiAsIHRoYXQgPSB1bmRlZmluZWQgKi8pIHtcbiAgICByZXR1cm4gJGZpbmQodGhpcywgY2FsbGJhY2tmbiwgYXJndW1lbnRzLmxlbmd0aCA+IDEgPyBhcmd1bWVudHNbMV0gOiB1bmRlZmluZWQpO1xuICB9XG59KTtcblxuLy8gaHR0cHM6Ly90YzM5LmVzL2VjbWEyNjIvI3NlYy1hcnJheS5wcm90b3R5cGUtQEB1bnNjb3BhYmxlc1xuYWRkVG9VbnNjb3BhYmxlcyhGSU5EKTtcbiIsIid1c2Ugc3RyaWN0Jztcbi8qIGVzbGludC1kaXNhYmxlIGVzL25vLWFycmF5LXByb3RvdHlwZS1pbmRleG9mIC0tIHJlcXVpcmVkIGZvciB0ZXN0aW5nICovXG52YXIgJCA9IHJlcXVpcmUoJy4uL2ludGVybmFscy9leHBvcnQnKTtcbnZhciAkaW5kZXhPZiA9IHJlcXVpcmUoJy4uL2ludGVybmFscy9hcnJheS1pbmNsdWRlcycpLmluZGV4T2Y7XG52YXIgYXJyYXlNZXRob2RJc1N0cmljdCA9IHJlcXVpcmUoJy4uL2ludGVybmFscy9hcnJheS1tZXRob2QtaXMtc3RyaWN0Jyk7XG5cbnZhciBuYXRpdmVJbmRleE9mID0gW10uaW5kZXhPZjtcblxudmFyIE5FR0FUSVZFX1pFUk8gPSAhIW5hdGl2ZUluZGV4T2YgJiYgMSAvIFsxXS5pbmRleE9mKDEsIC0wKSA8IDA7XG52YXIgU1RSSUNUX01FVEhPRCA9IGFycmF5TWV0aG9kSXNTdHJpY3QoJ2luZGV4T2YnKTtcblxuLy8gYEFycmF5LnByb3RvdHlwZS5pbmRleE9mYCBtZXRob2Rcbi8vIGh0dHBzOi8vdGMzOS5lcy9lY21hMjYyLyNzZWMtYXJyYXkucHJvdG90eXBlLmluZGV4b2ZcbiQoeyB0YXJnZXQ6ICdBcnJheScsIHByb3RvOiB0cnVlLCBmb3JjZWQ6IE5FR0FUSVZFX1pFUk8gfHwgIVNUUklDVF9NRVRIT0QgfSwge1xuICBpbmRleE9mOiBmdW5jdGlvbiBpbmRleE9mKHNlYXJjaEVsZW1lbnQgLyogLCBmcm9tSW5kZXggPSAwICovKSB7XG4gICAgcmV0dXJuIE5FR0FUSVZFX1pFUk9cbiAgICAgIC8vIGNvbnZlcnQgLTAgdG8gKzBcbiAgICAgID8gbmF0aXZlSW5kZXhPZi5hcHBseSh0aGlzLCBhcmd1bWVudHMpIHx8IDBcbiAgICAgIDogJGluZGV4T2YodGhpcywgc2VhcmNoRWxlbWVudCwgYXJndW1lbnRzLmxlbmd0aCA+IDEgPyBhcmd1bWVudHNbMV0gOiB1bmRlZmluZWQpO1xuICB9XG59KTtcbiIsIid1c2Ugc3RyaWN0JztcbnZhciAkID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL2V4cG9ydCcpO1xudmFyIEluZGV4ZWRPYmplY3QgPSByZXF1aXJlKCcuLi9pbnRlcm5hbHMvaW5kZXhlZC1vYmplY3QnKTtcbnZhciB0b0luZGV4ZWRPYmplY3QgPSByZXF1aXJlKCcuLi9pbnRlcm5hbHMvdG8taW5kZXhlZC1vYmplY3QnKTtcbnZhciBhcnJheU1ldGhvZElzU3RyaWN0ID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL2FycmF5LW1ldGhvZC1pcy1zdHJpY3QnKTtcblxudmFyIG5hdGl2ZUpvaW4gPSBbXS5qb2luO1xuXG52YXIgRVMzX1NUUklOR1MgPSBJbmRleGVkT2JqZWN0ICE9IE9iamVjdDtcbnZhciBTVFJJQ1RfTUVUSE9EID0gYXJyYXlNZXRob2RJc1N0cmljdCgnam9pbicsICcsJyk7XG5cbi8vIGBBcnJheS5wcm90b3R5cGUuam9pbmAgbWV0aG9kXG4vLyBodHRwczovL3RjMzkuZXMvZWNtYTI2Mi8jc2VjLWFycmF5LnByb3RvdHlwZS5qb2luXG4kKHsgdGFyZ2V0OiAnQXJyYXknLCBwcm90bzogdHJ1ZSwgZm9yY2VkOiBFUzNfU1RSSU5HUyB8fCAhU1RSSUNUX01FVEhPRCB9LCB7XG4gIGpvaW46IGZ1bmN0aW9uIGpvaW4oc2VwYXJhdG9yKSB7XG4gICAgcmV0dXJuIG5hdGl2ZUpvaW4uY2FsbCh0b0luZGV4ZWRPYmplY3QodGhpcyksIHNlcGFyYXRvciA9PT0gdW5kZWZpbmVkID8gJywnIDogc2VwYXJhdG9yKTtcbiAgfVxufSk7XG4iLCIndXNlIHN0cmljdCc7XG52YXIgJCA9IHJlcXVpcmUoJy4uL2ludGVybmFscy9leHBvcnQnKTtcbnZhciAkbWFwID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL2FycmF5LWl0ZXJhdGlvbicpLm1hcDtcbnZhciBhcnJheU1ldGhvZEhhc1NwZWNpZXNTdXBwb3J0ID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL2FycmF5LW1ldGhvZC1oYXMtc3BlY2llcy1zdXBwb3J0Jyk7XG5cbnZhciBIQVNfU1BFQ0lFU19TVVBQT1JUID0gYXJyYXlNZXRob2RIYXNTcGVjaWVzU3VwcG9ydCgnbWFwJyk7XG5cbi8vIGBBcnJheS5wcm90b3R5cGUubWFwYCBtZXRob2Rcbi8vIGh0dHBzOi8vdGMzOS5lcy9lY21hMjYyLyNzZWMtYXJyYXkucHJvdG90eXBlLm1hcFxuLy8gd2l0aCBhZGRpbmcgc3VwcG9ydCBvZiBAQHNwZWNpZXNcbiQoeyB0YXJnZXQ6ICdBcnJheScsIHByb3RvOiB0cnVlLCBmb3JjZWQ6ICFIQVNfU1BFQ0lFU19TVVBQT1JUIH0sIHtcbiAgbWFwOiBmdW5jdGlvbiBtYXAoY2FsbGJhY2tmbiAvKiAsIHRoaXNBcmcgKi8pIHtcbiAgICByZXR1cm4gJG1hcCh0aGlzLCBjYWxsYmFja2ZuLCBhcmd1bWVudHMubGVuZ3RoID4gMSA/IGFyZ3VtZW50c1sxXSA6IHVuZGVmaW5lZCk7XG4gIH1cbn0pO1xuIiwiJ3VzZSBzdHJpY3QnO1xudmFyIGZpeFJlZ0V4cFdlbGxLbm93blN5bWJvbExvZ2ljID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL2ZpeC1yZWdleHAtd2VsbC1rbm93bi1zeW1ib2wtbG9naWMnKTtcbnZhciBhbk9iamVjdCA9IHJlcXVpcmUoJy4uL2ludGVybmFscy9hbi1vYmplY3QnKTtcbnZhciB0b0xlbmd0aCA9IHJlcXVpcmUoJy4uL2ludGVybmFscy90by1sZW5ndGgnKTtcbnZhciB0b0ludGVnZXIgPSByZXF1aXJlKCcuLi9pbnRlcm5hbHMvdG8taW50ZWdlcicpO1xudmFyIHJlcXVpcmVPYmplY3RDb2VyY2libGUgPSByZXF1aXJlKCcuLi9pbnRlcm5hbHMvcmVxdWlyZS1vYmplY3QtY29lcmNpYmxlJyk7XG52YXIgYWR2YW5jZVN0cmluZ0luZGV4ID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL2FkdmFuY2Utc3RyaW5nLWluZGV4Jyk7XG52YXIgZ2V0U3Vic3RpdHV0aW9uID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL2dldC1zdWJzdGl0dXRpb24nKTtcbnZhciByZWdFeHBFeGVjID0gcmVxdWlyZSgnLi4vaW50ZXJuYWxzL3JlZ2V4cC1leGVjLWFic3RyYWN0Jyk7XG5cbnZhciBtYXggPSBNYXRoLm1heDtcbnZhciBtaW4gPSBNYXRoLm1pbjtcblxudmFyIG1heWJlVG9TdHJpbmcgPSBmdW5jdGlvbiAoaXQpIHtcbiAgcmV0dXJuIGl0ID09PSB1bmRlZmluZWQgPyBpdCA6IFN0cmluZyhpdCk7XG59O1xuXG4vLyBAQHJlcGxhY2UgbG9naWNcbmZpeFJlZ0V4cFdlbGxLbm93blN5bWJvbExvZ2ljKCdyZXBsYWNlJywgMiwgZnVuY3Rpb24gKFJFUExBQ0UsIG5hdGl2ZVJlcGxhY2UsIG1heWJlQ2FsbE5hdGl2ZSwgcmVhc29uKSB7XG4gIHZhciBSRUdFWFBfUkVQTEFDRV9TVUJTVElUVVRFU19VTkRFRklORURfQ0FQVFVSRSA9IHJlYXNvbi5SRUdFWFBfUkVQTEFDRV9TVUJTVElUVVRFU19VTkRFRklORURfQ0FQVFVSRTtcbiAgdmFyIFJFUExBQ0VfS0VFUFNfJDAgPSByZWFzb24uUkVQTEFDRV9LRUVQU18kMDtcbiAgdmFyIFVOU0FGRV9TVUJTVElUVVRFID0gUkVHRVhQX1JFUExBQ0VfU1VCU1RJVFVURVNfVU5ERUZJTkVEX0NBUFRVUkUgPyAnJCcgOiAnJDAnO1xuXG4gIHJldHVybiBbXG4gICAgLy8gYFN0cmluZy5wcm90b3R5cGUucmVwbGFjZWAgbWV0aG9kXG4gICAgLy8gaHR0cHM6Ly90YzM5LmVzL2VjbWEyNjIvI3NlYy1zdHJpbmcucHJvdG90eXBlLnJlcGxhY2VcbiAgICBmdW5jdGlvbiByZXBsYWNlKHNlYXJjaFZhbHVlLCByZXBsYWNlVmFsdWUpIHtcbiAgICAgIHZhciBPID0gcmVxdWlyZU9iamVjdENvZXJjaWJsZSh0aGlzKTtcbiAgICAgIHZhciByZXBsYWNlciA9IHNlYXJjaFZhbHVlID09IHVuZGVmaW5lZCA/IHVuZGVmaW5lZCA6IHNlYXJjaFZhbHVlW1JFUExBQ0VdO1xuICAgICAgcmV0dXJuIHJlcGxhY2VyICE9PSB1bmRlZmluZWRcbiAgICAgICAgPyByZXBsYWNlci5jYWxsKHNlYXJjaFZhbHVlLCBPLCByZXBsYWNlVmFsdWUpXG4gICAgICAgIDogbmF0aXZlUmVwbGFjZS5jYWxsKFN0cmluZyhPKSwgc2VhcmNoVmFsdWUsIHJlcGxhY2VWYWx1ZSk7XG4gICAgfSxcbiAgICAvLyBgUmVnRXhwLnByb3RvdHlwZVtAQHJlcGxhY2VdYCBtZXRob2RcbiAgICAvLyBodHRwczovL3RjMzkuZXMvZWNtYTI2Mi8jc2VjLXJlZ2V4cC5wcm90b3R5cGUtQEByZXBsYWNlXG4gICAgZnVuY3Rpb24gKHJlZ2V4cCwgcmVwbGFjZVZhbHVlKSB7XG4gICAgICBpZiAoXG4gICAgICAgICghUkVHRVhQX1JFUExBQ0VfU1VCU1RJVFVURVNfVU5ERUZJTkVEX0NBUFRVUkUgJiYgUkVQTEFDRV9LRUVQU18kMCkgfHxcbiAgICAgICAgKHR5cGVvZiByZXBsYWNlVmFsdWUgPT09ICdzdHJpbmcnICYmIHJlcGxhY2VWYWx1ZS5pbmRleE9mKFVOU0FGRV9TVUJTVElUVVRFKSA9PT0gLTEpXG4gICAgICApIHtcbiAgICAgICAgdmFyIHJlcyA9IG1heWJlQ2FsbE5hdGl2ZShuYXRpdmVSZXBsYWNlLCByZWdleHAsIHRoaXMsIHJlcGxhY2VWYWx1ZSk7XG4gICAgICAgIGlmIChyZXMuZG9uZSkgcmV0dXJuIHJlcy52YWx1ZTtcbiAgICAgIH1cblxuICAgICAgdmFyIHJ4ID0gYW5PYmplY3QocmVnZXhwKTtcbiAgICAgIHZhciBTID0gU3RyaW5nKHRoaXMpO1xuXG4gICAgICB2YXIgZnVuY3Rpb25hbFJlcGxhY2UgPSB0eXBlb2YgcmVwbGFjZVZhbHVlID09PSAnZnVuY3Rpb24nO1xuICAgICAgaWYgKCFmdW5jdGlvbmFsUmVwbGFjZSkgcmVwbGFjZVZhbHVlID0gU3RyaW5nKHJlcGxhY2VWYWx1ZSk7XG5cbiAgICAgIHZhciBnbG9iYWwgPSByeC5nbG9iYWw7XG4gICAgICBpZiAoZ2xvYmFsKSB7XG4gICAgICAgIHZhciBmdWxsVW5pY29kZSA9IHJ4LnVuaWNvZGU7XG4gICAgICAgIHJ4Lmxhc3RJbmRleCA9IDA7XG4gICAgICB9XG4gICAgICB2YXIgcmVzdWx0cyA9IFtdO1xuICAgICAgd2hpbGUgKHRydWUpIHtcbiAgICAgICAgdmFyIHJlc3VsdCA9IHJlZ0V4cEV4ZWMocngsIFMpO1xuICAgICAgICBpZiAocmVzdWx0ID09PSBudWxsKSBicmVhaztcblxuICAgICAgICByZXN1bHRzLnB1c2gocmVzdWx0KTtcbiAgICAgICAgaWYgKCFnbG9iYWwpIGJyZWFrO1xuXG4gICAgICAgIHZhciBtYXRjaFN0ciA9IFN0cmluZyhyZXN1bHRbMF0pO1xuICAgICAgICBpZiAobWF0Y2hTdHIgPT09ICcnKSByeC5sYXN0SW5kZXggPSBhZHZhbmNlU3RyaW5nSW5kZXgoUywgdG9MZW5ndGgocngubGFzdEluZGV4KSwgZnVsbFVuaWNvZGUpO1xuICAgICAgfVxuXG4gICAgICB2YXIgYWNjdW11bGF0ZWRSZXN1bHQgPSAnJztcbiAgICAgIHZhciBuZXh0U291cmNlUG9zaXRpb24gPSAwO1xuICAgICAgZm9yICh2YXIgaSA9IDA7IGkgPCByZXN1bHRzLmxlbmd0aDsgaSsrKSB7XG4gICAgICAgIHJlc3VsdCA9IHJlc3VsdHNbaV07XG5cbiAgICAgICAgdmFyIG1hdGNoZWQgPSBTdHJpbmcocmVzdWx0WzBdKTtcbiAgICAgICAgdmFyIHBvc2l0aW9uID0gbWF4KG1pbih0b0ludGVnZXIocmVzdWx0LmluZGV4KSwgUy5sZW5ndGgpLCAwKTtcbiAgICAgICAgdmFyIGNhcHR1cmVzID0gW107XG4gICAgICAgIC8vIE5PVEU6IFRoaXMgaXMgZXF1aXZhbGVudCB0b1xuICAgICAgICAvLyAgIGNhcHR1cmVzID0gcmVzdWx0LnNsaWNlKDEpLm1hcChtYXliZVRvU3RyaW5nKVxuICAgICAgICAvLyBidXQgZm9yIHNvbWUgcmVhc29uIGBuYXRpdmVTbGljZS5jYWxsKHJlc3VsdCwgMSwgcmVzdWx0Lmxlbmd0aClgIChjYWxsZWQgaW5cbiAgICAgICAgLy8gdGhlIHNsaWNlIHBvbHlmaWxsIHdoZW4gc2xpY2luZyBuYXRpdmUgYXJyYXlzKSBcImRvZXNuJ3Qgd29ya1wiIGluIHNhZmFyaSA5IGFuZFxuICAgICAgICAvLyBjYXVzZXMgYSBjcmFzaCAoaHR0cHM6Ly9wYXN0ZWJpbi5jb20vTjIxUXplUUEpIHdoZW4gdHJ5aW5nIHRvIGRlYnVnIGl0LlxuICAgICAgICBmb3IgKHZhciBqID0gMTsgaiA8IHJlc3VsdC5sZW5ndGg7IGorKykgY2FwdHVyZXMucHVzaChtYXliZVRvU3RyaW5nKHJlc3VsdFtqXSkpO1xuICAgICAgICB2YXIgbmFtZWRDYXB0dXJlcyA9IHJlc3VsdC5ncm91cHM7XG4gICAgICAgIGlmIChmdW5jdGlvbmFsUmVwbGFjZSkge1xuICAgICAgICAgIHZhciByZXBsYWNlckFyZ3MgPSBbbWF0Y2hlZF0uY29uY2F0KGNhcHR1cmVzLCBwb3NpdGlvbiwgUyk7XG4gICAgICAgICAgaWYgKG5hbWVkQ2FwdHVyZXMgIT09IHVuZGVmaW5lZCkgcmVwbGFjZXJBcmdzLnB1c2gobmFtZWRDYXB0dXJlcyk7XG4gICAgICAgICAgdmFyIHJlcGxhY2VtZW50ID0gU3RyaW5nKHJlcGxhY2VWYWx1ZS5hcHBseSh1bmRlZmluZWQsIHJlcGxhY2VyQXJncykpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIHJlcGxhY2VtZW50ID0gZ2V0U3Vic3RpdHV0aW9uKG1hdGNoZWQsIFMsIHBvc2l0aW9uLCBjYXB0dXJlcywgbmFtZWRDYXB0dXJlcywgcmVwbGFjZVZhbHVlKTtcbiAgICAgICAgfVxuICAgICAgICBpZiAocG9zaXRpb24gPj0gbmV4dFNvdXJjZVBvc2l0aW9uKSB7XG4gICAgICAgICAgYWNjdW11bGF0ZWRSZXN1bHQgKz0gUy5zbGljZShuZXh0U291cmNlUG9zaXRpb24sIHBvc2l0aW9uKSArIHJlcGxhY2VtZW50O1xuICAgICAgICAgIG5leHRTb3VyY2VQb3NpdGlvbiA9IHBvc2l0aW9uICsgbWF0Y2hlZC5sZW5ndGg7XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICAgIHJldHVybiBhY2N1bXVsYXRlZFJlc3VsdCArIFMuc2xpY2UobmV4dFNvdXJjZVBvc2l0aW9uKTtcbiAgICB9XG4gIF07XG59KTtcbiJdLCJzb3VyY2VSb290IjoiIn0=
JavaScript
CL
d813a5a5bf04ebbbd5d884b506bb0ae0580c75c40789b9b8ce7058e7605862ba
const webpack = require('webpack') const merge = require('webpack-merge') const common = require('./webpack.common.js') const HtmlWebpackPlugin = require('html-webpack-plugin') const taskUtils = require('./utils/task')(); const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; const path = require('path'); module.exports = merge(common, { mode: 'development', devServer: { host: '0.0.0.0', contentBase: path.resolve(__dirname), watchContentBase: true, port: 8080 }, module: { rules: [ { test: /\.scss$/, use: [ 'style-loader', 'css-loader', { loader: "postcss-loader", options: { ident: 'postcss', plugins: [ require('autoprefixer')({ 'browsers': ['> 1%', 'last 2 versions'] }), ] } }, 'resolve-url-loader', { loader: 'sass-loader', options: { includePaths: ['./node_modules'], } } ] }, { test: /\.css$/, use: [ 'to-string-loader', 'css-loader', 'resolve-url-loader' ] }, { test: /\.(png|svg|jpg|gif|eot)$/, use: [ { loader: 'file-loader' } ] }, { test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } }, { test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } }, { test: /\.(ttf|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' } ] }, plugins: [ /* new BundleAnalyzerPlugin({ analyzerMode: 'static', reportFilename: '../webpack-analizer/report.html' }), */ new webpack.HotModuleReplacementPlugin(), new webpack.DefinePlugin(taskUtils.iterObj(require('./config/config.dev.json'))), new HtmlWebpackPlugin({ template: 'src/index.html', inject: 'body', chunksSortMode: 'none' }) ] })
JavaScript
CL
f030ed2ce85b23e670377410fece7a6d24b922fa12cd0c86afba24f7ec6b5e12
const cron = require('node-cron') const { prisma } = require('../generated/prisma-client') const moment = require('moment') const { sendSlackDM } = require('./slack') // TODO PRIORITY - THIS NEEDS TESTING ON MY IMAC // TODO instead of doing one chek every 24 hours, we chould check every few hours and only send a notification if they haven't already recieved one for that task in the last 24 hours. // TODO compile all notifications for user in to one daily message to avoid unnececarry calls // to slack API // Delay function to dealy 1 min between each user to avoid too many slack calls const delay = ms => new Promise(res => setTimeout(res, ms)) // Get Due in MS const calcDueIn = (task) => { // Get due date in miliseconds const due = new Date(task.dueDate).getTime() // MS between due date and now return Date.now() - due } const sendMessage = (task, dueIn, notificationType) => { // Is it due today ? const dueToday = new Date(Date.now()).getDate() === new Date(task.dueDate).getDate() // Find out if the number is negative i.e. due date has passed const overdue = dueIn > 0 // Work out user friendly time from now const fromNow = moment(task.dueDate).fromNow() // TODO different message if today // Is task due by or on date const byOrOn = task.due === 'BYDATE' ? 'by' : 'on' // human readable duedate const dueDate = moment(task.dueDate).format('dddd, MMMM Do YYYY') // Send the slack message overdue ? sendSlackDM(user.slackHandle, `🚨 *Task Overdue - due ${fromNow}* \n \n A task you ${notificationType} \`${task.title}\` was due ${byOrOn} ${dueDate}. \n \n Click here to view the task ${process.env.FRONTEND_URL}/task/${task.id} \r \n`) : sendSlackDM(user.slackHandle, `⏰ *Task Due ${fromNow}* \n \n A task you ${notificationType} \`${task.title}\` is due ${byOrOn} ${dueDate}. \n \n Click here to view the task ${process.env.FRONTEND_URL}/task/${task.id} \r \n`) } module.exports = () => { cron.schedule("0 9 * * *", async () => { const taskQuery = `( where: { status_not_in: [COMPLETED, CLOSED], due_in:[BYDATE, ONDATE] } ){ id title status due dueDate }` const query = ` query { users(where: { OR: [ { tasksCreated_some: { status_not_in: [COMPLETED, CLOSED], due_in:[BYDATE, ONDATE] } }, { tasksAssignedTo_some: { status_not_in: [COMPLETED, CLOSED], due_in:[BYDATE, ONDATE] } }, { subscribedTasks_some: { status_not_in: [COMPLETED, CLOSED], due_in:[BYDATE, ONDATE] } } ] }) { id name slackHandle tasksCreated${taskQuery} tasksAssignedTo${taskQuery} subscribedTasks${taskQuery} } } ` const users = await prisma.$graphql(query) // One day in MS const day = 86400000 for(const user of users.users) { let tasksNotified = [] for(const task of user.tasksCreated) { // MS between due date and now const dueIn = calcDueIn(task) // If it's due in more than 3 days from now, // no need to send a notification if(dueIn > (day * 3)) continue // Now we know we're going to send a notification so add // the task ID to the list of tasks that we've already notified // this user about. tasksNotified = [...tasksNotified, task.id] // Send the message sendMessage(task, dueIn, 'created') } for(const task of user.tasksAssignedTo) { // If the ID is in the array it means we've already // sent a notification above about this task because the user is the // tasks creator. so there's no need to send another if(tasksNotified.includes(task.id)) continue // MS between due date and now const dueIn = calcDueIn(task) // If it's due in more than 3 days from now, // no need to send a notification if(dueIn > (day * 3)) continue // Now we know we're going to send a notification so add // the task ID to the list of tasks that we've already notified // this user about. tasksNotified = [...tasksNotified, task.id] // Send the message sendMessage(task, dueIn, 'are assigned to') } for(const task of user.subscribedTasks) { // If the ID is in the array it means we've already // sent a notification above about this task because the user is the // tasks creator. so there's no need to send another if(tasksNotified.includes(task.id)) continue // MS between due date and now const dueIn = calcDueIn(task) // If it's due in more than 3 days from now, // no need to send a notification if(dueIn > (day * 3)) continue // Now we know we're going to send a notification so add // the task ID to the list of tasks that we've already notified // this user about. tasksNotified = [...tasksNotified, task.id] // Send the message sendMessage(task, dueIn, 'are subscribed to') } // Delay before processing next user await delay(60000) } }) }
JavaScript
CL
1c1b721332698cd020a52892f6b76b1a92dbc52a86e0d44df2c14019c682676a
import map from '@redux/Map/reducer'; import user from '@redux/User/reducer'; import token from '@redux/Token/reducer'; import packages from '@redux/Package/reducer'; import regions from '@redux/Package/reducer'; import products from '@redux/Product/reducer'; import profile from '@redux/Profile/reducer'; import message from '@redux/Message/reducer'; export { token, map, user, packages, regions, products, profile, message, };
JavaScript
CL
c9d0f4dd58fdff2f3ff3b5709e58d187cd064173b3dfabccf7fcbf70ca0773b1
#!/usr/bin/gjs // Copyright (c) 2014 Wojciech Dzierżanowski. // Use of this software is governed by the MIT license. See the LICENSE file // for details. const Lang = imports.lang; const Gst = imports.gi.Gst; let State = { STOPPED: 1, PLAYING: 2, }; const Player = new Lang.Class({ Name: "player", _init: function() { this.parent(); this._createPlaybin(); }, finalize: function() { this._playbin.get_bus().remove_signal_watch(); this._playbin.set_state(Gst.State.NULL); }, get uri() { return this._uri; }, set uri(v) { this._uri = v; }, set stateChangeCallback(c) { this._stateChangeCallback = c; }, toggle: function() { let [rv, state, pstate] = this._playbin.get_state(Gst.Clock.TIME_NONE); print("playbin state = " + Gst.Element.state_get_name(state)); if (state != Gst.State.PLAYING) { if (this._uri) { print("Playing " + this._uri); this._playbin.set_property("uri", this._uri); } else if (state == Gst.State.NULL) { // No URI and we've never played the player => bail out. return false; } this._playbin.set_state(Gst.State.PLAYING); this._stateChangeCallback(State.PLAYING); return true; } this._playbin.set_state(Gst.State.NULL); this._stateChangeCallback(State.STOPPED); return false; }, _createPlaybin: function() { this._playbin = Gst.ElementFactory.make("playbin", null); let bus = this._playbin.get_bus(); bus.add_signal_watch(); bus.connect("message::eos", Lang.bind(this, function() { print("EOS"); this._playbin.set_state(Gst.State.NULL); this._stateChangeCallback(State.STOPPED); })); }, });
JavaScript
CL
8eac15324f13b0bd9d6d3f3ba3dd46ebf38f155287b1ff0080d774606695a12d
// John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. // For example, there are socks with colors . There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is . // Function Description // Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available. // sockMerchant has the following parameter(s): // n: the number of socks in the pile // ar: the colors of each sock // Input Format // The first line contains an integer , the number of socks represented in . // The second line contains space-separated integers describing the colors of the socks in the pile. // Constraints // where // Output Format // Return the total number of matching pairs of socks that John can sell. // Sample Input // 9 // 10 20 20 10 10 30 50 10 20 // Sample Output // 3 'use strict'; const fs = require('fs'); process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.replace(/\s*$/, '') .split('\n') .map(str => str.replace(/\s*$/, '')); main(); }); function readLine() { return inputString[currentLine++]; } // Complete the sockMerchant function below. // // // //////////////////////////////////////////// //////////////////////////////////////////// // //Main function just below // // /////////////////////////////////////////// function sockMerchant(n, ar) { //look into the array //make into a dictionary //go back through the dictionary for each color, divide by two an round down //add that number to the count //return count let storage = {}; for (let i = 0; i < n; i++) { let color = ar[i] if (storage[color]) { storage[color] += 1; } else { storage[color] = 1; } } let pairs = 0; for (let sock in storage) { pairs += Math.floor(storage[sock] / 2); } return pairs; } function main() { const ws = fs.createWriteStream(process.env.OUTPUT_PATH); const n = parseInt(readLine(), 10); const ar = readLine().split(' ').map(arTemp => parseInt(arTemp, 10)); let result = sockMerchant(n, ar); ws.write(result + "\n"); ws.end(); }
JavaScript
CL
9365d8be9be7157b61338b7fdac7b0b2f2b61d4d78de8d1bc2ec1e962e89d314
// VERSION 2.4.3 Modules.UTILS = true; Modules.CLEAN = false; // window - Similarly to Windows.callOnMostRecent, the window property returns the most recent navigator:browser window object this.__defineGetter__('window', function() { return Services.wm.getMostRecentWindow('navigator:browser'); }); // document - Returns the document object associated with the most recent window object this.__defineGetter__('document', function() { return window.document; }); // Styles - handle loading and unloading of stylesheets in a quick and easy way this.__defineGetter__('Styles', function() { delete this.Styles; Modules.load('utils/Styles'); return Styles; }); // Windows - Aid object to help with window tasks involving window-mediator and window-watcher this.__defineGetter__('Windows', function() { delete this.Windows; Modules.load('utils/Windows'); return Windows; }); // Browsers - Aid object to track and perform tasks on all document browsers across the windows this.__defineGetter__('Browsers', function() { Windows; delete this.Browsers; Modules.load('utils/Browsers'); return Browsers; }); // Messenger - Aid object to communicate with browser content scripts (e10s). this.__defineGetter__('Messenger', function() { delete this.Messenger; Modules.load('utils/Messenger'); return Messenger; }); // Observers - Helper for adding and removing observers this.__defineGetter__('Observers', function() { delete this.Observers; Modules.load('utils/Observers'); return Observers; }); // Overlays - to use overlays in my bootstraped add-ons this.__defineGetter__('Overlays', function() { Browsers; Observers; Piggyback; delete this.Overlays; Modules.load('utils/Overlays'); return Overlays; }); // Keysets - handles editable keysets for the add-on this.__defineGetter__('Keysets', function() { Windows; delete this.Keysets; Modules.load('utils/Keysets'); return Keysets; }); // Keysets - handles editable keysets for the add-on this.__defineGetter__('PrefPanes', function() { Browsers; delete this.PrefPanes; Modules.load('utils/PrefPanes'); return PrefPanes; }); // DnDprefs - this.__defineGetter__('DnDprefs', function() { delete this.DnDprefs; Modules.load('utils/DnDprefs'); return DnDprefs; }); // closeCustomize() - useful for when you want to close the customize tabs for whatever reason this.closeCustomize = function() { Windows.callOnAll(function(aWindow) { if(aWindow.gCustomizeMode) { aWindow.gCustomizeMode.exit(); } }, 'navigator:browser'); }; Modules.UNLOADMODULE = function() { Modules.clean(); };
JavaScript
CL
a9672dc903a6ce8bef0d1b962ce064985ad380807198a7d51f423726b5f65893
console.log('Hello world, this is a test.'); //console.log = print = cout let temp_var = "Some value goes here"; // Puntos y coma como C++ son requisito en algunas secciones // 'let' se usa para hacer variables, tambien se usa 'var' y se hace igual que C++ console.log(temp_var); let Person = { name: undefined, age: undefined, isApproved: false // Person Object }; function cambio() { alert('Undiste el boton'); } // console.warn("Solo es un warning chiquito"); /* Documentation string como C++. Primitie data types: 1 - Strings (Escape sequences iguales que Python y C++) 2 - Number 3 - Bool (true/false --> minuscula) 4 - undefined ('undefined') 5 - Null (used when explicitly want to clear the value of a variable) Objects: Ex. let Person = { name: "John", age: 21 }; - Se puede usar dor operator Person.name - Se puede usar bracket operator Person["name"] Arrays: - Syntax igual que Python - Son dinamicos de por si y el largo del array puede cambiar whenever - ".shift()" saca el primer item, ".pop()" saca el ultimo - ".unshift()" agrega por el principio, ".push()" por el final Functions: - Se define una funcion con el keyword "function" seguido por el nombre de la funcion - No llevan punto y coma al final como los objetos - 'return' se usa aqui tambien For loops: - for (*let or var* *variable* 'of' *iterable*) */
JavaScript
CL
0cd6cdf753c48a527edddf2f80de9c1a82fa64f3f5dee564f09fdf2573958579
/******************************************************************************************************* * File: upload.js * Project: hootenanny-ui * @author Matt Putipong - matt.putipong@radiantsolutions.com on 7/5/18 *******************************************************************************************************/ import { d3combobox } from '../../../../lib/hoot/d3.combobox'; export default class Upload { constructor( instance ) { this.instance = instance; this.schemaOpts = Hoot.translations.availableTranslations.map(v => { return { key: v, value: v }; }); this.uploadButtons = [ { title: 'Upload File(s)', icon: 'play_for_work', uploadType: 'FILE', multiple: true, accept: '.shp, .shx, .dbf, .zip, .geojson, .gpkg' }, { title: 'Upload Folder', icon: 'move_to_inbox', uploadType: 'DIR', multiple: false, webkitdirectory: '', directory: '' } ]; } render() { this.createUploadForm(); this.createSchemaSelector(); this.createUploadButtons(); } createUploadForm() { this.uploadForm = this.instance.panelWrapper .append( 'form' ) .classed( 'ta-upload-form round keyline-all fill-white', true ); } createSchemaSelector() { let schemaListContainer = this.uploadForm .append( 'div' ) .classed( 'ta-filter-container ta-schema-select fill-dark0 keyline-bottom', true ) .classed( 'inline schema-option', true ); let control = schemaListContainer .append( 'div' ) .classed( 'ta-filter-control', true ); control .append( 'label' ) .text( 'Tag Schema' ); let combobox = d3combobox().data(this.schemaOpts); control .append( 'input' ) .classed('inline schema-option', true) .attr( 'type', 'text' ) .attr( 'id', 'tagSchema' ) .attr( 'value', 'OSM' ) .attr( 'readonly', true ) .call(combobox); } createUploadButtons() { let that = this; let buttonContainer = this.uploadForm .append( 'div' ) .classed( 'button-row pad2', true ) .selectAll( 'button' ) .data( this.uploadButtons ); let buttons = buttonContainer .enter() .append( 'button' ) .attr( 'type', 'button' ) .classed( 'primary text-light big', true ) .on( 'click', function() { d3.select( this ).select( 'input' ).node().click(); } ); buttons .append( 'input' ) .attr( 'type', 'file' ) .attr( 'name', 'taFiles' ) .attr( 'multiple', d => d.multiple ) .attr( 'accept', d => d.accept && d.accept ) .attr( 'webkitdirectory', d => d.webkitdirectory && d.webkitdirectory ) .attr( 'directory', d => d.directory && d.directory ) .classed( 'hidden', true ) .on( 'click', () => d3.event.stopPropagation() ) .on( 'change', function( d ) { that.processSchemaData( d3.select( this ).node(), d.uploadType ); } ); buttons .append( 'i' ) .classed( 'material-icons', true ) .text( d => d.icon ); buttons .append( 'span' ) .classed( 'label', true ) .text( d => d.title ); } async processSchemaData( input, type ) { let formData = new FormData(); for ( let i = 0; i < input.files.length; i++ ) { let file = input.files[ i ]; formData.append( i, file ); } // reset the file input value so on change will fire // if the same files/folder is selected twice in a row input.value = null; return Hoot.api.uploadSchemaData( type, formData ) .then( resp => { this.loadingState(d3.select(input.parentElement), true); this.jobId = resp.data.jobId; return Hoot.api.statusInterval( this.jobId ); } ) .then( resp => { let message; if (resp.data && resp.data.status === 'cancelled') { message = 'Translation Assistant job cancelled'; } else { message = 'Translation Assistant job completed'; } Hoot.message.alert( { data: resp.data, message: message, status: 200, type: resp.type } ); return resp; } ) .then( async (resp) => { if (resp.data && resp.data.status !== 'cancelled') { const attrValues = await Hoot.api.getSchemaAttrValues( this.jobId ); const valuesMap = this.convertUniqueValues( attrValues ); this.instance.initMapping( valuesMap ); } } ) .catch( err => { console.error( err ); let message = 'Error running Translation Assistant', status = err.status, type = err.type; return Promise.reject( { message, status, type } ); } ) .finally( () => { this.loadingState(d3.select(input.parentElement), false); } ); } convertUniqueValues( json ) { let obj = {}; d3.values( json ).forEach( v => { d3.entries( v ).forEach( e => { let map = d3.map(); d3.entries( e.value ).forEach( a => { // Omit empty fields if ( a.value.length ) { map.set( a.key, d3.set( a.value ) ); } } ); obj[ e.key ] = map; } ); } ); return obj; } loadingState(submitButton, isLoading) { const text = isLoading ? 'Cancel Upload' : submitButton.data()[0].title; submitButton .select( 'span' ) .text( text ); const spinnerId = 'importSpin'; if (isLoading) { // overwrite the submit click action with a cancel action submitButton.on( 'click', () => { Hoot.api.cancelJob(this.jobId); } ); submitButton .append( 'div' ) .classed( '_icon _loading float-right', true ) .attr( 'id', spinnerId ); } else { // reattach old click event submitButton.on('click', function() { submitButton.select( 'input' ).node().click(); }); submitButton .select(`#${ spinnerId }`) .remove(); } } }
JavaScript
CL
bcf5d6388fdac2291f0ce8016460c225d5b11cc9f85a49004c5726a0b4a02026
import { Reducer } from 'redux-testkit'; import Immutable from 'seamless-immutable'; import addEvent from '../events/addEvent'; import { ADD_EVENT_FULFILLED, ADD_EVENT_PENDING, ADD_EVENT_REJECTED, ADD_EVENT_RETURN_TO_INITIAL_STATE } from '../../constants/Events'; const initialState = { pending: false, received: false, error: null }; describe('reducers/events/addEvent', () => { it('should have initial state', () => { expect(addEvent()).toEqual(initialState); }); it('should not affect state', () => { Reducer(addEvent).expect({ type: 'NOT_EXISTING' }).toReturnState(initialState); }); it('should set pending to true on pending', () => { const action = { type: ADD_EVENT_PENDING }; Reducer(addEvent).expect(action).toReturnState({ ...initialState, pending: true }); }); it('should set pending state to false and received state to true on fulfilled', () => { const action = { type: ADD_EVENT_FULFILLED }; Reducer(addEvent).expect(action).toReturnState({ ...initialState, pending: false, received: true }); }); it('should set pending and received state to false, and set error on rejected', () => { const action = { type: ADD_EVENT_REJECTED, payload: 'Some error' }; Reducer(addEvent) .expect(action) .toReturnState({ ...initialState, pending: false, received: false, error: action.payload }); }); it('should set existing state to initial state on return to initial state', () => { const existingState = Immutable({ ...initialState, error: 'Some error', received: true }); const action = { type: ADD_EVENT_RETURN_TO_INITIAL_STATE }; Reducer(addEvent).withState(existingState).expect(action).toReturnState(initialState); }); });
JavaScript
CL
de81bd8a48e91be4ed074f2bd15cd87928a38d9cbbef5934173e47d8ece66aa6
/** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ require(['domready', 'style/main.scss', 'grid/Grid', 'interface/Bottom', 'sound/Sequencer', 'Tone/core/Transport', 'sound/Player', 'node_modules/startaudiocontext', 'grid/ML', 'data/Config', 'node_modules/firebase/app'], //'node_modules/@google-cloud/storage'], function(domReady, mainStyle, Grid, Bottom, Sequencer, Transport, Player, StartAudioContext, ML, Config, Firebase) { domReady(function() { var fConfig = { apiKey: "AIzaSyCj6NshDarYyN80l06qQjxYRuu1hbQYqAo", authDomain: "melodymaker-17f94.firebaseapp.com", databaseURL: "https://melodymaker-17f94.firebaseio.com", projectId: "melodymaker-17f94", storageBucket: "melodymaker-17f94.appspot.com", messagingSenderId: "976762320760" }; Firebase.initializeApp(fConfig); var storage = Storage({ projectid: "melodymaker-17f94", storageBucket: "melodymaker-17f94.appspot.com" }); var storageRef = storage.ref(); Config.gridWidth = Config.subdivisions*Config.beatsPerMeasure*Config.numMeasures; window.parent.postMessage("loaded", "*"); var grid = new Grid(document.body); var ml = new ML(document.body); var bottom = new Bottom(document.body); bottom.onDirection = function(dir) { grid.setDirection(dir); }; bottom.removeML = function() { grid.removeML(); }; ml.addTile = function(x, y, hover, ml, prob){ grid._addTile(x, y, hover, ml, prob); }; ml.getGridState = function(){ return grid.getState(); }; bottom.generatePattern = function(temperature) { ml.generatePattern(temperature); }; var player = new Player(); var seq = new Sequencer(function(time, step) { var notes = grid.select(step); player.play(notes, time); }); grid.onNote = function(note) { player.tap(note); }; Transport.on('stop', function() { grid.select(-1); }); Transport.setLoopPoints(0,Config.numMeasures.toString()+"m") // // Modal // // TODO: Refactor this into its own file // Get the <span> element that closes the modal var settingsSpan = document.getElementById("closeSettings"); var introSpan = document.getElementById("closeIntro"); // Get the modal var introModal = document.getElementById('introModal'); var settingsModal = document.getElementById("settingsModal") // // When the user clicks on <span> (x), close the modal // settingsSpan.onclick = function() { settingsModal.style.display = "none"; bottom._settingsButtonClicked(); } introSpan.onclick = function() { introModal.style.display = "none"; } // // When the user clicks anywhere outside of the modal, close it // window.onclick = function(event) { if (event.target == settingsModal) { settingsModal.style.display = "none"; bottom._settingsButtonClicked(); } else if (event.target == introModal) { introModal.style.display = "none"; } } // Add models to settings modal var modelDiv = document.getElementById("ModelSettings"); for (var i = 0; i < Config.modelNames.length; i++){ var button = document.createElement("input"); button.setAttribute("name","model"); button.setAttribute("type","radio"); button.modelIndex = i; if (i == Config.activeModel) { button.checked = true; } var label = document.createElement("span"); label.innerHTML = Config.modelNames[i]; modelDiv.appendChild(button); modelDiv.appendChild(label); modelDiv.appendChild(document.createElement("br")); // Update settings on click button.addEventListener("click", function(){ Config.activeModel = this.modelIndex; ml._initModel(this.modelIndex); }) } // Grid Settings functionality var measureNumInput = document.getElementById("MeasureNum"); measureNumInput.defaultValue = Config.numMeasures; measureNumInput.onchange = function(){ var diff, i, harmonyOn = false; // If harmony is on, then we have to turn it off first if (bottom._directionIndex != 0){ harmonyOn = true; bottom._directionClicked(); } Config.numMeasures = this.value; var newWidth = Config.subdivisions*Config.beatsPerMeasure*Config.numMeasures; diff = newWidth - Config.gridWidth; Config.gridWidth = newWidth; if (diff > 1){ // Increase size of array for (i = 0; i < diff ; i++){ grid._tiles.push(null); grid._mlTiles.push(null); } } else { // Decrease size of array for (i = 0; i > diff ; i--){ grid._tiles.pop(null); grid._mlTiles.pop(null); } } if (harmonyOn){ bottom._directionClicked(); } else { grid._ai = []; } grid._resize(); seq.changeSequenceLength(function(time, step) { var notes = grid.select(step); player.play(notes, time); }); Transport.setLoopPoints(0,Config.numMeasures.toString()+"m"); console.log("tiles",grid._tiles); }; // // Keyboard shortcuts // document.body.addEventListener('keyup', function(e) { var key = e.which; // // Pause/play on spacebar // if (key === 32){ bottom._playClicked(e); } // // Move last note on arrow press // else if (key === 37){ // Left arrow pressed // grid.lastDragTile } else if (key === 39){ // Right arrow pressed } else if (key === 38){ // Up arrow pressed } else if (key === 40){ // Down arrow pressed } }) //send the ready message to the parent var isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; var isAndroid = /Android/.test(navigator.userAgent) && !window.MSStream; //full screen button on iOS if (isIOS || isAndroid){ //make a full screen element and put it in front var iOSTapper = document.createElement("div"); iOSTapper.id = "iOSTap"; document.body.appendChild(iOSTapper); new StartAudioContext(Transport.context, iOSTapper).then(function() { iOSTapper.remove(); window.parent.postMessage('ready','*'); }); } else { window.parent.postMessage('ready','*'); } }); });
JavaScript
CL
224ff587f4d801ba766a3ddcbe438767fb4b8e8b1246f5e7d85f541831423c8f
////////////////////////////////////////////////////////////////////////////// // Nation Website 2016 // Latest work slideshow // Author: Chris Bews ////////////////////////////////////////////////////////////////////////////// (function(window, document, undefined) { "use strict"; NATION.Utils.createNamespace("NATION2016.views.work"); //------------------------------------------------ // Constructor //------------------------------------------------ var WorkSlideshow = function(element, options) { this.__DOMElement = element; NATION.Slideshow.call(this, element, options); this.__flourish = this.__DOMElement.querySelector(".js-flourish"); this.__customStylesheet = null; this.deaultMediaTransform = "translateX(-5%) translateY(-5%)"; this.currentMediaX = -5; this.currentMediaY = -5; this.targetMediaX = 0; this.targetMediaY = 0; this.mouseRequest = null; this.projectButtonLength = 0; this.animatedButtons = []; this.createAnimatedButtons(); this.createSlideStyles(); this.setFlourishColors(0, true); } WorkSlideshow.prototype = Object.create(NATION.Slideshow.prototype); WorkSlideshow.prototype.constructor = WorkSlideshow; //------------------------------------------------ // Create an animated vector button for each slide //------------------------------------------------ WorkSlideshow.prototype.createAnimatedButtons = function() { var buttonElements = this.__DOMElement.querySelectorAll(".js-project-button"); var i = 0, length = buttonElements.length; for (; i < length; i++) { this.animatedButtons.push(new NATION2016.views.global.AnimatedVectorButton(buttonElements[i])); } } //------------------------------------------------ // Listen for mouse movements to position the active // slide's background dynamically in response //------------------------------------------------ WorkSlideshow.prototype.createListeners = function() { NATION.Slideshow.prototype.createListeners.call(this); if (!NATION2016.Settings.TOUCH_DEVICE) { // Listen for mouse move events this.handler_mouseMoved = this.onMouseMoved.bind(this); this.__DOMElement.addEventListener("mousemove", this.handler_mouseMoved); this.onMouseTimerTicked(); } } //------------------------------------------------ // Cleanup before the slideshow is removed from the page //------------------------------------------------ WorkSlideshow.prototype.destroy = function() { document.getElementsByTagName("head")[0].removeChild(this.__customStylesheet); // Stop any potentially running animations var __previousSlideImage = this.__slideElements[this.previousSlideID].querySelector(".js-slide-image"); NATION.Animation.stop(__previousSlideImage); var __nextSlide = this.__slideElements[this.currentSlideID]; NATION.Animation.stop(__nextSlide); var __nextSlideOverlay = __nextSlide.querySelector(".js-overlay"); NATION.Animation.stop(__nextSlideOverlay); // Remove extra listeners if (!NATION2016.Settings.TOUCH_DEVICE) { this.__DOMElement.removeEventListener("mousemove", this.handler_mouseMoved); if (this.mouseRequest) { cancelAnimationFrame(this.mouseRequest); this.mouseRequest = null; } var i = 0, length = this.animatedButtons.length; for (; i < length; i++) { this.animatedButtons[i].destroy(); } } } //------------------------------------------------ // Resize each animated button to ensure it wraps // correctly around it's text //------------------------------------------------ WorkSlideshow.prototype.resize = function() { var i = 0, length = this.animatedButtons.length; for (; i < length; i++) { this.animatedButtons[i].resize(); } } //------------------------------------------------ // Generate new style rules for each slide's colour scheme //------------------------------------------------ WorkSlideshow.prototype.createSlideStyles = function() { var newCSS = ""; // Create new CSS rules var i = 0, length = this.__slideElements.length, primaryColor, summaryBG, summaryCopy, summaryArrow, slideID = 0; for (; i < length; i++) { slideID = i + 1; primaryColor = this.__slideElements[i].getAttribute("data-primary-color"); summaryBG = this.__slideElements[i].getAttribute("data-summary-bg"); summaryCopy = this.__slideElements[i].getAttribute("data-summary-copy"); summaryArrow = this.__slideElements[i].getAttribute("data-summary-arrow"); // Set new rules for each slide newCSS += ".work-latest .js-slide:nth-child(" + slideID + ") .js-primary {\n"; newCSS += " color: " + primaryColor + ";\n"; newCSS += "}\n"; newCSS += ".work-latest .js-slide:nth-child(" + slideID + ") {\n"; newCSS += " background: " + summaryBG + ";\n"; newCSS += "}\n"; // Set new rules for each project button newCSS += ".work-latest .js-slide:nth-child(" + slideID + ") .js-foreground-shape {\n"; newCSS += " stroke: " + primaryColor + ";\n"; newCSS += "}\n"; // Set new rules for the summary background newCSS += ".work-latest .js-slide:nth-child(" + slideID + ") .project-summary {\n"; newCSS += " background: " + summaryBG + ";\n"; newCSS += "}\n"; newCSS += ".work-latest .js-slide:nth-child(" + slideID + ") .summary-body {\n"; newCSS += " color: " + summaryCopy + ";\n"; newCSS += "}\n"; // Set new rules for the summary background newCSS += ".work-latest .js-slide:nth-child(" + slideID + ") .project-summary .view-details-button:after {\n"; newCSS += " border-color: " + summaryArrow + ";\n"; newCSS += "}\n"; // Set new rules for each pip newCSS += ".work-latest .js-pips li:nth-child(" + slideID + ") a:hover,\n"; newCSS += ".work-latest .js-pips li:nth-child(" + slideID + ") a.active {\n"; newCSS += " color: " + primaryColor + ";\n"; newCSS += "}\n"; newCSS += ".work-latest .js-pips li:nth-child(" + slideID + ") .active .number:after,"; newCSS += ".work-latest .js-pips li:nth-child(" + slideID + ") a:hover .number:after {\n"; newCSS += " background: " + primaryColor + ";\n"; newCSS += "}\n"; } this.__customStylesheet = document.createElement("style"); if (this.__customStylesheet.stylesheet) { this.__customStylesheet.stylesheet.cssText = newCSS; } else { this.__customStylesheet.appendChild(document.createTextNode(newCSS)); } document.getElementsByTagName("head")[0].appendChild(this.__customStylesheet); i = 0; for (; i < length; i++) { // Hide slides except the first one if (i > 0) { NATION.Utils.setStyle(this.__slideElements[i], {transform: "translateY(100%)"}); } } } //------------------------------------------------ // Show a slide specified by slideID //------------------------------------------------ WorkSlideshow.prototype.showSlideByID = function(slideID, reverse, immediate) { // NATION.Slideshow.prototype.showSlideByID.call(this, slideID, reverse, immediate); if (slideID !== this.currentSlideID && !this.animating) { if (!immediate) { this.animating = true; } if (this.autoCycling && this.cycleTimer) { clearTimeout(this.cycleTimer); this.cycleTimer = null; } var __previousSlide = this.__slideElements[this.currentSlideID]; var __nextSlide = this.__slideElements[slideID]; var __previousSlideImage = __previousSlide.querySelector(".js-slide-image"); var __nextSlideOverlay = __nextSlide.querySelector(".js-overlay"); if (!immediate) { // Swap slide depths to ensure next slide is on top of previous slide NATION.Utils.setStyle(__previousSlide, {transform: "translateY(0)", zIndex: "auto"}); NATION.Utils.setStyle(__nextSlide, {transform: "translateY(100%)", zIndex: 20}); // Animate current slide out NATION.Utils.setStyle(__previousSlideImage, {transform: "translate(-50%, -50%)"}); NATION.Animation.start(__previousSlideImage, {transform: "translate(-50%, -57%)"}, {duration: this.options.duration, easing: this.options.easing}); // Animate new slide in NATION.Animation.start(__nextSlide, {transform: "translateY(0)"}, {duration: this.options.duration, easing: this.options.easing}); // Fade in the overlay after a delay NATION.Utils.setStyle(__nextSlideOverlay, {opacity: 0}); NATION.Animation.start(__nextSlideOverlay, {opacity: 1}, {delay: 250, duration: this.options.duration, easing: this.options.easing}, this.onSlideAnimationComplete.bind(this)); } else { NATION.Utils.setStyle(__previousSlide, {transform: "translateY(100%)", zIndex: "auto"}); NATION.Utils.setStyle(__nextSlide, {transform: "translateY(0)", zIndex: 20}); } if (this.options.pips) this.updatePips(this.currentSlideID, slideID); // Set the new slide as the current one this.previousSlideID = this.currentSlideID; this.currentSlideID = slideID; // Get next slide into the right position for the mouse this.positionSlideMedia(); this.setFlourishColors(slideID); this.trigger(this.SLIDE_CHANGE); } } //------------------------------------------------ // Animate the flourish to the new slide's colour // scheme, or fade it out if it's not needed for // the current slide //------------------------------------------------ WorkSlideshow.prototype.setFlourishColors = function(slideID, immediate) { var __slide = this.__slideElements[slideID]; // If the next slide should show the flourish if (__slide.getAttribute("data-has-flourish")) { var primaryColor = __slide.getAttribute("data-primary-color"); // Set fill colours where needed var __graphics = this.__flourish.querySelectorAll(".js-flourish-graphic"); for (var i = 0, length = __graphics.length; i < length; i++) { if (!immediate) { NATION.Animation.start(__graphics[i], {fill: primaryColor}, {duration: 500}); } else { __graphics[i].style.fill = primaryColor; } } // Set stroke colours where needed if (!immediate) { NATION.Animation.start(this.__flourish.querySelector(".js-flourish-line"), {stroke: primaryColor}, {duration: 500}); } else { this.__flourish.querySelector(".js-flourish-line").style.stroke = primaryColor; } // Fade flourish back in if needed if (this.__flourish.style.opacity !== 1) { if (!immediate) { NATION.Animation.start(this.__flourish, {opacity: 1}, {duration: 300}); } else { this.__flourish.style.opacity = 1; } } } else { // If flourish is not needed for this slide, fade it out if (this.__flourish.style.opacity !== 0) { if (!immediate) { NATION.Animation.start(this.__flourish, {opacity: 0}, {duration: 300}); } else { this.__flourish.style.opacity = 0; } } } } //------------------------------------------------ // Stop animation of the flourish elements //------------------------------------------------ WorkSlideshow.prototype.stopFlourishAnimations = function() { var __graphics = this.__flourish.querySelectorAll(".js-flourish-graphic"); for (var i = 0, length = __graphics.length; i < length; i++) { NATION.Animation.stop(__graphics[i]); } NATION.Animation.stop(this.__flourish.querySelector(".js-flourish-line")); NATION.Animation.stop(this.__flourish.querySelector(".js-flourish-line")); NATION.Animation.stop(this.__flourish); } //------------------------------------------------ // Reset the previous slide's state //------------------------------------------------ WorkSlideshow.prototype.onSlideAnimationComplete = function(e) { NATION.Slideshow.prototype.onSlideAnimationComplete.call(this, e); var __previousSlideImage = this.__slideElements[this.previousSlideID].querySelector(".js-slide-image"); NATION.Utils.setStyle(__previousSlideImage, {transform: "translate(-50%, -50%)"}); NATION.Utils.setStyle(this.__slideElements[this.previousSlideID], {transform: "translateY(100%)"}); var previousSlideMedia = this.__slideElements[this.previousSlideID].querySelector(".js-media"); NATION.Utils.setStyle(previousSlideMedia, {transform: this.deaultMediaTransform}); } //------------------------------------------------ // Work out the new target position for the active // slide's background image //------------------------------------------------ WorkSlideshow.prototype.onMouseMoved = function(e) { if (!this.animating) { var percentageX = e.pageX / this.__DOMElement.offsetWidth; var percentageY = e.pageY / this.__DOMElement.offsetHeight; // Images are at 110% width/height var newX = -(percentageX * 5); var newY = -(percentageY * 5); this.targetMediaX = newX; this.targetMediaY = newY; } } //------------------------------------------------ // Ease towards the target position for the slide image //------------------------------------------------ WorkSlideshow.prototype.onMouseTimerTicked = function() { if (!this.animating) { var diffX = (this.targetMediaX - this.currentMediaX)/10; var diffY = (this.targetMediaY - this.currentMediaY)/10; this.currentMediaX = Math.round((this.currentMediaX + diffX) * 1000) / 1000; this.currentMediaY = Math.round((this.currentMediaY + diffY) * 1000) / 1000; // Actually positon the image this.positionSlideMedia(); } // Reposition again on the next frame this.mouseRequest = requestAnimationFrame(this.onMouseTimerTicked.bind(this)); } //------------------------------------------------ // Set the new position of the slide's background // image as it gradually moves towards the new // target position //------------------------------------------------ WorkSlideshow.prototype.positionSlideMedia = function() { var activeSlide = this.__slideElements[this.currentSlideID].querySelector(".js-media"); NATION.Utils.setStyle(activeSlide, {transform: "translateX(" + this.currentMediaX + "%) translateY(" + this.currentMediaY + "%)"}); } //------------------------------------------------ // Clear changed styles on the current slide //------------------------------------------------ WorkSlideshow.prototype.resetSlideMedia = function(immediate, duration, easing) { var activeSlideMedia = this.__slideElements[this.currentSlideID].querySelector(".js-media"); if (!immediate) { NATION.Animation.start(activeSlideMedia, {transform: this.deaultMediaTransform}, {duration: duration, easing: easing}); } else { NATION.Utils.setStyle(activeSlideMedia, {transform: this.deaultMediaTransform}); } if (this.mouseRequest) { cancelAnimationFrame(this.mouseRequest); this.mouseRequest = null; } } window.NATION2016.views.work.WorkSlideshow = WorkSlideshow; }(window, document, undefined));
JavaScript
CL
93464bbdd023609640b6ce83b659595031b38e8074bd0d41a054ba791337030e
import React, { useState, useEffect } from "react"; import { makeStyles } from "@material-ui/core/styles"; import clsx from "clsx"; import Card from "@material-ui/core/Card"; import CardHeader from "@material-ui/core/CardHeader"; import CardMedia from "@material-ui/core/CardMedia"; import CardContent from "@material-ui/core/CardContent"; import Avatar from "@material-ui/core/Avatar"; import Typography from "@material-ui/core/Typography"; import { red } from "@material-ui/core/colors"; import MoreVertIcon from "@material-ui/icons/MoreVert"; import firebase from "firebase"; import { Dropdown, Form, Col, Row, Image } from "react-bootstrap"; import { db } from "../../firebase"; import "./Post.scss"; const useStyles = makeStyles((theme) => ({ root: { // maxWidth: 345, }, media: { height: 0, paddingTop: "56.25%", // 16:9 width: "100%", }, avatar: { backgroundColor: red[500], }, })); const Post = ({ postId, post, loggedInUser }) => { const { caption, imageUrl, username } = post; const [comments, setComments] = useState([]); const [comment, setComment] = useState(""); useEffect(() => { if (post) { const unsubscribe = db .collection("posts") .doc(postId) .collection("comments") .orderBy("timestamp", "asc") .onSnapshot((snapshot) => { setComments( snapshot.docs.map((doc) => ({ commentId: doc.id, comment: doc.data(), })) ); }); return () => { unsubscribe(); }; } }, [post, postId]); const submitCommentHandler = (event) => { db.collection("posts").doc(postId).collection("comments").add({ text: comment, username: loggedInUser, timestamp: firebase.firestore.FieldValue.serverTimestamp(), }); setComment(""); }; const classes = useStyles(); return ( <div className="post"> <Card className={classes.root}> <CardHeader avatar={ <Avatar aria-label="recipe" className={classes.avatar}> R </Avatar> } action={ <MoreVertIcon /> } title={username} /> <CardMedia alt="Contemplative Reptile" className={classes.media} image={imageUrl} title="Paella dish" /> <CardContent> <Typography className={clsx("post__caption")} variant="body2" color="textSecondary" component="p" > <strong>{username}</strong> {caption} </Typography> {comments.length ? comments.map(({ commentId, comment: { username, text } }) => ( <Typography key={commentId} variant="body2" color="textSecondary" component="p" className={clsx("post__comment")} > <strong>{username}</strong> {text} </Typography> )) : null} {loggedInUser ? ( <div className="post__newComment"> <input type="text" value={comment} placeholder="Add a comment..." onChange={(event) => setComment(event.target.value)} /> <button type="button" onClick={submitCommentHandler} disabled={!comment} > Post </button> </div> ) : null} </CardContent> </Card> </div> ); }; export default Post;
JavaScript
CL
9c9e108d5335b2ef5b7e966d61ad1d65a9e36d39e6d54c3cd2b7b9163fc86a52
// Import React import React from 'react'; // Import Spectacle Core tags import { Appear, BlockQuote, Cite, CodePane, Deck, Heading, Image, // Layout, // Link, ListItem, List, Notes, Quote, Slide, Text, } from 'spectacle'; // Import image preloader util import preloader from 'spectacle/lib/utils/preloader'; // Import theme import createTheme from 'spectacle/lib/themes/default'; const secondaryColor = '#f5fbff'; const tertiaryColor = '#baccde'; const theme = createTheme( { primary: '#2e3648', secondary: secondaryColor, tertiary: tertiaryColor, quartenary: '#772e2e', }, { primary: 'Montserrat', secondary: 'Montserrat', } ); // console.log(theme.screen); theme.screen.components.codePane.fontSize = '0.7rem'; theme.screen.components.heading.h2.color = tertiaryColor; theme.screen.components.heading.h3.color = tertiaryColor; theme.screen.components.heading.h4.color = tertiaryColor; theme.screen.components.heading.h5.color = tertiaryColor; theme.screen.components.heading.h6.color = tertiaryColor; theme.screen.components.image.display = 'inline'; theme.screen.components.quote.fontSize = '3.9rem'; theme.screen.components.text.color = secondaryColor; // Fix line height theme.screen.components.listItem.lineHeight = 1.28; theme.screen.components.quote.lineHeight = 1.28; theme.screen.components.text.lineHeight = 1.28; // Require CSS require('normalize.css'); const images = { jeffMorrison: require('../assets/jeffMorrison.jpg'), jordanHarband: require('../assets/jordanHarband.jpg'), llvmBackend: require('../assets/llvm-backend.png'), logoAdobe: require('../assets/logo-adobe.svg'), logoAirbnb: require('../assets/logo-airbnb.svg'), logoApple: require('../assets/logo-apple.svg'), logoEbay: require('../assets/logo-ebay.svg'), logoFacebook: require('../assets/logo-facebook.svg'), logoGoogle: require('../assets/logo-google.svg'), logoIntel: require('../assets/logo-intel.svg'), logoJquery: require('../assets/logo-jquery.svg'), logoMozilla: require('../assets/logo-mozilla.svg'), logoMicrosoft: require('../assets/logo-microsoft.svg'), logoOpera: require('../assets/logo-opera.svg'), logoPaypal: require('../assets/logo-paypal.svg'), logoSamsung: require('../assets/logo-samsung.svg'), logoW3C: require('../assets/logo-w3c.svg'), logoYahoo: require('../assets/logo-yahoo.svg'), reactVirtualDom: require('../assets/react-virtual-dom.svg'), sebastianMarkbage: require('../assets/sebastianMarkbage.jpg'), sebastianMarkbage2: require('../assets/sebastianMarkbage-2.jpg'), twitterTranspilation: require('../assets/twitter-transpilation.png'), }; preloader(images); export default class Presentation extends React.Component { render() { return ( <Deck progress="none" theme={theme} transition={['fade', ]} transitionDuration={0} controls={false} contentWidth={1024} contentHeight={768} > <Slide> <Heading size={1}>The Effect of React on Web Standards</Heading> <Notes> Personal intro <List> <ListItem>Canadian / Austrian JavaScript Engineer</ListItem> <ListItem>Twitter handle top right</ListItem> </List> Talk <List> <ListItem>Canadian / Austrian JavaScript Engineer</ListItem> <ListItem>slides top left</ListItem> <ListItem>Twitter handle top right</ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}> The Effect of React on <br /> Web Standards </Heading> <List> <ListItem>Web Standards: Definitions</ListItem> <ListItem>Discontent, New Approaches</ListItem> <ListItem>React: Principles, Opinions</ListItem> <ListItem>Web Standards Proposals</ListItem> <ListItem>Future: Convergence</ListItem> </List> <Notes> <List> <ListItem>Standards: What, Who, How</ListItem> <ListItem> Discontent with web standards and new approaches with simplified APIs </ListItem> <ListItem> React: Principles, Embracing standards, discontent with standards, comparison to web components, who is involved, other influences </ListItem> <ListItem>Web Standards Proposals</ListItem> <ListItem> Future: Integration efforts, specs, alternatives to the DOM, new languages </ListItem> </List> </Notes> </Slide> <Slide> <Heading size={1}>React</Heading> <Heading size={2}>Not just a library</Heading> <List style={{ marginLeft: 65, }}> <Appear> <ListItem textSize={70}>A Paradigm</ListItem> </Appear> <Appear> <ListItem textSize={70}>An Ecosystem</ListItem> </Appear> <Appear> <ListItem textSize={70}>A Philosophy</ListItem> </Appear> </List> <Notes> <List> <ListItem> paradigm: declaratively describing UIs (ex. JSX). can be extended to: native app, VR, command line interfaces, music </ListItem> <ListItem> ecosystem: rich community, including members of standards committees </ListItem> <ListItem> philosophy: incl. minimalism, functional programming, immutability </ListItem> </List> </Notes> </Slide> <Slide bgColor="quartenary"> <Heading size={1} textColor="#fff7de"> Web Standards </Heading> </Slide> <Slide> <Heading size={4}>Web Standards: What?</Heading> <Heading size={5}>DOM Manipulation</Heading> <br /> <CodePane lang="javascript" source={require('raw-loader!../assets/web-standards-dom.example')} textSize={27} theme="external" /> <Notes> <List> <ListItem>one of most basic things to want w. JS</ListItem> <ListItem>verbosity</ListItem> </List> </Notes> </Slide> {/* <Slide> <Heading size={4}>Web Standards: What?</Heading> <Heading size={5}>this keyword</Heading> <br /> <CodePane lang="javascript" source={require('raw-loader!../assets/web-standards-this.example')} textSize={28} theme="external" /> <Notes>this</Notes> </Slide> */} <Slide> <Heading size={4}>Web Standards: What?</Heading> <Heading size={5}>&lt;video&gt; tag</Heading> <br /> <CodePane lang="js" source={require('raw-loader!../assets/web-standards-video.example')} textSize={15} theme="external" /> </Slide> {/* <Slide> <Heading size={4}>Web Standards: What?</Heading> <Heading size={5}>XMLHttpRequest</Heading> <br /> <CodePane lang="js" source={require('raw-loader!../assets/web-standards-xhr.example')} textSize={28} theme="external" /> <Notes>XmlHttpRequest(AJAX)</Notes> </Slide> */} <Slide> <Heading size={4}>Web Standards: What?</Heading> <Heading size={5}>Web Components</Heading> <br /> <CodePane lang="js" source={require('raw-loader!../assets/web-standards-custom-elements.example')} textSize={16} theme="external" /> <Notes>custom elements spec</Notes> </Slide> <Slide> <Heading size={4}>Web Standards: Who?</Heading> <Heading size={5}>Relevant Spec Groups</Heading> <List> <ListItem>W3C TAG</ListItem> <ListItem>TC39</ListItem> <ListItem>CSSWG</ListItem> <ListItem>CSS Houdini task force</ListItem> <ListItem>WHATWG</ListItem> <ListItem>WICG</ListItem> </List> <Notes> Which organizations make the standards? <List> <ListItem>W3C TAG</ListItem> <ListItem>TC39</ListItem> <ListItem>CSSWG</ListItem> <ListItem>CSS Houdini task force</ListItem> <ListItem>WHATWG</ListItem> <ListItem>WICG</ListItem> </List> </Notes> </Slide> <Slide bgColor="secondary"> <Heading size={4} textColor="primary"> Web Standards: Who? </Heading> <Heading size={5} textColor="primary"> Who is on the spec groups? </Heading> <div style={{ marginLeft: -30, marginRight: -30, }}> <Image src={images.logoW3C} style={{ height: 56, borderRadius: 5, marginTop: 30, }} /> <Image src={images.logoGoogle} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoMozilla} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoMicrosoft} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoApple} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, filter: 'drop-shadow( 0 0 10px #444 )', }} /> <Image src={images.logoAdobe} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoFacebook} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoIntel} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoOpera} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoEbay} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoYahoo} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoSamsung} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoPaypal} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoAirbnb} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoJquery} style={{ height: 56, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> </div> <Notes> <List> <ListItem> mostly large companies + a few invited experts </ListItem> <ListItem> orgs such as the TC39 require a fee to be paid to be a member </ListItem> </List> </Notes> </Slide> <Slide bgColor="secondary"> <Heading size={4} textColor="primary"> Web Standards: Who? </Heading> <Heading size={5} textColor="primary"> Implementers </Heading> <div style={{ marginLeft: -40, marginRight: -40, }}> <Image src={images.logoGoogle} style={{ height: 50, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoMozilla} style={{ height: 50, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoMicrosoft} style={{ height: 50, borderRadius: 5, marginLeft: 54, marginTop: 30, }} /> <Image src={images.logoApple} style={{ height: 50, borderRadius: 5, marginLeft: 54, marginTop: 30, filter: 'drop-shadow(0 0 10px #444)', }} /> </div> <Notes> But who has the final word on if, when and how the standards get published to developers? Only a handful of large companies. </Notes> </Slide> <Slide> <Heading size={4}>Web Standards: How?</Heading> <Heading size={5}>Consensus-Based</Heading> <List> <Appear> <ListItem textSize={50}>multiple stakeholders</ListItem> </Appear> <Appear> <ListItem textSize={50}> ignored recommendations or proprietary APIs </ListItem> </Appear> <Appear> <ListItem textSize={50}> vendors blocking standards{' '} <small style={{ opacity: 0.5, }}>⏎</small> </ListItem> </Appear> </List> <Notes> 3 bullets <List> <ListItem> changes need to be agreed upon by multiple stakeholders </ListItem> <ListItem> dominant market share => potential to ignore recommendations or create non-standard APIs: IE's JScript & AJAX, Chrome's default passive touch listeners) </ListItem> <ListItem> Microsoft blocking ES4 because ES4 team didn't want to consider any other options </ListItem> </List> </Notes> </Slide> <Slide bgColor="tertiary"> <BlockQuote> <Quote> We&rsquo;re instituting strong guidelines on new features that emphasize standards, interoperability, and transparency. </Quote> <Cite textColor="primary"> Chrome Team, "Chromium Developer FAQ" </Cite> </BlockQuote> <Notes> However, this is improving, with browser vendors pledging to support a more standards-based model of development </Notes> </Slide> <Slide> <Heading size={4}>Web Standards</Heading> <Heading size={5}>Different than userland</Heading> <br /> <Text lineHeight={1.4} textSize={60}> The web standards process is fundamentally different than single-owner library API development </Text> <Notes> all of this goes to show process is very diff. than userland library development where you may have monoculture </Notes> </Slide> <Slide bgColor="quartenary"> <Heading size={1} textColor="#fff7de" fit> Discontent &<br /> New Approaches </Heading> </Slide> <Slide> <Heading size={4}>Discontent with Web Standards</Heading> <List> <Appear> <ListItem textSize={50}> excessive boilerplate (verbose APIs) </ListItem> </Appear> <Appear> <ListItem textSize={50}> missing, incompatible or inadequate implementations </ListItem> </Appear> <Appear> <ListItem textSize={50}> confusing or non-memorable syntax </ListItem> </Appear> <Appear> <ListItem textSize={50}> imperative, stateful approach{' '} <small style={{ opacity: 0.5, }}>⏎</small> </ListItem> </Appear> </List> <Notes> 4 bullets <List> <ListItem textSize={20}> verbose standard APIs w. lots of ceremony </ListItem> <ListItem textSize={20}> features missing from or incompatible with 1 or more browsers, or features that just aren't good enough (ex. dialog element) </ListItem> <ListItem textSize={20}>substr vs substring, ajax</ListItem> <ListItem textSize={20}>vs. declarative, immutable APIs</ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>New Approaches</Heading> <Heading size={5}>Prototype, jQuery, Dojo, MooTools (2005-6)</Heading> <br /> <CodePane lang="js" source={require('raw-loader!../assets/jquery-post.example')} textSize={33} theme="external" /> <Notes> <List> <ListItem>some people took things into own hands</ListItem> <ListItem>ex. jQuery's take on AJAX</ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>New Approaches</Heading> <Heading size={5}>Prototype, jQuery, Dojo, MooTools (2005-6)</Heading> <br /> <CodePane lang="js" source={require('raw-loader!../assets/dojo-dom.example')} textSize={22} theme="external" /> <Notes>Ex. Dojo's take on DOM manipulation</Notes> </Slide> <Slide> <Heading size={4}>New Approaches: Inspiration</Heading> <Heading size={5}>Prototype, jQuery, Dojo, MooTools (2005-6)</Heading> <br /> <CodePane lang="js" source={require('raw-loader!../assets/jquery-querySelectorAll.example')} textSize={29} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/tE2SLC </Text> <Notes> <List> <ListItem>libs inspired improvements to web standards</ListItem> <ListItem> ex. jQuery inspr. of document.querySelectorAll </ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>New Approaches</Heading> <Heading size={5}>CoffeeScript (2009)</Heading> <br /> <CodePane lang="coffeescript" source={require('raw-loader!../assets/coffeescript.example')} textSize={32} theme="external" /> <Notes> <List> <ListItem>CoffeeScript: new compile-to-JS language</ListItem> <ListItem>easier, nicer JS; added new features</ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>New Approaches</Heading> <Heading size={5}>CoffeeScript (2009)</Heading> <br /> <CodePane lang="coffeescript" source={require('raw-loader!../assets/coffeescript-arrow-functions.example')} textSize={27} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/txbD6C </Text> <Notes>arrow func inflnc. on standards</Notes> </Slide> <Slide> <Heading size={4}>New Approaches</Heading> <Heading size={6}>Angular, Knockout, Ember (2009-11)</Heading> <br /> <CodePane lang="js" source={require('raw-loader!../assets/angular.example')} textSize={22} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Prior art: .NET Windows Presentation Foundation (XAML) </Text> <Notes> <List> <ListItem>2009: new wave of frameworks</ListItem> <ListItem>data binding: new approach to DOM manip</ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>New Approaches</Heading> <Heading size={6}>Angular, Knockout, Ember (2009-11)</Heading> <br /> <CodePane lang="js" source={require('raw-loader!../assets/ember-js.example')} textSize={18} theme="external" /> <br /> <CodePane lang="handlebars" source={require('raw-loader!../assets/ember-hbs.example')} textSize={18} theme="external" /> <Notes>data binding in ember</Notes> </Slide> <Slide bgColor="quartenary"> <Heading size={1} textColor="#fff7de"> React (2013) </Heading> <Heading size={2} textColor="#fff7de"> New and Improved Paradigms </Heading> <Notes> <List> <ListItem>improvements on existing ideas</ListItem> <ListItem>introductions of new paradigms</ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>React: Paradigms</Heading> <Heading size={6}>Simpler one-way data binding via JSX</Heading> <br /> <CodePane lang="js" source={require('raw-loader!../assets/react-data-binding-jsx.example')} textSize={22} theme="external" /> <Notes> <List> <ListItem>more like regular JS fns</ListItem> <ListItem> almost no impl. details of data binding from library </ListItem> <ListItem>no DSL allows full power of JS</ListItem> </List> </Notes> </Slide> {/* <Slide bgColor="tertiary"> <BlockQuote> <Quote> There&rsquo;s not a single data binding artifact here ... you&rsquo;re just writing JavaScript. </Quote> <Cite textColor="primary"> Pete Hunt, "The Secrets of React's Virtual DOM" </Cite> </BlockQuote> <Notes> because the data binding is just done with JavaScript functions </Notes> </Slide> */} <Slide> <Heading size={4}>React: Paradigms</Heading> <Heading size={5}>Data binding: Virtual DOM</Heading> <br /> <Image src={images.reactVirtualDom} style={{ // height: 56, borderRadius: 5, // marginLeft: 54, // marginTop: 30, border: 'solid #fff', borderWidth: '20px 60px 20px 0', background: '#fff', }} /> <br /> <Text lineHeight={1.6} textSize={30}> Credit: goo.gl/g8fWvi </Text> <Notes> <List> <ListItem> React calculates diff + makes minimal DOM updates </ListItem> <ListItem> user writes declarative components + doesn't need to touch imperative DOM </ListItem> </List> </Notes> </Slide> {/* <Slide> <Heading size={4}>React: Paradigms</Heading> <Heading size={5}>JSX</Heading> <List> <Appear> <ListItem textSize={44}> JavaScript instead of a domain-specific language </ListItem> </Appear> <Appear> <ListItem textSize={44}>functions instead of strings</ListItem> </Appear> </List> <Notes> How does one declare what should go into the Virtual DOM to be updated? React proposes JSX, which is a declarative, familiar HTML-like syntax sugar over {'function'} calls. <br /> JS instead of DSL: This allows use of the full power of JavaScript instead of a domain-specific language... <br /> functions instead of strings: ...since components are built using functions and not strings. <br /> </Notes> </Slide> */} <Slide> <Heading size={4}>React: Paradigms</Heading> <Heading size={5}>Functional Programming</Heading> <List> <Appear> <ListItem textSize={46}>roots in functional programming</ListItem> </Appear> <Appear> <ListItem textSize={46}> immutability easier to reason about{' '} <small style={{ opacity: 0.5, }}>⏎</small> </ListItem> </Appear> </List> <Notes> The functional approach is promoted in ways other than JSX. <List> <ListItem>early prototypes of React built in StandardML</ListItem> <ListItem> immutability: less potential interactions with data </ListItem> </List> </Notes> </Slide> {/* <Slide bgColor="tertiary"> <BlockQuote> <Quote> While it is influenced by ... functional programming, staying accessible to ... developers with different skills and experience levels is an explicit goal of the project. </Quote> <Cite textColor="primary">React Docs</Cite> </BlockQuote> <Notes> <List> <ListItem>quote from React docs</ListItem> <ListItem>pragmatism over idealism</ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>React: Paradigms</Heading> <Heading size={5}>Immutability, Unidirectional Data Flow</Heading> <Text lineHeight={1.4} textSize={60}> Less power over data interactions is easier to reason about </Text> <Notes> less potential interactions with your data results in an app that&rsquo;s easier to reason about </Notes> </Slide> */} <Slide> <Heading size={4}>React: Paradigms</Heading> <Heading size={5}>Component Model</Heading> <List> <Appear> <ListItem textSize={53}> simple, consistent composability </ListItem> </Appear> <Appear> <ListItem textSize={53}> decoupled from output target (ex. DOM){' '} <small style={{ opacity: 0.5, }}>⏎</small> </ListItem> </Appear> </List> <Notes> <List> <ListItem> standardized model for how to write + what to be able to expect from React components </ListItem> <ListItem>allows other usages ex. native, SSR, etc.</ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>React: Paradigms</Heading> <Heading size={5}>Minimalism</Heading> <Text lineHeight={1.4} textSize={60}> React's API surface area is limited, with features actively being removed. </Text> <Notes>amount of things to learn+remember kept low</Notes> </Slide> <Slide bgColor="quartenary"> <Heading size={1} textColor="#fff7de"> React </Heading> <Heading size={2} textColor="#fff7de"> Web Standards </Heading> <Notes> <List> <ListItem> approach of embracing and curating standards when possible </ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>React</Heading> <Heading size={4}>Embracing Standards</Heading> <Text lineHeight={1.4} textSize={60}> React builds on a curated set of JavaScript features, by polyfilling proposals </Text> <Notes> don't invent propreitary abstractions, use standards-based JS + polyfill where necessary </Notes> </Slide> {/* <Slide bgColor="tertiary"> <BlockQuote> <Quote> Strategy to make a better library: listen to slow moving standards committees </Quote> <Cite textColor="primary"> Sebastian Markbåge, "Minimal API Surface Area" </Cite> </BlockQuote> <Notes> Listening to standards committees is part of React&rsquo;s philosophy, as noted by Sebastian Markbåge (Markboge), one of the core React contributors at Facebook </Notes> </Slide> */} <Slide bgColor="tertiary"> <BlockQuote> <Quote textSize={56}> How do we remove existing features from the existing language? ...you can&rsquo;t remove things from the web. But they can be removed from our industry&rsquo;s mental surface area </Quote> <Cite textColor="primary"> Sebastian Markbåge, "Minimal API Surface Area" goo.gl/QCULgG </Cite> </BlockQuote> <Notes> by curating which standards React promotes, the mental surface area required to program in JavaScript can be reduced </Notes> </Slide> <Slide> <Heading size={4}>React</Heading> <Heading size={5}>Discontent with Standards</Heading> <List> <Appear> <ListItem>verbose, imperative APIs such as the DOM</ListItem> </Appear> <Appear> <ListItem>tight coupling</ListItem> </Appear> <Appear> <ListItem> foundational quirks <small style={{ opacity: 0.5, }}>⏎</small> </ListItem> </Appear> </List> <Notes> <List> <ListItem> as seen in first examples, verbosity. also imperative vs declarative </ListItem> <ListItem> tight coupling between layers (ex. HTML + CSS coupled to DOM) </ListItem> <ListItem> workarounds + hacks needed to abstract over quirks (ex. properties vs attributes) </ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>React</Heading> <Heading size={5}>Web Components Pros</Heading> <List> <ListItem>shadow DOM encapsulation</ListItem> <ListItem>could become interoperable standard</ListItem> </List> <Notes> <List> <ListItem> strong encapsulation imposs. w. existing standards </ListItem> <ListItem> with enough adoption and easy integration, Web Components could provide an interoperable standard to be used across frameworks </ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>React</Heading> <Heading size={5}>Web Components Cons</Heading> <List> <ListItem>no enforcement of declarative APIs</ListItem> <ListItem>most web components imperative</ListItem> <ListItem>no focus on composability</ListItem> <ListItem>Web Components embrace the DOM</ListItem> </List> <Notes> From React&rsquo;s perspective, Web Components do not live up to their promises <List> <ListItem>no enforcement simpler declarative models</ListItem> <ListItem> assumption of stateful, imperative API: harder to reason about </ListItem> <ListItem>no focus on data flow between parent + child</ListItem> <ListItem>all problems of DOM come with WCs</ListItem> </List> </Notes> </Slide> <Slide bgColor="quartenary"> <Heading size={1} textColor="#fff7de"> Web Standards Proposals </Heading> <Notes>from the community or following same React paradigms</Notes> </Slide> <Slide> <Heading size={4}>Web Standards Proposals</Heading> <Heading size={5}>Specification process</Heading> <List> <ListItem>Stage 0 (strawman): request input</ListItem> <ListItem>Stage 1 (proposal): challenges, polyfill, etc.</ListItem> <ListItem>Stage 2 (draft): formal, precise language</ListItem> <ListItem> Stage 3 (candidate): signed-off spec text, needs implementations and user feedback </ListItem> <ListItem> Stage 4 (finished): two compatible implementations shipped, ready for inclusion in spec </ListItem> </List> <Notes> <List> <ListItem>0: early input + discussion</ListItem> <ListItem> 1: describe case, shape of solution, potential challenges <br />> prereqs: "champion", informal doc </ListItem> <ListItem> 2: make it formal: precise desc of syntax + semantics <br />> prereq: formal spec text <br /> --> feature is expected to be developed + included in standard </ListItem> <ListItem> 3: internal work complete, needs implm'n + external feedback <br />> prereqs: complete spec text w. signoff </ListItem> <ListItem> 4: done + ready for inclusion in spec. <br />> prereqs: acceptance tests, 2 compatible implm'ns </ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>React Goals</Heading> <List> <Appear> <ListItem textSize={48}>lower React paradigms into JS</ListItem> </Appear> <Appear> <ListItem textSize={48}> new low-level APIs for optimization </ListItem> </Appear> <Appear> <ListItem textSize={48}> make React obsolete <small style={{ opacity: 0.5, }}> ⏎</small> </ListItem> </Appear> </List> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/o8pjF2 </Text> <Notes> <List> <ListItem>fp, immutability, declarative APIs</ListItem> <ListItem>expose low-level browser functionality</ListItem> <ListItem>longer term: obsolescence</ListItem> </List> </Notes> </Slide> {/* <Slide bgColor="tertiary"> <BlockQuote> <Quote> One day when React isn&rsquo;t needed anymore, in a few years or so... </Quote> <Cite textColor="primary"> Cheng Lou, "Taming the Meta Language" </Cite> </BlockQuote> <Notes> Cheng Lou philosophized about such a future at React Conf 2017 </Notes> </Slide> */} <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Declarativity</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Sebastian Markbåge - Object Rest/Spread Properties (ES2018) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-rest-spread-properties.example')} textSize={22} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/YTq1xM </Text> <Notes> <List> <ListItem>improved declarativity</ListItem> </List> </Notes> </Slide> {/* <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Declarativity</Heading> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-rest-spread-properties-react-redux.example')} textSize={21} theme="external" /> <Notes> Here it&rsquo;s being used in the React docs to spread properties over a component and for extending the previous state in Redux </Notes> </Slide> */} <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Declarativity</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Sebastian Markbåge - Silent Property Access on null/undefined <br /> (unproposed) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-silent-property-access-undefined.example')} textSize={22} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/stLEKU </Text> <Notes>less complicated syntax when accessing data</Notes> </Slide> <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Declarativity</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Claude Pache, Gabriel Isenberg - Optional Chaining (Stage 1) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-optional-chaining.example')} textSize={38} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/2vpyK5 </Text> <Notes>similar proposal further in spec process (stg 1)</Notes> </Slide> {/* <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Declarativity</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Claude Pache, Gabriel Isenberg - Optional Chaining (Stage 1) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-optional-chaining-2.example')} textSize={19} theme="external" /> <Notes> Optional chaining also defines semantics for how function and method calls should be treated </Notes> </Slide> */} <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Declarativity</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Daniel Ehrenberg, Jeff Morrison - Class Fields (Stage 3) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-class-fields.example')} textSize={25} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/LgvhbJ </Text> <Notes> <List> <ListItem> simpler, declarative way to init properties on classes </ListItem> <ListItem>fewer state transitions for instances</ListItem> </List> </Notes> </Slide> {/* <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Declarativity</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Daniel Ehrenberg, Jeff Morrison - Class Fields (Stage 3) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-class-fields-react.example')} textSize={22} theme="external" /> <Notes>This also made it into the React documentation</Notes> </Slide> */} <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Declarativity</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Sebastian Markbåge - Scoped Constructor Arguments (unproposed) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-scoped-constructor-arguments.example')} textSize={22} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/nttJoD </Text> <Notes> <List> <ListItem>builds on class fields</ListItem> <ListItem> declarative init of props from constructor arg's </ListItem> </List> </Notes> </Slide> {/* <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Declarativity</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Sebastian Markbåge - Scoped Constructor Arguments (unproposed) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-scoped-constructor-arguments-2.example')} textSize={22} theme="external" /> <Notes> It also allows for captured arguments, which refer to a private slot on `this` </Notes> </Slide> */} <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Functional Programming</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Brian Terlson, Sebastian Markbåge, Kat Marchán - Pattern Matching (Stage 1) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-pattern-matching.example')} textSize={22} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/BFFuxw </Text> <Notes> <List> <ListItem>pattern matching paradigm from fp</ListItem> <ListItem>inspiration from Rust and F#.</ListItem> </List> </Notes> </Slide> {/* <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Functional Programming</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Dave Herman - Do Expressions (Stage 1) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-do-expressions.example')} textSize={22} theme="external" /> <Notes>evaluating the last expression</Notes> </Slide> */} {/* <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Functional Programming</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Dave Herman - Do Expressions (Stage 1) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-do-expressions-react.example')} textSize={22} theme="external" /> <Notes> Do expressions can be useful to conditionally return components in templating languages like JSX </Notes> </Slide> */} <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Functional Programming</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Jordan Harband - Object.values / Object.entries (ES2017) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-object-values-entries.example')} textSize={22} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/LgvhbJ </Text> <Notes>can be helpful in functional programming</Notes> </Slide> <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Immutability</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Sebastian Markbåge - Immutable Data Structures (presented in 2015) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-immutable-js.example')} textSize={22} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/jYQSEg </Text> <Notes> <List> <ListItem>presented in 2015</ListItem> <ListItem>unproven value</ListItem> <ListItem>large impl'n effort</ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Immutability</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Sebastian Markbåge - Shallow Equality Test (Stage 0) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-shallow-object-equality.example')} textSize={27} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/6AFh3j </Text> <Notes> <List> <ListItem> further enables use of immutable data structures </ListItem> <ListItem>proposed, received a lot of concerns</ListItem> </List> </Notes> </Slide> {/* <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Immutability, Performance</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Jordan Harband - Object.getOwnPropertyDescriptors (ES2017) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-getOwnPropertyDescriptors.example')} textSize={22} theme="external" /> <Notes> Jordan Harband of Airbnb proposes a way to get all properties of an object to facilitate proper copying of objects. This has made it into the standard in ES2017. </Notes> </Slide> */} {/* <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Developer Experience</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Jeff Morrison - Trailing commas in functions (ES2017) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-trailing-commas.example')} textSize={22} theme="external" /> <Notes> On the developer experience front, Jeff Morrison proposed grammar to allow trailing commas in function declarations and calls, allowing for less changed lines in version control when adding new parameters <br /> <br /> For example, this example shows that two lines have been modified for each addition (such as param2 and param3 in the declaration or bar and baz in the call) have been </Notes> </Slide> */} {/* <Slide> <Heading size={4}>Standards Proposals</Heading> <Heading size={5}>Developer Experience</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Jeff Morrison - Trailing commas in functions (ES2017) </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/proposal-trailing-commas-2.example')} textSize={22} theme="external" /> <Notes> The proposal allows for trailing commas on the last parameter or argument, mitigating this problem. </Notes> </Slide> */} <Slide bgColor="quartenary"> <Heading size={1} textColor="#fff7de"> Why hasn&rsquo;t there been more progress? </Heading> <br /> <Text lineHeight={1.4} textSize={60}> Sebastian and Jake weigh in </Text> <Notes> why not bigger proposals? (ex. full declarative component API) </Notes> </Slide> <Slide bgColor="tertiary"> <BlockQuote> <Quote> Unfortunately, I think this might be too radical. ... [browser vendors] would probably build [the virtual DOM] on top of the existing imperative API. </Quote> <Cite textColor="primary"> Sebastian Markbåge, "DOM as a Second-class citizen (2015)" goo.gl/K5UtvR </Cite> </BlockQuote> <Notes>big changes often too big + get rejected</Notes> </Slide> <Slide bgColor="tertiary"> <BlockQuote> <Quote> This is why the web platform must be really cautious about throwing trends into specs. </Quote> <Cite textColor="primary"> Jake Archibald, Twitter goo.gl/q7wCLY </Cite> </BlockQuote> <Notes> <List> <ListItem>ex. Object.observe</ListItem> <ListItem> trends become obsolete, (eg. what is after React?) </ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>Why hasn&rsquo;t there been more progress?</Heading> <List> <ListItem> can&rsquo;t remove anything from the web (don&rsquo;t break the web) </ListItem> <ListItem>deliberately slow process for maturity</ListItem> <ListItem>a way forward: expose more browser APIs</ListItem> </List> <Notes> <List> <ListItem> tenet "don't break the web" - once shipped, features cannot be removed again </ListItem> <ListItem>ideas tested over time, carefully considered</ListItem> <ListItem> expose more APIs that browsers already implement </ListItem> </List> </Notes> </Slide> <Slide bgColor="tertiary"> <BlockQuote> <Quote> Expose more APIs [that browsers already implement]. That&rsquo;s what the extensible web manifesto is all about. And that&rsquo;s really good. </Quote> <Cite textColor="primary"> Sebastian Markbåge, "DOM as a Second-class Citizen" goo.gl/K5UtvR </Cite> </BlockQuote> <Notes>expose more existing APIs, including low level</Notes> </Slide> {/* <Slide bgColor="quartenary"> <Heading size={1} textColor="#fff7de"> React: Other influence </Heading> <Notes> Outside of web standards proposals, React paradigms have also had an effect on many frameworks and libraries. </Notes> </Slide> */} {/* <Slide> <Heading size={4}>React: Other influence</Heading> <List> <Appear> <ListItem>Angular.js</ListItem> </Appear> <Appear> <ListItem>Ember</ListItem> </Appear> <Appear> <ListItem>Polymer</ListItem> </Appear> <Appear> <ListItem>Vue</ListItem> </Appear> <Appear> <ListItem>Web Components</ListItem> </Appear> </List> <Notes> <List> <ListItem> Angular: after the outburst in popularity of React, Angular provided a method for doing single-direction data flow </ListItem> <ListItem> Ember: also unidirectional data flow, component-first view </ListItem> <ListItem> Polymer: at the last polymer summit in 2017, announcement about move from HTML imports to es6 modules, which React strongly pushes </ListItem> <ListItem> Vue: API similarities, single-file components, other borrowed ideas like higher order component improvements </ListItem> <ListItem> Web Components: React drives discussion among web components folks </ListItem> </List> </Notes> </Slide> <Slide bgColor="tertiary"> <BlockQuote> <Quote> React is awesome and drives a ton of discussion among folks who work on Web Components. </Quote> <Cite textColor="primary"> Rob Dodson, "Regarding the broken promise of Web Components" </Cite> </BlockQuote> <Notes> Rob mentions that here, how people are watching what React is proposing </Notes> </Slide> */} <Slide bgColor="quartenary"> <Heading size={1} textColor="#fff7de"> Future </Heading> <Notes>what does the future hold?</Notes> </Slide> <Slide bgColor="tertiary"> <BlockQuote> <Quote> The golden use case for WCs would be as primitive leaf components </Quote> <Cite textColor="primary"> André Staltz, "React Could Love Web Components" </Cite> </BlockQuote> <Notes> Such as the suggestion by André Staltz to use web components as leaf nodes (so that they can be used within React) </Notes> </Slide> <Slide> <Heading size={4}>Future</Heading> <Heading size={5}>Integration / Interop</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> Reactive Elements: Convert React.js components into Web Components </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/reactive-elements.example')} textSize={22} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/3oztFs </Text> </Slide> <Slide> <Heading size={4}>Future</Heading> <Heading size={5}>Integration / Interop</Heading> <br /> <Text lineHeight={1.6} textSize={40} fit> SkateJS: Effortless custom elements for modern view libraries </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/skatejs.example')} textSize={22} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/zxdBS4 </Text> <Notes> Some alternative approaches to mixing React and Web Components can be seen with Reactive Elements and SkateJS </Notes> </Slide> <Slide> <Heading size={4}>Future</Heading> <Heading size={5}>Integration / Interop</Heading> <Image src={images.twitterTranspilation} style={{ width: 750, borderRadius: 5, marginTop: 30, }} /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/YRzcaU </Text> <Notes>Jason Miller project to transpile between f/works</Notes> </Slide> <Slide> <Heading size={4}>Future</Heading> <Heading size={5}>Alternative Specifications</Heading> <br /> <Text lineHeight={1.6} textSize={40}> Sean Larkin&rsquo;s Unity Component Specification </Text> <br /> <CodePane lang="js" source={require('raw-loader!../assets/unity-component-spec.example')} textSize={22} theme="external" /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/LgvhbJ </Text> <Notes> specification to standardize single-file components for interop between f/works </Notes> </Slide> <Slide> <Heading size={4}>Future</Heading> <Heading size={5}>Alternatives to the DOM</Heading> <List> <ListItem> Douglas Crockford&rsquo;s "Helper App" ("Upgrading the Web" at AngularU 2015) goo.gl/A8mKxv </ListItem> <ListItem> Ken Wheeler&rsquo;s "App Browser" ("Why We Need An App Browser" at Chain React 2017) goo.gl/6YsnQb </ListItem> </List> <Notes> <List> <ListItem> 2015 Douglas Crockford's idea to discarding the old model of the DOM for something more robust </ListItem> <ListItem> program for navigating to native apps (also alternative model to the DOM) </ListItem> </List> </Notes> </Slide> <Slide> <Heading size={4}>Future</Heading> <Heading size={5}>New Languages</Heading> <br /> <Text lineHeight={1.6} textSize={40}> ReasonML </Text> <br /> <CodePane lang="ocaml" source={require('raw-loader!../assets/reason.example')} textSize={17} theme="external" /> <Notes> ...Such as ReasonML, Facebooks new syntax on top of Ocaml </Notes> </Slide> <Slide> <Heading size={4}>Future</Heading> <Heading size={5}>New Languages</Heading> <br /> <Text lineHeight={1.6} textSize={40}> Sebastian Markbåge&rsquo;s Prepack LLVM Backend </Text> <br /> <Image src={images.llvmBackend} style={{ borderRadius: 5, }} /> <br /> <Text lineHeight={1.6} textSize={30}> Source: goo.gl/UohQJt <small style={{ opacity: 0.5, }}> ⏎</small> </Text> <Notes>compile code to native machine code or web assembly</Notes> </Slide> <Slide> <Heading size={1}>Takeaways</Heading> <List> <Appear> <ListItem>standards move slowly, need consensus</ListItem> </Appear> <Appear> <ListItem>React: embracing sound standards</ListItem> </Appear> <Appear> <ListItem>we need a better model than the DOM</ListItem> </Appear> <Appear> <ListItem> lowering React paradigms into the language helps </ListItem> </Appear> <Appear> <ListItem> New low-level APIs enable alternative approaches </ListItem> </Appear> <Appear> <ListItem> DOM alternatives, new languages may offer better models in the future </ListItem> </Appear> </List> <Notes> <List> <ListItem>standards move slowly, need consensus</ListItem> <ListItem>React: embracing sound standards</ListItem> <ListItem>we need a better model than the DOM</ListItem> <ListItem> lowering React paradigms into the language helps </ListItem> <ListItem> New low-level APIs enable alternative approaches </ListItem> <ListItem> DOM alternatives, new languages may offer better models in the future </ListItem> </List> </Notes> </Slide> </Deck> ); } }
JavaScript
CL
76f3d9437e143fc6f7100712d4266c2f045b64989ad8f6a5d232de68b618a938
// alert('WOW ! Tu es toujours avec Moi !!!'); // Deux Slash pour faire un commentaire uniligne /* Ici, Je peux faire un commmentaire sur plusieurs lignes Raccourcis : CTRL + / ou ALT + SHIFT + A */ // -- 1. Déclarer une variable en JS var Prenom; // -- 2. Affecter une valeur Prenom="Pascal"; // -- 3. Afficher la valeur de ma vaiable dans la console console.log(Prenom); /*-------------------------------------------------- | ~ ~ ~ ~ ~ LES TYPES DE VARIABLES ~ ~ ~ ~ ~ ~ | ---------------------------------------------------*/ // Ici type permet de connaitre le type de variable // console.log(typeof Prenom); // Même chose avec l'Age var Age; Age="49"; console.log(Age); console.log(typeof Age); /* |-------------------------------------------------- | ~ ~ ~ ~ ~ LA PORTEE DES VARIABLES ~ ~ ~ ~ ~ ~ | | Les variables déclarées directement à la racine | | du fichier JS sont appelées variables GLOBALES. | | Elles sont disponibles dans l'ensemble de votre | | document, y compris dans les fonctions. | | | | ### | | | | Les variables déclarées à l'intéreiur d'une | | fonction sont appelées variables LOCALES. | | | | Elles sont disponibles uniquement dans le | | contexte de la fonction, ou du bloc qui les | | contients. | | | | ### | | | | Depuis ECMA 6, vous pouvez déclarer une variable | | avec le mot-clé "let". | | | | Votre variable sera alors accessible uniquement | | dans le bloc dans lequel elle est contenue. | | | | Si elle est déclaré dans une condition elle | | disponible uniquement dans le bloc de la | | condition. | | | | | |---------------------------------------------------| */ //Les variables FLOAT var uneDecimale = -2.897; console.log(uneDecimale); console.log(typeof uneDecimale); // Les Booléens Vrai / Faux var unBooleen = false; // ou TRUE console.log(unBooleen); console.log(typeof unBooleen); // Les Constantes /** * * La déclaration CONST permet de crééer une constante accessible uniquement en lecture. * Sa valeur ne pourra pas être modifiée par des réacffectations ultérieures. * Une constante ne peut pas être déclarée à nouveau. * * Généralement, par convention, les constantes sont en majuscules. * * Depuis ECMA 6, on recommande l'utilisation des constantes plutôt que VAR ou LET * s'il n'y aura pas de modification de valeur à votre variable. * */ const HOST = "localhost" const USER = " root" const PASSWORD = "mysql" // je ne peux pas faire ça : // USER = "Pascal" // Message d'erreur : Uncaught SyntaxError: Identifier 'USER' has already been declared // ni ça : // const USER = "Pascal" // Message d'erreur : Uncaught SyntaxError: Unexpected identifier /* |----------------------------------------------------------| | ~ ~ ~ ~ ~ ~ ~ ~ ~ LA MINUTE INFO ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ | |----------------------------------------------------------| | | | | | Au fur et à mesure que l'on affecte ou réaffecte | | des valeurs à une variable, celle-ci prend la nouvelle | | valeur et son type | | | | En Javascript ECMA Script; les variables sont auto-typées| | | | Pour Convertir une variable de type NUMBER en STRING | | et vis versa je peux utiliser les fonctions natives | | de javascript | | | |----------------------------------------------------------| */ var unNombre = "24"; console.log(unNombre); /** * La Fonction parseInt() pour retourner * Un Entier à partir de mon string. */ unNombre = parseInt(unNombre); console.log(unNombre); console.log(typeof unNombre); // -- Je réaffecte une valeur à ma variable unNombre = "12.55"; unNombre = parseFloat(unNombre); console.log(unNombre); console.log(typeof unNombre); //-- Convertion d'un nombre en Sting avec toString() unNombre = 10 var monNomNombreEnString = unNombre.toString(); console.log(unNombre); console.log(monNomNombreEnString);
JavaScript
CL
7a1be51d03ebcf1e0f972c2705da08fbfe0df9f22c55906e1252e830d7522e37
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ /** * Internal dependencies */ import { setupReducer } from './_utils'; describe('copySelectedElement', () => { it('should do nothing if no selection', () => { const { restore, copySelectedElement } = setupReducer(); // Set an initial state with a current page. const initialState = restore({ pages: [ { id: '111', animations: [], elements: [ { id: '123', isBackground: true, type: 'shape' }, { id: '456', x: 0, y: 0, type: 'shape' }, { id: '789', x: 0, y: 0, type: 'shape' }, ], }, ], current: '111', selection: [], }); const result = copySelectedElement(); expect(result).toStrictEqual(initialState); }); it('copies the styles of an element and animations', () => { const { restore, copySelectedElement } = setupReducer(); // Set an initial state with a current page. const initialState = restore({ pages: [ { id: '111', animations: [{ id: '1234', targets: ['456'], effect: 'bounce' }], elements: [ { id: '123', isBackground: true, type: 'shape' }, { id: '456', x: 0, y: 0, type: 'shape', background: 'blue', backgroundColor: 'red', backgroundTextMode: null, textAlign: 'middle', }, { id: '789', x: 0, y: 0, type: 'shape' }, ], }, ], current: '111', selection: ['456'], }); const result = copySelectedElement(); expect(result).toStrictEqual({ ...initialState, copiedElementState: { animations: [ { effect: 'bounce', id: '1234', targets: ['456'], }, ], styles: { background: 'blue', backgroundColor: 'red', backgroundTextMode: null, textAlign: 'middle', }, type: 'shape', }, }); }); it('copies the styles of an element if no animations', () => { const { restore, copySelectedElement } = setupReducer(); // Set an initial state with a current page. const initialState = restore({ pages: [ { id: '111', elements: [ { id: '123', isBackground: true, type: 'shape' }, { id: '456', x: 0, y: 0, type: 'shape', background: 'blue', backgroundColor: 'red', backgroundTextMode: null, textAlign: 'middle', }, { id: '789', x: 0, y: 0, type: 'shape' }, ], }, ], current: '111', selection: ['456'], }); const result = copySelectedElement(); expect(result).toStrictEqual({ ...initialState, copiedElementState: { animations: [], styles: { background: 'blue', backgroundColor: 'red', backgroundTextMode: null, textAlign: 'middle', }, type: 'shape', }, }); }); it('should not update state if multiple elements selected', () => { const { restore, copySelectedElement } = setupReducer(); // Set an initial state with a current page. const initialState = restore({ pages: [ { id: '111', animations: [], elements: [ { id: '123', isBackground: true, type: 'shape' }, { id: '456', x: 0, y: 0, type: 'shape' }, { id: '789', x: 0, y: 0, type: 'shape' }, ], }, ], current: '111', selection: ['789', '456'], }); const result = copySelectedElement(); expect(result).toStrictEqual(initialState); }); });
JavaScript
CL
02d0cea3728f7ebc74938465b6ca8b859a0ec3f7836112981531c198bbc81790
/* Variables */ var gulp = require('gulp'), notify = require('gulp-notify'), livereload = require('gulp-livereload'), connect = require('gulp-connect'), historyApiFallback = require('connect-history-api-fallback'), install = require("gulp-install"); var paths = { scripts: [ 'assets/**/*', '*/**/*.html' ] }; gulp.task('reload', function() { return gulp.src(paths.scripts) .pipe(connect.reload()); }); /* Install all dependencies */ gulp.task('install', function() { return gulp.src(['./bower.json', './package.json']) .pipe(install()); }); /* Init GulpServer */ gulp.task('default', function() { gulp.start('install', 'reload', 'watch', 'webserver'); }); /* Cambio de archivos */ gulp.task('watch', function() { gulp.watch(paths.scripts, ['reload']); }); /* LocalServer */ gulp.task('webserver', function() { connect.server({ root: './', hostname: '0.0.0.0', port: 9000, livereload: true, middleware: function(connect, opt) { return [ historyApiFallback ]; } }); });
JavaScript
CL
711a5bb939e7c7ecae096c85322cf34f19724678320655cb00209dbacb6e3f6e
// Include Gulp var gulp = require( 'gulp' ); // Include Plugins var sass = require( 'gulp-sass' ); var autoprefixer = require( 'gulp-autoprefixer' ); var imagemin = require( 'gulp-imagemin' ); var pngquant = require( 'imagemin-pngquant' ); var jshint = require( 'gulp-jshint' ); var concat = require( 'gulp-concat' ); var notify = require( 'gulp-notify' ); var cache = require( 'gulp-cache' ); var sourcemaps = require( 'gulp-sourcemaps' ); var csscomb = require( 'gulp-csscomb' ); var livereload = require( 'gulp-livereload' ); var svgmin = require( 'gulp-svgmin' ); var cheerio = require( 'gulp-cheerio' ); var svgstore = require( 'gulp-svgstore' ); // Styles tasks gulp.task( 'styles', function() { return gulp.src( 'assets/stylesheets/style.scss' ) .pipe( sourcemaps.init() ) .pipe( sass( { style: 'expanded' } ) ) .on( 'error', notify.onError( function( err ) { return "Stylesheet Error in " + err.message; } ) ) .pipe( autoprefixer( { browsers: ['last 2 versions', 'ie >= 9'], cascade: false } ) ) //.pipe( csscomb() ) .pipe( sourcemaps.write( './', { includeContent: false, sourceRoot: 'source' } ) ) .on( 'error', function ( err ) { console.error( 'Error!', err.message ); } ) .pipe( gulp.dest( './' ) ) .pipe( livereload() ); }); // Scripts gulp.task( 'scripts', function() { return gulp.src( 'assets/js/*.js' ) .pipe( jshint.reporter( 'default' ) ) //.pipe( concat( 'main.js' ) ) .pipe( gulp.dest( 'assets/js' ) ); //.pipe( notify( { message: 'Scripts task complete' } ) ); }); // Minify our icons and make them into an inline sprite gulp.task( 'icons', function() { return gulp.src( 'assets/svg/icons/*.svg' ) .pipe( svgmin() ) .pipe( svgstore( { fileName: 'icons.svg', inlineSvg: true } ) ) .pipe( cheerio( { run: function( $, file ) { $( 'svg' ).addClass( 'hide' ); $( '[fill]' ).removeAttr( 'fill' ); }, parserOptions: { xmlMode: true } })) .pipe( gulp.dest( 'assets/svg' ) ); }); // Generate style guide assets. gulp.task( 'style-guide', function() { return gulp.src( 'assets/style-guide/stylesheets/style-guide.scss' ) .pipe( sass( { style: 'expanded' } ).on( 'error', sass.logError ) ) .on( 'error', function ( err ) { console.error( 'Error!', err.message ); } ) .pipe( gulp.dest( 'assets/style-guide' ) ) }); // Watch files for changes gulp.task( 'watch', function() { livereload.listen(); gulp.watch( 'assets/stylesheets/**/*.scss', ['styles'] ); gulp.watch( 'assets/js/**/*.js', ['scripts'] ); gulp.watch( 'assets/svg/icons/*', ['icons'] ); gulp.watch( 'assets/style-guide/**/*.scss', ['style-guide'] ); }); // Default Task gulp.task( 'default', ['styles', 'scripts', 'icons', 'style-guide', 'watch'] );
JavaScript
CL
a6a064510aca2da13aab7957fb0f1fcfd9024df32613a9cf27e63cf33c1fad96
import { message, Table, Tooltip } from "antd"; import Column from "antd/lib/table/Column"; import React, { useState } from "react"; import { ExportOutlined } from "@ant-design/icons"; import localStorageService from "../../../helper/localStorage/localStorageService"; import Roles from "../../../helper/config/Roles"; import manageRequest from "../../../helper/axios/facilityApi/manageApi"; import EditModal from "./EditModal"; import OtherRoleModal from "./OtherRoleModal"; const TableView = (props) => { const { data, setDataTable, setIsRerender } = props; const PAGE_SIZE = 8; const [isModalOpen, setIsModalOpen] = useState(false); const [recordItem, setRecordItem] = useState(null); const [isOtherModalOpen, setIsOtherModalOpen] = useState(false); const getCurrentRole = () => { const userRole = localStorageService.getRole(); const designRole = [ Roles.ACCOUNTANT_LEAD, Roles.DIRECTOR, Roles.FM_ADMIN_LEAD, Roles.FM_DEPUTY_HEAD, Roles.FM_FACILITY_TEAM_LEAD, ]; for (const role of userRole) { if (designRole.includes(role)) { return role; } } }; const getCurrentRoleKey = (role) => { switch (role) { case Roles.FM_DEPUTY_HEAD: return "isDeputyHeadApproval"; case Roles.FM_FACILITY_TEAM_LEAD: return "isFMTeamLeadApproval"; case Roles.FM_ADMIN_LEAD: return "isAdminLeadApproval"; case Roles.ACCOUNTANT_LEAD: return "isAccountLeadApproval"; case Roles.DIRECTOR: return "isDirectorApproval"; default: break; } }; const seenRequest = async (requestId) => { try { await manageRequest.seenRequest(requestId); } catch (error) { message.error("Something went wrong! Please try again", 5); } }; const renderStatus = (text, record, index) => { const roleKey = getCurrentRoleKey(getCurrentRole()); console.log("role", roleKey); if ( record.status.overallStatus === false && record.status[roleKey] === false ) { record.status.check = "Đã huỷ đề xuất"; return "Đã huỷ đề xuất"; } if ( record.status.overallStatus === true && record.status[roleKey] === false ) { record.status.check = "Chưa duyệt"; return "Chưa duyệt"; } if ( record.status.overallStatus === true && record.status[roleKey] === true ) { record.status.check = "Đã duyệt"; return "Đã duyệt"; } record.status.check = "Chưa duyệt"; return "Chưa duyệt"; }; const sortHandler = (a, b) => { if ( typeof a.status.check === "string" && typeof b.status.check === "string" ) { return a.status.check.localeCompare(b.status.check); } }; const openModalHandler = async (isOpen, record) => { const roleKey = getCurrentRoleKey(getCurrentRole()); setRecordItem(record); setDataTable((pre) => { const data = pre; for (const item of data) { if (item._id === record._id) { item.isRead[roleKey] = true; } } return [...data]; }); await seenRequest(record._id); if (roleKey === "isFMTeamLeadApproval") { setIsModalOpen(isOpen); } else { setIsOtherModalOpen(true); } }; return ( <> {recordItem && isModalOpen && ( <EditModal setIsRerender={setIsRerender} record={recordItem} isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen} /> )} {recordItem && isOtherModalOpen && ( <OtherRoleModal setIsRerender={setIsRerender} record={recordItem} isOtherModalOpen={isOtherModalOpen} setIsOtherModalOpen={setIsOtherModalOpen} /> )} <Table dataSource={data} bordered pagination={{ pageSize: PAGE_SIZE }} scroll={{ x: 600, y: 600 }} > <Column title="#" dataIndex="fmNumber" key="fmNumber" width="4%" /> <Column title="Danh mục đề xuất" dataIndex="fmName" key="fmName" width="20" render={(text, record) => { const roleKey = getCurrentRoleKey(getCurrentRole()); if (!record.isRead[roleKey]) { return ( <div onClick={() => openModalHandler(true, record)} className="manage-fm__name" > <b>{text}</b> </div> ); } return ( <div onClick={() => openModalHandler(true, record)} className="manage-fm__name" > {text} </div> ); }} sorter={(a, b) => { if (typeof a.fmName === "string" && typeof b.fmName === "string") { return a.fmName.localeCompare(b.fmName); } }} /> <Column title="Nhân viên" dataIndex="fmEmployee" key="fmEmployee" width="20" /> <Column title="Bộ phận" dataIndex="fmDepartment" key="fmDepartment" width="20" /> <Column title="Ngày đề xuất" dataIndex="fmDate" key="fmDate" width="20" sorter={(a, b) => new Date(a.updatedAt) - new Date(b.updatedAt)} /> <Column title="Tình trạng" dataIndex="fmStatus" key="fmStatus" width="20" render={renderStatus} sorter={sortHandler} /> <Column title="Thao tác" key="fmAction" render={(_, record) => { return ( <div className="manage-fm__name" onClick={() => openModalHandler(true, record)} > <Tooltip title="Xem"> <ExportOutlined className="ant-icon icon-primary" /> </Tooltip> </div> ); }} /> </Table> </> ); }; export default TableView;
JavaScript
CL
d1bd9213dc6a71869cbf3d167eec68a15b416cd1c78b267cacdb39e9dc438829
(self["webpackChunkBhogeWeb"] = self["webpackChunkBhogeWeb"] || []).push([["src_app_announcements_announcements_module_ts"],{ /***/ 4997: /*!***************************************************************!*\ !*** ./src/app/announcements/announcements-routing.module.ts ***! \***************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "AnnouncementsPageRoutingModule": () => (/* binding */ AnnouncementsPageRoutingModule) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! tslib */ 4762); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/core */ 7716); /* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/router */ 9895); /* harmony import */ var _announcements_page__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./announcements.page */ 1494); const routes = [ { path: '', component: _announcements_page__WEBPACK_IMPORTED_MODULE_0__.AnnouncementsPage } ]; let AnnouncementsPageRoutingModule = class AnnouncementsPageRoutingModule { }; AnnouncementsPageRoutingModule = (0,tslib__WEBPACK_IMPORTED_MODULE_1__.__decorate)([ (0,_angular_core__WEBPACK_IMPORTED_MODULE_2__.NgModule)({ imports: [_angular_router__WEBPACK_IMPORTED_MODULE_3__.RouterModule.forChild(routes)], exports: [_angular_router__WEBPACK_IMPORTED_MODULE_3__.RouterModule], }) ], AnnouncementsPageRoutingModule); /***/ }), /***/ 1162: /*!*******************************************************!*\ !*** ./src/app/announcements/announcements.module.ts ***! \*******************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "AnnouncementsPageModule": () => (/* binding */ AnnouncementsPageModule) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tslib */ 4762); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/core */ 7716); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @angular/common */ 8583); /* harmony import */ var _angular_forms__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @angular/forms */ 3679); /* harmony import */ var _ionic_angular__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @ionic/angular */ 476); /* harmony import */ var _announcements_routing_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./announcements-routing.module */ 4997); /* harmony import */ var _announcements_page__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./announcements.page */ 1494); let AnnouncementsPageModule = class AnnouncementsPageModule { }; AnnouncementsPageModule = (0,tslib__WEBPACK_IMPORTED_MODULE_2__.__decorate)([ (0,_angular_core__WEBPACK_IMPORTED_MODULE_3__.NgModule)({ imports: [ _angular_common__WEBPACK_IMPORTED_MODULE_4__.CommonModule, _angular_forms__WEBPACK_IMPORTED_MODULE_5__.FormsModule, _ionic_angular__WEBPACK_IMPORTED_MODULE_6__.IonicModule, _announcements_routing_module__WEBPACK_IMPORTED_MODULE_0__.AnnouncementsPageRoutingModule ], declarations: [_announcements_page__WEBPACK_IMPORTED_MODULE_1__.AnnouncementsPage] }) ], AnnouncementsPageModule); /***/ }), /***/ 1494: /*!*****************************************************!*\ !*** ./src/app/announcements/announcements.page.ts ***! \*****************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "AnnouncementsPage": () => (/* binding */ AnnouncementsPage) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tslib */ 4762); /* harmony import */ var _raw_loader_announcements_page_html__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! !raw-loader!./announcements.page.html */ 2750); /* harmony import */ var _announcements_page_scss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./announcements.page.scss */ 5249); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/core */ 7716); let AnnouncementsPage = class AnnouncementsPage { constructor() { } ngOnInit() { } }; AnnouncementsPage.ctorParameters = () => []; AnnouncementsPage = (0,tslib__WEBPACK_IMPORTED_MODULE_2__.__decorate)([ (0,_angular_core__WEBPACK_IMPORTED_MODULE_3__.Component)({ selector: 'app-announcements', template: _raw_loader_announcements_page_html__WEBPACK_IMPORTED_MODULE_0__.default, styles: [_announcements_page_scss__WEBPACK_IMPORTED_MODULE_1__.default] }) ], AnnouncementsPage); /***/ }), /***/ 5249: /*!*******************************************************!*\ !*** ./src/app/announcements/announcements.page.scss ***! \*******************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ("\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJhbm5vdW5jZW1lbnRzLnBhZ2Uuc2NzcyJ9 */"); /***/ }), /***/ 2750: /*!*********************************************************************************************!*\ !*** ./node_modules/raw-loader/dist/cjs.js!./src/app/announcements/announcements.page.html ***! \*********************************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ("<ion-header>\n <ion-toolbar>\n <ion-title>announcements</ion-title>\n </ion-toolbar>\n</ion-header>\n\n<ion-content>\n\n</ion-content>\n"); /***/ }) }]); //# sourceMappingURL=src_app_announcements_announcements_module_ts.js.map
JavaScript
CL
881153abd69b9f33127a62f5d90edea484c56bbc3b26ba6bd52b85d16a771a39
import React from 'react' import Header from '../header/Header' import { render } from 'react-storefront/renderers' import AppModel from '../AppModel' import theme from '../theme' /** * Inserts the PWA header into adapt pages. * @param {Object} stats Webpack build stats object for the client build */ export default function renderHeader(stats) { const { html } = render({ component: <Header />, state: createState(), theme, stats, clientChunk: 'header' // the name of the entry injected into config/web.dev.*.js }) // remove the existing header $body.find('header').remove() // add the new header and supporting resources to the document const $header = $(tag('div', { class: 'mw-header' })).append(html) $body .find('#page-container') .attr('id', null) .prepend($header) } /** * Extracts a menu item from a nav menu element on www.moovweb.com. The logic here is * specific to www.moovweb.com and only serves an example of extracting MenuModel data from * the upstream site. * @return {AppModel} */ function createState() { function extractMenuItem() { const el = $(this) const link = el.children('a') const href = link.attr('href') const children = el .find('.sub-menu > .menu-item') .map(extractMenuItem) .get() return { text: link.text(), url: children.length ? null : href, items: children.length ? children : null } } return AppModel.create({ menu: { levels: [ { root: true, items: $body .find('#top-menu > .menu-item') .map(extractMenuItem) .get() } ] } }) }
JavaScript
CL
32dc0c9fa55e85a6aa834606b9a247c0591a72e0d2c97dd1c7e25809be04f468
// ========================================== // dépendances ============================== // ========================================== var express = require('express'); var path = require('path'); var child_process = require('child_process'); // ========================================== // SERVEUR EXPRESS ========================== // ========================================== // création du serveur var server = express(); // dossier statique (tous les fichiers du // dossier pourront être chargés dans le navigateur) server.use(express.static('client')); // GET / : affichage de la page html server.get('/', function (request, response) { response.sendFile(path.join(__dirname, 'client/index.html')); // sendFile nécessite un chemin absolu }); // écoute des requêtes sur le port 8000 server.listen(8000, function () { console.log('Server now listening on port 8000'); }); // ========================================== // SERVEUR DE SOCKETS ======================= // ========================================== // création du serveur de sockets var io = require('socket.io').listen(8080); // namespaces var clientio = io.of('/client'); var calcio = io.of('/calc'); // map socketId - processus de calcul var processes = {}; // map socketId processus - socketId interface var clientToPs = {}; // ========================================== // SOCKETS CLIENTS ========================== // ========================================== clientio.on('connection', function (socket) { console.log('Client connecté'); // détection des déconnexions socket.on('disconnect', function() { console.log('Client déconnecté'); endCalc(socket.id); }); // détection évènement 'launch_calc' socket.on('launch_calc', function (message) { launchCalc(socket.id, message.number); }); // détection évènement 'end_calc' socket.on('end_calc', function () { endCalc(socket.id); }); // détection évènement 'change_param' socket.on('change_param', function (message) { changeParam(socket.id, message.number); }); }); // fonction lancement calcul function launchCalc(socketId, number) { if (!processes[socketId]) { var cmd = 'python calcul.py ' + socketId + ' ' + number; var ps = child_process.exec(cmd, function (error, stdout, stderr) { console.log('Un processus s\'est terminé'); }); processes[socketId] = ps; } } // fonction terminaison calcul function endCalc(socketId) { var ps = processes[socketId]; if (ps) { ps.kill('SIGTERM'); delete processes[socketId]; } } // fonction changement de paramètre function changeParam(socketId, param) { processSocketId = clientToPs[socketId]; calcio.to(processSocketId).emit('change_param', param); } // ========================================== // SOCKETS CALCULATEURS ===================== // ========================================== calcio.on('connection', function (socket) { console.log('Calculateur connecté'); var clientId = socket.request._query.clientId; clientToPs[clientId] = socket.id; clientio.to(clientId).emit('calc_on'); // détection évènement 'data' socket.on('data', sendData); // détection déconnexion socket.on('disconnect', function () { clientio.to(clientId).emit('calc_off'); }); }); // fonction envoi de données function sendData(message) { clientio.to(message.clientId).emit('calc_data', message); }
JavaScript
CL
e79b54aef30261f846f83769b0348fa55244f40da95675ac22adceddcdbc63e7
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var platform_browser_1 = require("@angular/platform-browser"); var app_routing_1 = require("./app.routing"); var http_1 = require("@angular/http"); var app_component_1 = require("./app.component"); var forms_1 = require("@angular/forms"); var BuyerRegister_component_1 = require("./user/Buyer/BuyerRegister.component"); var BuyerLogin_component_1 = require("./user/Buyer/BuyerLogin.component"); var SellerRegister_component_1 = require("./user/Seller/SellerRegister.component"); var SellerLogin_component_1 = require("./user/Seller/SellerLogin.component"); var AdminLogin_component_1 = require("./user/Admin/AdminLogin.component"); var BuyerHome_component_1 = require("./user/Buyer/BuyerHome.component"); var SellerHome_component_1 = require("./user/Seller/SellerHome.component"); var AdminHome_component_1 = require("./user/Admin/AdminHome.component"); var SysProd_component_1 = require("./user/Admin/SysProd.component"); var Brand_component_1 = require("./user/Admin/Brand.component"); var AddStore_component_1 = require("./user/Seller/AddStore.component"); var AddProd_component_1 = require("./user/Seller/AddProd.component"); var Stat_component_1 = require("./user/Admin/Stat.component"); var AddColla_component_1 = require("./user/Seller/AddColla.component"); var ShowProdsO_component_1 = require("./user/Seller/ShowProdsO.component"); var ShowProdsC_component_1 = require("./user/Seller/ShowProdsC.component"); var EditO_component_1 = require("./user/Seller/EditO.component"); var EditC_component_1 = require("./user/Seller/EditC.component"); var DeleteO_component_1 = require("./user/Seller/DeleteO.component"); var DeleteC_component_1 = require("./user/Seller/DeleteC.component"); var AddProdC_component_1 = require("./user/Seller/AddProdC.component"); var History_component_1 = require("./user/Seller/History.component"); var AppModule = /** @class */ (function () { function AppModule() { } AppModule = __decorate([ core_1.NgModule({ imports: [platform_browser_1.BrowserModule, app_routing_1.routers, http_1.HttpModule, forms_1.FormsModule], declarations: [app_component_1.AppComponent, BuyerRegister_component_1.BuyerRegisterComponent, BuyerLogin_component_1.BuyerLoginComponent, SellerRegister_component_1.SellerRegisterComponent, SellerLogin_component_1.SellerLoginComponent, AdminLogin_component_1.AdminLoginComponent, BuyerHome_component_1.BuyerHomeComponent, SellerHome_component_1.SellerHomeComponent, AdminHome_component_1.AdminHomeComponent, SysProd_component_1.SysProdComponent, Brand_component_1.BrandComponent, AddStore_component_1.AddStoreComponent, AddProd_component_1.AddProdComponent, Stat_component_1.ShowStatComponent, AddColla_component_1.AddCollaComponent, ShowProdsO_component_1.ShowProdsOComponent, ShowProdsC_component_1.ShowProdsCComponent, EditO_component_1.EditOComponent, DeleteO_component_1.DeleteOComponent, DeleteC_component_1.DeleteCComponent, EditC_component_1.EditCComponent, AddProdC_component_1.AddProdCComponent, History_component_1.HistoryComponent], bootstrap: [app_component_1.AppComponent] }) ], AppModule); return AppModule; }()); exports.AppModule = AppModule; //# sourceMappingURL=app.module.js.map
JavaScript
CL
70787bb0120d6c6829588748544fda36b7a518dc33eaa9dc6f9d6ac499aaf897
import React from 'react'; import PropTypes from 'prop-types'; import { BrowserRouter as Router, Route, Link, Redirect, withRouter } from 'react-router-dom' import './TasksFunctions.css'; class TasksFunctions extends React.Component { constructor(props) { super(props); this.state = { error: null, isLoaded: false, items: [] }; } componentDidMount() { fetch("/tasks/findall") .then(res => res.json()) .then( (result) => { // check the URL param whichTask from the router and set value of result for proper render of the click task if (this.props.match.params.whichTask === "all") { this.setState({ isLoaded: true, items: [result[0]] }); } else { let taskIndexClicked = parseInt(this.props.match.params.whichTask); console.log(taskIndexClicked); this.setState({ isLoaded: true, items: result // string to integer the index of the item clicked in the side bar }); } }, // Note: it's important to handle errors here // instead of a catch() block so that we don't swallow // exceptions from actual bugs in components. (error) => { this.setState({ isLoaded: true, error }); } ) } componentDidMount() { fetch("/tasks/findall") .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, items: result }); }, // Note: it's important to handle errors here // instead of a catch() block so that we don't swallow // exceptions from actual bugs in components. (error) => { this.setState({ isLoaded: true, error }); } ) } componentWillReceiveProps() { console.log("inside update"); fetch("/tasks/findall") .then(res => res.json()) .then( (result) => { // check the URL param whichTask from the router and set value of result for proper render of the click task if (this.props.match.params.whichTask === "all") { this.setState({ items: result }); } else { let taskIndexClicked = parseInt(this.props.match.params.whichTask); console.log(taskIndexClicked); this.setState({ items: [result[taskIndexClicked]] // string to integer the index of the item clicked in the side bar }); } }, // Note: it's important to handle errors here // instead of a catch() block so that we don't swallow // exceptions from actual bugs in components. (error) => { this.setState({ error }); } ) } render() { const { error, isLoaded, items } = this.state; console.log(this.props.match.params); if (error) { return <div>Error: {error.message}</div>; } else if (!isLoaded) { return <div>Loading...</div>; } else { return ( <div> <div className="accordion" id="accordion eachJobAccordion"> {items.map((item, index) => ( <div className="card eachJobCard" key={"card" + index}> <div className="card-header eachJobHeader" id={"card" + index}> <button className="btn eachJobBtn" type="button" data-toggle="collapse" data-target={"#" + item.name} aria-expanded="false" aria-controls={item.name} > {item.name} </button> </div> <div className="card-body collapse eachJobBody" id={item.name} aria-labelledby={"card" + index} data-parent="#accordion"> <div className="row align-middle tasksViewTopLinks"> <h5 className="col-4 align-middle text-left card-title">Supervisor: <span>{item.supervisor}</span></h5> <Link className="col-8 align-middle text-right dashViewButtons" id="newTaskBtn" to="/newtask" > <p id="addTaskText">Add A New Task<img id="addBtn" src="/img/addBtn.svg" alt="Add A New Task" /></p> </Link> </div> <div className="accordion" id="accordion2 eachTaskAccordion"> {item.tasks.map((tasks, index) => ( <div className="card eachTaskCard" key={"task" + index}> <div className="card-header eachTaskHeader" id={"task" + index}> <button className="btn eachTaskBtn" type="button" data-toggle="collapse" data-target={"#" + tasks.item} aria-expanded="false" aria-controls={tasks.item} > Task: <span className="taskName">{tasks.item}</span> </button> </div> <div className="card-body eachTaskBody collapse" id={tasks.item} aria-labelledby={"task" + index} data-parent="#accordion2"> <ul className="descriptionListUL"> {tasks.description.map((description, index) => ( <li className="list-group-item eachTaskDescription" key={"description" + index} id={"description" + index}>Description: <span className="eachDescriptionText">{description}</span></li> ))} </ul> </div> </div> ))} </div> </div> </div> ))} </div> </div> ); } } } //end of class export default TasksFunctions;
JavaScript
CL
934324e8be9d92ceab831d4b9fe0debb472e04d3e260d73f87a5fe3512f13a73
var config = require('config'); var gulp = require('gulp'); var browserSync = require('browser-sync'); var webpackMiddleware = require('webpack-dev-middleware'); var webpack = require('webpack'); var runSequence = require('run-sequence'); var webpackConfig = config.get('webpack'); var yargs = require('yargs'); var bsConfig = config.util.cloneDeep(config.get('browserSync')); var argv = yargs.option('open', { alias: 'o', default: bsConfig.open }).argv; bsConfig.open = argv.open; webpackConfig.devtool = 'eval'; var msg = 'Run browserSync with webpack middleware (for live reloading/syncing)'; gulp.task('serve:browser-sync', msg, function(cb) { bsConfig.middleware = webpackMiddleware(webpack(webpackConfig), { stats: { colors: true }, publicPath: '/js/bndl/', }); // Load BS and trigger initial build browserSync(bsConfig); // Do an initial build and reload // Building inside init because browserSync.active must be true browserSync.emitter.on('init', function() { runSequence( 'build', function() { browserSync.reload(); cb(); } ); }); });
JavaScript
CL
2ce1d55966e8ae807540498aafca4447212834dfdd308733a1bdb324d0a777c3
// https://developers.google.com/sheets/api/quickstart/nodejs const fs = require('fs'); const readline = require('readline'); const GoogleAuth = require('google-auth-library'); const config = require('../config'); const logger = require('../log'); const { googleClientSecret: GOOGLE_CLIENT_SECRET, googleClientId: GOOGLE_CLIENT_ID, googleRedirectURIs: GOOGLE_REDIRECT_URIS, googleScopes: GOOGLE_SCOPES, googleTokenPath: GOOGLE_TOKEN_PATH, } = config; function storeToken(token) { fs.writeFile(GOOGLE_TOKEN_PATH, JSON.stringify(token), (err) => { if (err) { logger.log('info', err); } }); } function getNewToken(oauth2Client) { const authURL = oauth2Client.generateAuthUrl({ access_type: 'offline', scope: GOOGLE_SCOPES, }); console.log(`Authorize this app by visiting this url: ${authURL}`); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question('Enter the code from that page here: ', (code) => { rl.close(); oauth2Client.getToken(code, (err, token) => { if (err) { console.log(`Error while trying to retrieve access token: ${err}`); logger.log('info', err); } else { storeToken(token); } }); }); } (function init() { const auth = new GoogleAuth(); const oauth2Client = new auth.OAuth2( GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URIS[0], ); getNewToken(oauth2Client); }());
JavaScript
CL
57f5b7df1e6d5691f60b9103d173b8643918410c25a3103a05dede1d9404750f
import { all, take, put, call, race, fork, delay } from 'redux-saga/effects'; import { push } from 'connected-react-router'; import userSaga from './user'; import institutionSaga from './institution'; import groupSaga from './group'; import gameSaga from './game'; import quizSaga from './quiz'; import hostSaga from './host'; import questionSaga from './question'; import { userActions, userTypes } from '../redux'; import { userApi } from '../api'; const getCurrentUser = function* () { yield put(userActions.requestGetCurrentUser()); yield delay(2000); try { const response = yield call(userApi.getCurrentUser); yield put(userActions.receiveGetCurrentUser(response.data.data)); } catch (error) { yield put(userActions.receiveGetCurrentUserFail()); yield put(push('/login')); } }; export default function* rootSaga() { const token = localStorage.getItem('access_token'); if (token) { // if there is a token get the currentUser before taking any other sagas; // using 'take' will block any actions from being caught; yield take(userTypes.GET_CURRENT_USER); yield fork(getCurrentUser); yield race({ success: take('RECEIVE_GET_CURRENT_USER'), fail: take('RECEIVE_GET_CURRENT_USER_FAIL'), }); } yield all([ userSaga(), institutionSaga(), groupSaga(), gameSaga(), quizSaga(), hostSaga(), questionSaga(), ]); }
JavaScript
CL
54fb0e21b07c106eb16284a6ea7284495a67994e6127d909a81d992c3f61bb61
"use strict"; const request = require('request'); // fetching remote files from repos const fs = require('fs'); // file system operations like copying, renaming, reading files const path = require('path'); // needed for some OS-agnostic file / folder path operations const rm = require('rimraf'); // used to synchronously delete the git repos after generating API ref const { execSync } = require('child_process'); // to trigger the external processes like cloning or Nim calling module.exports = { ready () { console.log("Initializing library docs fetching"); let rawdata = fs.readFileSync('config.json'); let configuration = JSON.parse(rawdata); let repos = configuration.repos; let mainReadme = fs.readFileSync('README.template', 'utf8'); console.log("Loaded main README template."); let mainReadmeLibs = ""; let startSeparators = configuration.separators[0].split(configuration.separators[2]); let endSeparators = configuration.separators[1].split(configuration.separators[2]); for (let i = 0; i < repos.length; i++) { console.log("Processing " + repos[i].label); let tags = repos[i].tags; mainReadmeLibs += "::: theorem <a href='/lib/"+repos[i].name.replace(/\/?$/, '/')+"'>"+repos[i].label+"</a>"; for (let tagIndex = 0; tagIndex < tags.length; tagIndex++) { mainReadmeLibs += "<Badge text='"+tags[tagIndex]+"' "; let selTag = configuration.tags[tags[tagIndex]] if (selTag !== undefined && selTag.type !== undefined) { mainReadmeLibs += "type='"+configuration.tags[tags[tagIndex]].type+"'"; } mainReadmeLibs += "/>" } mainReadmeLibs += "\n" + repos[i].description + "\n:::\n\n"; // Skip iteration if update is disabled, library is fully manual if (repos[i].update === false) { console.log("Skipping " + repos[i].label + " because it's set to manual."); continue; } let repoPath = repos[i].location.replace(/\/?$/, '/'); let rawPath = repoPath.replace("https://github.com", "https://raw.githubusercontent.com"); let readmePath = rawPath + "master/README.md"; processReadme(readmePath); function processReadme(path) { console.log("Fetching " + readmePath); request.get(readmePath, async function (error, response, body) { if (!error && response.statusCode == 200) { console.log("File fetched successfully"); let content = body; let ss, es; for (let ssLen = 0; ssLen < startSeparators.length; ssLen++) { if (content.indexOf(startSeparators[ssLen]) > -1) { ss = startSeparators[ssLen]; break; } } for (let esLen = 0; esLen < endSeparators.length; esLen++) { if (content.indexOf(endSeparators[esLen]) > -1) { es = endSeparators[esLen]; break; } } let readmeBody = content let readmeParts = content.split(ss) if (readmeParts.length >= 2) { readmeBody = readmeParts[1]; } readmeBody = "# " + repos[i].label + "\n\n" + readmeBody.split(es)[0]; console.log("Fixing images"); // Apply only to local images in repo readmeBody = readmeBody.replace(/\!\[(.*)\]\((?!http)(.*)\)/igm, function (match, g1, g2) { return "![" + g1 + "](" + repos[i].location.replace(/\/?$/, '/')+"raw/master/" + g2 + "?sanitize=true)"; }); if (repos[i].subdocs !== undefined && readmeBody.indexOf(repos[i].subdocs) > -1) { console.log("Subdocs detected in README. Parsing nested docs."); // Grab the whole section, from subdocs label to next newline starting with # (new subheading) let subSection = readmeBody.split(repos[i].subdocs)[1]; subSection = subSection.split(/^##\s.*/gmi)[0]; // console.log("-----------------"); // console.log(readmeBody); readmeBody = readmeBody.replace(repos[i].subdocs + subSection, "--subdocs--"); // console.log(readmeBody); // console.log(readmeBody.indexOf(subSection)); // console.log("-----------------"); let rex = /\((.*\.md)\)/gmi; let match = rex.exec(subSection); //let matches = []; let subdocsContent = ""; while (match != null) { //matches.push(match[1]); // Got all the links, let's fetch them. // console.log("Fetchable link " + readmePath.replace("README.md", match[1])); let subdoc = await downloadPage(readmePath.replace("README.md", match[1])); match = rex.exec(subSection); // Deepen heading level for all subheadings if H1 detected subdoc = deepenHeadings(subdoc); subdocsContent += subdoc; } //console.log(subdocsContent); readmeBody = readmeBody.replace("--subdocs--", subdocsContent); } //if (repos[i].apiref !== undefined) { // switch (repos[i].apiref.lang) { // case "nim": // try { // const apiRefTemplateNim = "#### {name} \n\n {description} \n\n```nim{code}\n```\n\n"; // console.log("Starting nimdoc generation for repo " + repos[i].label); // // execSync('git clone ' + repos[i].location + " " + repos[i].name); // // Bootstrap if needed // if (repos[i].apiref.bootstrap !== undefined) { // process.chdir(repos[i].name); // console.log(execSync(repos[i].apiref.bootstrap).toString()); // process.chdir('..'); // } // // Two passes because jsondoc is kinda broken // // Bug: https://github.com/nim-lang/Nim/issues/11953 // console.log("Generating docs"); // execSync('nim doc --project ' + repos[i].name + '/' + repos[i].apiref.mainfile); // console.log("Generating jsondocs"); // execSync('nim jsondoc --project ' + repos[i].name + '/' + repos[i].apiref.mainfile); // console.log("Consuming files"); // let dir = repos[i].name + '/' + repos[i].apiref.subfolder; // let extension = '.json'; // let jsonFiles = []; // // Consume main file // jsonFiles.push(JSON.parse(fs.readFileSync(dir + "/" + repos[i].apiref.mainfile.split(".nim")[0] + extension))); // // Consume all other files // let subdir = dir + "/" + repos[i].apiref.mainfile.split(".nim")[0]; // let files = fs.readdirSync(subdir); // files.forEach(file => { // if(file.indexOf(extension ) > -1) { // let jsonContent = fs.readFileSync(subdir + "/" + file); // jsonFiles.push( // JSON.parse(jsonContent) // ); // } // }); // console.log("Found " + jsonFiles.length + " doc file to MD-ify"); // let md = ""; // for (let z = 0; z < jsonFiles.length; z++) { // // Turn each into MD // console.log(jsonFiles[z].orig + " has " + jsonFiles[z].entries.length + " entries to document."); // // let entries = jsonFiles[z].entries; // console.log("Processing " + jsonFiles[z].orig.match(/(\w+)\.nim$/gmi)[0].replace('.nim', '')); // // let prefix = (z === 0) ? "# API reference: " : "## "; // md += prefix + jsonFiles[z].orig.match(/(\w+)\.nim$/gmi)[0].replace('.nim', '') + "\n"; // // if (entries.length) { // // Sort entries by type like in HTML docs // let content = { // "types": "", // skType // "procs": "", // skProc // "templates": "" // skTemplate // } // console.log("Working through entries of " + jsonFiles[z].orig); // for (let z1 = 0; z1 < entries.length; z1++) { // let newTpl = apiRefTemplateNim // .replace("{description}", entries[z1].description) // .replace("{name}", entries[z1].name) // .replace("{code}", "\n" + entries[z1].code.trim()); // switch(entries[z1].type) { // case "skType": // content.types += newTpl; // break; // case "skProc": // content.procs += newTpl; // break; // case "skTemplate": // content.templates += newTpl; // break; // default: break; // } // } // md += "### Types\n\n" + content.types + "\n\n---\n\n### Procs\n\n---\n\n" + content.procs + "\n\n---\n\n### Templates\n\n---\n\n" + content.templates + "\n\n"; // } // } // // fs.writeFileSync("lib/" + repos[i].name + "/api.md", "---\nsidebar: auto\n---\n\n" + md); // rm.sync(repos[i].name); // break; // } catch (e) { // console.log(e); // rm.sync(repos[i].name); // } // default: break; // } //} let frontMatter = ""; if (repos[i].frontMatter !== undefined) { for (let key in repos[i].frontMatter) { if (repos[i].frontMatter.hasOwnProperty(key)) { frontMatter += key + ": " + repos[i].frontMatter[key] + "\n"; } } frontMatter = "---\n" + frontMatter + "---\n\n"; } let finalFile = frontMatter + readmeBody; var dir = './docs/lib/'+repos[i].name; if (!fs.existsSync(dir)){ fs.mkdirSync(dir); } console.log("Writing " + dir+"/README.md"); fs.writeFileSync(dir+"/README.md", finalFile, function(err) { if(err) { return console.log(err); } console.log("The file " + dir + "/README.md" + " was saved!"); }); } }); } } console.log("Preparing to write new main README file"); mainReadme = mainReadme.replace("{{{libraries}}}", mainReadmeLibs); fs.writeFileSync("./docs/README.md", mainReadme, function(err) { if(err) { return console.log(err); } console.log("The main README.md file was saved!"); }); } } function downloadPage(url) { return new Promise((resolve, reject) => { request(url, (error, response, body) => { if (error) reject(error); if (response.statusCode != 200) { reject('Invalid status code <' + response.statusCode + '>'); } resolve(body); }); }); } function deepenHeadings(content) { // Detect if H1 exists let h1rex = /^#\s.*/gmi; if (h1rex.test(content)) { // Increase all headings by one console.log("Subdoc has H1 heading, pushing all headings one level down"); content = content.replace(/^#/gmi, "##"); } return content; } const listDir = (dir, fileList = []) => { let files = fs.readdirSync(dir); files.forEach(file => { if (fs.statSync(path.join(dir, file)).isDirectory()) { fileList = listDir(path.join(dir, file), fileList); } else { if(/\.html$/.test(file)) { let name = file.split('.')[0].replace(/\s/g, '_') + '.json'; let src = path.join(dir, file); let newSrc = path.join(dir, name); fileList.push({ oldSrc: src, newSrc: newSrc }); } } }); return fileList; };
JavaScript
CL
f2e53eface9e13719feb138f93792a537cfcb4ec365534069e888db3c11593d3
import React, { lazy, Suspense, Fragment } from "react"; import { Switch, Route } from "react-router-dom"; // import LoadingScreen from "src/components/LoadingScreen"; import Layout from './hoc/Layout'; const routesConfig = [ { path: "/tracking-shipment", component: lazy(() => import("./views/Shipment")), layout: Layout, }, { exact: true, path: "/", component: lazy(() => import("./views/Home")), layout: Layout, }, ]; const renderRoutes = (routes) => routes ? ( <Suspense fallback={<div></div>}> <Switch> {routes.map((route, i) => { const Layout = route.layout || Fragment; const Component = route.component; return ( <Route key={i} path={route.path} exact={route.exact} render={(props) => ( <Layout> {route.routes ? ( renderRoutes(route.routes) ) : ( <Component {...props} /> )} </Layout> )} /> ); })} </Switch> </Suspense> ) : null; function Routes() { return renderRoutes(routesConfig); } export default Routes;
JavaScript
CL
a4e2a833aadf62b9df216ef4fe710ad91900e317037e4e745793176cd4e570a8
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } (function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports", "react"], factory); } else if (typeof exports !== "undefined") { factory(exports, require("react")); } else { var mod = { exports: {} }; factory(mod.exports, global.react); global.Ndz = mod.exports; } })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports, React) { "use strict"; Object.defineProperty(_exports, "__esModule", { value: true }); _exports["default"] = void 0; React = _interopRequireWildcard(React); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } var SvgNdz = function SvgNdz(props) { return /*#__PURE__*/React.createElement("div", { className: props.className, style: props.style }, /*#__PURE__*/React.createElement("svg", _extends({ xmlns: "http://www.w3.org/2000/svg", xmlnsXlink: "http://www.w3.org/1999/xlink", viewBox: "0 0 32 32" }, props), /*#__PURE__*/React.createElement("defs", null, /*#__PURE__*/React.createElement("filter", { id: "ndz_svg__a", width: "111.7%", height: "111.7%", x: "-5.8%", y: "-4.2%", filterUnits: "objectBoundingBox" }, /*#__PURE__*/React.createElement("feOffset", { dy: 0.5, "in": "SourceAlpha", result: "shadowOffsetOuter1" }), /*#__PURE__*/React.createElement("feGaussianBlur", { "in": "shadowOffsetOuter1", result: "shadowBlurOuter1", stdDeviation: 0.5 }), /*#__PURE__*/React.createElement("feComposite", { "in": "shadowBlurOuter1", in2: "SourceAlpha", operator: "out", result: "shadowBlurOuter1" }), /*#__PURE__*/React.createElement("feColorMatrix", { "in": "shadowBlurOuter1", values: "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.199473505 0" })), /*#__PURE__*/React.createElement("filter", { id: "ndz_svg__d", width: "119.4%", height: "117.5%", x: "-9.7%", y: "-6.2%", filterUnits: "objectBoundingBox" }, /*#__PURE__*/React.createElement("feOffset", { dy: 0.5, "in": "SourceAlpha", result: "shadowOffsetOuter1" }), /*#__PURE__*/React.createElement("feGaussianBlur", { "in": "shadowOffsetOuter1", result: "shadowBlurOuter1", stdDeviation: 0.5 }), /*#__PURE__*/React.createElement("feColorMatrix", { "in": "shadowBlurOuter1", values: "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.204257246 0" })), /*#__PURE__*/React.createElement("linearGradient", { id: "ndz_svg__c", x1: "50%", x2: "50%", y1: "0%", y2: "100%" }, /*#__PURE__*/React.createElement("stop", { offset: "0%", stopColor: "#FFF", stopOpacity: 0.5 }), /*#__PURE__*/React.createElement("stop", { offset: "100%", stopOpacity: 0.5 })), /*#__PURE__*/React.createElement("circle", { id: "ndz_svg__b", cx: 16, cy: 15, r: 15 }), /*#__PURE__*/React.createElement("path", { id: "ndz_svg__e", d: "M18.586 16.376c-.087.027-.171.06-.253.098l-3.676-3.821a1.91 1.91 0 00-1.14-2.794V7.186l-.984-.55 2.273-1.315a2.384 2.384 0 012.388 0l4.519 2.616-1.786 1.033a1.911 1.911 0 00-2.686 1.747 1.91 1.91 0 001.345 1.824v3.835zm1.138 0V12.54a1.91 1.91 0 001.092-2.773l2.03-1.174.97.56A2.372 2.372 0 0125 11.207v7.586c0 .846-.451 1.628-1.185 2.053l-4.09 2.368v-3.192a1.91 1.91 0 001.344-1.823 1.91 1.91 0 00-1.345-1.823zm-2.227.869a1.91 1.91 0 001.089 2.777v3.851l-1.392.806a2.384 2.384 0 01-2.388 0L9.94 21.863l1.828-1.428a1.91 1.91 0 001.231.447 1.911 1.911 0 001.914-1.91 1.91 1.91 0 00-1.397-1.838v-3.598c.105-.029.207-.067.304-.113l3.676 3.822zm-5.118-.079a1.91 1.91 0 00-1.226 2.308L8.882 21.25l-.697-.403A2.372 2.372 0 017 18.793v-7.586c0-.846.451-1.628 1.185-2.053l3.205-1.856.99.553v2.04a1.91 1.91 0 00-1.294 1.807c0 .837.541 1.55 1.293 1.806v3.662zM13 12.523a.827.827 0 11-.002-1.653.827.827 0 01.002 1.653zm0 7.275a.827.827 0 11-.002-1.653.827.827 0 01.002 1.653zm6.155-8.255a.827.827 0 11-.002-1.653.827.827 0 01.002 1.653zm0 7.482a.827.827 0 11-.002-1.654.827.827 0 01.002 1.654z" })), /*#__PURE__*/React.createElement("g", { fill: "none", fillRule: "evenodd" }, /*#__PURE__*/React.createElement("g", { fillRule: "nonzero" }, /*#__PURE__*/React.createElement("use", { fill: "#000", filter: "url(#ndz_svg__a)", xlinkHref: "#ndz_svg__b" }), /*#__PURE__*/React.createElement("use", { fill: "#622FBA", fillRule: "evenodd", xlinkHref: "#ndz_svg__b" }), /*#__PURE__*/React.createElement("use", { fill: "url(#ndz_svg__c)", fillRule: "evenodd", style: { mixBlendMode: "soft-light" }, xlinkHref: "#ndz_svg__b" }), /*#__PURE__*/React.createElement("circle", { cx: 16, cy: 15, r: 14.5, stroke: "#000", strokeOpacity: 0.097 })), /*#__PURE__*/React.createElement("use", { fill: "#000", filter: "url(#ndz_svg__d)", xlinkHref: "#ndz_svg__e" }), /*#__PURE__*/React.createElement("use", { fill: "#FFF", xlinkHref: "#ndz_svg__e" })))); }; var _default = SvgNdz; _exports["default"] = _default; });
JavaScript
CL
8f45da215e92fde17393e3698a2eeef8e59576600f3ad1b871b252db0a6b86f6
/* струткуру папкок source_folder scss scss_blocks html_blocks js img fonts project_folder css js img fonts */ const project_folder = 'dist'; const source_folder = '#src'; const preprocessor = 'scss'; const path = { build: { html: project_folder + "/", css: project_folder + "/css/", js: project_folder + "/js/", img: project_folder + "/img/", fonts: project_folder + "/fonts" }, src: { html: [source_folder + '/*.html', '!' + source_folder + '/**/_*.html'], css: [source_folder + '/' + preprocessor + '/*.' + preprocessor], js: source_folder + '/js/**/*.js', img: source_folder + "/img/**/*.{jpg,png,svg,gif,ico,webp}", fonts: source_folder + "/fonts/*.{ttf,otf,woff}" }, watch: { html: source_folder + "/**/*.html", css: source_folder + '/' + preprocessor + '/**/*.' + preprocessor, js: source_folder + "/js/**/*.js", img: source_folder + "/img/**/*.{jpg,png,svg,gif,ico,webp}", fonts: source_folder + "/fonts/*.{ttf,otf,woff}" }, clean: './' + project_folder + '/', server: './' + project_folder + '/' } const { src, dest, series, parallel, watch } = require('gulp'), browserSync = require('browser-sync'), concat = require('gulp-concat'), uglify = require('gulp-uglify-es').default, fileinclude = require('gulp-file-include'), htmlhint = require('gulp-htmlhint'), stripcomment = require('gulp-strip-comments'), scss = require('gulp-sass'), // less = require('gulp-less'), /* c less что-то странное, надо будет выяснить */ autoprefixer = require('gulp-autoprefixer'), cssCommentsDel = require('gulp-strip-css-comments'), cleancss = require('gulp-clean-css'), rename = require('gulp-rename'), newer = require('gulp-newer'), imagemin = require('gulp-imagemin'), del = require('del'), plumber = require('gulp-plumber'), sourcemap = require('gulp-sourcemaps'); const browsersync = () => { browserSync.init({ server: { baseDir: path.server }, /* baseDir: 'app/' папка которая используется в качестве сервера*/ port: 3000, notify: false, online: true }) } const images = () => { return src(path.src.img) /*путь по которому проводятся дальнейшие манипуляции */ // .pipe(newer(project_folder + '/images')) /*проверяет наличие оптимизированных изображений, чтобы не оптимизировать их повторно*/ .pipe(imagemin()) /*оптимизирует изображения */ .pipe(dest(path.build.img)) /*выгрузка результата всех предыдущих манипуляций*/ .pipe(browserSync.stream()) } const fontcopy = () => { return src(path.src.fonts) .pipe(newer(path.build.fonts)) .pipe(dest(path.build.fonts)) } const html = () => { return src(path.src.html) .pipe(fileinclude()) .pipe(stripcomment()) .pipe(htmlhint()) .pipe(dest(path.build.html)) .pipe(browserSync.stream()) } const stylesProcess = () => { return src(path.src.css) .pipe(eval(preprocessor)()) .pipe(autoprefixer({ overrideBrowserslist: ['last 10 versions'], grid: true })) .pipe(cssCommentsDel()) /*Удаление комментариев*/ .pipe(dest(path.build.css)) .pipe(dest(path.build.css)) .pipe(browserSync.stream()) } const stylesFinal = () => { return src(path.src.css) .pipe(plumber()) .pipe(sourcemap.init()) .pipe(eval(preprocessor)()) .pipe(autoprefixer({ overrideBrowserslist: ['last 10 versions'], grid: true })) .pipe(cssCommentsDel()) /*Удаление комментариев*/ .pipe(dest(path.build.css)) .pipe(cleancss(({ level: { 1: { specialComments: 0 } }, format: 'beautify' /*для чистого читаемого кода*/ }))) /*cleancss минифицирует css*/ .pipe(rename('styles.min.css')) /*переименование результата (это уже отдельный файл)*/ .pipe(sourcemap.write('.')) /*сохраняет карту css кода, чтобы проблему было легко найти в исходнике scs или less*/ .pipe(dest(path.build.css)) } const scripts = () => { return src(path.src.js) .pipe(concat('script.min.js')) .pipe(uglify()) .pipe(dest(path.build.js)) .pipe(browserSync.stream()) } const cleanimg = () => { return del(project_folder + '/img/**/*', { force: true }) /*удаление ненужных изображений */ } // const cleandb = () => { // return del(source_folder + '/img/**/*.db', { force: true }) // } const cleanProjDir = () => { return del(project_folder + '/**', { force: true }) /*удаление всех файлов в папке. Наличие параметра { force: true } обязательно, без него не сработает*/ } const startwatch = () => { watch(path.watch.css, stylesProcess) watch(path.watch.html, html) watch(path.watch.js, scripts) watch(path.watch.img, images) watch(path.watch.fonts, fontcopy) } exports.cleanimg = cleanimg; exports.scripts = scripts; exports.html = html; exports.stylesProcess = stylesProcess; exports.stylesFinal = stylesFinal; exports.browsersync = browsersync; exports.cleanProjDir = cleanProjDir; exports.default = parallel(fontcopy, cleanimg, images, html, stylesFinal, scripts, browsersync, startwatch);
JavaScript
CL
4a019c21f6ef97a733c678eb84ffd0ee1a55b7374b22d45c8058c452bdb70714
import React from 'react'; import {connect} from 'react-redux'; import {ContentLoader, Table, Tooltip} from '@xanda/react-components'; import {api, fn} from 'app/utils'; import {url} from 'app/constants'; import {fetchData} from 'app/actions'; import {ButtonStandard, Link, PageDescription, PageTitle, Back} from 'app/components'; @connect((store) => { return { assessments: store.assessmentTemplate, }; }) export default class List extends React.PureComponent { constructor(props) { super(props); this.state = { currentPage: 1, filters: '', }; } componentWillMount() { this.fetchData(); } fetchData = (currentPage = 1, newFilters) => { this.setState({ currentPage, filters: newFilters || this.state.filters, }); const filters = newFilters === undefined ? this.state.filters : newFilters; this.props.dispatch(fetchData({ type: 'ASSESSMENT_TEMPLATE', url: `/assessments/templates?page=${currentPage}${filters}`, page: currentPage, })); } render() { const {assessments} = this.props; const {currentPage} = this.state; return ( <div id="content" className="site-content-inner"> <PageTitle value="Assesment Forms"/> <PageDescription>Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Sed posuere consectetur est at lobortis. Curabitur blandit tempus porttitor. Donec id elit non mi porta gravida at eget metus.</PageDescription> {fn.isAdmin() && <div className="page-actions"> <ButtonStandard to={`${url.assessmentTemplate}/add`} icon={<i className="ion-edit"/>}>Create New Form </ButtonStandard> <ButtonStandard to={`${url.coachAssessment}/add`} className="medium" icon={<i className="ion-checkmark" />}>Assess A Coach </ButtonStandard> </div> } <ContentLoader filter={{ filters: assessments.filters, onUpdate: this.fetchData, }} pagination={{ currentPage, onPageChange: this.fetchData, total: assessments.count, }} data={assessments.currentCollection} forceRefresh isLoading={assessments.isLoading} notFound="No assessment" > <Table className="header-transparent" total={assessments.count} headers={['', 'Options']} icon="ion-android-clipboard" > {_.map(assessments.currentCollection, (id) => { const assessment = assessments.collection[id]; return ( <tr key={`assessment_${assessment.assessment_id}`}> <td><Link to={`${url.assessmentTemplate}/${assessment.assessment_id}`}> {assessment.title}</Link> </td> <td className="short"> <Link to={`${url.assessmentTemplate}/${assessment.assessment_id}`} className="button no-border"> <Tooltip icon={<i className="ion-search"></i>} message="View"/> </Link> </td> </tr> ); })} </Table> </ContentLoader> <div className="age-group-buttons"> <Back className="button">Back</Back> </div> </div> ); } }
JavaScript
CL
7d087b153f8eff00f59c7196cb0c2271cee4b4ac22db5b1dceac44776ca3858a
const h = starling.h; const newAction = starling.newAction; //------------------------------------------------------------------------------- // DATA //------------------------------------------------------------------------------- const initialState = { counter: 0, step: 1, }; //------------------------------------------------------------------------------- // INIT //------------------------------------------------------------------------------- const init = (_environment) => { return { diff: initialState, tasks: [], }; }; //------------------------------------------------------------------------------- // UPDATE //------------------------------------------------------------------------------- const update = (state, action) => { switch (action.msg) { case 'DECREMENT': return { diff: { counter: state.counter - state.step }, tasks: [], }; case 'INCREMENT': return { diff: { counter: state.counter + state.step }, tasks: [], }; case 'SET_STEP': return { diff: { step: parseInt(action.data.step) }, tasks: [], }; case 'RESET': return { diff: initialState, tasks: [], }; default: throw 'Incomplete case analysis!'; } }; //------------------------------------------------------------------------------- // VIEW //------------------------------------------------------------------------------- const view = (state) => { return h('div', {}, [ counter(state), stepInput(state), h('button', { onclick: () => newAction('RESET') }, 'Reset'), ]); }; const counter = (state) => { return h('div', { className: 'counter' }, [ h('button', { onclick: () => newAction('DECREMENT') }, '-'), h('span', {}, state.counter), h('button', { onclick: () => newAction('INCREMENT') }, '+'), ]); }; const stepInput = (state) => { return h('label', {}, [ h('span', {}, 'Step:'), h('input', { type: 'number', value: state.step, oninput: (e) => { newAction('SET_STEP', { step: e.target.value }); } }, []), ]); }; //------------------------------------------------------------------------------- // BOOTSTRAP //------------------------------------------------------------------------------- // Use `environment` for external state that you'd like to provide to the // application when `init` is called. The `environment` argument to `embed` is // optional and is provided here solely as documentation. The default value is // `{}`. const environment = {}; const root = document.getElementById('app'); starling.createApp(init, update, view).embed(root, environment);
JavaScript
CL
6239048ee2137999c8c5a2a3db88fe19829e58b9e8885f1144f2b33133a90fc4
/* ** ** textkey.js ** ** These are the TextKey js handling functions. They handle the interaction with the backend handler code as well as the client side interaction/integration. ** */ /* ** ** TextKey modal default options ** ** These settings define what shows up in the TextKey Modal dialog. ** ** NOTES: ** ** urlTextKeyAuth: This is the polling handler which checks to see if the TextKey has been received or not. ** pollFreq: This defines how often to poll the back end handler (in Milliseconds). ** pollTime: This defines the time the user is given to send the TextKey code for authentication (in Seconds - Max is 180 seconds). ** tkHTML: This is the HTML content displayed in the TextKey Modal. Overide this with the setTextKeyHTML call. ** tkcontainerCss: This is the container styling for the TextKey Modal. Overide this with the setTextKeyContainerCss call. ** tkdataCss: This is the data styling for the TextKey Modal. Overide this with the setTextKeyDataCss call. ** tkoverlayCss: This is the overlay styling for the TextKey Modal. Overide this with the setTextKeyOverlayCss call. ** ** See Simple Modal Documentation for more info: http://www.ericmmartin.com/projects/simplemodal/ ** ** The remaining elemtns are used to hold inforation/state. ** */ error_message = ''; tkSettings = { urlTextKeyAuth: 'textkeycheck.php?callback=?', pollFreq: 5000, pollTime: 120, tkHTML: '<div id="simplemodal-container"><h3>Waiting for TextKey Authentication...</h3><div id="tkTime"></div></div>', tkcontainerCss: {'height':'100px', 'width':'600px', 'color':'#bbb', 'background-color':'#333', 'border':'4px solid #444', 'padding':'12px'}, tkdataCss: {'padding':'8px'}, tkoverlayCss: {'background-color':'#000', 'cursor':'wait'}, tkTextKey: '', tkShortCode: '', tkTextKeyUnloackSound: 'audio/door_open.mp3', tkTextKeySuccess: false, tkTextKeyMessage: '', tkTextKeyStatus: false, tkFnSuccess: null, tkFnFail: null }; /* ** Standard modal dialog handling */ function closeModal() { $.modal.close(); }; function showModal(title, msg, md_closeProc, md_height, md_width) { if (typeof(md_height) === "undefined") { md_height = 160; }; if (typeof(md_width) === "undefined") { md_width = 625; }; // Build the hmtl to display tkModalHTML = ('<div id="basic-modal-content"><h3>'+title+'</h3><p>'+msg+'</p><div class="modal-buttons"><span><a class="modal-button" onclick="javascript:$.modal.close();">Close</a></span></div></div><!-- preload the images --><div style="display:none"><img src="./images/x.png" alt="" /></div>'); $.modal( tkModalHTML, { onClose: md_closeProc, containerCss:{ height:md_height, width:md_width }, }); return true; }; /* * TextKey Change Standard Settings * */ function setTextKeyAuth(urlTextKeyAuth) { tkSettings.urlTextKeyAuth = urlTextKeyAuth; } function setPollFreq(pollFreq) { tkSettings.pollFreq = pollFreq; } function setPollTime(newpollTime) { tkSettings.pollTime = newpollTime; pollTime = tkSettings.pollTime; } function setTextKeyHTML(tkHTML) { tkSettings.tkHTML = tkHTML; } function setTextKeyContainerCss(tkcontainerCss) { tkSettings.tkcontainerCss = tkcontainerCss; } function setTextKeyDataCss(tkdataCss) { tkSettings.tkdataCss = tkdataCss; } function setTextKeyOverlayCss(tkoverlayCss) { tkSettings.tkoverlayCss = tkoverlayCss; } /* * TextKey Globals * */ var pollTime = tkSettings.pollTime; var tkTextKeyHandled = false; var timer_is_on = 0; var t; /* * * Hide and show the scoll bar * */ function hideScrollBar() { $("body").css("overflow", "hidden"); } function showScrollBar() { $("body").css("overflow", "auto"); } /* * * Close the TextKey dialog * */ function closeTKModal() { // Set the handled flag tkTextKeyHandled = true; // Reset the poll time pollTime=tkSettings.pollTime; doTimer(1); // Clear out the messages $("#tkTime").text(""); // Hide the modal dialog $.modal.close(); // Show the scroll bar showScrollBar(); } /* * * TextKey Post Handler * */ function postRedirect(redirectURL) { var tkredirectform = $('<form id="tkredirectform" action="' + redirectURL + '" method="post">' + '<input type="text" name="textkeymessage" value="' + tkSettings.tkTextKeyMessage + '" />' + '<input type="text" name="textkeystatus" value="' + tkSettings.tkTextKeyStatus + '" />' + '</form>'); $('body').append(tkredirectform); $('#tkredirectform').submit(); } /* * * TextKey Login was succesful * */ function completeLogin() { // Set flag to success tkSettings.tkTextKeySuccess = true; // Hide the modal dialog closeTKModal(); // Handle the Client Call back or URL redirect if ($.isFunction(tkSettings.tkFnSuccess)) { tkSettings.tkFnSuccess(tkSettings.tkTextKeyMessage, tkSettings.tkTextKeyStatus); } else { postRedirect(tkSettings.tkFnSuccess); } } /* * * TextKey Login failed * */ function errorLogin() { // Handle the Session login.handlelogout(false); // Hide the modal dialog closeTKModal(); // Handle the Client Call back or URL redirect if ($.isFunction(tkSettings.tkFnFail)) { tkSettings.tkFnFail(tkSettings.tkTextKeyMessage, tkSettings.tkTextKeyStatus); } else { postRedirect(tkSettings.tkFnFail); } } /* * * Show an error modal * */ function errorShow() { showModal('Login Error...', 'The TextKey authentication did not complete. You can try again if you think this was an error.', closeModal); error_message = ""; } /* * * Show the TextKey modal dialog * */ function showTKModal(TextKey, ShortCode, fnCallSuccess, fnCallFailed) { // Check for valid call backs if (typeof(fnCallSuccess) === "undefined") { alert("Please make sure you pass in your success and failure handler parameters..."); return; }; if (typeof(fnCallFailed) === "undefined") { alert("Please make sure you pass in your success and failure handler parameters..."); return; }; // Set the tkSettings values tkSettings.tkTextKey = TextKey; tkSettings.tkShortCode = ShortCode; tkSettings.tkFnSuccess = fnCallSuccess; tkSettings.tkFnFail = fnCallFailed; // Set the status & handls variables tkSettings.tkTextKeySuccess = false; tkSettings.tkTextKeyMessage = ''; tkSettings.tkTextKeyStatus = false; tkTextKeyHandled = false; // Hide the scroll bar hideScrollBar(); // Show the dialog $.modal( tkSettings.tkHTML, { onClose: function (dialog) { dialog.data.fadeOut('slow', function () { dialog.container.slideUp('slow', function () { dialog.overlay.fadeOut('slow', function () { // Handle the user initiated close if (!(tkTextKeyHandled)) { // Set the status values tkSettings.tkTextKeyMessage = 'User cancelled the TextKey check...'; tkSettings.tkTextKeyStatus = false; // Handle the failed login errorLogin(); // Show the dialog error_message = tkSettings.tkTextKeyMessage; setTimeout("errorShow()", 1000); } else { $.modal.close(); if (error_message != "") { setTimeout("errorShow()", 1000); }; }; }); }); }); }, position: ["15%",], containerCss: tkSettings.tkcontainerCss, dataCss: tkSettings.tkdataCss, overlayCss: tkSettings.tkoverlayCss } ); // Hide the close button $('#simplemodal-container a.modalCloseImg').hide(); // Start the TextKey handler sendTextKeyCheck(); } /* * * Handle the JS timer * */ function doTimer(clr) { // Handle cancelling the timer if(clr == 1 && timer_is_on == 1) { clearTimeout(t); timer_is_on = 0; }; // Handle starting the timer if (clr == 0) { timer_is_on = 1; t = setTimeout("sendTextKeyCheck()",tkSettings.pollFreq); } } // Validate the TextKey and finalize the login function validateTextKey() { $.ajax({ url: 'loginvalidate.php', type: 'post', cache: false, dataType: 'html', success: function (jsondata) { // Convert to an object data = eval(jsondata); if (typeof(console) !== 'undefined' && console != null) { console.log("data: " + jsondata); console.log(data); }; // Check for a valid login if (data.error == "") { handleUnlock(); $("#tkTime").html('<p><span class="bigmsg colorsuccess">SUCCESS!</span></br><p>TextKey accepted. Completing login now...</p>'); tkSettings.tkTextKeyMessage = 'SUCCESS! TextKey accepted and verified.'; setTimeout("completeLogin()",3000); } else { $("#tkTime").html('<p><span class="bigmsg colorfailed">FAILED!</span></br><p>'+data.error+'</p>'); tkSettings.tkTextKeyMessage = 'FAILED! TextKey was not verified.'; error_message = 'ERROR: '+data.error; setTimeout("errorLogin()",3000); }; } }); }; function changeLock() { $(".poweredby img").attr("src", "images/poweredbyunlocked.gif"); } // Handle the unlock image/sound function handleUnlock() { // Switch to unlocked logo if there if (tkSettings.tkTextKeyUnloackSound != "") { $("#tkSound").html('<audio src="'+tkSettings.tkTextKeyUnloackSound+'" autoplay></audio>'); }; setTimeout("changeLock()",1500); } /* * * The TextKey Handler * */ function sendTextKeyCheck() { // Setup the data payload var DTO = { 'textKey': tkSettings.tkTextKey }; // Show the results in the console if (typeof(console) !== 'undefined' && console != null) { console.log(DTO); console.log(JSON.stringify(DTO)); }; try { // Made a request to check for response $.getJSON(tkSettings.urlTextKeyAuth, DTO, function(responseS) { if (typeof(console) !== 'undefined' && console != null) { console.log(responseS); }; if (responseS.errorDescr) { error_message = 'ERROR: '+responseS.errorDescr; tkSettings.tkTextKeyMessage = error_message; $("#tkTime").html('<p>'+error_message+'</p>'); doTimer(1); setTimeout("errorLogin()",3000); } else { // Look at the response tkSettings.tkTextKeyStatus = responseS.ActivityDetected; // Show the results in the console if (typeof(console) !== 'undefined' && console != null) { console.log('tkSettings.tkTextKeyStatus: ' + tkSettings.tkTextKeyStatus); }; // Check for an expired textKey if (responseS.TimeExpired) { error_message = '<span class="bigmsg colorfailed">FAILED!</span></br><p>Time for response has expired.<p>'; tkSettings.tkTextKeyMessage = error_message; $("#tkTime").html('<p>'+error_message+'</p>'); doTimer(1); setTimeout("errorLogin()",10000); } else { // Check for activity detected if (responseS.ActivityDetected) { $("#tkTime").html('<p><span class="bigmsg colorverify">TEXTKEY RECEIVED</span></br><p>Completing verification now...</p>'); tkSettings.tkTextKeyMessage = 'Verifying TextKey...'; // Validate the TextKey to make sure it was legal doTimer(1); setTimeout("validateTextKey()",3000); } else { $("#tkTime").html('<p>To complete this login, text the following code to '+tkSettings.tkShortCode+':</p><p id="tkCode">' + tkSettings.tkTextKey + '</p><p>within '+pollTime+' seconds...</p>'); pollTime -= 5; } } } }); } catch(err) { error_message = 'ERROR: '+err; tkSettings.tkTextKeyMessage = error_message; $("#tkTime").html('<p>'+error_message+'</p>'); doTimer(1); setTimeout("errorLogin()",3000); }; // Start the timer doTimer(0); }
JavaScript
CL
3c78a9b98cf1b8f16529cbf1cb2208797b4e83c4dd9102985a1fd9123d2887d7
var Interactions = {}; Interactions.interact = function() { Scene.players.forEach(function(player) { // Perform collision detection between player and components in the world var collisionDistances = Interactions.detectCollisions(player); // Act on any collisions between the player and components collisionDistances.collidedElements.forEach(function(component) { player.collide(component); }); // Calculate the vertical position from the starting time var t = new Date().getTime() - player.initialTime; var y0 = player.initialPosition; var v0 = player.initialVelocity; var a = player.gravity; var proposedPlayerPosition = y0 + v0 * t + 0.5 * a * t * t; // Move to y height corresponding to the current time without going through any components if (collisionDistances.distanceToFloor !== -1 && proposedPlayerPosition > player.y + collisionDistances.distanceToFloor) { // Player would go through the floor, so move to floor player.y += collisionDistances.distanceToFloor; player.justTouchedFloor = true; } else if (collisionDistances.distanceToCeiling !== -1 && proposedPlayerPosition < player.y - collisionDistances.distanceToCeiling) { // Player would go through the ceiling, so move to ceiling player.y -= collisionDistances.distanceToCeiling; player.initialVelocity = 0; player.initialTime = new Date().getTime(); player.initialPosition = player.y; } else { // Player will not hit anything, so move to proposed position player.y = proposedPlayerPosition; } // Evaluates when player first touches the floor if (collisionDistances.distanceToFloor >= 0 && player.justTouchedFloor) { // Set jump or rest trajectory if (player.jumpPressed && !player.jumpStillPressed) { // Player is about to move upwards quickly player.initialTime = new Date().getTime(); player.initialPosition = player.y; player.initialVelocity = -0.01; player.jumpStillPressed = true; player.holdingGlide = true; } else { // Player is standing on a component player.initialVelocity = 0; player.initialTime = new Date().getTime(); player.initialPosition = player.y; } // Reset glide and floor touched states player.gravity = Scene.gravity; player.startedGliding = false; player.justTouchedFloor = false; //player.setAnimation("run"); } // Handle gliding beginning at the apogee of the jump if (new Date().getTime() - player.initialTime > -player.initialVelocity / Scene.gravity) { // Turn on or off gliding mode if (player.jumpPressed) { // Run only once at the start if (!player.startedGliding) { // Set player gravity to 1/3 for the glide player.initialVelocity = player.initialVelocity + player.gravity * (new Date().getTime() - player.initialTime); player.initialPosition = player.y; player.gravity = Scene.gravity / 3; player.initialTime = new Date().getTime(); player.startedGliding = true; } } else { // Run only once when the player stops gliding if (player.startedGliding) { player.initialVelocity = player.initialVelocity + player.gravity * (new Date().getTime() - player.initialTime); player.initialPosition = player.y; player.gravity = Scene.gravity; player.initialTime = new Date().getTime(); //player.startedGliding = false; // Enables gliding again after letting go } } } }); }; Interactions.detectCollisions = function(player) { // Keep track of the smallest positive values of the component's distance to the player and which components collide inside var distanceToFloor = -1; var distanceToCeiling = -1; var collidedElements = []; // Go through each component, storing its position above and below the player Scene.components.forEach(function(component) { // Only check collision on components aligned horizontally to handle X axis collision if (player.x + player.width >= component.x && component.x + component.width >= player.x) { // Check for intersection between player and component if (player.y > component.y - component.height && player.y - player.height < component.y) { collidedElements.push(component); } // Stop checking this component for collision if it is not solid (so players cannot stand on it) if (!component.solid) return; // Calculate distance from player to closest floor below player var elementDistanceToFloor = component.y - component.height - player.y; if (elementDistanceToFloor >= 0 && (elementDistanceToFloor < distanceToFloor || distanceToFloor < 0)) { distanceToFloor = elementDistanceToFloor; } // Calculate distance from player to closest ceiling above player var elementDistanceToCeiling = player.y - player.height - component.y; if (elementDistanceToCeiling >= 0 && (elementDistanceToCeiling < distanceToCeiling || distanceToCeiling < 0)) { distanceToCeiling = elementDistanceToCeiling; } } else if (player.scoredComponents.indexOf(component) === -1 && player.hitComponents.indexOf(component) === -1 && player.x > component.x + component.width) { player.score++; player.scoredComponents.push(component); } }); // Return the distance from the floor to the player, the distance from the ceiling to the player, and an array of all collided objects return { distanceToFloor: distanceToFloor, distanceToCeiling: distanceToCeiling, collidedElements: collidedElements }; };
JavaScript
CL
99e66bf71babfba1491cb47f61f75fa80c3b08658bd849f76e5e7e7a89c7392c
import PropTypes from 'utils/PropTypes'; import React, { Component } from 'react'; import renderProp from 'utils/renderProp'; import joinKeys from 'utils/joinKeys'; import { REF } from 'utils/Issuers'; import { isFunction } from 'utils/fp'; import withTable from 'hocs/withTable'; import withIssuer from 'hocs/withIssuer'; // import withStore from 'hocs/withStore'; import { ModalConsumer } from 'components/Modal'; import TableBody from 'components/TableBody'; import TableQuery from 'components/TableQuery'; import Toolbar from 'components/Toolbar'; import QueryConnector from 'components/QueryConnector'; @withTable({ prop: 'contextStore' }) @withTable() @withIssuer({ issuer: REF }) export default class RefModal extends Component { static propTypes = { table: PropTypes.string.isRequired, fetch: PropTypes.stringOrFunc, keys: PropTypes.string, save: PropTypes.stringOrFunc, noQuery: PropTypes.any, store: PropTypes.object, contextStore: PropTypes.object.isRequired, title: PropTypes.node, width: PropTypes.stringOrNumber, header: PropTypes.component, footer: PropTypes.component, toolbar: PropTypes.oneOfType([ PropTypes.component, PropTypes.bool, PropTypes.node, ]), modalFooter: PropTypes.component, }; static defaultProps = { fetch: 'fetch', save: 'request', noQuery: false, title: 'Reference', width: 800, toolbar: false, }; constructor(props, context) { super(props, context); const { fetch, store: refStore } = props; isFunction(fetch) ? fetch(props) : refStore.call(fetch, props); } _handleOk = () => { const { props, props: { keys, save, store: refStore }, } = this; const { pathname } = refStore; const refKeys = refStore.selectedKeys; const url = joinKeys(keys) + `/${pathname}/` + joinKeys(refKeys); const options = { method: 'POST', url, ...props, keys, refKeys, refStore }; isFunction(save) ? save(options) : refStore.call(save, options); }; render() { const { noQuery, store, title, width, header: Header, footer: Footer, modalFooter: ModalFooter, toolbar, } = this.props; return ( <QueryConnector store={store}> <ModalConsumer width={width} title={title} onOk={this._handleOk} footer={ModalFooter && <ModalFooter store={store} />} > {renderProp(Header)} {Header && <Header store={store} />} {!noQuery && <TableQuery store={store} />} {toolbar === true ? <Toolbar /> : renderProp(toolbar, { store })} <TableBody store={store} selectionType="radio" /> {Footer && <Footer store={store} />} </ModalConsumer> </QueryConnector> ); } }
JavaScript
CL
b4f640f5c1cf8c3713c1fbcb844697b8437f546aaf5cea4caf388e2d694087af
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; }; var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var _authnUrl, _authnPrivateUrl, _appDomain, _username, _password, _keystore, _log; Object.defineProperty(exports, "__esModule", { value: true }); exports.KeratinAuthNClient = void 0; /** * API client for the Keratin-AuthN server. * This is meant to be used in a Node.js-based server. */ const querystring_1 = __importDefault(require("querystring")); const url_1 = require("url"); const crypto_1 = require("crypto"); const node_fetch_1 = __importStar(require("node-fetch")); const jose_1 = require("jose"); class KeratinAuthNError extends Error { constructor(statusCode, statusText, errors) { super(`AuthN API Call Failed: ${statusCode} ${statusText}`); this.errors = errors; // This clips the constructor invocation to make the stack trace a little nicer. Error.captureStackTrace(this, this.constructor); } } /** Compare URLs, ignoring minor changes like misisng trailing slash or port number */ function urlsEqual(url1, url2) { if (url1 === url2) { return true; } let u1, u2; try { u1 = new url_1.URL(url1); u2 = new url_1.URL(url2); } catch (_a) { return false; } return ((u1.protocol === u2.protocol) && (u1.hostname === u2.hostname) && ((u1.port || "80") === (u2.port || "80")) && (u1.pathname === u2.pathname)); } class KeratinAuthNClient { constructor(options) { _authnUrl.set(this, void 0); _authnPrivateUrl.set(this, void 0); _appDomain.set(this, void 0); _username.set(this, void 0); _password.set(this, void 0); _keystore.set(this, void 0); _log.set(this, void 0); __classPrivateFieldSet(this, _authnUrl, options.authnUrl); __classPrivateFieldSet(this, _authnUrl, __classPrivateFieldGet(this, _authnUrl).replace(/\/+$/g, "")); // Strip trailing slash __classPrivateFieldSet(// Strip trailing slash this, _authnPrivateUrl, options.authnPrivateUrl || options.authnUrl); __classPrivateFieldSet(this, _authnPrivateUrl, __classPrivateFieldGet(this, _authnPrivateUrl).replace(/\/+$/g, "")); // Strip trailing slash __classPrivateFieldSet(// Strip trailing slash this, _appDomain, options.appDomain); __classPrivateFieldSet(this, _username, options.username); __classPrivateFieldSet(this, _password, options.password); __classPrivateFieldSet(this, _keystore, new jose_1.JWKS.KeyStore()); __classPrivateFieldSet(this, _log, options.debugLogger || ((msg) => { })); } get authnUrl() { return __classPrivateFieldGet(this, _authnUrl); } get authnPrivateUrl() { return __classPrivateFieldGet(this, _authnPrivateUrl); } /** * Validate a session token (would usually be passed as a JWT in the "Authorization" HTTP header). * Returns an object with the account ID if the token is valid, or undefined if the token is invalid. */ async validateSessionToken(token) { // The token must be a (non-empty) string: if (!token || typeof token !== "string") { __classPrivateFieldGet(this, _log).call(this, `AuthN: Session token ${token} is empty or not a string.`); return undefined; } // Parse token let data; try { data = jose_1.JWT.decode(token); } catch (err) { __classPrivateFieldGet(this, _log).call(this, `AuthN: Invalid JWT: ${err}`); return undefined; } // Check issuer if (!urlsEqual(data.iss, __classPrivateFieldGet(this, _authnUrl))) { __classPrivateFieldGet(this, _log).call(this, `AuthN: Invalid JWT issuer: ${data.iss} (expected ${__classPrivateFieldGet(this, _authnUrl)})`); return undefined; } // Check audience const audience = Array.isArray(data.aud) ? data.aud : [data.aud]; if (!audience.includes(__classPrivateFieldGet(this, _appDomain))) { __classPrivateFieldGet(this, _log).call(this, `AuthN: Invalid JWT audience: ${data.aud} (expected ${__classPrivateFieldGet(this, _appDomain)})`); return undefined; } // Verify signature try { jose_1.JWT.verify(token, __classPrivateFieldGet(this, _keystore)); } catch (err) { if (err.code === "ERR_JWKS_NO_MATCHING_KEY") { // Fetch new key and retry try { await this.refreshKeys(); jose_1.JWT.verify(token, __classPrivateFieldGet(this, _keystore)); } catch (err) { __classPrivateFieldGet(this, _log).call(this, `AuthN: JWT Signature validation failed: ${err}`); return undefined; } } else { __classPrivateFieldGet(this, _log).call(this, `AuthN: JWT Signature validation failed: ${err}`); return undefined; } } // Return data const accountId = parseInt(data.sub, 10); return { accountId, }; } /** * Register a new account. Normally the frontend should call this directly, but sometimes you need to create * accounts on the backend, e.g. for importing a user or dev/test accounts. * * Password may be either an existing BCrypt hash or a plaintext (raw) string. The password will not be validated * for complexity. If a password is not specified, a random one will be securely generated. */ async createUser(args) { if (!args.password) { // Generate a secure password automatically args = { ...args, password: crypto_1.randomBytes(64).toString("hex") }; } const result = await this.callApi("post", "/accounts/import", args); __classPrivateFieldGet(this, _log).call(this, `AuthN: Created user ${args.username}`); return { accountId: result.id }; } /** Check if a user with the given username exists. */ async isUsernameRegistered(args) { const result = await this.callApiRaw("get", "/accounts/available", args); if (result.status === 200) { return false; } else if (result.status === 422) { return true; } throw new Error(`Unable to check username status: response was ${result.status} ${result.statusText}`); } /** Get a user via their account ID (get account ID from validateSessionToken()) */ async getAccount(args) { return this.callApi("get", `/accounts/${args.accountId}`); } /** * Change a user's username (or email) or locked status * May throw a KeratinAuthNError with error.errors[0].message as either NOT_FOUND or FORMAT_INVALID */ async update(args) { if (args.username !== undefined) { await this.callApi("patch", `/accounts/${args.accountId}`, { username: args.username }); } if (args.locked === true) { await this.callApi("patch", `/accounts/${args.accountId}/lock`); } else if (args.locked === false) { await this.callApi("patch", `/accounts/${args.accountId}/unlock`); } } /** Wipe all personal information, including username and password. Intended for user deletion routine. */ async archive(args) { const result = this.callApi("delete", `/accounts/${args.accountId}`, undefined, false); } /** Flags the account for a required password change on their next login */ async expirePassword(args) { return this.callApi("patch", `/accounts/${args.accountId}/expire_password`); } /** * Request passwordless login for user with specified username. * This is useful in cases where your backend needs to look up the user (e.g. by email) to get their username, * if you are not using email as authn username. * * Always claims to succeed - use isUsernameRegistered() if you need to know if this will succeed or not. */ async requestPasswordlessLogin(args) { const result = await this.callApi("get", `/session/token`, { username: args.username }, false); } async callApi(method, url, data, jsonResult = true) { const result = await this.callApiRaw(method, url, data); if (result.status >= 200 && result.status <= 300) { if (jsonResult) { return (await result.json()).result; } else { return await result.text(); } } else { const msg = await result.text(); let errors = undefined; try { errors = (await result.json()).errors; } catch (_a) { } __classPrivateFieldGet(this, _log).call(this, `AuthN: ${method} to ${url} failed with ${result.status} ${result.statusText} (${msg})`); throw new KeratinAuthNError(result.status, result.statusText, errors); } } async callApiRaw(method, url, data) { const headers = new node_fetch_1.Headers(); const authToken = Buffer.from(`${__classPrivateFieldGet(this, _username)}:${__classPrivateFieldGet(this, _password)}`).toString("base64"); headers.set("Authorization", `Basic ${authToken}`); // Required for private endpoints headers.set("Origin", `http://${__classPrivateFieldGet(this, _appDomain)}`); // Required for public endpoints const opts = { method: method }; if (method === "get") { if (data) { url = url + "?" + querystring_1.default.stringify(data); } } else { opts.body = JSON.stringify(data || {}); headers.set("Content-Type", "application/json"); } opts.headers = headers; return node_fetch_1.default(`${__classPrivateFieldGet(this, _authnPrivateUrl)}${url}`, opts); } async refreshKeys() { const response = await this.callApiRaw("get", "/jwks"); if (response.status !== 200) { throw new Error("Unable to fetch new key from AuthN microservice."); } const keydata = await response.json(); __classPrivateFieldGet(this, _log).call(this, `AuthN: Refreshed keys (current keys are ${keydata.keys.map((k) => k.kid).join(", ")})`); __classPrivateFieldSet(this, _keystore, jose_1.JWKS.asKeyStore(keydata)); } } exports.KeratinAuthNClient = KeratinAuthNClient; _authnUrl = new WeakMap(), _authnPrivateUrl = new WeakMap(), _appDomain = new WeakMap(), _username = new WeakMap(), _password = new WeakMap(), _keystore = new WeakMap(), _log = new WeakMap(); //# sourceMappingURL=authn-api.js.map
JavaScript
CL
bf4e9fc37be66c1c30af683464ce57eb518d4fbbeb850dcb9187d5bc0512744c