text
stringlengths
2
6.14k
// Restrict output in a codecell to a maximum length define([ 'base/js/namespace', 'jquery', 'notebook/js/outputarea', 'base/js/dialog', 'notebook/js/codecell', 'services/config', 'base/js/utils' ], function(IPython, $, oa, dialog, cc, configmod, utils) { "use strict"; var base_url = utils.get_body_data("baseUrl"); var config = new configmod.ConfigSection('notebook', {base_url: base_url}); // define default values for config parameters var params = { // maximum number of characters the output area is allowed to print limit_output : 10000, // message to print when output is limited limit_ouput_message : "**OUTPUT MUTED**" }; // to be called once config is loaded, this updates default config vals // with the ones specified by the server's config file var update_params = function() { for (var key in params) { if (config.data.hasOwnProperty(key) ){ params[key] = config.data[key]; } } }; function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function makePrintCounter() { var count = 0, currentCount = 0, lastWasCR = false; // Libraries like TQDM don't nessessarily send messages on clean // boundaries (i.e. line breaks). This makes counting stateful! var printCounter = function(str) { for(var i=0; i<str.length; i+=1){ switch(str[i]) { case '\b': lastWasCR = false; currentCount -= 1; break; case '\r': // See if this sets up a CR without an LF. lastWasCR = true; currentCount += 1; break; case '\n': lastWasCR = false; count += currentCount + 1; currentCount = 0; break; default: if(lastWasCR) { currentCount = 1; } else { currentCount += 1; } lastWasCR = false; } } return count + currentCount; }; return printCounter; } config.loaded.then(function() { var MAX_CHARACTERS = params.limit_output; update_params(); if (isNumber(params.limit_output)) MAX_CHARACTERS = params.limit_output; oa.OutputArea.prototype._handle_output = oa.OutputArea.prototype.handle_output; oa.OutputArea.prototype.handle_output = function (msg) { if (this.count === undefined) { this.count=0; } if (this.counter === undefined) { this.counter = makePrintCounter(); } if (this.max_count === undefined) { this.max_count = MAX_CHARACTERS; } console.log("}}}}" + String(msg.content.text)); if(msg.content.text !== undefined) { this.count = this.counter(String(msg.content.text)); console.log(">>>" + String(msg.content.text)); if(this.count > this.max_count) { if (this.drop) return; console.log("limit_output: output exceeded", this.max_count, "characters. Further output muted."); msg.content.text = msg.content.text.substr(0, this.max_count) + params.limit_ouput_message; this.drop = true; } } return this._handle_output(msg); }; cc.CodeCell.prototype._execute = cc.CodeCell.prototype.execute; cc.CodeCell.prototype.execute = function() { // reset counter on execution. this.output_area.count = 0; this.output_area.drop = false; return this._execute(); }; }); var load_ipython_extension = function() { config.load(); }; var extension = { load_ipython_extension : load_ipython_extension }; return extension; });
(function(config, models, views, routers, utils, templates) { // This is the top-level piece of UI. views.Application = Backbone.View.extend({ // Events // ------ events: { 'click .toggle-view': 'toggleView' }, toggleView: function (e) { e.preventDefault(); e.stopPropagation(); var link = $(e.currentTarget), route = link.attr('href').replace(/^\//, ''); $('.toggle-view.active').removeClass('active'); link.addClass('active'); router.navigate(route, true); }, // Initialize // ---------- initialize: function () { _.bindAll(this); var that = this; this.header = new views.Header({model: this.model}); // No longer needed // $(window).on('scroll', function() { // if ($(window).scrollTop()>60) { // $('#post').addClass('sticky-menu'); // } else { // $('#post').removeClass('sticky-menu'); // } // }); function calculateLayout() { if (that.mainView && that.mainView.refreshCodeMirror) { that.mainView.refreshCodeMirror(); } } var lazyLayout = _.debounce(calculateLayout, 300); $(window).resize(lazyLayout); }, // Should be rendered just once render: function () { $(this.header.render().el).prependTo(this.el); return this; }, // Helpers // ------- replaceMainView: function (name, view) { $('body').removeClass().addClass('current-view '+name); // Make sure the header gets shown if (name !== "start") $('#header').show(); if (this.mainView) { this.mainView.remove(); } else { $('#main').empty(); } this.mainView = view; $(view.el).appendTo(this.$('#main')); }, // Main Views // ---------- static: function() { this.header.render(); // No-op ;-) }, posts: function (user, repo, branch, path) { this.loading('Loading posts ...'); loadPosts(user, repo, branch, path, _.bind(function (err, data) { this.loaded(); if (err) return this.notify('error', 'The requested resource could not be found.'); this.header.render(); this.replaceMainView("posts", new views.Posts({ model: data, id: 'posts' }).render()); }, this)); }, post: function (user, repo, branch, path, file, mode) { this.loading('Loading post ...'); loadPosts(user, repo, branch, path, _.bind(function (err, data) { if (err) return this.notify('error', 'The requested resource could not be found.'); loadPost(user, repo, branch, path, file, _.bind(function (err, data) { this.loaded(); this.header.render(); if (err) return this.notify('error', 'The requested resource could not be found.'); data.preview = !(mode === "edit") || !window.authenticated; data.lang = _.mode(file); this.replaceMainView(window.authenticated ? "post" : "read-post", new views.Post({ model: data, id: 'post' }).render()); var that = this; }, this)); this.header.render(); }, this)); }, newPost: function (user, repo, branch, path) { this.loading('Creating file ...'); loadPosts(user, repo, branch, path, _.bind(function (err, data) { emptyPost(user, repo, branch, path, _.bind(function(err, data) { this.loaded(); data.jekyll = _.jekyll(path, data.file); data.preview = false; data.markdown = _.markdown(data.file); this.replaceMainView("post", new views.Post({ model: data, id: 'post' }).render()); this.mainView._makeDirty(); app.state.file = data.file; this.header.render(); }, this)); }, this)); }, profile: function(username) { var that = this; app.state.title = username; this.loading('Loading profile ...'); loadRepos(username, function(err, data) { that.header.render(); that.loaded(); data.authenticated = !!window.authenticated; that.replaceMainView("start", new views.Profile({id: "start", model: data}).render()); }); }, start: function(username) { var that = this; app.state.title = ""; this.header.render(); this.replaceMainView("start", new views.Start({ id: "start", model: _.extend(this.model, { authenticated: !!window.authenticated} ) }).render()); }, notify: function(type, message) { this.header.render(); this.replaceMainView("notification", new views.Notification(type, message).render()); }, loading: function(msg) { $('#main').html('<div class="loading"><span>'+ msg || 'Loading ...' +'</span></div>'); }, loaded: function() { $('#main .loading').remove(); } }); }).apply(this, window.args);
'use strict'; angular.module('27th.common.services.alert', []) .service('alertService', class { constructor($rootScope) { this.alerts = []; this.$rootScope = $rootScope; } success(msg) { this.alerts.push({ type: 'success', message: msg }); this.$rootScope.$emit('alerts.new'); } error(msg) { let message = msg; if(typeof msg !== 'string') { if(msg.message) { message = msg.message; } else if(msg.error && msg.error.message) { message = msg.error.message; } } this.alerts.push({ type: 'error', message: message }); this.$rootScope.$emit('alerts.new'); } nextAlert() { return this.alerts.pop(); } });
/* @flow */ import * as React from "react"; import { nest } from "d3-collection"; import { scaleLinear } from "d3-scale"; import TooltipContent from "../tooltip-content"; const parentPath = (d, pathArray) => { if (d.parent) { pathArray = parentPath(d.parent, [d.key, ...pathArray]); } else { pathArray = ["root", ...pathArray]; } return pathArray; }; const hierarchicalTooltip = (d, primaryKey, metric) => { const pathString = d.parent ? parentPath(d.parent, (d.key && [d.key]) || []).join("->") : ""; const content = []; if (!d.parent) { content.push(<h2 key="hierarchy-title">Root</h2>); } else if (d.key) { content.push(<h2 key="hierarchy-title">{d.key}</h2>); content.push(<p key="path-string">{pathString}</p>); content.push(<p key="hierarchy-value">Total Value: {d.value}</p>); content.push(<p key="hierarchy-children">Children: {d.children.length}</p>); } else { content.push( <p key="leaf-label"> {pathString} -> {primaryKey.map(p => d[p]).join(", ")} </p> ); content.push( <p key="hierarchy-value"> {metric}: {d[metric]} </p> ); } return content; }; const hierarchicalColor = (colorHash: Object, d: Object) => { if (d.depth === 0) return "white"; if (d.depth === 1) return colorHash[d.key]; let colorNode = d; for (let x = d.depth; x > 1; x--) { colorNode = colorNode.parent; } const lightenScale = scaleLinear() .domain([6, 1]) .clamp(true) .range(["white", colorHash[colorNode.key]]); return lightenScale(d.depth); }; export const semioticHierarchicalChart = ( data: Array<Object>, schema: Object, options: Object ) => { const { hierarchyType = "dendrogram", chart, selectedDimensions, primaryKey, colors } = options; const { metric1 } = chart; if (selectedDimensions.length === 0) { return {}; } const nestingParams = nest(); selectedDimensions.forEach(d => { nestingParams.key(p => p[d]); }); const colorHash = {}; const sanitizedData = []; data.forEach(d => { if (!colorHash[d[selectedDimensions[0]]]) colorHash[d[selectedDimensions[0]]] = colors[Object.keys(colorHash).length]; sanitizedData.push({ ...d, sanitizedR: d.r, r: undefined }); }); const entries = nestingParams.entries(sanitizedData); const rootNode = { values: entries }; return { edges: rootNode, edgeStyle: () => ({ fill: "lightgray", stroke: "gray" }), nodeStyle: (d: Object) => { return { fill: hierarchicalColor(colorHash, d), stroke: d.depth === 1 ? "white" : "black", strokeOpacity: d.depth * 0.1 + 0.2 }; }, networkType: { type: hierarchyType, hierarchySum: (d: Object) => d[metric1], hierarchyChildren: (d: Object) => d.values, padding: hierarchyType === "treemap" ? 3 : hierarchyType === "circlepack" ? 2 : 0 }, edgeRenderKey: (d: Object, i: number) => { return i; }, baseMarkProps: { forceUpdate: true }, margin: { left: 100, right: 100, top: 10, bottom: 10 }, hoverAnnotation: true, tooltipContent: (d: Object) => { return ( <TooltipContent> {hierarchicalTooltip(d, primaryKey, metric1)} </TooltipContent> ); } }; };
/* * Copyright (c) 2013, Yahoo! Inc. All rights reserved. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE.txt file for terms. */ /*jslint nomen:true, node:true */ 'use strict'; var core = require('./core'); module.exports = { describe: { summary: 'Compile dust templates to yui modules', extensions: ['dust'], nameParser: core.name }, fileUpdated: function (evt, api) { var self = this, file = evt.file, source_path = file.fullPath, bundleName = file.bundleName, templateName = this.describe.nameParser(source_path), moduleName = bundleName + '-templates-' + templateName, destination_path = moduleName + '.js'; return api.promise(function (fulfill, reject) { var compiled, partials; try { partials = core.partials(source_path); compiled = core.compile(source_path, templateName); } catch (e) { reject(e); } // trying to write the destination file which will fulfill or reject the initial promise api.writeFileInBundle(bundleName, destination_path, self._wrapAsYUI(bundleName, templateName, moduleName, compiled, partials)) .then(function () { // provisioning the module to be used on the server side automatically evt.bundle.useServerModules = evt.bundle.useServerModules || []; evt.bundle.useServerModules.push(moduleName); // we are now ready to roll fulfill(); }, reject); }); }, _wrapAsYUI: function (bundleName, templateName, moduleName, compiled, partials) { // base dependency var dependencies = ["template-base", "template-dust"]; // each partial should be provisioned thru another yui module // and the name of the partial should translate into a yui module // to become a dependency partials = partials || []; partials.forEach(function (name) { // adding prefix to each partial dependencies.push(bundleName + '-templates-' + name); }); return [ 'YUI.add("' + moduleName + '",function(Y, NAME){', ' var dust = Y.config.global.dust;', '', compiled, '', ' Y.Template.register("' + bundleName + '/' + templateName + '", function (data) {', ' var content;', ' dust.render("' + templateName + '", data, function (err, content) {', ' result = content;', ' });', ' return result; // hack to make dust sync', ' });', '}, "", {requires: ' + JSON.stringify(dependencies) + '});' ].join('\n'); } };
/** * +--------------------------------------------------------------------+ * | This HTML_CodeSniffer file is Copyright (c) | * | Squiz Australia Pty Ltd ABN 53 131 581 247 | * +--------------------------------------------------------------------+ * | IMPORTANT: Your use of this Software is subject to the terms of | * | the Licence provided in the file licence.txt. If you cannot find | * | this file please contact Squiz (www.squiz.com.au) so we may | * | provide you a copy. | * +--------------------------------------------------------------------+ * */ /* Japanese translation by Yoshiki Kato @burnworks - v1.0.0 - 2016-03-01 */ var HTMLCS_Section508_Sniffs_C = { /** * Determines the elements to register for processing. * * Each element of the returned array can either be an element name, or "_top" * which is the top element of the tested code. * * @returns {Array} The list of elements. */ register: function() { return ['_top']; }, /** * Process the registered element. * * @param {DOMNode} element The element registered. * @param {DOMNode} top The top element of the tested code. */ process: function(element, top) { HTMLCS.addMessage(HTMLCS.NOTICE, top, '色が情報を伝える、あるいは視覚的な要素を判別するための唯一の視覚的手段になっていないことを確認してください。 Ensure that any information conveyed using colour alone is also available without colour, such as through context or markup.', 'Colour'); } };
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //var MODAL = $("#modalProducto"); var URL = Define.URL_BASE; window.onload=function(){ //toastr.error("Ingresaaaaaaaaa"); var url_ajax = URL + Define.URL_OLVIDE; //le decimos a qué url tiene que mandar la información var data = { action: 'validar' }; httpPetition.ajxPost(url_ajax, data, function (data) { if(data.mensaje == "Ok"){ toastr.success("Bienvenido amante del cafe, esto es Coffee Market House"); redireccionar(Define.URL_BASE + "socialcoffee"); } }); }; function redireccionar(url_direccionar){ setTimeout(function(){ location.href=url_direccionar; }, 5000); //tiempo expresado en milisegundos } $("#olvide").delegate('#semeolvido', 'click', function () {//buscar pedido en bd var usuario_a_buscar = $("#username").val(); var url_ajax = URL + Define.URL_OLVIDE; //le decimos a qué url tiene que mandar la información var data = { action: 'semeolvido', username: usuario_a_buscar }; if(!SOLICITUSEMEOLVIDO){ httpPetition.ajxPost(url_ajax, data, function (data) { if(data.itemsCount != 0){ SOLICITUSEMEOLVIDO = true; url_direccionar = Define.URL_BASE + "cuenta/login" toastr.warning("Hola " + data.data[0].usuarioNombres + ", se te enviará la nueva contraseña al correo: " + data.data[0].usuarioEmail); redireccionar(url_direccionar); }else{ toastr.error("No existe una cuenta asociada a ese nombre de usuario."); } }); }else{ toastr.error("La solicitud ya fue enviada, revisa tu correo."); }; }); $("#login").delegate('#ingresoLogin', 'click', function () {//validar usuario var url_ajax = URL + Define.URL_LOGIN; //le decimos a qué url tiene que mandar la información var usuario_a_buscar = $("#name").val(); var passwd_user = $("#pswd").val(); var recordame_ve = false; if($('#recuerdame').is(':checked')){ recordame_ve = true; } alert(recordame_ve); var data = { action: 'ingresar', username: usuario_a_buscar, password_user: passwd_user, recuerdame: recordame_ve }; if(usuario_a_buscar == '' || passwd_user == ''){ toastr.error("Username y/o contraseña vacíos, por favor digite un valor"); }else{ httpPetition.ajxPost(url_ajax, data, function (data) { if(data.mensaje == "Ok"){ toastr.success("Bienvenido amante del cafe, esto es Coffee Market House"); redireccionar(Define.URL_BASE + "socialcoffee"); } }); }; });
// Plugin for using a local directory as a Library. Generates the payload for // an AssetList REST endpoint consisting of asset models as well as pagination // helpers. var _ = require('underscore'), fs = require('fs'), url = require('url'), path = require('path'), querystring = require('querystring'), Step = require('step'); module.exports = function(app, options, callback) { // Recursive readdir. `callback(err, files)` is given a `files` array where // each file is an object with `filename` and `stat` properties. var lsR = function(basedir, callback) { var files = []; var ls = []; Step( function() { fs.readdir(basedir, this); }, function(err, data) { if (data.length === 0) return this(); var group = this.group(); ls = _.map(data, function(v) { return path.join(basedir, v); }); _.each(ls, function(v) { fs.stat(v, group()); }); }, function(err, stats) { if (ls.length === 0) return this(); var group = this.group(); _.each(ls, function(v, k) { var next = group(); if (stats[k].isDirectory()) { lsR(v, next); } else { files.push({ filename: v, stat: stats[k] }); next(); } }); }, function(err, sub) { _.each(sub, function(v) { v && (files = files.concat(v)); }); callback(err, files); } ); } // Filter an array of files where filenames match regex `re`. var lsFilter = function(files, re) { return _.filter(files, function(f) { return f.filename.match(re); }); }; // Convert a list of files into asset models. var toAssets = function(files, base_dir, port) { return _.map(files, function(f) { return { url: url.format({ host: 'localhost:' + port, protocol: 'http:', pathname: path.join( '/api/Library/' + options.id + '/files/' // Ensure only one trailing slash + querystring.escape(f.filename.replace( base_dir.replace(/(\/)$/, '') + '/', '')) ) }), bytes: (Math.ceil(parseInt(f.stat.size) / 1048576)) + ' MB', id: path.basename(f.filename) }; }); }; // Sort and slice to the specified page. var paginate = function(objects, page, limit) { return _.sortBy(objects, function(f) { return f.id; }).slice(page * limit, page * limit + limit); }; // Generate the AssetList payload object. lsR(options.directory_path, function(err, files) { var assets = toAssets( lsFilter(files, /\.(zip|json|geojson|vrt|tiff?)$/i), options.directory_path, require('settings').port ); callback({ models: paginate( assets, options.page, options.limit ), page: options.page, pageTotal: Math.ceil(assets.length / options.limit) }); }); };
(function () { "use strict"; angular.module('BuDirectives', []). directive('bindHtmlWithJs', ['$sce', '$parse', function ($sce, $parse) { /** * It removes script tags from html and inserts it into DOM. * * Testing: * html += '<script>alert(1234)</script><script type="text/javascript">alert(12345)</script><script type="asdf">alert(1234)</script><script src="/js/alert.js">alert(1234)</script><span style="color: red;">1234</span>'; * or * html += '<script src="/js/alert.js"></script><script type="text/javascript">console.log(window.qwerqwerqewr1234)</script><span style="color: red;">1234</span>'; * * @param html {String} * @returns {String} */ function handleScripts(html) { // html must start with tag - it's angularjs' jqLite bug/feature html = '<i></i>' + html; var originElements = angular.element(html), elements = angular.element('<div></div>'); if (originElements.length) { // start from 1 for removing first tag we just added for (var i = 1, l = originElements.length; i < l; i ++) { var $el = originElements.eq(i), el = $el[0]; if (el.nodeName == 'SCRIPT' && ((! el.type) || el.type == 'text/javascript')) { evalScript($el[0]); } else { elements.append($el); } } } // elements = elements.contents(); html = elements.html(); return html; } /** * It's taken from AngularJS' jsonpReq function. * It's not ie < 9 compatible. * @param {DOMElement} element */ function evalScript(element) { var script = document.createElement('script'), body = document.body, doneWrapper = function() { script.onload = script.onerror = null; body.removeChild(script); }; script.type = 'text/javascript'; if (element.src) { script.src = element.src; script.async = element.async; script.onload = script.onerror = function () { doneWrapper(); }; } else { // doesn't work on ie... try { script.appendChild(document.createTextNode(element.innerText)); } // IE has funky script nodes catch (e) { script.text = element.innerText; } setTimeout(function () {doneWrapper()}, 10); } body.appendChild(script); } return function ($scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.bindHtmlWithJs); var parsed = $parse(attr.bindHtmlWithJs); function getStringValue() { return (parsed($scope) || '').toString(); } $scope.$watch(getStringValue, function bindHtmlWithJsWatchAction(value) { var html = value ? $sce.getTrustedHtml(parsed($scope)) : ''; if (html) { html = handleScripts(html); } element.html(html || ''); }); }; }]). /* This filter is for demo only */ filter('trustAsHtml', ['$sce', function ($sce) { return function trustAsHtml(value) { return $sce.trustAsHtml(value); } }]); }());
var Backbone = require('backbone'), $ = require('jquery'), lang = require('../lang'), template = require('../templates/nav.hbs') module.exports = Backbone.View.extend({ events: { 'click .js-nav': 'navigate' }, initialize: function (options) { this.$el.html(template({ name: window.app.name, lang: lang })) this.$navLis = this.$('.js-li') this.setActivePage() this.listenTo(options.router, 'route', this.setActivePage) return this }, setActivePage: function () { var pathname = window.location.pathname this.$navLis.removeClass('active') this.$('.js-nav').each(function (index, value) { var $this = $(this) var href = $this.attr('href') if(href === '/') { if(pathname === '/') $this.parent().addClass('active') } else { if(href && pathname.match(new RegExp('^' + href.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')))) { $this.parent().addClass('active') } } }) }, navigate: function (e) { e.preventDefault() this.$('.navbar-collapse').removeClass('in') Backbone.history.navigate($(e.target).attr('href'), { trigger: true, replace: false }) } })
import Subject from "parsers/Subject"; describe("parsers/Subject", () => { it("should split valid subject lines into object hash", () => { let subject = "type(scope): summary summary summary"; let pull = { commits: [{ commit: { message: subject } }] }; expect((new Subject()).parse(pull)).toEqual({ type: "type", scope: "scope", summary: "summary summary summary" }); }); it("should return object with null values on invalid message", () => { let subject = "type(scope) summary summary summary"; let pull = { commits: [{ commit: { message: subject } }] }; expect((new Subject()).parse(pull)).toEqual({ type: null, scope: null, summary: null }); }); it("should parse subjects with special characters", () => { let subject = "type($state!): summary summary summary"; let pull = { commits: [{ commit: { message: subject } }] }; expect((new Subject()).parse(pull).scope).toBe("$state!"); }); });
(function($){ $(function(){ $('#zen-gallery a').lightBox({ fixedNavigation:true, imageLoading: 'zen-gallery/images/lightbox-btn-loading.gif', imageBtnClose: 'zen-gallery/images/lightbox-btn-close.gif', imageBtnPrev: 'zen-gallery/images/lightbox-btn-prev.gif', imageBtnNext: 'zen-gallery/images/lightbox-btn-next.gif' }); }); })(jQuery);
// Generated by CoffeeScript 1.3.3 (function() { var CMinion, Minion, port, restify, server; restify = require("restify"); CMinion = require("../../minion"); Minion = new CMinion(); server = restify.createServer(); server.use(restify.queryParser()); server.get("/", function(req, res) { res.send("Hello World."); return Minion.logRequest(req.query); }); port = process.env.PORT || 3000; Minion.started(); server.listen(port, function() { return console.log("Listening on port " + port); }); }).call(this);
var _ = require('underscore'); module.exports = function () { beforeEach(function () { spyOn(_, 'debounce').and.callFake(function (func) { return function () { func.apply(this, arguments); }; }); this.geometryView.render(); }); describe('when the model is removed', function () { it('should remove each geometry', function () { this.geometry.geometries.each(function (polygon) { spyOn(polygon, 'remove'); }); this.geometry.remove(); expect(this.geometry.geometries.all(function (geometry) { return geometry.remove.calls.count() === 1; })).toBe(true); }); it('should remove the view', function () { spyOn(this.geometryView, 'remove'); this.geometry.remove(); expect(this.geometryView.remove).toHaveBeenCalled(); }); }); };
var _ = require('underscore') module.exports = function (cdb) { (function () { var Layers = cdb.vis.Layers; /* * if we are using http and the tiles of base map need to be fetched from * https try to fix it */ var HTTPS_TO_HTTP = { 'https://dnv9my2eseobd.cloudfront.net/': 'http://a.tiles.mapbox.com/', 'https://maps.nlp.nokia.com/': 'http://maps.nlp.nokia.com/', 'https://tile.stamen.com/': 'http://tile.stamen.com/', "https://{s}.maps.nlp.nokia.com/": "http://{s}.maps.nlp.nokia.com/", "https://cartocdn_{s}.global.ssl.fastly.net/": "http://{s}.api.cartocdn.com/", "https://cartodb-basemaps-{s}.global.ssl.fastly.net/": "http://{s}.basemaps.cartocdn.com/" }; function transformToHTTP(tilesTemplate) { for (var url in HTTPS_TO_HTTP) { if (tilesTemplate.indexOf(url) !== -1) { return tilesTemplate.replace(url, HTTPS_TO_HTTP[url]) } } return tilesTemplate; } function transformToHTTPS(tilesTemplate) { for (var url in HTTPS_TO_HTTP) { var httpsUrl = HTTPS_TO_HTTP[url]; if (tilesTemplate.indexOf(httpsUrl) !== -1) { return tilesTemplate.replace(httpsUrl, url); } } return tilesTemplate; } Layers.register('tilejson', function (vis, data) { var url = data.tiles[0]; if (vis.https === true) { url = transformToHTTPS(url); } else if (vis.https === false) { // Checking for an explicit false value. If it's undefined the url is left as is. url = transformToHTTP(url); } return new cdb.geo.TileLayer({ urlTemplate: url }); }); Layers.register('tiled', function (vis, data) { var url = data.urlTemplate; if (vis.https === true) { url = transformToHTTPS(url); } else if (vis.https === false) { // Checking for an explicit false value. If it's undefined the url is left as is. url = transformToHTTP(url); } data.urlTemplate = url; return new cdb.geo.TileLayer(data); }); Layers.register('wms', function (vis, data) { return new cdb.geo.WMSLayer(data); }); Layers.register('gmapsbase', function (vis, data) { return new cdb.geo.GMapsBaseLayer(data); }); Layers.register('plain', function (vis, data) { return new cdb.geo.PlainLayer(data); }); Layers.register('background', function (vis, data) { return new cdb.geo.PlainLayer(data); }); function normalizeOptions(vis, data) { if (data.infowindow && data.infowindow.fields) { if (data.interactivity) { if (data.interactivity.indexOf('cartodb_id') === -1) { data.interactivity = data.interactivity + ",cartodb_id"; } } else { data.interactivity = 'cartodb_id'; } } // if https is forced if (vis.https) { data.tiler_protocol = 'https'; data.tiler_port = 443; data.sql_api_protocol = 'https'; data.sql_api_port = 443; } data.cartodb_logo = vis.cartodb_logo == undefined ? data.cartodb_logo : vis.cartodb_logo; } var cartoLayer = function (vis, data) { normalizeOptions(vis, data); // if sublayers are included that means a layergroup should // be created if (data.sublayers) { data.type = 'layergroup'; return new cdb.geo.CartoDBGroupLayer(data); } return new cdb.geo.CartoDBLayer(data); }; Layers.register('cartodb', cartoLayer); Layers.register('carto', cartoLayer); Layers.register('layergroup', function (vis, data) { normalizeOptions(vis, data); return new cdb.geo.CartoDBGroupLayer(data); }); Layers.register('namedmap', function (vis, data) { normalizeOptions(vis, data); return new cdb.geo.CartoDBNamedMapLayer(data); }); Layers.register('torque', function (vis, data) { normalizeOptions(vis, data); // default is https if (vis.https) { if (data.sql_api_domain && data.sql_api_domain.indexOf('cartodb.com') !== -1) { data.sql_api_protocol = 'https'; data.sql_api_port = 443; data.tiler_protocol = 'https'; data.tiler_port = 443; } } data.cartodb_logo = vis.cartodb_logo == undefined ? data.cartodb_logo : vis.cartodb_logo; return new cdb.geo.TorqueLayer(data); }); })(); }
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 50; // 50 seconds describe('marker_selection_test', function () { it('all_aml', function (done) { var dataset; var referenceDataset; var promises = []; promises.push(morpheus.DatasetUtil.read('test_files/all_aml_train.gct').done(function (d) { dataset = d; })); promises.push(morpheus.DatasetUtil.read('test_files/aml_aml_train_marker_selection.gct').done(function (d) { referenceDataset = d; })); Promise.all(promises).then(function () { var project = new morpheus.Project(dataset); new morpheus.MarkerSelection().execute({ project: project, input: { background: false, permutations: 1000, number_of_markers: 0, field: 'id', metric: morpheus.SignalToNoise.toString(), class_a: ['AML_12', 'AML_13', 'AML_14', 'AML_16', 'AML_20', 'AML_1', 'AML_2', 'AML_3', 'AML_5', 'AML_6', 'AML_7'], class_b: ['ALL_19769_B-cell', 'ALL_23953_B-cell', 'ALL_28373_B-cell', 'ALL_9335_B-cell', 'ALL_9692_B-cell', 'ALL_14749_B-cell', 'ALL_17281_B-cell', 'ALL_19183_B-cell', 'ALL_20414_B-cell', 'ALL_21302_B-cell', 'ALL_549_B-cell', 'ALL_17929_B-cell', 'ALL_20185_B-cell', 'ALL_11103_B-cell', 'ALL_18239_B-cell', 'ALL_5982_B-cell', 'ALL_7092_B-cell', 'ALL_R11_B-cell', 'ALL_R23_B-cell', 'ALL_16415_T-cell', 'ALL_19881_T-cell', 'ALL_9186_T-cell', 'ALL_9723_T-cell', 'ALL_17269_T-cell', 'ALL_14402_T-cell', 'ALL_17638_T-cell', 'ALL_22474_T-cell'] } }); // compare metadata fields var vector = dataset.getRowMetadata().getByName('p_value'); var referenceVector = referenceDataset.getRowMetadata().getByName('p-value'); for (var i = 0, size = vector.size(); i < size; i++) { expect(vector.getValue(i)).toBeCloseTo(referenceVector.getValue(i), 0.001); } var vector = dataset.getRowMetadata().getByName('FDR(BH)'); var referenceVector = referenceDataset.getRowMetadata().getByName('FDR(BH)'); for (var i = 0, size = vector.size(); i < size; i++) { expect(vector.getValue(i)).toBeCloseTo(referenceVector.getValue(i), 0.001); } var vector = dataset.getRowMetadata().getByName('Signal to noise'); var referenceVector = referenceDataset.getRowMetadata().getByName('Signal to noise'); for (var i = 0, size = vector.size(); i < size; i++) { expect(vector.getValue(i)).toBeCloseTo(referenceVector.getValue(i), 0.001); } done(); }); }); });
module.exports = function Clock() { // TODO }
'use strict'; describe('Registry', function() { describe('create()', function() { it('name', function() { let blot = Registry.create('bold'); expect(blot instanceof BoldBlot).toBe(true); expect(blot.statics.blotName).toBe('bold'); }); it('node', function() { let node = document.createElement('strong'); let blot = Registry.create(node); expect(blot instanceof BoldBlot).toBe(true); expect(blot.statics.blotName).toBe('bold'); }); it('block', function() { let blot = Registry.create(Registry.Scope.BLOCK_BLOT); expect(blot instanceof BlockBlot).toBe(true); expect(blot.statics.blotName).toBe('block'); }); it('inline', function() { let blot = Registry.create(Registry.Scope.INLINE_BLOT); expect(blot instanceof InlineBlot).toBe(true); expect(blot.statics.blotName).toBe('inline'); }); it('string index', function() { let blot = Registry.create('header', '2'); expect(blot instanceof HeaderBlot).toBe(true); expect(blot.formats()).toEqual({ header: 'h2' }); }); it('invalid', function() { expect(function() { Registry.create(BoldBlot); }).toThrowError(/\[Parchment\]/); }); }); describe('register()', function() { it('invalid', function() { expect(function() { Registry.register({}); }).toThrowError(/\[Parchment\]/); }); it('abstract', function() { expect(function() { Registry.register(ShadowBlot); }).toThrowError(/\[Parchment\]/); }); }); describe('find()', function() { it('exact', function() { let blockNode = document.createElement('p'); blockNode.innerHTML = '<span>01</span><em>23<strong>45</strong></em>'; let blockBlot = Registry.create(blockNode); expect(Registry.find(document.body)).toBeFalsy(); expect(Registry.find(blockNode)).toBe(blockBlot); expect(Registry.find(blockNode.querySelector('span'))).toBe(blockBlot.children.head); expect(Registry.find(blockNode.querySelector('em'))).toBe(blockBlot.children.tail); expect(Registry.find(blockNode.querySelector('strong'))).toBe( blockBlot.children.tail.children.tail, ); let text01 = blockBlot.children.head.children.head; let text23 = blockBlot.children.tail.children.head; let text45 = blockBlot.children.tail.children.tail.children.head; expect(Registry.find(text01.domNode)).toBe(text01); expect(Registry.find(text23.domNode)).toBe(text23); expect(Registry.find(text45.domNode)).toBe(text45); }); it('bubble', function() { let blockBlot = Registry.create('block'); let textNode = document.createTextNode('Test'); blockBlot.domNode.appendChild(textNode); expect(Registry.find(textNode)).toBeFalsy(); expect(Registry.find(textNode, true)).toEqual(blockBlot); }); it('detached parent', function() { let blockNode = document.createElement('p'); blockNode.appendChild(document.createTextNode('Test')); expect(Registry.find(blockNode.firstChild)).toBeFalsy(); expect(Registry.find(blockNode.firstChild, true)).toBeFalsy(); }); }); describe('query()', function() { it('class', function() { let node = document.createElement('em'); node.setAttribute('class', 'author-blot'); expect(Registry.query(node)).toBe(AuthorBlot); }); it('type mismatch', function() { let match = Registry.query('italic', Registry.Scope.ATTRIBUTE); expect(match).toBeFalsy(); }); it('level mismatch for blot', function() { let match = Registry.query('italic', Registry.Scope.BLOCK); expect(match).toBeFalsy(); }); it('level mismatch for attribute', function() { let match = Registry.query('color', Registry.Scope.BLOCK); expect(match).toBeFalsy(); }); it('either level', function() { let match = Registry.query('italic', Registry.Scope.BLOCK | Registry.Scope.INLINE); expect(match).toBe(ItalicBlot); }); it('level and type match', function() { let match = Registry.query('italic', Registry.Scope.INLINE & Registry.Scope.BLOT); expect(match).toBe(ItalicBlot); }); it('level match and type mismatch', function() { let match = Registry.query('italic', Registry.Scope.INLINE & Registry.Scope.ATTRIBUTE); expect(match).toBeFalsy(); }); it('type match and level mismatch', function() { let match = Registry.query('italic', Registry.Scope.BLOCK & Registry.Scope.BLOT); expect(match).toBeFalsy(); }); }); });
import propertyTest from '../../helpers/propertyTest' propertyTest('DTEND', { transformableValue: new Date('1991-03-07 09:00:00'), transformedValue: '19910307T090000' })
module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { EXTEND_PROTOTYPES: false, FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; ENV.APP.autoboot = false; } if (environment === 'production') { ENV.baseURL = '/ember-collection'; ENV.locationType = 'hash'; } return ENV; };
/** * Created by fengyuanzemin on 17/2/15. */ import Vue from 'vue'; import Vuex from 'vuex'; import * as actions from './actions'; import * as mutations from './mutations'; Vue.use(Vuex); const state = { isShow: false, msg: '出错了', isBig: true, token: localStorage.getItem('f-token'), init: false }; export default new Vuex.Store({ state, actions, mutations });
/*global describe, it, expect, require*/ const nodeToBox = require('../../../src/core/layout/node-to-box'); describe('nodeToBox', function () { 'use strict'; it('should convert node to a box', function () { expect(nodeToBox({x: 10, styles: ['blue'], y: 20, width: 30, height: 40, level: 2})).toEqual({left: 10, styles: ['blue'], top: 20, width: 30, height: 40, level: 2}); }); it('should append default styles if not provided', function () { expect(nodeToBox({x: 10, y: 20, width: 30, height: 40, level: 2})).toEqual({left: 10, styles: ['default'], top: 20, width: 30, height: 40, level: 2}); }); it('should return falsy for undefined', function () { expect(nodeToBox()).toBeFalsy(); }); it('should return falsy for falsy', function () { expect(nodeToBox(false)).toBeFalsy(); }); });
//= require redactor-rails/plugins/clips //= require redactor-rails/plugins/fontcolor //= require redactor-rails/plugins/fontfamily //= require redactor-rails/plugins/fontsize //= require redactor-rails/plugins/fullscreen //= require redactor-rails/plugins/table //= require redactor-rails/plugins/textdirection //= require redactor-rails/plugins/video
import webpack from "webpack" import { spawn } from "child_process" import appRootDir from "app-root-dir" import path from "path" import { createNotification } from "./util" import HotServerManager from "./HotServerManager" import HotClientManager from "./HotClientManager" import ConfigFactory from "../webpack/ConfigFactory" import StatusPlugin from "../webpack/plugins/Status" function safeDisposer(manager) { return manager ? manager.dispose() : Promise.resolve() } /* eslint-disable arrow-body-style, no-console */ function createCompiler({ name, start, done }) { try { const webpackConfig = ConfigFactory({ target: name === "server" ? "node" : "web", mode: "development" }) // Offering a special status handling until Webpack offers a proper `done()` callback // See also: https://github.com/webpack/webpack/issues/4243 webpackConfig.plugins.push(new StatusPlugin({ name, start, done })) return webpack(webpackConfig) } catch (error) { createNotification({ title: "development", level: "error", message: "Webpack config is invalid, please check the console for more information.", notify: true }) console.error(error) throw error } } export default class HotController { constructor() { this.hotClientManager = null this.hotServerManager = null this.clientIsBuilding = false this.serverIsBuilding = false this.timeout = 0 const createClientManager = () => { return new Promise((resolve) => { const compiler = createCompiler({ name: "client", start: () => { this.clientIsBuilding = true createNotification({ title: "Hot Client", level: "info", message: "Building new bundle..." }) }, done: () => { this.clientIsBuilding = false createNotification({ title: "Hot Client", level: "info", message: "Bundle is ready.", notify: true }) resolve(compiler) } }) this.hotClientCompiler = compiler this.hotClientManager = new HotClientManager(compiler) }) } const createServerManager = () => { return new Promise((resolve) => { const compiler = createCompiler({ name: "server", start: () => { this.serverIsBuilding = true createNotification({ title: "Hot Server", level: "info", message: "Building new bundle..." }) }, done: () => { this.serverIsBuilding = false createNotification({ title: "Hot Server", level: "info", message: "Bundle is ready.", notify: true }) this.tryStartServer() resolve(compiler) } }) this.compiledServer = path.resolve( appRootDir.get(), compiler.options.output.path, `${Object.keys(compiler.options.entry)[0]}.js`, ) this.hotServerCompiler = compiler this.hotServerManager = new HotServerManager(compiler, this.hotClientCompiler) }) } createClientManager().then(createServerManager).catch((error) => { console.error("Error during build:", error) }) } tryStartServer = () => { if (this.clientIsBuilding) { if (this.serverTryTimeout) { clearTimeout(this.serverTryTimeout) } this.serverTryTimeout = setTimeout(this.tryStartServer, this.timeout) this.timeout += 100 return } this.startServer() this.timeout = 0 } startServer = () => { if (this.server) { this.server.kill() this.server = null createNotification({ title: "Hot Server", level: "info", message: "Restarting server..." }) } const newServer = spawn("node", [ "--inspect", this.compiledServer, "--colors" ], { stdio: [ process.stdin, process.stdout, "pipe" ] }) createNotification({ title: "Hot Server", level: "info", message: "Server running with latest changes.", notify: true }) newServer.stderr.on("data", (data) => { createNotification({ title: "Hot Server", level: "error", message: "Error in server execution, check the console for more info." }) process.stderr.write("\n") process.stderr.write(data) process.stderr.write("\n") }) this.server = newServer } dispose() { // First the hot client server. Then dispose the hot node server. return safeDisposer(this.hotClientManager).then(() => safeDisposer(this.hotServerManager)).catch((error) => { console.error(error) }) } }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let SyncDisabled = props => <SvgIcon {...props}> <path d="M10 6.35V4.26c-.8.21-1.55.54-2.23.96l1.46 1.46c.25-.12.5-.24.77-.33zm-7.14-.94l2.36 2.36C4.45 8.99 4 10.44 4 12c0 2.21.91 4.2 2.36 5.64L4 20h6v-6l-2.24 2.24C6.68 15.15 6 13.66 6 12c0-1 .25-1.94.68-2.77l8.08 8.08c-.25.13-.5.25-.77.34v2.09c.8-.21 1.55-.54 2.23-.96l2.36 2.36 1.27-1.27L4.14 4.14 2.86 5.41zM20 4h-6v6l2.24-2.24C17.32 8.85 18 10.34 18 12c0 1-.25 1.94-.68 2.77l1.46 1.46C19.55 15.01 20 13.56 20 12c0-2.21-.91-4.2-2.36-5.64L20 4z" /> </SvgIcon>; SyncDisabled = pure(SyncDisabled); SyncDisabled.muiName = 'SvgIcon'; export default SyncDisabled;
// Generated by CoffeeScript 1.6.3 (function() { var Stl, stl_parser; stl_parser = require('../parser/stl_parser'); Stl = (function() { function Stl() {} return Stl; })(); Stl.PovRay = (function() { function PovRay() {} PovRay.prototype._povHeaders = function(name) { return "#declare " + name + " = mesh {\n"; }; PovRay.prototype._povFooters = function() { return "}"; }; PovRay.prototype.convertFile = function(filePath, callback, progressCb) { var output, _this = this; output = ""; return stl_parser.parseFile(filePath, function(err, polygons, name) { var unique_name; if (err != null) { callback(err); return; } unique_name = '__' + name + '__'; output += _this._povFooters(); return callback(null, output, unique_name); }, function(err, polygon, name) { var povPolygon, unique_name; unique_name = '__' + name + '__'; if (output.length === 0) { output += _this._povHeaders(unique_name); } povPolygon = _this.convertPolygon(polygon); output += povPolygon; if (progressCb != null) { return progressCb(err, povPolygon, unique_name); } }); }; PovRay.prototype.convertPolygon = function(polygon) { var idx, output, vertex, _i, _len, _ref; output = ""; output += " triangle {\n"; _ref = polygon.verticies; for (idx = _i = 0, _len = _ref.length; _i < _len; idx = ++_i) { vertex = _ref[idx]; output += " <" + vertex[0] + ", " + (-vertex[1]) + ", " + vertex[2] + ">"; if (idx !== (polygon.verticies.length - 1)) { output += ",\n"; } } output += " }\n"; return output; }; return PovRay; })(); module.exports = new Stl.PovRay(); }).call(this);
ace.define("ace/snippets/apache_conf",["require","exports","module"], function(require, exports, module) { "use strict"; exports.snippetText = ""; exports.scope = "apache_conf"; }); (function() { ace.require(["ace/snippets/apache_conf"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
// @flow var React = require('react') var {assign} = require('lodash') import {Source, emptySource} from './model/source' import {displayIf, Colors} from './style' // but get the images at 2x resolution so they can be retina yo // or just get the photos at that ratio // 200x320 x2 // 150x240 // 100x160 // Blank Image - http://i.imgur.com/bMwt85W.jpg type Size = { Width: number; Height: number; } export var CoverSize = { Width: 150, Height: 240, Ratio: 1.6 } export var CoverThumb = { Width: 50, Height: 80, } export function coverStyle(url:string, size:Size = CoverSize):Object { // otherwise it forgets about the cover. Wait until the image is ready if (!url) { return {} } return { background: 'url('+url+') no-repeat center center', backgroundSize: 'cover', width: size.Width, height: size.Height } } export class CoverOverlay extends React.Component { render():React.Element { var style = assign( displayIf(this.props.show !== false), OverlayStyle, CoverTextStyle, this.props.style ) return <div style={style}> {this.props.children} </div> } } export class Cover extends React.Component { props: { src: string; size?: Size; children: Array<React.Element>; }; render():React.Element { var size = this.props.size || CoverSize return <div style={assign(coverStyle(this.props.src, size), {position: 'relative'})}> {this.props.children} </div> } } export class SourceCover extends React.Component { render():React.Element { var source:Source = this.props.source || emptySource() var showTitle:bool = source.imageMissingTitle return <Cover src={source.imageUrl}> <CoverOverlay show={showTitle}>{source.name}</CoverOverlay> </Cover> } } // I could specify it in terms of percentages instead? // that's a good idea. // so do I want 2 or 3 across? // definitely 3 :) export var OverlayStyle = { padding: 10, color: Colors.light, textAlign: 'center', position: 'absolute', bottom: 0, fontSize: 18, backgroundColor: 'rgba(0, 0, 0, 0.5)', width: CoverSize.Width } export var CoverTextStyle = { fontSize: 18, }
define([ 'jquery', 'underscore', 'backbone', 'views/AdminView', 'authentication', 'models/Beach' ], function ( $, _, Backbone, AdminView, Authentication, BeachModel) { var AdminRouter = Backbone.Router.extend({ routes: { 'admin' : 'index' }, index: function () { Authentication.authorize(function () { $('#content').html("<p style='display: block; font-size: 15%; text-align: center; line-height: 100vh; margin: 0;'>LOADING</p>"); beaches = new BeachModel.Collection(); beaches.fetch( { success: function( collection, response, options) { var adminView = new AdminView({ collection: collection }); $('#content').html(adminView.el); }, failure: function( collection, response, options) { $('#content').html("An error has occured."); } }); }, true); }, }); return AdminRouter; });
const labels = { collectionFilterLabels: { edit: { name: 'Event name', event_type: 'Type of event', address_country: 'Country', uk_region: 'UK Region', organiser: 'Organiser', start_date_after: 'From', start_date_before: 'To', }, }, } module.exports = labels
(function ($) { var smileys = [ ":(", ":)", ":O", ":D", ":p", ":*", ":-)", ":-(", ":-O", ":-D" ], extras = { "<3": true, "&lt;3": true }, smileParts = { "O": "middle-mouth", "D": "middle-mouth", "d": "middle-mouth", "p": "low-mouth", "*": "high-mouth", "-": "nose" }, oppositeSmileParts = { "p": "d", ")": "(", "(": ")" }, reverseSmileys = []; for (var i = 0; i < smileys.length; i++) { var reverse = ""; for (var j = smileys[i].length - 1; j >= 0; j--) { var character = smileys[i][j]; if (character in oppositeSmileParts) { reverse += oppositeSmileParts[smileys[i][j]]; } else { reverse += smileys[i][j]; } } reverseSmileys.push(reverse); } function toggleSmiley() { $(this).toggleClass("active"); } function prepareSmileys(html) { for (var extra in extras) { html = checkForSmiley(html, extra, extras[extra]); } for (var i = smileys.length - 1; i >= 0; i--) { html = checkForSmiley(html, smileys[i], false); } for (var i = reverseSmileys.length - 1; i >= 0; i--) { html = checkForSmiley(html, reverseSmileys[i], true); } return html; } function checkForSmiley(html, smiley, isReverse) { var index = html.indexOf(smiley), replace = null; while (index >= 0) { if (replace === null) { replace = prepareSmiley(smiley, isReverse); } html = replaceString(html, replace, index, index + smiley.length); index = html.indexOf(smiley, index + replace.length); } return html; } function prepareSmiley(smiley, isReverse) { var html = '<span class="smiley-wrapper"><span class="smiley' + (isReverse ? ' smiley-reverse' : '') + '">'; for (var i = 0; i < smiley.length; i++) { if (smiley[i] in smileParts) { html += '<span class="' + smileParts[smiley[i]] + '">' + smiley[i] + '</span>'; } else { html += smiley[i]; } }; html += '</span></span>'; return html; } function replaceString(string, replace, from, to) { return string.substring(0, from) + replace + string.substring(to); } function fixSmiles($el) { var smiles = prepareSmileys($el.html()); $el.html(smiles); } $(document).on("click", ".smiley", toggleSmiley); $.fn.smilify = function() { var $els = $(this).each(function () { fixSmiles($(this)); }); setTimeout(function () { $els.find(".smiley").each(toggleSmiley); }, 20); return this; }; }(jQuery));
//@flow var x = 42; x = "true"; var y = 42; if (x) { y = "hello world"; } (42: string); // should still have some errors!
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let BeachAccess = props => <SvgIcon {...props}> <path d="M13.127 14.56l1.43-1.43 6.44 6.443L19.57 21zm4.293-5.73l2.86-2.86c-3.95-3.95-10.35-3.96-14.3-.02 3.93-1.3 8.31-.25 11.44 2.88zM5.95 5.98c-3.94 3.95-3.93 10.35.02 14.3l2.86-2.86C5.7 14.29 4.65 9.91 5.95 5.98zm.02-.02l-.01.01c-.38 3.01 1.17 6.88 4.3 10.02l5.73-5.73c-3.13-3.13-7.01-4.68-10.02-4.3z" /> </SvgIcon>; BeachAccess = pure(BeachAccess); BeachAccess.muiName = 'SvgIcon'; export default BeachAccess;
{ var x = f; x = items[0]; x = items[1]; }
import xhr from './lib/xhr'; class ShowsModel { constructor() { this.shows = []; } fetch(cb) { xhr('https://raw.githubusercontent.com/dashersw/erste.js-demo/master/src/static/data/shows.json', (err, data) => { this.shows = data.slice(0, 20); cb(this.shows); }); }; } export default new ShowsModel();
export default function calculateScore (subject, chosenId, time) { const isCorrectAnswer = subject.id === chosenId let score if(isCorrectAnswer) { if(time < 7) { score = 3 } else { // Needs review score = .9 + (2 * (1/subject.seenCount)) } } else { // Degrees of failure score = 1/subject.seenCount } subject.score = score return [subject, score] }
import { createRouter, createWebHistory } from "vue-router/dist/vue-router.esm.js"; import Home from "./views/Home.vue"; const routerHistory = createWebHistory("/"); let router = createRouter({ history: routerHistory, routes: [ { path: '/', component: Home, name: '' }, { path: '/who', component: Home, name: 'who' }, { path: '/what', component: Home, name: 'what' }, { path: '/where', component: Home, name: 'where' }, { path: '/when', component: Home, name: 'when' }, { path: '/why', component: Home, name: 'why' } ] }); router.afterEach((to, from) => { console.info((to, from, window.location.pathname)); }) export default router;
'use strict'; var crypto = require('crypto'); exports.typeOf = function(obj) { var classToType; if (obj === void 0 || obj === null) { return String(obj); } classToType = { '[object Boolean]': 'boolean', '[object Number]': 'number', '[object String]': 'string', '[object Function]': 'function', '[object Array]': 'array', '[object Date]': 'date', '[object RegExp]': 'regexp', '[object Object]': 'object' }; return classToType[Object.prototype.toString.call(obj)]; }; exports.unauthResp = function(res) { res.statusCode = 401; res.setHeader('content-type', 'application/json; charset=UTF-8'); return res.end(JSON.stringify({ code: 401, error: 'Unauthorized.' })); }; exports.signHook = function(masterKey, hookName, ts) { return ts + ',' + crypto.createHmac('sha1', masterKey).update(hookName + ':' + ts).digest('hex'); }; exports.verifyHookSign = function(masterKey, hookName, sign) { if (sign) { return exports.signHook(masterKey, hookName, sign.split(',')[0]) === sign; } else { return false; } }; /* options: req, user, params, object*/ exports.prepareRequestObject = function(options) { var req = options.req; var user = options.user; var currentUser = user || (req && req.AV && req.AV.user); return { expressReq: req, params: options.params, object: options.object, meta: { remoteAddress: req && req.headers && getRemoteAddress(req) }, user: user, currentUser: currentUser, sessionToken: (currentUser && currentUser.getSessionToken()) || (req && req.sessionToken) }; }; exports.prepareResponseObject = function(res, callback) { return { success: function(result) { callback(null, result); }, error: function(error) { callback(error); } }; }; var getRemoteAddress = exports.getRemoteAddress = function(req) { return req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress }; exports.endsWith = function(str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; };
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M17 3H3v18h18V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z" }), 'SaveSharp');
import fulfillQuery from '../../../src/webserver/db/fulfillQuery' // eslint-disable-line describe('webserver/db/fulfillQuery', () => { it('should work') })
'use strict'; var Foundationify = (function () { // Initalize product image gallery function on product pages function initProductImages() { // Define the scope var $productImages = $('#product-images', 'body.product'); // Select the thumbnails var $thumbs = $('ul img', $productImages); if ($thumbs.length) { // Select the large image var $largeImage = $('img', $productImages).first(); // Change the large image src and alt attributes on click $thumbs.on('click', function (e) { e.preventDefault(); // Skip if thumb matches large if ($largeImage.attr('src') === $(this).parent('a').attr('href')) { return; } // Change the cursor to the loading cursor $('body').css('cursor', 'progress'); // Change the src and alt attributes of the large image $largeImage.attr('src', $(this).parent('a').attr('href')) .attr('alt', $(this).attr('alt')); }); // Return the loading cursor to default after the large image has loaded $largeImage.on('load', function () { $('body').css('cursor', 'auto'); }); } } return { init: function () { initProductImages(); } }; }()); $(document).ready(function () { Foundationify.init(); });
/* eslint-env mocha */ import { Controller } from '../' import assert from 'assert' import { equals } from './' import { state, props } from '../tags' describe('operator.equals', () => { it('should go down path based on props', () => { let count = 0 const controller = Controller({ state: { foo: 'bar', }, signals: { test: [ equals(props`foo`), { bar: [ () => { count++ }, ], otherwise: [], }, ], }, }) controller.getSignal('test')({ foo: 'bar' }) assert.equal(count, 1) }) it('should go down path based on state', () => { let count = 0 const controller = Controller({ state: { foo: 'bar', }, signals: { test: [ equals(state`foo`), { bar: [ () => { count++ }, ], otherwise: [], }, ], }, }) controller.getSignal('test')() assert.equal(count, 1) }) it('should throw on bad argument', done => { const controller = Controller({ state: { foo: 'bar', }, signals: { test: [ equals('foo'), { bar: [() => {}], otherwise: [], }, ], }, }) controller.removeListener('error') controller.once('error', error => { assert.ok(error) done() }) controller.getSignal('test')() }) })
module.exports = function(EmailAddress) { };
import { create } from 'ember-cli-page-object'; import leadershipCollapsed from 'ilios-common/page-objects/components/leadership-collapsed'; import overview from './overview'; import header from './header'; import leadershipExpanded from './leadership-expanded'; const definition = { scope: '[data-test-program-details]', header, overview, leadershipCollapsed, leadershipExpanded, }; export default definition; export const component = create(definition);
version https://git-lfs.github.com/spec/v1 oid sha256:07e25b6c05d06d085c2840d85f2966476dc38544be904c978d7c66dbe688decb size 4672
/** * Copyright 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @providesModule relayUnstableBatchedUpdates * * @format */ 'use strict'; module.exports = require('react-dom').unstable_batchedUpdates;
// support CommonJS, AMD & browser /* istanbul ignore next */ if (typeof exports === T_OBJECT) module.exports = riot else if (typeof define === 'function' && define.amd) define(function() { return (window.riot = riot) }) else window.riot = riot })(typeof window != 'undefined' ? window : void 0);
/* $(document.body).ready(function() { FormKit.install(); FormKit.initialize(document.body); }); Inside Ajax Region: $(document.body).ready(function() { FormKit.initialize( div element ); }); */ var FormKit = { register: function(initHandler,installHandler) { $(FormKit).bind('formkit.initialize',initHandler); if( installHandler ) { $(this).bind('formkit.install',installHandler); } }, initialize: function(scopeEl) { if(!scopeEl) scopeEl = document.body; $(FormKit).trigger('formkit.initialize',[scopeEl]); }, install: function() { $(FormKit).trigger('formkit.install'); } };
// webpack.config.js module.exports = { module: { rules: [ { test: /\.css$/, use: [ 'vue-style-loader', { loader: 'css-loader', options: { importLoaders: 1 } }, 'postcss-loader' ] } ] } }
/** * @module kat-cr/lib/fetch * @description * Wraps request in a Promise */ /** * The HTTP response class provided by request * @external HTTPResponse * @see {@link http://github.com/request/request} */ "use strict"; const request = (function loadPrivate(module) { let modulePath = require.resolve(module), cached = require.cache[modulePath]; delete require.cache[modulePath]; let retval = require(module); require.cache[modulePath] = cached; return retval; })('request'), USER_AGENTS = require('../config/user-agents'); // Not necessary as of now, but in case Kickass Torrents requires cookies enabled in the future, and in case the library user needs to use request with his or her own cookie jar, we load a private copy of request so we can use our own cookie jar instead of overriding the global one request.defaults({ jar: true }); /** * @description * Wraps request in a Promise, also sets a random user agent * @param {Object} config The details of the request as if it were passed to request directly * @returns {Promise.<external:HTTPResponse>} A promise which resolves with the response, or rejects with an error * @example * // Make a request to a JSON API * require('kat-cr/lib/fetch')({ * method: 'GET', * url: 'http://server.com/json-endpoint', * }).then(function (response) { * JSON.parse(response.body); * }); */ module.exports = function fetch(config) { if (!config) config = {}; if (!config.headers) config.headers = {}; config.headers['user-agent'] = USER_AGENTS[Math.floor(Math.random()*USER_AGENTS.length)]; return new Promise(function (resolve, reject) { request(config, function (err, resp, body) { if (err) reject(err); resolve(resp); }); }); }; /** Expose private request module for debugging */ module.exports._request = request;
/** * Method to set dom events * * @example * wysihtml.dom.observe(iframe.contentWindow.document.body, ["focus", "blur"], function() { ... }); */ wysihtml.dom.observe = function(element, eventNames, handler) { eventNames = typeof(eventNames) === "string" ? [eventNames] : eventNames; var handlerWrapper, eventName, i = 0, length = eventNames.length; for (; i<length; i++) { eventName = eventNames[i]; if (element.addEventListener) { element.addEventListener(eventName, handler, false); } else { handlerWrapper = function(event) { if (!("target" in event)) { event.target = event.srcElement; } event.preventDefault = event.preventDefault || function() { this.returnValue = false; }; event.stopPropagation = event.stopPropagation || function() { this.cancelBubble = true; }; handler.call(element, event); }; element.attachEvent("on" + eventName, handlerWrapper); } } return { stop: function() { var eventName, i = 0, length = eventNames.length; for (; i<length; i++) { eventName = eventNames[i]; if (element.removeEventListener) { element.removeEventListener(eventName, handler, false); } else { element.detachEvent("on" + eventName, handlerWrapper); } } } }; };
import { includes } from './array_proxy' /** * Given a record and an update object, apply the update on the record. Note * that the `operate` object is unapplied. * * @param {Object} record * @param {Object} update */ export default function applyUpdate (record, update) { for (let field in update.replace) record[field] = update.replace[field] for (let field in update.push) { const value = update.push[field] record[field] = record[field] ? record[field].slice() : [] if (Array.isArray(value)) record[field].push(...value) else record[field].push(value) } for (let field in update.pull) { const value = update.pull[field] record[field] = record[field] ? record[field].slice().filter(exclude.bind(null, Array.isArray(value) ? value : [ value ])) : [] } } function exclude (values, value) { return !includes(values, value) }
#!/usr/bin/env node var logger = require('../lib/logger')('test-logger'); var config = require('../lib/config'); var count = 1; setInterval(function() { logger.debug(count); logger.info(count); count += 1; }, 1000);
/** * Parse an array of chromsizes, for example that result * from reading rows of a chromsizes CSV file. * @param {array} data Array of [chrName, chrLen] "tuples". * @returns {object} Object containing properties * { cumPositions, chrPositions, totalLength, chromLengths }. */ function parseChromsizesRows(data) { const cumValues = []; const chromLengths = {}; const chrPositions = {}; let totalLength = 0; for (let i = 0; i < data.length; i++) { const length = Number(data[i][1]); totalLength += length; const newValue = { id: i, chr: data[i][0], pos: totalLength - length, }; cumValues.push(newValue); chrPositions[newValue.chr] = newValue; chromLengths[data[i][0]] = length; } return { cumPositions: cumValues, chrPositions, totalLength, chromLengths, }; } export default parseChromsizesRows;
'use strict'; /** * Module dependencies */ var hbs = require('express-hbs'); function content(options) { return new hbs.handlebars.SafeString(this.html || ''); } module.exports = content; // downsize = Tag-safe truncation for HTML and XML. Works by word!
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M15 6H4v12.01h16V11h-5z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M4 4c-1.1 0-2 .9-2 2v12.01c0 1.1.9 1.99 2 1.99h16c1.1 0 2-.9 2-2v-8l-6-6H4zm16 14.01H4V6h11v5h5v7.01z" }, "1")], 'NoteTwoTone'); exports.default = _default;
/* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const _ = require("underscore") const path = require("path") const jade = require("jade") const fs = require("fs") const moment = require("moment") const Curation = require("../../../../../models/curation.coffee") const Article = require("../../../../../models/article.coffee") const render = function (templateName) { const filename = path.resolve( __dirname, `../../../components/venice_2017/templates/${templateName}.jade` ) return jade.compile(fs.readFileSync(filename), { filename }) } describe("Venice index", () => it("uses social metadata", function () { const curation = new Curation({ sections: [ { social_description: "Social Description", social_title: "Social Title", social_image: "files.artsy.net/img/social_image.jpg", seo_description: "Seo Description", }, ], sub_articles: [], }) const html = render("index")({ videoIndex: 0, curation, isSubscribed: false, sub_articles: [], videoGuide: new Article(), crop(url) { return url }, resize(url) { return url }, moment, sd: {}, markdown() {}, asset() {}, }) html.should.containEql( '<meta property="og:image" content="files.artsy.net/img/social_image.jpg">' ) html.should.containEql('<meta property="og:title" content="Social Title">') html.should.containEql( '<meta property="og:description" content="Social Description">' ) return html.should.containEql( '<meta name="description" content="Seo Description">' ) })) describe("Venice video_completed", () => it("passes section url to social mixin", function () { const html = render("video_completed")({ section: { social_title: "Social Title", slug: "ep-1", }, sd: { APP_URL: "http://localhost:5000" }, }) html.should.containEql( "https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Flocalhost%3A5000%2Fvenice-biennale%2Fep-1" ) return html.should.containEql("Social Title") })) describe("Venice video_description", () => it("passes section url to social mixin", function () { const html = render("video_description")({ section: { social_title: "Social Title", slug: "ep-1", published: true, }, sd: { APP_URL: "http://localhost:5000" }, markdown() {}, }) html.should.containEql( "https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Flocalhost%3A5000%2Fvenice-biennale%2Fep-1" ) return html.should.containEql("Social Title") }))
module.exports = require('../lib/') .extend('faker', function() { try { return require('faker/locale/zh_CN'); } catch (e) { return null; } });
var webpack = require("webpack"), HtmlWebpackPlugin = require("html-webpack-plugin"), ExtractTextPlugin = require("extract-text-webpack-plugin"), CopyWebpackPlugin = require("copy-webpack-plugin"), helpers = require("./helpers"); const exercisePath = process.env.exercise; var plugins = [ new webpack.optimize.CommonsChunkPlugin({ name: ["app", "vendor", "polyfills"] }), new ExtractTextPlugin("[name].css"), new HtmlWebpackPlugin({ template: "index.html" }) ]; if (exercisePath === 'localization') { plugins.push( new CopyWebpackPlugin([{ from: "i18n", to: "i18n" }]) ) } module.exports = { context: helpers.root() + '/' + exercisePath + "/src", entry: { app: "./main.ts", vendor: helpers.root() + "/common/vendor.ts", polyfills: helpers.root() + "/common/polyfills.ts" }, resolve: { extensions: [".webpack.js", ".web.js", ".ts", ".js"] }, module: { exprContextCritical: false, loaders: [ { test: /\.ts$/, loaders: ["ts-loader", "angular2-router-loader?debug=true"] }, { test: /\.html$/, loader: "html-loader" }, { test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/, loader: "file?name=assets/[name].[hash].[ext]" }, { test: /\.css$/, exclude: helpers.root("src", "app"), loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' }) }, { test: /\.css$/, include: helpers.root("src", "app"), loader: "raw-loader" }, { test: /\.s(a|c)ss$/, loaders: ["raw-loader", "sass-loader"] } ] }, plugins: plugins, devtool: "source-map", output: { path: helpers.root("dist"), publicPath: "http://localhost:8080/", filename: "[name].js", chunkFilename: "[id].chunk.js" }, devServer: { historyApiFallback: { index: "http://localhost:8080/index.html" } } }
import React, { Component, PropTypes } from 'react'; import DatePicker from 'material-ui/lib/date-picker/date-picker'; import * as layouts from '../../store/db_layouts.js'; function fmtDate( dt ) { return dt.toLocaleDateString(); } const CompFormDate = (props) => { const f = props.field; const curr_date = new Date( props.value ); // Drop the first argument, and send date in a god format for us let handleChange = ( this_is_null, new_date ) => { props.onChange( f, layouts.asYYYYMMDD( new_date )); }; return ( <DatePicker hintText={f.field} className="form_input" floatingLabelText={f.field} autoOk textFieldStyle={f.textstyle} style={f.style} formatDate={fmtDate} value={curr_date} mode="landscape" onChange={handleChange} />); }; CompFormDate.propTypes = { field: PropTypes.object.isRequired, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired }; export default CompFormDate;
/*global console: false, creatis_carpenterStorage_replaceContentFromStorage: false */ $(function () { function initDesktop() { $("#accordion").accordion({ collapsible: true, active: localStorage.selectedCarpenter ? false : true, }); // Kontaktseite Suche $("#search-site-submit").click(function () { var searchQuery = $("#search-query-site").val(); if (isValidPostal(searchQuery)) { document.location = "/tischler?query=" + searchQuery; } return false; }); $("#search-query-site").on('input', function () { var isValid = isValidPostal($("#search-query-site").val()); $("#search-query-site").css('border-color', !isValid ? 'red' : '#d5d5d5'); }); $("#search-query").on('input', function () { var isValid = isValidPostal($("#search-query").val()); $("#search-query").css('border-color', !isValid ? 'red' : '#d5d5d5'); }); //Prevent default on enter $('#search-query').keypress(function (event) { if (event.keyCode == 10 || event.keyCode == 13) event.preventDefault(); }); $("#accordion").removeClass('c-hidden'); $("#search-flyout-submit").click(function () { var searchQuery = $("#search-query").val(); if (searchQuery !== null && searchQuery !== "" && isValidPostal(searchQuery)) { document.location = "/tischler?query=" + searchQuery; } return false; }); if (typeof (creatis_carpenterStorage_replaceContentFromStorage) !== "undefined") { creatis_carpenterStorage_replaceContentFromStorage(); } } function initMobile() { //code taken from https://github.com/codrops/ButtonComponentMorph/blob/master/index.html var docElem = window.document.documentElement, didScroll, scrollPosition; // trick to prevent scrolling when opening/closing button function noScrollFn() { window.scrollTo(scrollPosition ? scrollPosition.x : 0, scrollPosition ? scrollPosition.y : 0); } function noScroll() { window.removeEventListener('scroll', scrollHandler); window.addEventListener('scroll', noScrollFn); } function scrollFn() { window.addEventListener('scroll', scrollHandler); } function canScroll() { window.removeEventListener('scroll', noScrollFn); scrollFn(); } function scrollHandler() { if (!didScroll) { didScroll = true; setTimeout(function () { scrollPage(); }, 60); } }; function scrollPage() { scrollPosition = { x: window.pageXOffset || docElem.scrollLeft, y: window.pageYOffset || docElem.scrollTop }; didScroll = false; }; scrollFn(); // Mobile carpenter search button var mobileSearchButton = document.querySelector('#search-mobile .morph-button'); $('#search-mobile .morph-button').click(function (ev) { if (ev.originalEvent) { ev.originalEvent.preventDefault(); } }); var mobileSearchMorphingButton = new UIMorphingButton(mobileSearchButton, { closeEl: '.icon-close', onBeforeOpen: function () { // don't allow to scroll noScroll(); }, onAfterOpen: function () { // can scroll again canScroll(); $('.dialog-page').hide(); $('.mobile-search-page-overview').show(); }, onBeforeClose: function () { // don't allow to scroll noScroll(); }, onAfterClose: function () { // can scroll again if (window.buyWithoutCarpenter && localStorage.selectedCarpenter !== null) { $('#purchase-request-starter')[0].click(); } else { window.buyWithoutCarpenter = false; } canScroll(); } }); } (function startup() { if (isMobile()) { initMobile(); } else { if ($("#accordion").length > 0) { initDesktop(); } } //initDesktop(); //initMobile(); displaySelectedCarpenter(); })(); }); function isMobile() { return $("#search-mobile").css("visibility") === "visible"; } function displaySelectedCarpenter() { if (localStorage.selectedCarpenter) { $('#div_text').css('display', 'none'); var data = JSON.parse(localStorage.getItem('selectedCarpenter')); var cId = data.id; setTimeout(function () { $('#' + cId + ' .btn-select').first().trigger('click'); }, 50); } }
import { create, visitable } from 'ember-cli-page-object'; import accountSetup from 'code-corps-ember/tests/pages/components/payments/account-setup'; export default create({ visit: visitable(':organization/:project/settings/donations/payments'), accountSetup });
'use strict'; /* main App */ var app = angular.module('submitConformationcontroller', []); app.controller('confirmationCtrl', ['$scope', function($scope){ $scope.volunteerList = ["Joop Bakker", "Dirk Dijkstra", "Sterre Hendriks", "Hendrik Jacobs", "Hans Heuvel", "Jaap Beek", "Jan-Jaap Dijk", "Marleen Jansen", "Geert Hoek", "Beer Heuvel"]; $scope.jobTitle = ''; $scope.jobType = ''; $scope.describeWork = ''; function getParameterByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } $scope.jobTitle = getParameterByName('jobTitle'); $scope.jobType = getParameterByName('jobType'); $scope.describeWork = getParameterByName('describeWork'); }]);
var React = require('react'); var Router = require('react-router'); var whenKeys = require('when/keys'); var EventEmitter = require('events').EventEmitter; var { Route, DefaultRoute, RouteHandler, Link } = Router; var API = 'http://addressbook-api.herokuapp.com'; var loadingEvents = new EventEmitter(); function getJSON(url) { if (getJSON._cache[url]) return Promise.resolve(getJSON._cache[url]); return new Promise((resolve, reject) => { var req = new XMLHttpRequest(); req.onload = function () { if (req.status === 404) { reject(new Error('not found')); } else { // fake a slow response every now and then setTimeout(function () { var data = JSON.parse(req.response); resolve(data); getJSON._cache[url] = data; }, Math.random() > 0.5 ? 0 : 1000); } }; req.open('GET', url); req.send(); }); } getJSON._cache = {}; var App = React.createClass({ statics: { fetchData (params) { return getJSON(`${API}/contacts`).then((res) => res.contacts); } }, getInitialState () { return { loading: false }; }, componentDidMount () { var timer; loadingEvents.on('loadStart', () => { clearTimeout(timer); // for slow responses, indicate the app is thinking // otherwise its fast enough to just wait for the // data to load timer = setTimeout(() => { this.setState({ loading: true }); }, 300); }); loadingEvents.on('loadEnd', () => { clearTimeout(timer); this.setState({ loading: false }); }); }, renderContacts () { return this.props.data.contacts.map((contact) => { return ( <li> <Link to="contact" params={contact}>{contact.first} {contact.last}</Link> </li> ); }); }, render () { return ( <div className={this.state.loading ? 'loading' : ''}> <ul> {this.renderContacts()} </ul> <RouteHandler {...this.props}/> </div> ); } }); var Contact = React.createClass({ statics: { fetchData (params) { return getJSON(`${API}/contacts/${params.id}`).then((res) => res.contact); } }, render () { var { contact } = this.props.data; return ( <div> <p><Link to="contacts">Back</Link></p> <h1>{contact.first} {contact.last}</h1> <img key={contact.avatar} src={contact.avatar}/> </div> ); } }); var Index = React.createClass({ render () { return ( <div> <h1>Welcome!</h1> </div> ); } }); var routes = ( <Route name="contacts" path="/" handler={App}> <DefaultRoute name="index" handler={Index}/> <Route name="contact" path="contact/:id" handler={Contact}/> </Route> ); function fetchData(routes, params) { return whenKeys.all(routes.filter((route) => { return route.handler.fetchData; }).reduce((data, route) => { data[route.name] = route.handler.fetchData(params); return data; }, {})); } Router.run(routes, function (Handler, state) { loadingEvents.emit('loadStart'); fetchData(state.routes, state.params).then((data) => { loadingEvents.emit('loadEnd'); React.render(<Handler data={data}/>, document.getElementById('example')); }); });
//= require ./core/monocle //= require ./compat/env //= require ./compat/css //= require ./compat/stubs //= require ./compat/browser //= require ./compat/gala //= require ./core/bookdata //= require ./core/factory //= require ./core/events //= require ./core/styles //= require ./core/formatting //= require ./core/reader //= require ./core/book //= require ./core/place //= require ./core/component //= require ./core/selection //= require ./core/billboard //= require ./controls/panel //= require ./panels/twopane //= require ./panels/imode //= require ./panels/eink //= require ./panels/marginal //= require ./panels/magic //= require ./dimensions/columns //= require ./flippers/slider //= require ./flippers/scroller //= require ./flippers/instant
/** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; const fs = jest.genMockFromModule('fs'); const mockFiles = new Map(); function __setMockFiles(newMockFiles) { mockFiles.clear(); Object.keys(newMockFiles).forEach(fileName => { mockFiles.set(fileName, newMockFiles[fileName]); }); } fs.__setMockFiles = __setMockFiles; fs.readFileSync = jest.fn(file => mockFiles.get(file)); module.exports = fs;
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('Profiles', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, first_name: { type: Sequelize.STRING }, last_name: { type: Sequelize.STRING }, gender: { type: Sequelize.STRING }, age: { type: Sequelize.INTEGER }, country_origin: { type: Sequelize.STRING }, catch_phrase: { type: Sequelize.STRING }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('Profiles'); } };
'use strict'; exports.__esModule = true; var _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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactMixin = require('react-mixin'); var _reactMixin2 = _interopRequireDefault(_reactMixin); var _mixins = require('./mixins'); var _utilsHexToRgb = require('../../utils/hexToRgb'); var _utilsHexToRgb2 = _interopRequireDefault(_utilsHexToRgb); var styles = { base: { paddingTop: 3, paddingBottom: 3, paddingRight: 0, marginLeft: 14 }, label: { display: 'inline-block', marginRight: 5 } }; var JSONStringNode = (function (_React$Component) { _inherits(JSONStringNode, _React$Component); function JSONStringNode() { _classCallCheck(this, _JSONStringNode); _React$Component.apply(this, arguments); } JSONStringNode.prototype.render = function render() { var backgroundColor = 'transparent'; if (this.props.previousValue !== this.props.value) { var bgColor = _utilsHexToRgb2['default'](this.props.theme.base06); backgroundColor = 'rgba(' + bgColor.r + ', ' + bgColor.g + ', ' + bgColor.b + ', 0.1)'; } return _react2['default'].createElement( 'li', { style: _extends({}, styles.base, { backgroundColor: backgroundColor }), onClick: this.handleClick.bind(this) }, _react2['default'].createElement( 'label', { style: _extends({}, styles.label, { color: this.props.theme.base0D }) }, this.props.keyName, ':' ), _react2['default'].createElement( 'span', { style: { color: this.props.theme.base0B } }, '"', this.props.value, '"' ) ); }; var _JSONStringNode = JSONStringNode; JSONStringNode = _reactMixin2['default'].decorate(_mixins.SquashClickEventMixin)(JSONStringNode) || JSONStringNode; return JSONStringNode; })(_react2['default'].Component); exports['default'] = JSONStringNode; module.exports = exports['default'];
import React, {PropTypes} from 'react' import styles from './Form.css' export default React.createClass({ propTypes: { username: PropTypes.string.isRequired, onLogout: PropTypes.func }, render() { return ( <div className={styles.forms}> <section> <label>当前用户:</label> <input type="text" value={this.props.username} readOnly /> </section> <section> <button onClick={this.props.onLogout} className={`${styles.btn} ${styles.btnBorderOpen} ${styles.btnPurple}`} > 注销 </button> </section> </div> ) } })
(function() { 'use strict'; angular .module('echarliApp') .factory('Activate', Activate); Activate.$inject = ['$resource']; function Activate ($resource) { var service = $resource('api/activate', {}, { 'get': { method: 'GET', params: {}, isArray: false} }); return service; } })();
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M22 11h-5V6h-3v5h-4V3H7v8H1.84v2H7v8h3v-8h4v5h3v-5h5z" }), 'AlignVerticalCenterOutlined'); exports.default = _default;
// conf.js exports.config = { seleniumServerJar: "./node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar", specs: ["test/e2e/*.scenarios.coffee"], baseUrl: "http://localhost:3000", capabilities: { "browserName": "chrome" }, framework: "mocha" }
/* Magic Mirror * Log * * This logger is very simple, but needs to be extended. * This system can eventually be used to push the log messages to an external target. * * By Michael Teeuw https://michaelteeuw.nl * MIT Licensed. */ (function (root, factory) { if (typeof exports === "object") { if (process.env.JEST_WORKER_ID === undefined) { // add timestamps in front of log messages require("console-stamp")(console, { pattern: "yyyy-mm-dd HH:MM:ss.l", include: ["debug", "log", "info", "warn", "error"] }); } // Node, CommonJS-like module.exports = factory(root.config); } else { // Browser globals (root is window) root.Log = factory(root.config); } })(this, function (config) { let logLevel; let enableLog; if (typeof exports === "object") { // in nodejs and not running with jest enableLog = process.env.JEST_WORKER_ID === undefined; } else { // in browser and not running with jsdom enableLog = typeof window === "object" && window.name !== "jsdom"; } if (enableLog) { logLevel = { debug: Function.prototype.bind.call(console.debug, console), log: Function.prototype.bind.call(console.log, console), info: Function.prototype.bind.call(console.info, console), warn: Function.prototype.bind.call(console.warn, console), error: Function.prototype.bind.call(console.error, console), group: Function.prototype.bind.call(console.group, console), groupCollapsed: Function.prototype.bind.call(console.groupCollapsed, console), groupEnd: Function.prototype.bind.call(console.groupEnd, console), time: Function.prototype.bind.call(console.time, console), timeEnd: Function.prototype.bind.call(console.timeEnd, console), timeStamp: Function.prototype.bind.call(console.timeStamp, console) }; logLevel.setLogLevel = function (newLevel) { if (newLevel) { Object.keys(logLevel).forEach(function (key, index) { if (!newLevel.includes(key.toLocaleUpperCase())) { logLevel[key] = function () {}; } }); } }; } else { logLevel = { debug: function () {}, log: function () {}, info: function () {}, warn: function () {}, error: function () {}, group: function () {}, groupCollapsed: function () {}, groupEnd: function () {}, time: function () {}, timeEnd: function () {}, timeStamp: function () {} }; logLevel.setLogLevel = function () {}; } return logLevel; });
/** * Dummy file for grunt-nodemon to run node-inspector task */
'use strict'; var a = 0; var b = 1; var x = a; var y = b; console.log( x + y );
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S12.10_A1.4_T4; * @section: 12.10; * @assertion: The with statement adds a computed object to the front of the * scope chain of the current execution context; * @description: Using "with" statement within iteration statement, leading to completion by break; * @strict_mode_negative */ this.p1 = 1; this.p2 = 2; this.p3 = 3; var result = "result"; var myObj = {p1: 'a', p2: 'b', p3: 'c', value: 'myObj_value', valueOf : function(){return 'obj_valueOf';}, parseInt : function(){return 'obj_parseInt';}, NaN : 'obj_NaN', Infinity : 'obj_Infinity', eval : function(){return 'obj_eval';}, parseFloat : function(){return 'obj_parseFloat';}, isNaN : function(){return 'obj_isNaN';}, isFinite : function(){return 'obj_isFinite';} } var del; var st_p1 = "p1"; var st_p2 = "p2"; var st_p3 = "p3"; var st_parseInt = "parseInt"; var st_NaN = "NaN"; var st_Infinity = "Infinity"; var st_eval = "eval"; var st_parseFloat = "parseFloat"; var st_isNaN = "isNaN"; var st_isFinite = "isFinite"; do{ with(myObj){ st_p1 = p1; st_p2 = p2; st_p3 = p3; st_parseInt = parseInt; st_NaN = NaN; st_Infinity = Infinity; st_eval = eval; st_parseFloat = parseFloat; st_isNaN = isNaN; st_isFinite = isFinite; p1 = 'x1'; this.p2 = 'x2'; del = delete p3; var p4 = 'x4'; p5 = 'x5'; var value = 'value'; break; } } while(false); if(!(p1 === 1)){ $ERROR('#1: p1 === 1. Actual: p1 ==='+ p1 ); } if(!(p2 === "x2")){ $ERROR('#2: p2 === "x2". Actual: p2 ==='+ p2 ); } if(!(p3 === 3)){ $ERROR('#3: p3 === 3. Actual: p3 ==='+ p3 ); } if(!(p4 === "x4")){ $ERROR('#4: p4 === "x4". Actual: p4 ==='+ p4 ); } if(!(p5 === "x5")){ $ERROR('#5: p5 === "x5". Actual: p5 ==='+ p5 ); } if(!(myObj.p1 === "x1")){ $ERROR('#6: myObj.p1 === "x1". Actual: myObj.p1 ==='+ myObj.p1 ); } if(!(myObj.p2 === "b")){ $ERROR('#7: myObj.p2 === "b". Actual: myObj.p2 ==='+ myObj.p2 ); } if(!(myObj.p3 === undefined)){ $ERROR('#8: myObj.p3 === undefined. Actual: myObj.p3 ==='+ myObj.p3 ); } if(!(myObj.p4 === undefined)){ $ERROR('#9: myObj.p4 === undefined. Actual: myObj.p4 ==='+ myObj.p4 ); } if(!(myObj.p5 === undefined)){ $ERROR('#10: myObj.p5 === undefined. Actual: myObj.p5 ==='+ myObj.p5 ); } if(!(st_parseInt !== parseInt)){ $ERROR('#11: myObj.parseInt !== parseInt'); } if(!(st_NaN === "obj_NaN")){ $ERROR('#12: myObj.NaN !== NaN'); } if(!(st_Infinity !== Infinity)){ $ERROR('#13: myObj.Infinity !== Infinity'); } if(!(st_eval !== eval)){ $ERROR('#14: myObj.eval !== eval'); } if(!(st_parseFloat !== parseFloat)){ $ERROR('#15: myObj.parseFloat !== parseFloat'); } if(!(st_isNaN !== isNaN)){ $ERROR('#16: myObj.isNaN !== isNaN'); } if(!(st_isFinite !== isFinite)){ $ERROR('#17: myObj.isFinite !== isFinite'); } if(!(value === undefined)){ $ERROR('#18: value === undefined. Actual: value ==='+ value ); } if(!(myObj.value === "value")){ $ERROR('#19: myObj.value === "value". Actual: myObj.value ==='+ myObj.value ); }
frappe.ui.form.ControlCurrency = frappe.ui.form.ControlFloat.extend({ format_for_input: function(value) { var formatted_value = format_number(value, this.get_number_format(), this.get_precision()); return isNaN(parseFloat(value)) ? "" : formatted_value; }, get_precision: function() { // always round based on field precision or currency's precision // this method is also called in this.parse() if (!this.df.precision) { if(frappe.boot.sysdefaults.currency_precision) { this.df.precision = frappe.boot.sysdefaults.currency_precision; } else { this.df.precision = get_number_format_info(this.get_number_format()).precision; } } return this.df.precision; } });
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M19 5c0-1.1-.9-2-2-2h-6.17c-.53 0-1.04.21-1.42.59L7.95 5.06 19 16.11V5zM3.09 4.44c-.39.39-.39 1.02 0 1.41L5 7.78V19c0 1.11.9 2 2 2h11.23l.91.91c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L4.5 4.44a.9959.9959 0 0 0-1.41 0z" }), 'SignalCellularNoSimRounded'); exports.default = _default;
//Libraries const React = require("react"); const _ = require("lodash"); const DataActions = require("../actions/data_actions"); const DataStore = require("../stores/data_store"); const FilterStore = require("../stores/filter_store"); const ColumnsStore = require("../stores/columns_store"); //Mixins const cssMixins = require("morse-react-mixins").css_mixins; const textMixins = require("morse-react-mixins").text_mixins; class SearchFilters extends React.Component{ constructor(props) { super(props); this.dropdown = ["input-group-btn", {"open":false}]; this.state = { dropdown:this.getClasses(this.dropdown), expanded:"false", selectedkey:"all", searchVal:"" }; } componentDidMount() { this.quickSearch = (_.isBoolean(this.props.quickSearch)) ? this.props.quickSearch : true; if(FilterStore.isSelectedKey(this.props.item)){ this.active = [{active:true}]; this.setState({active:this.getClasses(this.active)}); } this.setState({searchVal:DataStore.getSearchVal()}); // FilterStore.addChangeListener("change_key", this._openDropdown.bind(this)); ColumnsStore.addChangeListener("adding", this._onAdd.bind(this)); } componentWillUnmount() { // FilterStore.removeChangeListener("change_key", this._openDropdown); ColumnsStore.removeChangeListener("adding", this._onAdd); } _onAdd(){ this.setState({ keys:ColumnsStore.getSearchable() }); } _onChange(e){ if(this.quickSearch){ if(this.loop){ window.clearTimeout(this.loop); } this.loop = window.setTimeout((val)=>{ if(val.length > 2 || val === ""){ DataActions.searching(val); } }, 200, e.target.value); this.setState({searchVal:e.target.value}); } // _.defer((val)=>{ // DataActions.searching(val); // }, e.target.value); } // _openDropdown(){ // this.dropdown = this.toggleCss(this.dropdown); // let expanded = (this.state.expended === "true") ? "false" : "true"; // this.setState({ // dropdown:this.getClasses(this.dropdown), // expanded:expanded, // selectedkey:FilterStore.getSelectedKey() // }); // } _preventSubmit(e){ // console.log("submiting", e); e.preventDefault(); } // renderKeys(){ // if(this.state.keys){ // let items = this.state.keys.map(function(k){ // return (<Keys item={k} key={_.uniqueId("key")} />); // }); // return items; // } // } render() { return ( <form onSubmit={this._preventSubmit.bind(this)} className="search-filter"> <input alt="Search" type="image" src={this.props.icon} /> <div className="fields-container"> <input type="text" name="querystr" id="querystr" placeholder="Search" value={this.state.searchVal} onChange={this._onChange.bind(this)} /> </div> </form> ); } } Object.assign(SearchFilters.prototype, cssMixins); Object.assign(SearchFilters.prototype, textMixins); module.exports = SearchFilters;
$(document).ready(function() { $("#frmChangePass").submit(function() { //get the url for the form AJAX.post( $("#frmChangePass").attr("action"), { _password_current : $("#currentPass").val(), _password : $("#newPass").val(), _password_confirm : $("#newPass2").val() }, $("#msgbox_changepass"), $("#btnChangepass")); //we dont what the browser to submit the form return false; }); });
/** * Created by joonkukang on 2014. 1. 16.. */ var math = require('./utils').math; let optimize = module.exports; optimize.hillclimb = function(options){ var domain = options['domain']; var costf = options['costf']; var i; var vec = []; for(i=0 ; i<domain.length ; i++) vec.push(math.randInt(domain[i][0],domain[i][1])); var current, best; while(true) { var neighbors = []; var i,j; for(i=0 ; i<domain.length ; i++) { if(vec[i] > domain[i][0]) { var newVec = []; for(j=0 ; j<domain.length ; j++) newVec.push(vec[j]); newVec[i]-=1; neighbors.push(newVec); } else if (vec[i] < domain[i][1]) { var newVec = []; for(j=0 ; j<domain.length ; j++) newVec.push(vec[j]); newVec[i]+=1; neighbors.push(newVec); } } current = costf(vec); best = current; for(i=0 ; i<neighbors.length ; i++) { var cost = costf(neighbors[i]); if(cost < best) { best = cost; vec = neighbors[i]; } } if(best === current) break; } return vec; } optimize.anneal = function(options){ var domain = options['domain']; var costf = options['costf']; var temperature = options['temperature']; var cool = options['cool']; var step = options['step']; var callback var i; var vec = []; for(i=0 ; i<domain.length ; i++) vec.push(math.randInt(domain[i][0],domain[i][1])); while(temperature > 0.1) { var idx = math.randInt(0,domain.length - 1); var dir = math.randInt(-step,step); var newVec = []; for(i=0; i<vec.length ; i++) newVec.push(vec[i]); newVec[idx]+=dir; if(newVec[idx] < domain[idx][0]) newVec[idx] = domain[idx][0]; if(newVec[idx] > domain[idx][1]) newVec[idx] = domain[idx][1]; var ea = costf(vec); var eb = costf(newVec); var p = Math.exp(-1.*(eb-ea)/temperature); if(eb < ea || Math.random() < p) vec = newVec; temperature *= cool; } return vec; } optimize.genetic = function(options){ var domain = options['domain']; var costf = options['costf']; var population = options['population']; var q = options['q'] || 0.3; var elite = options['elite'] || population * 0.04; var epochs = options['epochs'] || 100; var i,j; // Initialize population array var pop =[]; for(i=0; i<population; i++) { var vec = []; for(j=0; j<domain.length; j++) vec.push(math.randInt(domain[j][0],domain[j][1])); pop.push(vec); } pop.sort(function(a,b){return costf(a) - costf(b);}); for(i=0 ; i<epochs ; i++) { // elitism var newPop = []; for(j=0;j<elite;j++) newPop.push(pop[j]); // compute fitnesses var fitnesses = []; for(j=0; j<pop.length; j++) fitnesses[j] = q * Math.pow(1-q,j); fitnesses = math.normalizeVec(fitnesses); // crossover, mutate for(j=0; j<pop.length - elite;j++) { var idx1 = rouletteWheel(fitnesses); var idx2 = rouletteWheel(fitnesses); var crossovered = crossover(pop[idx1],pop[idx2]); var mutated = mutate(crossovered); newPop.push(mutated); } // replacement pop = newPop; pop.sort(function(a,b){return costf(a) - costf(b);}); //console.log("Current Cost : ",costf(pop[0])); } return pop[0]; function mutate(vec) { var idx = math.randInt(0,domain.length - 1); var newVec = []; var i; for(i=0; i<domain.length ; i++) newVec.push(vec[i]); newVec[idx] += (Math.random() < 0.5) ? 1 : -1; if(newVec[idx] < domain[idx][0]) newVec[idx] = domain[idx][0]; if(newVec[idx] > domain[idx][1]) newVec[idx] = domain[idx][1]; return newVec; } function crossover(vec1,vec2) { var idx = math.randInt(0,domain.length - 2); var newVec = []; var i; for(i=0; i<idx ; i++) newVec.push(vec1[i]); for(i=idx; i<domain.length; i++) newVec.push(vec2[i]); return newVec; } function rouletteWheel(vec) { var a = [0.0]; var i; for(i=0;i<vec.length;i++) { a.push(a[i] + vec[i]); } var rand = Math.random(); for(i=0;i< a.length;i++) { if(rand > a[i] && rand <= a[i+1]) return i; } return -1; } };
System.register(['@angular/core', '@angular/router', '../user/user.service', './login.service', '../shared/alert/dtalert.component', '../shared/spinner/dtspinner.component'], function(exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; 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; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1, router_1, user_service_1, login_service_1, dtalert_component_1, dtspinner_component_1; var LoginComponent; return { setters:[ function (core_1_1) { core_1 = core_1_1; }, function (router_1_1) { router_1 = router_1_1; }, function (user_service_1_1) { user_service_1 = user_service_1_1; }, function (login_service_1_1) { login_service_1 = login_service_1_1; }, function (dtalert_component_1_1) { dtalert_component_1 = dtalert_component_1_1; }, function (dtspinner_component_1_1) { dtspinner_component_1 = dtspinner_component_1_1; }], execute: function() { LoginComponent = (function () { function LoginComponent(_loginService, _router, _userService) { this._loginService = _loginService; this._router = _router; this._userService = _userService; this.pageTitle = "Login"; this.EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i; this.dtAlert = new dtalert_component_1.DtAlertComponent(); } LoginComponent.prototype.submit = function () { var _this = this; var isValid = this.validateEmailAndPassword(); if (!isValid) { return; } var payload = { "email": this.email, "password": this.password }; this._loginService .login(payload) .subscribe(function (result) { if (!result.success) { _this.dtAlert.failure(result.message); return; } _this._userService.add(result); _this._router.navigate(['dashboard']); }, function (error) { return _this.dtAlert.failure(error); }); }; LoginComponent.prototype.validateEmailAndPassword = function () { if (this.email == null || this.email == "" || !this.EMAIL_REGEXP.test(this.email)) { this.dtAlert.failure("Please enter a valid email"); return false; } if (this.password == null || this.password == "") { this.dtAlert.failure("Please enter a password"); return false; } return true; }; __decorate([ core_1.Input(), __metadata('design:type', String) ], LoginComponent.prototype, "email", void 0); __decorate([ core_1.Input(), __metadata('design:type', String) ], LoginComponent.prototype, "password", void 0); LoginComponent = __decorate([ core_1.Component({ templateUrl: 'app/login/login.component.html', directives: [dtalert_component_1.DtAlertComponent, dtspinner_component_1.DtSpinButtonComponent] }), __metadata('design:paramtypes', [login_service_1.LoginService, router_1.Router, user_service_1.UserService]) ], LoginComponent); return LoginComponent; }()); exports_1("LoginComponent", LoginComponent); } } }); //# sourceMappingURL=login.component.js.map
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm2 16H5V5h11.17L19 7.83V19zm-7-7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3zM6 6h9v4H6z" }), 'SaveOutlined'); exports.default = _default;
/*global module:false*/ module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: '<json:jquery-disqus.jquery.json>', meta: { banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' + '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */' }, concat: { dist: { src: ['<banner:meta.banner>', '<file_strip_banner:src/<%= pkg.name %>.js>'], dest: 'dist/<%= pkg.name %>.js' } }, min: { dist: { src: ['<banner:meta.banner>', '<config:concat.dist.dest>'], dest: 'dist/<%= pkg.name %>.min.js' } }, qunit: { files: ['test/**/*.html'] }, lint: { files: ['grunt.js', 'src/**/*.js', 'test/**/*.js'] }, watch: { files: '<config:lint.files>', tasks: 'lint qunit' }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, browser: true }, globals: { jQuery: true } }, uglify: {} }); // Default task. grunt.registerTask('default', 'lint qunit concat min'); };
define(['../lib/circle', '../lib/aura', './collision', '../lib/vector', '../lib/dictionary'],function(Circle, Aura, collision, Vector, Dictionary){ var Particle = function(world, options) { var options = options || {} Circle.call(this, options); //TODO: implement singleton for the world this.world = world; this.mass = this.radius; // this.energy = 100; this.speed = options.speed || 3; // todo: move this somewhere else this.directions = new Dictionary({ n: new Vector(0, 1), s: new Vector(0, -1), e: new Vector(1, 0), w: new Vector(-1, 0), ne: new Vector(1, 1), se: new Vector(1, -1), nw: new Vector(-1, 1), sw: new Vector(-1, -1) }); this.setDirection(options.direction || this.directions.random()); this.aura = new Aura(this); }; // inheritance Particle.prototype = Object.create(Circle.prototype); Particle.prototype.act = function() { this.move(); }; /** * Change position of object based on direction * and speed */ Particle.prototype.move = function() { var pos = this.position.add(new Vector(this.direction.normalize().x * this.speed, this.direction.normalize().y * this.speed)); this.setPosition(pos); }; /** * React to collision depending on the type of object */ Particle.prototype.reactToCollision = function(other) { //TODO: fix this //http://en.wikipedia.org/wiki/Elastic_collision //http://www.gamasutra.com/view/feature/131424/pool_hall_lessons_fast_accurate_.php?page=3 var n = this.position.sub(other.prevPosition).normalize(); var a1 = this.direction.dot(n); var a2 = other.prevDirection.dot(n); var optimizedP = (2 * (a1 - a2)) / (this.mass + other.mass); var newDir = this.direction.sub(n.mult(optimizedP * other.mass)); // this.setPosition(this.prevPosition); this.setDirection(newDir); // this.move(); }; /** * Needed to keep track of the previous direction */ Particle.prototype.setDirection = function(vector){ this.prevDirection = this.direction || vector; this.direction = vector; }; /** * Render */ Particle.prototype.render = function(){ this.aura.render(); this.constructor.prototype.render.call(this); }; Particle.prototype.setPosition = function(pos){ this.prevPosition = this.position || pos; this.constructor.prototype.setPosition.call(this, pos); }; return Particle; });
/* Copyright 2013-2015 ASIAL CORPORATION 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. */ import animit from '../../ons/animit'; import SplitterAnimator from './animator.js'; export default class PushSplitterAnimator extends SplitterAnimator { _getSlidingElements() { const slidingElements = [this._side, this._content]; if (this._oppositeSide && this._oppositeSide.mode === 'split') { slidingElements.push(this._oppositeSide); } return slidingElements; } translate(distance) { if (!this._slidingElements) { this._slidingElements = this._getSlidingElements(); } animit(this._slidingElements) .queue({ transform: `translate3d(${this.minus + distance}px, 0px, 0px)` }) .play(); } /** * @param {Function} done */ open(done) {console.log('opening'); const max = this._side.offsetWidth; this._slidingElements = this._getSlidingElements(); animit.runAll( animit(this._slidingElements) .wait(this.delay) .queue({ transform: `translate3d(${this.minus + max}px, 0px, 0px)` }, { duration: this.duration, timing: this.timing }) .queue(callback => { this._slidingElements = null; callback(); done && done(); }), animit(this._mask) .wait(this.delay) .queue({ display: 'block' }) ); } /** * @param {Function} done */ close(done) { this._slidingElements = this._getSlidingElements(); animit.runAll( animit(this._slidingElements) .wait(this.delay) .queue({ transform: 'translate3d(0px, 0px, 0px)' }, { duration: this.duration, timing: this.timing }) .queue(callback => { this._slidingElements = null; super.clearTransition(); done && done(); callback(); }), animit(this._mask) .wait(this.delay) .queue({ display: 'none' }) ); } }
config.$inject = [ '$stateProvider' ]; function config ($stateProvider) { $stateProvider .state('main.admin-dashboard', { url: '/inicio', templateUrl: 'templates/components/main/dashboard/admin-dashboard.html', controller: 'AdminDashboardController as vm', onEnter: onStateEnter }) .state('main.student-dashboard', { url: '/inicio', templateUrl: 'templates/components/main/dashboard/student-dashboard.html', controller: 'StudentDashboardController as vm', onEnter: onStateEnter }) .state('main.professor-dashboard', { url: '/inicio', templateUrl: 'templates/components/main/dashboard/professor-dashboard.html', controller: 'ProfessorDashboardController as vm', onEnter: onStateEnter }); } const onStateEnter = [ '$rootScope', rootScope => { rootScope.viewTitle = "Vinculacion | Inicio"; rootScope.viewStyles = "main dashboard"; } ]; module.exports = config;
;modjewel.define("weinre/target/SqlStepper", function(require, exports, module) { // Generated by CoffeeScript 1.3.3 var Binding, SqlStepper, executeSql, ourErrorCallback, runStep; Binding = require('../common/Binding'); module.exports = SqlStepper = (function() { function SqlStepper(steps) { var context; if (!(this instanceof SqlStepper)) { return new SqlStepper(steps); } this.__context = {}; context = this.__context; context.steps = steps; } SqlStepper.prototype.run = function(db, errorCallback) { var context; context = this.__context; if (context.hasBeenRun) { throw new Ex(arguments, "stepper has already been run"); } context.hasBeenRun = true; context.db = db; context.errorCallback = errorCallback; context.nextStep = 0; context.ourErrorCallback = new Binding(this, ourErrorCallback); context.runStep = new Binding(this, runStep); this.executeSql = new Binding(this, executeSql); return db.transaction(context.runStep); }; SqlStepper.example = function(db, id) { var errorCb, step1, step2, stepper; step1 = function() { return this.executeSql("SELECT name FROM sqlite_master WHERE type='table'"); }; step2 = function(resultSet) { var i, name, result, rows; rows = resultSet.rows; result = []; i = 0; while (i < rows.length) { name = rows.item(i).name; if (name === "__WebKitDatabaseInfoTable__") { i++; continue; } result.push(name); i++; } return console.log(("[" + this.id + "] table names: ") + result.join(", ")); }; errorCb = function(sqlError) { return console.log(("[" + this.id + "] sql error:" + sqlError.code + ": ") + sqlError.message); }; stepper = new SqlStepper([step1, step2]); stepper.id = id; return stepper.run(db, errorCb); }; return SqlStepper; })(); executeSql = function(statement, data) { var context; context = this.__context; return context.tx.executeSql(statement, data, context.runStep, context.ourErrorCallback); }; ourErrorCallback = function(tx, sqlError) { var context; context = this.__context; return context.errorCallback.call(this, sqlError); }; runStep = function(tx, resultSet) { var context, step; context = this.__context; if (context.nextStep >= context.steps.length) { return; } context.tx = tx; context.currentStep = context.nextStep; context.nextStep++; step = context.steps[context.currentStep]; return step.call(this, resultSet); }; require("../common/MethodNamer").setNamesForClass(module.exports); });
// Break out the application running from the configuration definition to // assist with testing. require(['config'], function() { // Kick off the application. require(['app', 'router'], function(app, Router) { // Define your master router on the application namespace and trigger all // navigation from this instance. app.router = new Router(); app.router.bind("all",function(route, router) { $('#wrap').css('background-image', 'none'); $('.navbar').removeClass('bg').removeClass('bg-black'); $('.footer').removeClass('transparent'); $('.dropdown-menu').removeClass('bg-inverse'); }); // Trigger the initial route and enable HTML5 History API support, set the // root folder to '/' by default. Change in app.js. Backbone.history.start(); }); });
const dec = () => {}; class Foo { @dec #x() {} bar() { ([...this.#x] = this.baz); } }
(function () { $(function () { var _userService = abp.services.app.user; var _$modal = $('#UserCreateModal'); var _$form = _$modal.find('form'); _$form.validate({ rules: { Password: "required", ConfirmPassword: { equalTo: "#Password" } } }); $('#RefreshButton').click(function () { refreshUserList(); }); $('.delete-user').click(function () { var userId = $(this).attr("data-user-id"); var userName = $(this).attr('data-user-name'); deleteUser(userId, userName); }); $('.edit-user').click(function (e) { var userId = $(this).attr("data-user-id"); e.preventDefault(); $.ajax({ url: abp.appPath + 'Users/EditUserModal?userId=' + userId, type: 'POST', contentType: 'application/html', success: function (content) { $('#UserEditModal div.modal-content').html(content); }, error: function (e) { } }); }); _$form.find('button[type="submit"]').click(function (e) { e.preventDefault(); if (!_$form.valid()) { return; } var user = _$form.serializeFormToObject(); //serializeFormToObject is defined in main.js user.roleNames = []; var _$roleCheckboxes = $("input[name='role']:checked"); if (_$roleCheckboxes) { for (var roleIndex = 0; roleIndex < _$roleCheckboxes.length; roleIndex++) { var _$roleCheckbox = $(_$roleCheckboxes[roleIndex]); user.roleNames.push(_$roleCheckbox.attr('data-role-name')); } } abp.ui.setBusy(_$modal); _userService.create(user).done(function () { _$modal.modal('hide'); location.reload(true); //reload page to see new user! }).always(function () { abp.ui.clearBusy(_$modal); }); }); _$modal.on('shown.bs.modal', function () { _$modal.find('input:not([type=hidden]):first').focus(); }); function refreshUserList() { location.reload(true); //reload page to see new user! } function deleteUser(userId, userName) { abp.message.confirm( "Delete user '" + userName + "'?", function (isConfirmed) { if (isConfirmed) { _userService.delete({ id: userId }).done(function () { refreshUserList(); }); } } ); } }); })();
//>>built define({nomatchMessage:"Die Kennw\u00f6rter stimmen nicht \u00fcberein.",badPasswordMessage:"Ung\u00fcltiges Kennwort."});
(function(){ if(!window.Prism) { return; } function $$(expr, con) { return Array.prototype.slice.call((con || document).querySelectorAll(expr)); } var CRLF = crlf = /\r?\n|\r/g; function highlightLines(pre, lines, classes) { var ranges = lines.replace(/\s+/g, '').split(','), offset = +pre.getAttribute('data-line-offset') || 0; var lineHeight = parseFloat(getComputedStyle(pre).lineHeight); for (var i=0, range; range = ranges[i++];) { range = range.split('-'); var start = +range[0], end = +range[1] || start; var line = document.createElement('div'); line.textContent = Array(end - start + 2).join(' \r\n'); line.className = (classes || '') + ' line-highlight'; line.setAttribute('data-start', start); if(end > start) { line.setAttribute('data-end', end); } line.style.top = (start - offset - 1) * lineHeight + 'px'; (pre.querySelector('code') || pre).appendChild(line); } } function applyHash() { var hash = location.hash.slice(1); // Remove pre-existing temporary lines $$('.temporary.line-highlight').forEach(function (line) { line.parentNode.removeChild(line); }); var range = (hash.match(/\.([\d,-]+)$/) || [,''])[1]; if (!range || document.getElementById(hash)) { return; } var id = hash.slice(0, hash.lastIndexOf('.')), pre = document.getElementById(id); if (!pre) { return; } if (!pre.hasAttribute('data-line')) { pre.setAttribute('data-line', ''); } highlightLines(pre, range, 'temporary '); document.querySelector('.temporary.line-highlight').scrollIntoView(); } var fakeTimer = 0; // Hack to limit the number of times applyHash() runs Prism.hooks.add('after-highlight', function(env) { var pre = env.element.parentNode; var lines = pre && pre.getAttribute('data-line'); if (!pre || !lines || !/pre/i.test(pre.nodeName)) { return; } clearTimeout(fakeTimer); $$('.line-highlight', pre).forEach(function (line) { line.parentNode.removeChild(line); }); highlightLines(pre, lines); fakeTimer = setTimeout(applyHash, 1); }); addEventListener('hashchange', applyHash); })();
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; var path = require("path"); var fs = require("fs"); var minify = require("jsonminify"); var js_beautify = require("js-beautify").js_beautify; var css_beautify = require("js-beautify").css; var html_beautify = require("js-beautify").html; // Older versions of node have `existsSync` in the `path` module, not `fs`. Meh. fs.existsSync = fs.existsSync || path.existsSync; path.sep = path.sep || "/"; // The source file to be prettified, original source's path and some options. var tempPath = process.argv[2] || ""; var filePath = process.argv[3] || ""; var pluginFolder = path.dirname(__dirname); var sourceFolder = path.dirname(filePath); var options = { html: {}, css: {}, js: {} }; var jsbeautifyrcPath; // Try and get some persistent options from the plugin folder. if (fs.existsSync(jsbeautifyrcPath = pluginFolder + path.sep + ".jsbeautifyrc")) { setOptions(jsbeautifyrcPath, options); } // When a JSBeautify config file exists in the same directory as the source // file, any directory above, or the user's home folder, then use that // configuration to overwrite the default prefs. var sourceFolderParts = path.resolve(sourceFolder).split(path.sep); var pathsToLook = sourceFolderParts.map(function(value, key) { return sourceFolderParts.slice(0, key + 1).join(path.sep); }); // Start with the current directory first, end with the user's home folder. pathsToLook.reverse(); pathsToLook.push(getUserHome()); pathsToLook.some(function(pathToLook) { if (fs.existsSync(jsbeautifyrcPath = path.join(pathToLook, ".jsbeautifyrc"))) { setOptions(jsbeautifyrcPath, options); return true; } }); // Dump some diagnostics messages, parsed out by the plugin. console.log("Using prettify options: " + JSON.stringify(options, null, 2)); // Read the source file and, when complete, beautify the code. fs.readFile(tempPath, "utf8", function(err, data) { if (err) { return; } // Mark the output as being from this plugin. console.log("*** HTMLPrettify output ***"); if (isCSS(filePath, data)) { console.log(css_beautify(data, options["css"])); } else if (isHTML(filePath, data)) { console.log(html_beautify(data, options["html"])); } else if (isJS(filePath, data)) { console.log(js_beautify(data, options["js"])); } }); // Some handy utility functions. function isTrue(value) { return value == "true" || value == true; } function getUserHome() { return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE; } function parseJSON(file) { try { return JSON.parse(minify(fs.readFileSync(file, "utf8"))); } catch (e) { console.log("Could not parse JSON at: " + file); return {}; } } function setOptions(file, optionsStore) { var obj = parseJSON(file); for (var key in obj) { var value = obj[key]; // Options are defined as an object for each format, with keys as prefs. if (key != "html" && key != "css" && key != "js") { continue; } for (var pref in value) { // Special case "true" and "false" pref values as actually booleans. // This avoids common accidents in .jsbeautifyrc json files. if (value == "true" || value == "false") { optionsStore[key][pref] = isTrue(value[pref]); } else { optionsStore[key][pref] = value[pref]; } } } } // Checks if a file type is allowed by regexing the file name and expecting a // certain extension loaded from the settings file. function isTypeAllowed(type, path) { var allowedFileExtensions = options[type]["allowed_file_extensions"] || { "html": ["htm", "html", "xhtml", "shtml", "xml", "svg"], "css": ["css", "scss", "sass", "less"], "js": ["js", "json", "jshintrc", "jsbeautifyrc"] }[type]; for (var i = 0, len = allowedFileExtensions.length; i < len; i++) { if (path.match(new RegExp("\\." + allowedFileExtensions[i] + "$"))) { return true; } } return false; } function isCSS(path, data) { // If file unsaved, there's no good way to determine whether or not it's // CSS based on the file contents. if (path == "?") { return false; } return isTypeAllowed("css", path); } function isHTML(path, data) { // If file unsaved, check if first non-whitespace character is &lt; if (path == "?") { return data.match(/^\s*</); } return isTypeAllowed("html", path); } function isJS(path, data) { // If file unsaved, check if first non-whitespace character is NOT &lt; if (path == "?") { return !data.match(/^\s*</); } return isTypeAllowed("js", path); }
module.exports = { ignorePatterns: ['bin', 'commitlint.config.js'], extends: [ 'plugin:@typescript-eslint/recommended', 'prettier', 'prettier/@typescript-eslint', 'plugin:prettier/recommended', ], parser: '@typescript-eslint/parser', parserOptions: { project: ['./tsconfig.json', './test/tsconfig.json'], tsconfigRootDir: './', }, plugins: ['@typescript-eslint', 'prettier'], rules: { 'arrow-body-style': ['warn', 'as-needed'], 'react/jsx-one-expression-per-line': 'off', 'react/jsx-wrap-multilines': 'off', 'no-param-reassign': ['error', { props: false }], 'import/prefer-default-export': 'off', curly: ['error', 'all'], 'eol-last': ['error', 'always'], 'no-debugger': 'error', 'import/no-unresolved': 'off', '@typescript-eslint/unified-signatures': 'error', '@typescript-eslint/member-delimiter-style': 'off', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-unused-vars': 'off', }, }
/** * simple */ var mysinleton = { property1 : 'something', property2 : 'something else', method1 : function() { console.log("hello world"); } } /*** * encapsulation like java get、set */ var mysinleton2 = function() { var privateVariable = 'something private'; function showPrivate() { console.log(privateVariable); } return { publicMethod : function(){ showPrivate(); }, publicVar : "this is a public variable" } } var mysinletonInstance = new mysinleton2(); mysinletonInstance.publicMethod(); console.log(mysinletonInstance.publicVar); /*** * * singleton realize */ var Mysingleton = (function(){ var _intstance ; function getInstance() { return _intstance; }; function init() { return { publicMethod : function() { console.log("this is public method"); }, publicProperty : 'test' } }; return { getInstance : function() { if(_intstance) { return _intstance; }else { _intstance = init(); return _intstance; } } } })(); Mysingleton.getInstance().publicMethod(); var SingletonTester = (function () { //参数:传递给单例的一个参数集合 function Singleton(args) { //设置args变量为接收的参数或者为空(如果没有提供的话) var args = args || {}; //设置name参数 this.name = 'SingletonTester'; //设置pointX的值 this.pointX = args.pointX || 6; //从接收的参数里获取,或者设置为默认值 //设置pointY的值 this.pointY = args.pointY || 10; } //实例容器 var instance; var _static = { name: 'SingletonTester', //获取实例的方法 //返回Singleton的实例 getInstance: function (args) { if (instance === undefined) { instance = new Singleton(args); } return instance; } }; return _static; })(); var singletonTest = SingletonTester.getInstance({ pointX: 5 }); console.log(singletonTest.pointX); // 输出 5
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+relay * @flow strict-local * @format */ // flowlint ambiguous-object-type:error 'use strict'; const useRelayEnvironment = require('./useRelayEnvironment'); const warning = require('warning'); const {getFragmentResourceForEnvironment} = require('./FragmentResource'); const {useEffect, useRef, useState} = require('react'); const {getFragmentIdentifier} = require('relay-runtime'); import type {ReaderFragment} from 'relay-runtime'; type ReturnType<TFragmentData: mixed> = {| data: TFragmentData, disableStoreUpdates: () => void, enableStoreUpdates: () => void, shouldUpdateGeneration: number | null, |}; function useFragmentNode<TFragmentData: mixed>( fragmentNode: ReaderFragment, fragmentRef: mixed, componentDisplayName: string, ): ReturnType<TFragmentData> { const environment = useRelayEnvironment(); const FragmentResource = getFragmentResourceForEnvironment(environment); const isMountedRef = useRef(false); const [, forceUpdate] = useState(0); const fragmentIdentifier = getFragmentIdentifier(fragmentNode, fragmentRef); // The values of these React refs are counters that should be incremented // under their respective conditions. This allows us to use the counters as // memoization values to indicate if computations for useMemo or useEffect // should be re-executed. const mustResubscribeGenerationRef = useRef(0); const shouldUpdateGenerationRef = useRef(0); const environmentChanged = useHasChanged(environment); const fragmentIdentifierChanged = useHasChanged(fragmentIdentifier); // If the fragment identifier changes, it means that the variables on the // fragment owner changed, or the fragment ref points to different records. // In this case, we need to resubscribe to the Relay store. const mustResubscribe = environmentChanged || fragmentIdentifierChanged; // We only want to update the component consuming this fragment under the // following circumstances: // - We receive an update from the Relay store, indicating that the data // the component is directly subscribed to has changed. // - We need to subscribe and render /different/ data (i.e. the fragment refs // now point to different records, or the context changed). // Note that even if identity of the fragment ref objects changes, we // don't consider them as different unless they point to a different data ID. // // This prevents unnecessary updates when a parent re-renders this component // with the same props, which is a common case when the parent updates due // to change in the data /it/ is subscribed to, but which doesn't affect the // child. if (mustResubscribe) { shouldUpdateGenerationRef.current++; mustResubscribeGenerationRef.current++; } // Read fragment data; this might suspend. const fragmentResult = FragmentResource.readWithIdentifier( fragmentNode, fragmentRef, fragmentIdentifier, componentDisplayName, ); const isListeningForUpdatesRef = useRef(true); function enableStoreUpdates() { isListeningForUpdatesRef.current = true; const didMissUpdates = FragmentResource.checkMissedUpdates( fragmentResult, )[0]; if (didMissUpdates) { handleDataUpdate(); } } function disableStoreUpdates() { isListeningForUpdatesRef.current = false; } function handleDataUpdate() { if ( isMountedRef.current === false || isListeningForUpdatesRef.current === false ) { return; } // If we receive an update from the Relay store, we need to make sure the // consuming component updates. shouldUpdateGenerationRef.current++; // React bails out on noop state updates as an optimization. // If we want to force an update via setState, we need to pass an value. // The actual value can be arbitrary though, e.g. an incremented number. forceUpdate(count => count + 1); } // Establish Relay store subscriptions in the commit phase, only if // rendering for the first time, or if we need to subscribe to new data useEffect(() => { isMountedRef.current = true; const disposable = FragmentResource.subscribe( fragmentResult, handleDataUpdate, ); return () => { // When unmounting or resubscribing to new data, clean up current // subscription. This will also make sure fragment data is no longer // cached for the so next time it its read, it will be read fresh from the // Relay store isMountedRef.current = false; disposable.dispose(); }; // NOTE: We disable react-hooks-deps warning because mustResubscribeGenerationRef // is capturing all information about whether the effect should be re-ran. // eslint-disable-next-line react-hooks/exhaustive-deps }, [mustResubscribeGenerationRef.current]); if (__DEV__) { if (fragmentRef != null && fragmentResult.data == null) { warning( false, 'Relay: Expected to have been able to read non-null data for ' + 'fragment `%s` declared in ' + '`%s`, since fragment reference was non-null. ' + "Make sure that that `%s`'s parent isn't " + 'holding on to and/or passing a fragment reference for data that ' + 'has been deleted.', fragmentNode.name, componentDisplayName, componentDisplayName, ); } } return { // $FlowFixMe data: fragmentResult.data, disableStoreUpdates, enableStoreUpdates, shouldUpdateGeneration: shouldUpdateGenerationRef.current, }; } function useHasChanged(value: mixed): boolean { const [mirroredValue, setMirroredValue] = useState(value); const valueChanged = mirroredValue !== value; if (valueChanged) { setMirroredValue(value); } return valueChanged; } module.exports = useFragmentNode;
/** * @providesModule Fabric */ 'use strict'; module.exports.Crashlytics = require('./Crashlytics'); module.exports.Answers = require('./Answers');
'use strict'; describe('LoginController', function () { // Load the parent app beforeEach(module('demoSite')); var $controller; var $scope, controller, $window; beforeEach(inject(function (_$controller_) { $controller = _$controller_; $scope = {}; $window = { location: {}, open: function () { } }; controller = $controller('LoginController', { $scope: $scope, $window: $window }); })); describe('isTapIn variable', function () { it('is true by default', function () { expect($scope.isTapIn).toBe(true); }); it('is true if that value is passed to initiateLogin', function () { $scope.initiateLogin(true); expect($scope.isTapIn).toBe(true); }); it('is false if that value is passed to initiateLogin', function () { $scope.initiateLogin(false); expect($scope.isTapIn).toBe(false); }); }); describe('popup creation', function () { it('should pop up a new window when a new login is initiated', function () { spyOn($window, 'open'); $scope.initiateLogin(true); expect($window.open).toHaveBeenCalled(); }) }) describe('error message framework', function () { it('should convert error codes to friendly messages', function () { expect($scope.showError).toBe(false); // Loop through each property in the errorMessages object and check that it is displayed properly. for (var property in $scope.errorMessages) { if ($scope.errorMessages.hasOwnProperty(property)) { $scope.showErrorFromCode(property); expect($scope.errorMessage).toBe($scope.errorMessages[property]); expect($scope.showError).toBe(true); } } }); it('should handle lack of connection to the server', function () { expect($scope.showError).toBe(false); $scope.handleGetURLError(); expect($scope.errorMessage).toBe($scope.errorMessages["no_connection"]); expect($scope.showError).toBe(true); }); it('should hide any errors when a new login is initiated', function () { $scope.showError = true; $scope.initiateLogin(true); expect($scope.showError).toBe(false); }) }); describe('polling framework', function () { beforeEach(function () { // Because the framework utilizes a popup, these variables are NOT inside the controller. dataHasReturned = false; returnedData = new Object(); }); it('should handle manually closing of the popup window', function () { $scope.popupWindow = window.open(); $scope.popupWindow.close(); $scope.pollPopupForCompletedAuth(); expect(dataHasReturned).toBe(false); }); it('should present an error if one comes back from the server', function () { dataHasReturned = true; returnedData.error = "access_denied"; expect($scope.showError).toBe(false); $scope.pollPopupForCompletedAuth(); expect($scope.showError).toBe(true); expect(dataHasReturned).toBe(false); }); it('should redirect the user to the auth page when proper data has returned', function () { dataHasReturned = true; returnedData = { subject: "1111-2222-3333-4444", username: "Test User", email: "testemail@privakey.invalid", details: "Tech+Details" }; $scope.pollPopupForCompletedAuth(); expect($window.location.href).toBe('/#/auth'); }); }) });
// Insert your JS here