code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
function recalculateBombCost() { var bombParams = getBombParams(); var bullets = bombParams.bullets; var trigger = bombParams.trigger; var visible = bombParams.visible; var cost = bombCostCalc(bullets, trigger, visible); $("#bombCost").text("Bomb Cost: " + cost); } function getBombParams() { var bullets = parseInt($("#bombBullets").val()); var trigger = parseInt($("#bombTrigger").val()); var visible = !$("#bombInvisible").is(':checked'); return {'bullets': bullets, 'trigger': trigger, 'visible': visible} } setInterval(function () { recalculateBombCost(); }, 100); $(document).ready(function () { recalculateBombCost(); //Unfocus inputs when mouse leaves bomb selector $("#bombSelectorOuter").mouseleave(function() { $("*").blur(); }); }); //Show hide bomb selector and remove its focus function toggleBombSelector(){ $("*").blur(); $("#bombSelectorOuter").slideToggle("fast"); }
raphy1234/The-Game-Of-Things
public/bombSelector.js
JavaScript
mit
967
import { breakpoints, fonts, colors, letterSpacings, lineHeights, radii, fontWeights, shadows, borders, fontSizes, space, zIndices, sizes, transition, } from "../presets" const theme = { colors: colors, breakpoints: breakpoints, borders: borders, fonts: fonts, fontSizes: fontSizes, fontWeights: fontWeights, letterSpacings: letterSpacings, lineHeights: lineHeights, radii: radii, space: space, shadows: shadows, zIndices: zIndices, sizes: sizes, transition: transition, } export default theme
ChristopherBiscardi/gatsby
www/src/utils/guidelines/theme.js
JavaScript
mit
552
{ "Toggle navigation": "Conmutar navegación", "Users": "Kullanıcı", "New": "Yeni", "Edit": "Düzenle", "My account": "Hesabım", "Article": "Makale", "Settings": "Ayarlar", "Files": "Dosyalar", "Export": "Dışarı aktar", "Cleanup files": "Dosyaları temizle", "Logout": "Çıkış", "Powered by": "'den besleniyor", "Home": "Ana sayfası", "Articles": "Makaleler", "Filter articles": "Makalelerı süz", "Filter": "Süz", "Reset": "Sıfırla", "All": "Bütün", "Published": "Yayımlandı", "Recent": "En son", "Are you sure you want to delete this article?": "Bu makaleyi silmek istediğinizden emin misiniz", "Search": "Ara", "Featured articles": "Özellikli makaleler", "Top articles": "En iyi makaleler", "Suggest": "Öner", "Login": "Giriş", "Please sign in": "Lütfen girin", "email address": "E-posta adresi", "Password": "Şifre", "Sign in": "Oturum aç", "Website": "Web sitesi", "Display": "Görüntüleme", "Update": "Güncelle", "Website title": "Web sitesi adı", "The title of your website": "Web sitenizin başlığı", "Website description": "Web sitesi tanımı", "A short website description when listing the homepage URL in search engines": "Arama motorlarında ana sayfanın BKK'sı listelendiğinde web sitenin bir kısa tanımı", "Show website logo": "Web sitenin logosu göster", "true": "Gerçek", "false": "Yanlış", "Controls whether to show the 'Website title' text or a logo located: '/public/logo.png' (by default)": "'Web sitesi başlığı' metnini veya '/public/logo.png' klasörde (varsayılan olarak) bulunan bir logo bulunan bir logo gösterip göstermeyeceğini kontrol eder", "Website context/base URL": "Web sitesinin ortam/temel BBK'sı", "Allows for the website to be run from a non root path. Eg: http://127.0.0.1:4444/openkb/": "Web sayfasının ana klasörden farklı bir dosyadan yürütülmesine izin verir. Örneği: http://127.0.0.1:4444/openkb/", "Allow API access": "API erişimine izin verir", "Whether to allow API access to insert articles - See documentation for further information": "Makaleleri eklemek için API erişimine izin verip vermeyeceği - Daha fazla bilgi için belgelere bakın", "API access token": "API erişim jetonu", "Requires 'Allow API access' to be set to 'true'. The value is the access token required to access the public API. Please set to a hard to guess value": "'API erişimine izin verir'nin doğru'ya olmasını gerektir. Requiere 'Permitir acceso a la API' activada. El valor es el token de acceso necesario para acceder a la API pública. Por favor, establece uno dificil para invitados", "Password protect": "Şifre koruması", "Setting to 'true' will require a user to login before viewing any pages": "'Gerçek' olarak ayarlamak, herhangi bir sayfayı görüntülemeden önce bir kullanıcının oturum açmasını gerektirir", "Index article body": "Makale gövdesi dizin et", "Whether to add the body of your articles to the search index (requires restart)": "Makalelerinizin gövdesini arama dizinine ekleyip eklememek (yeniden başlatma gerektirir)", "Select a theme": "Bir tema seçin", "The theme to use for public facing pages. Leave blank for default": "Halka açık sayfalar için kullanılacak tema. Varsayılan olarak boş bırakın", "Show logon link": "Logo bağlantısını göster", "Whether to show/hide the logon link in the top right of screen": "Ekranın sağ üst köşesindeki logo bağlantısını göstermek/gizlemek", "Date format": "Tarih formatı", "Sets the global date formatting. Uses moment.js date formatting, see more here: http://momentjs.com/docs/#/displaying": "Genel tarih biçimlendirmesini ayar. Moment.js tarih biçimlendirmesini kullanır, daha fazla bilgi için: http://momentjs.com/docs/#/displaying", "Article suggestions allowed": "Makale önerileri izin verdi", "If enabled non authenticated users can submit article suggestions for approval": "Etkinleştirilirse,kimliği doğrulanmayan kullanıcılar makale önerilerini onay için gönderebilirler", "Google analytics code": "Google analytics kodu", "Adds Google Analytics to public facing pages. Include the entire code from Google including the &lt;script&gt; tags": "Google Analytics'i herkese açık sayfalara ekler. &lt;script&gt; etiketlerini de içeren Google'ın tüm kodunu dahil eder", "Allow voting": "Oylamaya izin ver", "Whether to allow users to vote on an article": "Kullanıcılara bir makalede oylamaya izin verilir mi", "Show article meta data": "Makale meta verilerini göster", "Whether to show article meta data including published date, last updated date, author etc": "Yayınlanan tarih, son güncellenen tarihi, yazar falan falan makale meta verilerinde dahil olması gösterme", "Show author email": "Yazarın e-postasını göster", "Controls whether the authors email address is displayed in the meta. Requires 'Show article meta data' to be true": "Yazarın e-posta adresinin meta içinde görüntülenip görüntülenmediğini kontrol eder. 'Makale meta verilerini göster' gerçek olmasını gerektirir", "Article links open new page": "Makale bağlantıları yeni sayfa açar", "Controls whether links within articles open a new page (tab)": "Makaleler içindeki bağlantıları yeni bir sayfa açıp açmadığını kontrol eder (sekme)", "Add header anchors": "Başlık çapaları ekle", "Whether to add HTML anchors to all heading tags for linking within articles or direct linking from other articles": "Makaleler arasında bağlantı kurmak için tüm başlık etiketlerine veya diğer makalelerden doğrudan bağlanmak için HTML çapa ekleyip eklemediğini", "Enable editor spellchecker": "Düzenleyici yazım denetleyicisini etkinleştir", "Controls whether to enable the editor spellchecker": "Düzenleyici yazım denetleyicisini etkinleştirip etkinleştirmeyeceğini kontrol eder", "Allow article versioning": "Makale sürümüne izin ver", "Whether to track article versions with each save of the editor": "Düzenleyicinden her kaydetme ile makale sürümlerini izleyip izleme", "Number of top articles shown on homepage": "Anasayfada gösterilen en iyi makaleler sayısı", "Sets the number of results shown on the home page": "Ana sayfada gösterilen sonuç sayısını ayar", "Show published date": "Yayım tarihi göster", "Shows the published date next to the results on the homepage and search": "Yayınlanan tarihi ana sayfadaki ve aramasıdaki sonuçların yanında gösterir", "Show view count": "Görüntüle sayısını göster", "Shows the view count next to the results on the homepage and search": "Görüntü sayısını ana sayfadaki ve aramasıdakı sonuçların yanında gösterir", "Update view count when logged in": "Oturum açıldığını zaman görüntü sayısını günceller", "Updates the view count also when users are logged in": "kullanıcılar giriş yaptığını zaman da görüntü sayısını günceller", "Show featured articles": "Özellikli makalelerı göster", "Whether to show any articles set to featured in a sidebar": "Kenar çubuğunda özellikli olarak ayarlanmış herhangi bir makale gösterilip gösterilmemesi", "Show featured articles when viewing article": "Makale görüntülendiğinde özellikli makaleleri göster", "Whether to show any articles set to featured in a sidebar when viewing an article": "Bir makaleyi görüntülerken kenar çubuğunda özellikli olarak ayarlanmış herhangi bir makaleyi gösterip göstermeyeceğiniz", "Featured article count": "Öne çıkan makale sayısı", "The number of featured articles shown": "Gösterilen özellikli makalelerin sayısı", "Adds Google Analytics to public facing pages. Include the entire code from Google including the <script> tags": "Google Analytics'i herkese açık sayfalara ekler. <script> etiketlerini de içeren Google'ın tüm kodunu dahil eder", "New user": "Yeni kullanıcı", "Users name": "Kullanıcının adı", "User email": "Kullanıcının e-postası", "User password": "Kullanıcının şifresi", "Password confirm": "Şifre onayla", "Create": "Yarat", "A user with that email address already exists": "Bu e-posta adresine sahip bir kullanıcı zaten var", "User": "Kullanıcı", "Role": "Rol", "Admin": "Yönetici", "Are you sure you want to delete?": "Silmek istediğine emin misin", "User edit": "Kullanıcı düzenleme", "Password values do not match": "Parola değerleri uyuşmuyor", "Date": "Tarıhı", "View count": "Görüntüleme sayısı", "Settings successfully updated.": "Ayarlar başarıyla güncellendi.", "Controls whether to show the \"Website title\" text or a logo located: \"/public/logo.png\" (by default)": "\"Web sitesi başlığı\" metnini veya yer alan bir logosunun gösterilip gösterilmeyeceğini kontrol eder: \"/public/logo.png\" (varsayılan olarak)", "Requires \"Allow API access\" to be set to \"true\". The value is the access token required to access the public API. Please set to a hard to guess value": "\"gerçek\" olarak ayarlanacak \"API erişimine izin ver\" gerektirir. Değeri, genel API'ya erişmek için gereken erişim jeton. Lütfen değeri tahmin etmek zora ayarlayın.", "Setting to \"true\" will require a user to login before viewing any pages": "\"gerçek\" olarak ayarlamak, herhangi bir sayfayı görüntülemeden önce bir kullanıcının oturum açmasını gerektirir", "Select a language": "Bir dil seçin", "The language to use for public facing pages. Leave blank for default (English)": "Halka açık sayfalar için kullanılacak dil. Varsayılan değer için boş bırakın (İngilizce)", "Controls whether the authors email address is displayed in the meta. Requires \"Show article meta data\" to be true": "Yazarların e-posta adresinin meta içinde görüntülenip görüntülenmediğini kontrol eder. \"Makale meta verilerini göster\" gerçek olması gerekir.", "Import": "İçeri aktar" }
mrvautin/openKB
locales/tr.js
JavaScript
mit
9,941
import ssml from './ssml'; export default ssml; export renderToString from './renderToString';
cameronhunter/alexa
packages/ssml-jsx/src/index.js
JavaScript
mit
96
var assert = require('assert'); module.exports = function(getNewTester, noop) { var tester = getNewTester(); tester.plan('passing', noop); /* doesn't break easily */ assert.doesNotThrow(function() { tester.run(0); tester.runAll(); tester.runAllInParallel(); }); /* returns a promise */ assert(tester.run(0) instanceof Promise); assert(tester.runAll() instanceof Promise); assert(tester.runAllInParallel() instanceof Promise); };
dchekanov/austere-tester
tests/suites/running.js
JavaScript
mit
465
/*! Select2 4.0.3 | https://github.com/select2/select2/blob/master/LICENSE.md */ (function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;return e.define("select2/i18n/ko",[],function(){return{errorLoading:function(){return"ê²°ê³¼ë¥?불러ì˜?ìˆ?없습니다."},inputTooLong:function(e){var t=e.input.length-e.maximum,n="너무 깁니ë‹? "+t+" 글ìž?지워주세요.";return n},inputTooShort:function(e){var t=e.minimum-e.input.length,n="너무 짧습니다. "+t+" 글ìž?ë?입력해주세요.";return n},loadingMore:function(){return"불러오는 중â€?},maximumSelected:function(e){var t="최대 "+e.maximum+"개까지ë§?선택 가능합니다.";return t},noResults:function(){return"결과가 없습니다."},searching:function(){return"검ìƒ?중â€?}}}),{define:e.define,require:e.require}})();
zanjs/skipper
publishable/assets/js/select2/i18n/ko.js
JavaScript
mit
843
/*! ngTableExport v0.1.0 by Vitalii Savchuk(esvit666@gmail.com) - https://github.com/esvit/ng-table-export - New BSD License */ angular.module("ngTableExport", []).config(["$compileProvider", function(a) { a.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|data):/); }]).directive("exportCsv", [ "$parse", function(a) { return{ restrict: "A", scope: !1, link: function(b, c, d) { var e = "", f = { stringify: function(a) { return'"' + a.replace(/^\s\s*/, "").replace(/\s*\s$/, "").replace(/"/g, '""') + '"'; }, generate: function() { e = ""; var a = c.find("tr"); angular.forEach(a, function(a, b) { var c = angular.element(a), d = c.find("th"), g = ""; c.hasClass("ng-table-filters") || (0 == d.length && (d = c.find("td")), 1 != b && (angular.forEach(d, function(a) { g += f.stringify(angular.element(a).text()) + ";"; }), g = g.slice(0, g.length - 1)), e += g + "\n"); }); }, link: function() { return"data:text/csv;charset=UTF-8," + encodeURIComponent(e); } }; a(d.exportCsv).assign(b.$parent, f); } }; } ]);
makingsensetraining/angular-webapi
Source/Hiperion/Hiperion/Scripts/ng-table-export.js
JavaScript
mit
1,454
'use strict'; var _ = require('lodash'); var Api = require('./api.js'); var client = function client() { var waiting = []; var send = function send(type, message) { process.send({ type: type, message: message }); }; var api = new Api(send); process.on('message', function onMessage(metrics) { _.each(waiting, function eachWaiting(callback) { callback(metrics); }); waiting = []; }); api.getMetrics = function onMetrics(callback) { var inWaiting = waiting.length; waiting.push(callback); if (!inWaiting) { send('report', ''); } }; return api; }; module.exports = client;
dibyom/cluster-metrics
src/client.js
JavaScript
mit
640
//if(Meteor.isClient){ Template.slideMenu.rendered = function () { $(document).ready(function () { // make sure multiple click handlers are not registered to this $('.slideout-menu-toggle').off('click'); $('.slideout-menu-toggle').on('click', function(event){ event.preventDefault(); event.stopPropagation(); //console.log("SlideMenu - Click"); // create menu variables var slideoutMenu = $('.slideout-menu'); var slideoutMenuWidth = $('.slideout-menu').width(); // toggle open class slideoutMenu.toggleClass("open"); // slide menu Open if (slideoutMenu.hasClass("open")) { slideoutMenu.animate({left: "0px"}); // create a one-time event to close when a user clicks anywhere outside $(document).one('click', function(){ console.log("Event on the main doc"); slideoutMenu.toggleClass("open"); slideoutMenu.animate({left: -slideoutMenuWidth}, 250); }); } else { // slide menu close slideoutMenu.animate({left: -slideoutMenuWidth}, 250); } }); }); }; //}
dakarpt/PSocial
packages/easy-side-menu/easy-side-menu.js
JavaScript
mit
1,270
'use strict'; /** * Module dependencies. */ var debug = require('debug')('superagent'); var formidable = require('formidable'); var FormData = require('form-data'); var Response = require('./response'); var parse = require('url').parse; var format = require('url').format; var resolve = require('url').resolve; var methods = require('methods'); var Stream = require('stream'); var utils = require('../utils'); var unzip = require('./unzip').unzip; var extend = require('extend'); var mime = require('mime'); var https = require('https'); var http = require('http'); var fs = require('fs'); var qs = require('qs'); var zlib = require('zlib'); var util = require('util'); var pkg = require('../../package.json'); var RequestBase = require('../request-base'); var shouldRetry = require('../should-retry'); var request = exports = module.exports = function(method, url) { // callback if ('function' == typeof url) { return new exports.Request('GET', method).end(url); } // url first if (1 == arguments.length) { return new exports.Request('GET', method); } return new exports.Request(method, url); } /** * Expose `Request`. */ exports.Request = Request; /** * Expose the agent function */ exports.agent = require('./agent'); /** * Noop. */ function noop(){}; /** * Expose `Response`. */ exports.Response = Response; /** * Define "form" mime type. */ mime.define({ 'application/x-www-form-urlencoded': ['form', 'urlencoded', 'form-data'] }, true); /** * Protocol map. */ exports.protocols = { 'http:': http, 'https:': https }; /** * Default serialization map. * * superagent.serialize['application/xml'] = function(obj){ * return 'generated xml here'; * }; * */ exports.serialize = { 'application/x-www-form-urlencoded': qs.stringify, 'application/json': JSON.stringify }; /** * Default parsers. * * superagent.parse['application/xml'] = function(res, fn){ * fn(null, res); * }; * */ exports.parse = require('./parsers'); /** * Initialize internal header tracking properties on a request instance. * * @param {Object} req the instance * @api private */ function _initHeaders(req) { var ua = 'node-superagent/' + pkg.version; req._header = { // coerces header names to lowercase 'user-agent': ua }; req.header = { // preserves header name case 'User-Agent': ua }; } /** * Initialize a new `Request` with the given `method` and `url`. * * @param {String} method * @param {String|Object} url * @api public */ function Request(method, url) { Stream.call(this); if ('string' != typeof url) url = format(url); this._agent = false; this._formData = null; this.method = method; this.url = url; _initHeaders(this); this.writable = true; this._redirects = 0; this.redirects(method === 'HEAD' ? 0 : 5); this.cookies = ''; this.qs = {}; this._query = []; this.qsRaw = this._query; // Unused, for backwards compatibility only this._redirectList = []; this._streamRequest = false; this.once('end', this.clearTimeout.bind(this)); } /** * Inherit from `Stream` (which inherits from `EventEmitter`). * Mixin `RequestBase`. */ util.inherits(Request, Stream); RequestBase(Request.prototype); /** * Queue the given `file` as an attachment to the specified `field`, * with optional `options` (or filename). * * ``` js * request.post('http://localhost/upload') * .attach(new Buffer('<b>Hello world</b>'), 'hello.html') * .end(callback); * ``` * * A filename may also be used: * * ``` js * request.post('http://localhost/upload') * .attach('files', 'image.jpg') * .end(callback); * ``` * * @param {String} field * @param {String|fs.ReadStream|Buffer} file * @param {String|Object} options * @return {Request} for chaining * @api public */ Request.prototype.attach = function(field, file, options){ if (file) { if (this._data) { throw Error("superagent can't mix .send() and .attach()"); } var o = options || {}; if ('string' == typeof options) { o = { filename: options }; } if ('string' == typeof file) { if (!o.filename) o.filename = file; debug('creating `fs.ReadStream` instance for file: %s', file); file = fs.createReadStream(file); } else if (!o.filename && file.path) { o.filename = file.path; } this._getFormData().append(field, file, o); } return this; }; Request.prototype._getFormData = function() { if (!this._formData) { this._formData = new FormData(); var that = this; this._formData.on('error', function(err) { that.emit('error', err); that.abort(); }); } return this._formData; }; /** * Gets/sets the `Agent` to use for this HTTP request. The default (if this * function is not called) is to opt out of connection pooling (`agent: false`). * * @param {http.Agent} agent * @return {http.Agent} * @api public */ Request.prototype.agent = function(agent){ if (!arguments.length) return this._agent; this._agent = agent; return this; }; /** * Set _Content-Type_ response header passed through `mime.lookup()`. * * Examples: * * request.post('/') * .type('xml') * .send(xmlstring) * .end(callback); * * request.post('/') * .type('json') * .send(jsonstring) * .end(callback); * * request.post('/') * .type('application/json') * .send(jsonstring) * .end(callback); * * @param {String} type * @return {Request} for chaining * @api public */ Request.prototype.type = function(type){ return this.set('Content-Type', ~type.indexOf('/') ? type : mime.lookup(type)); }; /** * Set _Accept_ response header passed through `mime.lookup()`. * * Examples: * * superagent.types.json = 'application/json'; * * request.get('/agent') * .accept('json') * .end(callback); * * request.get('/agent') * .accept('application/json') * .end(callback); * * @param {String} accept * @return {Request} for chaining * @api public */ Request.prototype.accept = function(type){ return this.set('Accept', ~type.indexOf('/') ? type : mime.lookup(type)); }; /** * Add query-string `val`. * * Examples: * * request.get('/shoes') * .query('size=10') * .query({ color: 'blue' }) * * @param {Object|String} val * @return {Request} for chaining * @api public */ Request.prototype.query = function(val){ if ('string' == typeof val) { this._query.push(val); } else { extend(this.qs, val); } return this; }; /** * Write raw `data` / `encoding` to the socket. * * @param {Buffer|String} data * @param {String} encoding * @return {Boolean} * @api public */ Request.prototype.write = function(data, encoding){ var req = this.request(); if (!this._streamRequest) { this._streamRequest = true; } return req.write(data, encoding); }; /** * Pipe the request body to `stream`. * * @param {Stream} stream * @param {Object} options * @return {Stream} * @api public */ Request.prototype.pipe = function(stream, options){ this.piped = true; // HACK... this.buffer(false); this.end(); return this._pipeContinue(stream, options); }; Request.prototype._pipeContinue = function(stream, options){ var self = this; this.req.once('response', function(res){ // redirect var redirect = isRedirect(res.statusCode); if (redirect && self._redirects++ != self._maxRedirects) { return self._redirect(res)._pipeContinue(stream, options); } self.res = res; self._emitResponse(); if (self._aborted) return; if (self._shouldUnzip(res)) { res.pipe(zlib.createUnzip()).pipe(stream, options); } else { res.pipe(stream, options); } res.once('end', function(){ self.emit('end'); }); }); return stream; }; /** * Enable / disable buffering. * * @return {Boolean} [val] * @return {Request} for chaining * @api public */ Request.prototype.buffer = function(val){ this._buffer = (false !== val); return this; }; /** * Redirect to `url * * @param {IncomingMessage} res * @return {Request} for chaining * @api private */ Request.prototype._redirect = function(res){ var url = res.headers.location; if (!url) { return this.callback(new Error('No location header for redirect'), res); } debug('redirect %s -> %s', this.url, url); // location url = resolve(this.url, url); // ensure the response is being consumed // this is required for Node v0.10+ res.resume(); var headers = this.req._headers; var shouldStripCookie = parse(url).host !== parse(this.url).host; // implementation of 302 following defacto standard if (res.statusCode == 301 || res.statusCode == 302){ // strip Content-* related fields // in case of POST etc headers = utils.cleanHeader(this.req._headers, shouldStripCookie); // force GET this.method = 'HEAD' == this.method ? 'HEAD' : 'GET'; // clear data this._data = null; } // 303 is always GET if (res.statusCode == 303) { // strip Content-* related fields // in case of POST etc headers = utils.cleanHeader(this.req._headers, shouldStripCookie); // force method this.method = 'GET'; // clear data this._data = null; } // 307 preserves method // 308 preserves method delete headers.host; delete this.req; delete this._formData; // remove all add header except User-Agent _initHeaders(this) // redirect this._endCalled = false; this.url = url; this.qs = {}; this._query.length = 0; this.set(headers); this.emit('redirect', res); this._redirectList.push(this.url); this.end(this._callback); return this; }; /** * Set Authorization field value with `user` and `pass`. * * Examples: * * .auth('tobi', 'learnboost') * .auth('tobi:learnboost') * .auth('tobi') * .auth(accessToken, { type: 'bearer' }) * * @param {String} user * @param {String} [pass] * @param {Object} [options] options with authorization type 'basic' or 'bearer' ('basic' is default) * @return {Request} for chaining * @api public */ Request.prototype.auth = function(user, pass, options){ if (1 === arguments.length) pass = ''; if (2 === arguments.length && typeof pass === 'object') options = pass; if (!options) { options = { type: 'basic' }; } switch (options.type) { case 'bearer': return this.set('Authorization', 'Bearer ' + user); default: // 'basic' if (!~user.indexOf(':')) user = user + ':'; var str = new Buffer(user + pass).toString('base64'); return this.set('Authorization', 'Basic ' + str); } }; /** * Set the certificate authority option for https request. * * @param {Buffer | Array} cert * @return {Request} for chaining * @api public */ Request.prototype.ca = function(cert){ this._ca = cert; return this; }; /** * Set the client certificate key option for https request. * * @param {Buffer | String} cert * @return {Request} for chaining * @api public */ Request.prototype.key = function(cert){ this._key = cert; return this; }; /** * Set the key, certificate, and CA certs of the client in PFX or PKCS12 format. * * @param {Buffer | String} cert * @return {Request} for chaining * @api public */ Request.prototype.pfx = function(cert){ if(typeof cert === 'object' && !Buffer.isBuffer(cert)){ this._pfx = cert.pfx; this._passphrase = cert.passphrase; } else { this._pfx = cert; } return this; }; /** * Set the client certificate option for https request. * * @param {Buffer | String} cert * @return {Request} for chaining * @api public */ Request.prototype.cert = function(cert){ this._cert = cert; return this; }; /** * Return an http[s] request. * * @return {OutgoingMessage} * @api private */ Request.prototype.request = function(){ if (this.req) return this.req; var self = this; var options = {}; try { var query = qs.stringify(this.qs, { indices: false, strictNullHandling: true }); if (query) { this.qs = {}; this._query.push(query); } this._finalizeQueryString(); } catch (e) { return this.emit('error', e); } var url = this.url; var retries = this._retries; // default to http:// if (0 != url.indexOf('http')) url = 'http://' + url; url = parse(url); // support unix sockets if (/^https?\+unix:/.test(url.protocol) === true) { // get the protocol url.protocol = url.protocol.split('+')[0] + ':'; // get the socket, path var unixParts = url.path.match(/^([^/]+)(.+)$/); options.socketPath = unixParts[1].replace(/%2F/g, '/'); url.path = unixParts[2]; } // options options.method = this.method; options.port = url.port; options.path = url.path; options.host = url.hostname; options.ca = this._ca; options.key = this._key; options.pfx = this._pfx; options.cert = this._cert; options.passphrase = this._passphrase; options.agent = this._agent; // initiate request var mod = exports.protocols[url.protocol]; // request var req = this.req = mod.request(options); // set tcp no delay req.setNoDelay(true); if ('HEAD' != options.method) { req.setHeader('Accept-Encoding', 'gzip, deflate'); } this.protocol = url.protocol; this.host = url.host; // expose events req.once('drain', function(){ self.emit('drain'); }); req.once('error', function(err){ // flag abortion here for out timeouts // because node will emit a faux-error "socket hang up" // when request is aborted before a connection is made if (self._aborted) return; // if not the same, we are in the **old** (cancelled) request, // so need to continue (same as for above) if (self._retries !== retries) return; // if we've received a response then we don't want to let // an error in the request blow up the response if (self.response) return; self.callback(err); }); // auth if (url.auth) { var auth = url.auth.split(':'); this.auth(auth[0], auth[1]); } // add cookies if (this.cookies) req.setHeader('Cookie', this.cookies); for (var key in this.header) { if (this.header.hasOwnProperty(key)) req.setHeader(key, this.header[key]); } return req; }; /** * Invoke the callback with `err` and `res` * and handle arity check. * * @param {Error} err * @param {Response} res * @api private */ Request.prototype.callback = function(err, res){ // console.log(this._retries, this._maxRetries) if (this._maxRetries && this._retries++ < this._maxRetries && shouldRetry(err, res)) { return this._retry(); } // Avoid the error which is emitted from 'socket hang up' to cause the fn undefined error on JS runtime. var fn = this._callback || noop; this.clearTimeout(); if (this.called) return console.warn('superagent: double callback bug'); this.called = true; if (!err) { try { if (this._isResponseOK(res)) { return fn(err, res); } var msg = 'Unsuccessful HTTP response'; if (res) { msg = http.STATUS_CODES[res.status] || msg; } err = new Error(msg); err.status = res ? res.status : undefined; } catch (new_err) { err = new_err; } } err.response = res; if (this._maxRetries) err.retries = this._retries - 1; // only emit error event if there is a listener // otherwise we assume the callback to `.end()` will get the error if (err && this.listeners('error').length > 0) { this.emit('error', err); } fn(err, res); }; /** * Check if `obj` is a host object, * * @param {Object} obj * @return {Boolean} * @api private */ Request.prototype._isHost = function _isHost(obj) { return Buffer.isBuffer(obj) || obj instanceof Stream || obj instanceof FormData; } /** * Initiate request, invoking callback `fn(err, res)` * with an instanceof `Response`. * * @param {Function} fn * @return {Request} for chaining * @api public */ Request.prototype._emitResponse = function(body, files){ var response = new Response(this); this.response = response; response.redirects = this._redirectList; if (undefined !== body) { response.body = body; } response.files = files; this.emit('response', response); return response; }; Request.prototype.end = function(fn){ this.request(); debug('%s %s', this.method, this.url); if (this._endCalled) { console.warn("Warning: .end() was called twice. This is not supported in superagent"); } this._endCalled = true; // store callback this._callback = fn || noop; return this._end(); }; Request.prototype._end = function() { var self = this; var data = this._data; var req = this.req; var buffer = this._buffer; var method = this.method; this._setTimeouts(); // body if ('HEAD' != method && !req._headerSent) { // serialize stuff if ('string' != typeof data) { var contentType = req.getHeader('Content-Type') // Parse out just the content type from the header (ignore the charset) if (contentType) contentType = contentType.split(';')[0] var serialize = exports.serialize[contentType]; if (!serialize && isJSON(contentType)) { serialize = exports.serialize['application/json']; } if (serialize) data = serialize(data); } // content-length if (data && !req.getHeader('Content-Length')) { req.setHeader('Content-Length', Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data)); } } // response req.once('response', function(res){ debug('%s %s -> %s', self.method, self.url, res.statusCode); if (self._responseTimeoutTimer) { clearTimeout(self._responseTimeoutTimer); } if (self.piped) { return; } var max = self._maxRedirects; var mime = utils.type(res.headers['content-type'] || '') || 'text/plain'; var type = mime.split('/')[0]; var multipart = 'multipart' == type; var redirect = isRedirect(res.statusCode); var parser = self._parser; var responseType = self._responseType; self.res = res; // redirect if (redirect && self._redirects++ != max) { return self._redirect(res); } if ('HEAD' == self.method) { self.emit('end'); self.callback(null, self._emitResponse()); return; } // zlib support if (self._shouldUnzip(res)) { unzip(req, res); } if (!parser) { if (responseType) { parser = exports.parse.image; // It's actually a generic Buffer buffer = true; } else if (multipart) { var form = new formidable.IncomingForm(); parser = form.parse.bind(form); buffer = true; } else if (isImageOrVideo(mime)) { parser = exports.parse.image; buffer = true; // For backwards-compatibility buffering default is ad-hoc MIME-dependent } else if (exports.parse[mime]) { parser = exports.parse[mime]; } else if ('text' == type) { parser = exports.parse.text; buffer = (buffer !== false); // everyone wants their own white-labeled json } else if (isJSON(mime)) { parser = exports.parse['application/json']; buffer = (buffer !== false); } else if (buffer) { parser = exports.parse.text; } } // by default only buffer text/*, json and messed up thing from hell if (undefined === buffer && isText(mime) || isJSON(mime)) { buffer = true; } var parserHandlesEnd = false; if (buffer) { // Protectiona against zip bombs and other nuisance let responseBytesLeft = self._maxResponseSize || 200000000; res.on('data', function(buf) { responseBytesLeft -= buf.byteLength || buf.length; if (responseBytesLeft < 0) { // This will propagate through error event const err = Error("Maximum response size reached"); err.code = "ETOOLARGE"; // Parsers aren't required to observe error event, // so would incorrectly report success parserHandlesEnd = false; // Will emit error event res.destroy(err); } }); } if (parser) { try { // Unbuffered parsers are supposed to emit response early, // which is weird BTW, because response.body won't be there. parserHandlesEnd = buffer; parser(res, function(err, obj, files) { if (self.timedout) { // Timeout has already handled all callbacks return; } // Intentional (non-timeout) abort is supposed to preserve partial response, // even if it doesn't parse. if (err && !self._aborted) { return self.callback(err); } if (parserHandlesEnd) { self.emit('end'); self.callback(null, self._emitResponse(obj, files)); } }); } catch (err) { self.callback(err); return; } } self.res = res; // unbuffered if (!buffer) { debug('unbuffered %s %s', self.method, self.url); self.callback(null, self._emitResponse()); if (multipart) return // allow multipart to handle end event res.once('end', function(){ debug('end %s %s', self.method, self.url); self.emit('end'); }) return; } // terminating events res.once('error', function(err){ parserHandlesEnd = false; self.callback(err, null); }); if (!parserHandlesEnd) res.once('end', function(){ debug('end %s %s', self.method, self.url); // TODO: unless buffering emit earlier to stream self.emit('end'); self.callback(null, self._emitResponse()); }); }); this.emit('request', this); // if a FormData instance got created, then we send that as the request body var formData = this._formData; if (formData) { // set headers var headers = formData.getHeaders(); for (var i in headers) { debug('setting FormData header: "%s: %s"', i, headers[i]); req.setHeader(i, headers[i]); } // attempt to get "Content-Length" header formData.getLength(function(err, length) { // TODO: Add chunked encoding when no length (if err) debug('got FormData Content-Length: %s', length); if ('number' == typeof length) { req.setHeader('Content-Length', length); } var getProgressMonitor = function () { var lengthComputable = true; var total = req.getHeader('Content-Length'); var loaded = 0; var progress = new Stream.Transform(); progress._transform = function (chunk, encoding, cb) { loaded += chunk.length; self.emit('progress', { direction: 'upload', lengthComputable: lengthComputable, loaded: loaded, total: total }); cb(null, chunk); }; return progress; }; formData.pipe(getProgressMonitor()).pipe(req); }); } else { req.end(data); } return this; }; /** * Check whether response has a non-0-sized gzip-encoded body */ Request.prototype._shouldUnzip = function(res){ if (res.statusCode === 204 || res.statusCode === 304) { // These aren't supposed to have any body return false; } // header content is a string, and distinction between 0 and no information is crucial if ('0' === res.headers['content-length']) { // We know that the body is empty (unfortunately, this check does not cover chunked encoding) return false; } // console.log(res); return /^\s*(?:deflate|gzip)\s*$/.test(res.headers['content-encoding']); }; // generate HTTP verb methods if (methods.indexOf('del') == -1) { // create a copy so we don't cause conflicts with // other packages using the methods package and // npm 3.x methods = methods.slice(0); methods.push('del'); } methods.forEach(function(method){ var name = method; method = 'del' == method ? 'delete' : method; method = method.toUpperCase(); request[name] = function(url, data, fn){ var req = request(method, url); if ('function' == typeof data) fn = data, data = null; if (data) { if (method === 'GET' || method === 'HEAD') { req.query(data); } else { req.send(data); } } fn && req.end(fn); return req; }; }); /** * Check if `mime` is text and should be buffered. * * @param {String} mime * @return {Boolean} * @api public */ function isText(mime) { var parts = mime.split('/'); var type = parts[0]; var subtype = parts[1]; return 'text' == type || 'x-www-form-urlencoded' == subtype; } function isImageOrVideo(mime) { var type = mime.split('/')[0]; return 'image' == type || 'video' == type; } /** * Check if `mime` is json or has +json structured syntax suffix. * * @param {String} mime * @return {Boolean} * @api private */ function isJSON(mime) { return /[\/+]json\b/.test(mime); } /** * Check if we should follow the redirect `code`. * * @param {Number} code * @return {Boolean} * @api private */ function isRedirect(code) { return ~[301, 302, 303, 305, 307, 308].indexOf(code); }
TimAdamson21/a11ytext
node_modules/superagent/lib/node/index.js
JavaScript
mit
25,317
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M6.7 18.29c.39.39 1.02.39 1.41 0L12 14.42l3.88 3.88c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L12.7 12.3a.9959.9959 0 0 0-1.41 0L6.7 16.88c-.39.39-.39 1.02 0 1.41z" }, "0"), /*#__PURE__*/_jsx("path", { d: "M6.7 11.7c.39.39 1.02.39 1.41 0L12 7.83l3.88 3.88c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L12.7 5.71a.9959.9959 0 0 0-1.41 0L6.7 10.29c-.39.39-.39 1.02 0 1.41z" }, "1")], 'KeyboardDoubleArrowUpRounded');
oliviertassinari/material-ui
packages/mui-icons-material/lib/esm/KeyboardDoubleArrowUpRounded.js
JavaScript
mit
581
/* eslint max-len:0 */ // MSSQL Table Builder & Compiler // ------- const TableCompiler = require('../../../schema/tablecompiler'); const helpers = require('../../../util/helpers'); // Table Compiler // ------ class TableCompiler_MSSQL extends TableCompiler { constructor(client, tableBuilder) { super(client, tableBuilder); } createQuery(columns, ifNot) { const createStatement = ifNot ? `if object_id('${this.tableName()}', 'U') is null CREATE TABLE ` : 'CREATE TABLE '; const sql = createStatement + this.tableName() + (this._formatting ? ' (\n ' : ' (') + columns.sql.join(this._formatting ? ',\n ' : ', ') + ')'; if (this.single.comment) { const { comment } = this.single; // XXX: This is a byte limit, not character, so we cannot definitively say they'll exceed the limit without database collation info. if (comment.length > 7500 / 2) this.client.logger.warn( 'Your comment might be longer than the max comment length for MSSQL of 7,500 bytes.' ); } this.pushQuery(sql); } // Compiles column add. Multiple columns need only one ADD clause (not one ADD per column) so core addColumns doesn't work. #1348 addColumns(columns, prefix) { prefix = prefix || this.addColumnsPrefix; if (columns.sql.length > 0) { this.pushQuery({ sql: (this.lowerCase ? 'alter table ' : 'ALTER TABLE ') + this.tableName() + ' ' + prefix + columns.sql.join(', '), bindings: columns.bindings, }); } } alterColumns(columns, colBuilder) { for (let i = 0, l = colBuilder.length; i < l; i++) { const builder = colBuilder[i]; if (builder.modified.defaultTo) { const schema = this.schemaNameRaw || 'dbo'; const baseQuery = ` DECLARE @constraint varchar(100) = (SELECT default_constraints.name FROM sys.all_columns INNER JOIN sys.tables ON all_columns.object_id = tables.object_id INNER JOIN sys.schemas ON tables.schema_id = schemas.schema_id INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id WHERE schemas.name = '${schema}' AND tables.name = '${ this.tableNameRaw }' AND all_columns.name = '${builder.getColumnName()}') IF @constraint IS NOT NULL EXEC('ALTER TABLE ${ this.tableNameRaw } DROP CONSTRAINT ' + @constraint)`; this.pushQuery(baseQuery); } } // in SQL server only one column can be altered at a time columns.sql.forEach((sql) => { this.pushQuery({ sql: (this.lowerCase ? 'alter table ' : 'ALTER TABLE ') + this.tableName() + ' ' + (this.lowerCase ? this.alterColumnPrefix.toLowerCase() : this.alterColumnPrefix) + sql, bindings: columns.bindings, }); }); } // Compiles column drop. Multiple columns need only one DROP clause (not one DROP per column) so core dropColumn doesn't work. #1348 dropColumn() { const _this2 = this; const columns = helpers.normalizeArr.apply(null, arguments); const columnsArray = Array.isArray(columns) ? columns : [columns]; const drops = columnsArray.map((column) => _this2.formatter.wrap(column)); const schema = this.schemaNameRaw || 'dbo'; for (const column of columns) { const baseQuery = ` DECLARE @constraint varchar(100) = (SELECT default_constraints.name FROM sys.all_columns INNER JOIN sys.tables ON all_columns.object_id = tables.object_id INNER JOIN sys.schemas ON tables.schema_id = schemas.schema_id INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id WHERE schemas.name = '${schema}' AND tables.name = '${this.tableNameRaw}' AND all_columns.name = '${column}') IF @constraint IS NOT NULL EXEC('ALTER TABLE ${this.tableNameRaw} DROP CONSTRAINT ' + @constraint)`; this.pushQuery(baseQuery); } this.pushQuery( (this.lowerCase ? 'alter table ' : 'ALTER TABLE ') + this.tableName() + ' ' + this.dropColumnPrefix + drops.join(', ') ); } // Compiles the comment on the table. comment() {} changeType() {} // Renames a column on the table. renameColumn(from, to) { this.pushQuery( `exec sp_rename ${this.client.parameter( this.tableName() + '.' + from, this.tableBuilder, this.bindingsHolder )}, ${this.client.parameter( to, this.tableBuilder, this.bindingsHolder )}, 'COLUMN'` ); } dropFKRefs(runner, refs) { const formatter = this.client.formatter(this.tableBuilder); return Promise.all( refs.map(function (ref) { const constraintName = formatter.wrap(ref.CONSTRAINT_NAME); const tableName = formatter.wrap(ref.TABLE_NAME); return runner.query({ sql: `ALTER TABLE ${tableName} DROP CONSTRAINT ${constraintName}`, }); }) ); } createFKRefs(runner, refs) { const formatter = this.client.formatter(this.tableBuilder); return Promise.all( refs.map(function (ref) { const tableName = formatter.wrap(ref.TABLE_NAME); const keyName = formatter.wrap(ref.CONSTRAINT_NAME); const column = formatter.columnize(ref.COLUMN_NAME); const references = formatter.columnize(ref.REFERENCED_COLUMN_NAME); const inTable = formatter.wrap(ref.REFERENCED_TABLE_NAME); const onUpdate = ` ON UPDATE ${ref.UPDATE_RULE}`; const onDelete = ` ON DELETE ${ref.DELETE_RULE}`; return runner.query({ sql: `ALTER TABLE ${tableName} ADD CONSTRAINT ${keyName}` + ' FOREIGN KEY (' + column + ') REFERENCES ' + inTable + ' (' + references + ')' + onUpdate + onDelete, }); }) ); } index(columns, indexName) { indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); this.pushQuery( `CREATE INDEX ${indexName} ON ${this.tableName()} (${this.formatter.columnize( columns )})` ); } primary(columns, constraintName) { constraintName = constraintName ? this.formatter.wrap(constraintName) : this.formatter.wrap(`${this.tableNameRaw}_pkey`); if (!this.forCreate) { this.pushQuery( `ALTER TABLE ${this.tableName()} ADD CONSTRAINT ${constraintName} PRIMARY KEY (${this.formatter.columnize( columns )})` ); } else { this.pushQuery( `CONSTRAINT ${constraintName} PRIMARY KEY (${this.formatter.columnize( columns )})` ); } } unique(columns, indexName) { indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, columns); if (!Array.isArray(columns)) { columns = [columns]; } const whereAllTheColumnsAreNotNull = columns .map((column) => this.formatter.columnize(column) + ' IS NOT NULL') .join(' AND '); // make unique constraint that allows null https://stackoverflow.com/a/767702/360060 // to be more or less compatible with other DBs (if any of the columns is NULL then "duplicates" are allowed) this.pushQuery( `CREATE UNIQUE INDEX ${indexName} ON ${this.tableName()} (${this.formatter.columnize( columns )}) WHERE ${whereAllTheColumnsAreNotNull}` ); } // Compile a drop index command. dropIndex(columns, indexName) { indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); this.pushQuery(`DROP INDEX ${indexName} ON ${this.tableName()}`); } // Compile a drop foreign key command. dropForeign(columns, indexName) { indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('foreign', this.tableNameRaw, columns); this.pushQuery( `ALTER TABLE ${this.tableName()} DROP CONSTRAINT ${indexName}` ); } // Compile a drop primary key command. dropPrimary(constraintName) { constraintName = constraintName ? this.formatter.wrap(constraintName) : this.formatter.wrap(`${this.tableNameRaw}_pkey`); this.pushQuery( `ALTER TABLE ${this.tableName()} DROP CONSTRAINT ${constraintName}` ); } // Compile a drop unique key command. dropUnique(column, indexName) { indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, column); this.pushQuery(`DROP INDEX ${indexName} ON ${this.tableName()}`); } } TableCompiler_MSSQL.prototype.createAlterTableMethods = ['foreign', 'primary']; TableCompiler_MSSQL.prototype.lowerCase = false; TableCompiler_MSSQL.prototype.addColumnsPrefix = 'ADD '; TableCompiler_MSSQL.prototype.dropColumnPrefix = 'DROP COLUMN '; TableCompiler_MSSQL.prototype.alterColumnPrefix = 'ALTER COLUMN '; module.exports = TableCompiler_MSSQL;
tgriesser/knex
lib/dialects/mssql/schema/mssql-tablecompiler.js
JavaScript
mit
10,313
'use strict'; // Local dependencies var command = require('../lib/command'); /** * A USER request has a parameter showing a username. Subsequent pathnames are * interpreted relative to this username. * * The server may accept USER with code 230, meaning that the client has * permission to access files under that username; or with code 331 or 332, * meaning that permission might be granted after a PASS request. * * In theory, the server may reject USER with code 530, meaning that the * username is unacceptable. In practice, the server does not check the username * until after a PASS request. * * Some clients incorrectly treat 230 the same way as 530. * * Some servers can accept several USER requests in one FTP connection; some * can't. It is recommended that clients make a new connection instead. */ command.add('USER', 'USER <sp> username', function (username, commandChannel, session) { session.user = username; commandChannel.write(331, 'Password required to access user account ' + username.trim()); });
brandonwamboldt/nodeftpd
commands/user.js
JavaScript
mit
1,040
/* * Easy Slider 1.5 - jQuery plugin * written by Alen Grakalic * http://cssglobe.com/post/4004/easy-slider-15-the-easiest-jquery-plugin-for-sliding * * Copyright (c) 2009 Alen Grakalic (http://cssglobe.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * Built for jQuery library * http://jquery.com * */ /* * markup example for $("#slider").easySlider(); * * <div id="slider"> * <ul> * <li><img src="images/01.jpg" alt="" /></li> * <li><img src="images/02.jpg" alt="" /></li> * <li><img src="images/03.jpg" alt="" /></li> * <li><img src="images/04.jpg" alt="" /></li> * <li><img src="images/05.jpg" alt="" /></li> * </ul> * </div> * */ (function($) { $.fn.easySlider = function(options){ // default configuration properties var defaults = { prevId: 'prevBtn', prevText: 'Previous', nextId: 'nextBtn', nextText: 'Next', controlsShow: true, controlsBefore: '', controlsAfter: '', controlsFade: true, firstId: 'firstBtn', firstText: 'First', firstShow: false, lastId: 'lastBtn', lastText: 'Last', lastShow: false, vertical: false, speed: 600, auto: false, pause: 5000, continuous: false }; var options = $.extend(defaults, options); this.each(function() { var obj = $(this); var s = $("li", obj).length; var w = $("li", obj).width(); var h = $("li", obj).height(); obj.width(w); obj.height(h); obj.css("overflow","hidden"); var ts = s-1; var t = 0; $("ul", obj).css('width',s*w); if(!options.vertical) $("li", obj).css('float','left'); if(options.controlsShow){ }; $("a","#"+options.nextId).click(function(){ animate("next",true); }); $("a","#"+options.prevId).click(function(){ animate("prev",true); }); $("a","#"+options.firstId).click(function(){ animate("first",true); }); $("a","#"+options.lastId).click(function(){ animate("last",true); }); function animate(dir,clicked){ var ot = t; switch(dir){ case "next": t = (ot>=ts) ? (options.continuous ? 0 : ts) : t+1; break; case "prev": t = (t<=0) ? (options.continuous ? ts : 0) : t-1; break; case "first": t = 0; break; case "last": t = ts; break; default: break; }; var diff = Math.abs(ot-t); var speed = diff*options.speed; if(!options.vertical) { p = (t*w*-1); $("ul",obj).animate( { marginLeft: p }, speed ); } else { p = (t*h*-1); $("ul",obj).animate( { marginTop: p }, speed ); }; if(!options.continuous && options.controlsFade){ if(t==ts){ $("a","#"+options.nextId).hide(); $("a","#"+options.lastId).hide(); } else { $("a","#"+options.nextId).show(); $("a","#"+options.lastId).show(); }; if(t==0){ $("a","#"+options.prevId).hide(); $("a","#"+options.firstId).hide(); } else { $("a","#"+options.prevId).show(); $("a","#"+options.firstId).show(); }; }; if(clicked) clearTimeout(timeout); if(options.auto && dir=="next" && !clicked){; timeout = setTimeout(function(){ animate("next",false); },diff*options.speed+options.pause); }; }; // init var timeout; if(options.auto){; timeout = setTimeout(function(){ animate("next",false); },options.pause); }; if(!options.continuous && options.controlsFade){ $("a","#"+options.prevId).hide(); $("a","#"+options.firstId).hide(); }; }); }; })(jQuery);
zeusro/Blog_MVC4
Blog/Scripts/easySlider1.5.js
JavaScript
mit
3,810
'use strict'; var chai = require('chai'); var request = require('request'); chai.should(); require('dotenv').load(); describe('/', function() { describe('get', function() { it('should respond with 200 OK', function(done) { request({ url: 'http://localhost:10010/', json: true, qs: { accessToken: process.env.KEY }, method: 'GET', headers: { 'Content-Type': 'application/json' } }, function(error, res, body) { if (error) return done(error); res.statusCode.should.equal(200); body.should.equal(null); // non-json response or no schema done(); }); }); }); describe('head', function() { it('should respond with 200 OK', function(done) { request({ url: 'http://localhost:10010/', method: 'HEAD', headers: { 'Content-Type': 'application/json', accessToken: process.env.KEY_2 } }, function(error, res) { if (error) return done(error); res.statusCode.should.equal(200); done(); }); }); }); });
apigee-127/swagger-test-templates
test/minimal/compare/request/should/base-path-test.js
JavaScript
mit
1,153
// **License:** MIT /* global module, define */ ;(function (root, factory) { 'use strict' if (typeof module === 'object' && module.exports) { module.exports = factory(require('jsonrpc-lite'), require('engine.io-client')) } else if (typeof define === 'function' && define.amd) { define(['jsonrpc-lite', 'engine.io-client'], factory) } else root.Consumer = factory(root.jsonrpc, root.eio) }(typeof window === 'object' ? window : this, function (jsonrpc, Eio) { 'use strict' var DELAY = (Math.ceil(Math.random() * 50) + 10) * 1000 var TIMEOUT = 60 * 1000 function Consumer (url, options) { this.url = url this.options = options || {} this.reconnectionTime = DELAY this.lastId = null this.consumerId = null this.connection = null this.connected = false this.joinQueue = [] this.sendQueue = [] this.pending = {} } Consumer.prototype.onopen = noOp Consumer.prototype.onclose = noOp Consumer.prototype.onerror = function (error) { console.error(new Date(), error) } Consumer.prototype.onmessage = function (event) { console.log(new Date(), event.type, event.data) } Consumer.prototype.request = function (method, params, callback) { this.sendQueue.push(new RpcCommand(this.pending, method, params, callback)) flushRequest(this) return this } Consumer.prototype.join = function (room) { this.joinQueue.push(room) flushJoin(this) return this } Consumer.prototype._join = function (room, consumerId) { throw new Error('_join method not implemented') } Consumer.prototype._respond = function (event) { this.connection.send(JSON.stringify(jsonrpc.success(event.id, 'OK'))) } Consumer.prototype.getToken = function () { return this.options.token } Consumer.prototype.connect = function (url, options) { var ctx = this if (url) this.url = url if (options) this.options = options var token = this.getToken() if (token) this.options.query = 'token=' + token if (this.connection) { this.connection.off() this.connection.close() } this.connection = new Eio(this.url, this.options) this.connection .on('open', function () { ctx.reconnectionTime = DELAY ctx.consumerId = this.id ctx.connected = true ctx.onopen() flushJoin(ctx) flushRequest(ctx) }) .on('close', function (err) { if (err) ctx.onerror(err) ctx.close() setTimeout(function () { ctx.reconnectionTime *= 1.2 if (ctx.reconnectionTime > TIMEOUT) ctx.reconnectionTime = TIMEOUT ctx.connect() }, ctx.reconnectionTime) }) .on('error', function (err) { ctx.onerror(err) }) .on('message', function (message) { var event = new Event(jsonrpc.parse(message)) switch (event.type) { case 'invalid': return ctx.onerror(event.data) case 'notification': return ctx.onmessage(event) case 'success': case 'error': ctx.lastId = event.id if (ctx.pending[event.id]) { ctx.pending[event.id].done(event.data.error, event.data.result) } else { ctx.onmessage(event) } return case 'request': ctx._respond(event) if (event.id !== ctx.lastResponseId) { ctx.lastResponseId = event.id ctx.onmessage(event) } } }) return this } Consumer.prototype.close = function () { var ctx = this if (!this.connected && !this.connection) return this.consumerId = null this.connected = false if (this.connection) { this.connection.off() this.connection.once('close', function () { ctx.onclose() }) this.connection.close() this.connection = null } else this.onclose() } function Event (response) { this.type = response.type this.data = response.payload this.id = this.data.id } function RpcCommand (pending, method, params, callback) { var ctx = this this.id = genRpcId() this.params = JSON.stringify(jsonrpc.request(this.id, method, params)) this.callback = callback || noOp this.pending = pending this.pending[this.id] = this this.timer = setTimeout(function () { ctx.done(new Error('Send RPC time out, ' + ctx.id + ', ' + ctx.params)) }, TIMEOUT) } RpcCommand.prototype.clear = function () { if (!this.pending[this.id]) return false clearTimeout(this.timer) delete this.pending[this.id] return true } RpcCommand.prototype.done = function (err, res) { if (!this.clear()) return this this.callback(err, res) return this } function flushRequest (ctx) { if (!ctx.connected) return while (ctx.sendQueue.length) ctx.connection.send(ctx.sendQueue.shift().params) } function flushJoin (ctx) { if (!ctx.connected) return while (ctx.joinQueue.length) ctx._join(ctx.joinQueue.shift(), ctx.consumerId) } var count = 0 var ISN = (Date.now() - new Date().setMinutes(0, 0, 0)).toString(36) function genRpcId () { return ISN + ':' + (++count) } function noOp () {} return Consumer }))
teambition/snapper-consumer
index.js
JavaScript
mit
5,316
// flow-typed signature: 745a6c58001e7ff586b8ad9cd40ab44c // flow-typed version: <<STUB>>/eslint-config-prettier_v^6.7.0/flow_v0.113.0 /** * This is an autogenerated libdef stub for: * * 'eslint-config-prettier' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'eslint-config-prettier' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'eslint-config-prettier/@typescript-eslint' { declare module.exports: any; } declare module 'eslint-config-prettier/babel' { declare module.exports: any; } declare module 'eslint-config-prettier/bin/cli' { declare module.exports: any; } declare module 'eslint-config-prettier/bin/validators' { declare module.exports: any; } declare module 'eslint-config-prettier/flowtype' { declare module.exports: any; } declare module 'eslint-config-prettier/react' { declare module.exports: any; } declare module 'eslint-config-prettier/standard' { declare module.exports: any; } declare module 'eslint-config-prettier/unicorn' { declare module.exports: any; } declare module 'eslint-config-prettier/vue' { declare module.exports: any; } // Filename aliases declare module 'eslint-config-prettier/@typescript-eslint.js' { declare module.exports: $Exports<'eslint-config-prettier/@typescript-eslint'>; } declare module 'eslint-config-prettier/babel.js' { declare module.exports: $Exports<'eslint-config-prettier/babel'>; } declare module 'eslint-config-prettier/bin/cli.js' { declare module.exports: $Exports<'eslint-config-prettier/bin/cli'>; } declare module 'eslint-config-prettier/bin/validators.js' { declare module.exports: $Exports<'eslint-config-prettier/bin/validators'>; } declare module 'eslint-config-prettier/flowtype.js' { declare module.exports: $Exports<'eslint-config-prettier/flowtype'>; } declare module 'eslint-config-prettier/index' { declare module.exports: $Exports<'eslint-config-prettier'>; } declare module 'eslint-config-prettier/index.js' { declare module.exports: $Exports<'eslint-config-prettier'>; } declare module 'eslint-config-prettier/react.js' { declare module.exports: $Exports<'eslint-config-prettier/react'>; } declare module 'eslint-config-prettier/standard.js' { declare module.exports: $Exports<'eslint-config-prettier/standard'>; } declare module 'eslint-config-prettier/unicorn.js' { declare module.exports: $Exports<'eslint-config-prettier/unicorn'>; } declare module 'eslint-config-prettier/vue.js' { declare module.exports: $Exports<'eslint-config-prettier/vue'>; }
pCloud/pcloud-sdk-js
flow-typed/npm/eslint-config-prettier_vx.x.x.js
JavaScript
mit
2,847
// Generated on 2014-02-18 using generator-socketio 0.0.2 'use strict'; var moment = require('moment'); var LIVERELOAD_PORT = 35729; var RUNNING_PORT = 3000; // <- if you change this, you need to change in public/js/app.js and recompile var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT}); var mountFolder = function (connect, dir) { return connect.static(require('path').resolve(dir)); }; module.exports = function (grunt) { // load all grunt tasks require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ less: { options: { //report:'gzip' }, production: { options: { cleancss: true }, files: { "public/css/core.css": "public/bower_components/bootstrap/less/bootstrap.less" } } }, sass: { dist: { options: { style: 'compressed' }, files: { 'public/css/core.css': 'public/bower_components/sass-bootstrap/lib/bootstrap.scss', } } }, stylus: { compile: { options: { compress:true }, files: { 'public/css/core.css': 'public/bower_components/bootstrap-stylus/stylus/bootstrap.styl' } } }, concat: { options: { separator: ';', stripBanners:true }, dist: { src: ['public/js/app.js'], dest: 'public/js/concat.js', }, }, //this is currently turned off, since jquery KILLS it jshint: { options: { curly: true, eqeqeq: false, eqnull: true, browser: true, globals: { jQuery: true } }, files:{ src:['public/js/concat.js'] } }, uglify: { options: { mangle: false }, my_target: { files: { 'public/js/app.min.js': ['public/js/concat.js'] } } }, // Watch Config watch: { files: ['views/**/*'], options: { livereload: true }, scripts: { files: [ 'public/js/**/*.js' ], tasks:['build'] }, css: { files: [ 'public/css/**/*.css', ], }, less: { files: ['public/bower_components/bootstrap/less/**/*.less'], tasks: ['build'] }, express: { files: [ 'server.js', '!**/node_modules/**', '!Gruntfile.js' ], tasks: [ 'build' ], options: { nospawn: true // Without this option specified express won't be reloaded } }, }, connect: { options: { port: RUNNING_PORT,//variable at top of this file // change this to '0.0.0.0' to access the server from outside hostname: 'localhost' }, livereload: { options: { middleware: function (connect) { return [ lrSnippet, mountFolder(connect, '.') ]; } } } }, nodemon:{ dev: { options: { file: 'server.js', //args: ['dev'], //nodeArgs: ['--debug'], ignoredFiles: ['node_modules/**'], //watchedExtensions: ['js'], watchedFolders: ['views', 'routes'], //delayTime: 1, legacyWatch: true, env: { PORT: RUNNING_PORT }, cwd: __dirname } } }, // run 'watch' and 'nodemon' indefinitely, together // 'launch' will just kick it off, and won't stay running concurrent: { target: { tasks: ['nodemon', 'watch', 'launch'], options: { logConcurrentOutput: true } } }, wait:{ options: { delay: 1000 }, pause:{ options:{ before:function(options){ console.log('pausing %dms before launching page', options.delay); }, after : function() { console.log('pause end, heading to page (using default browser)'); } } } }, open: { server: { path: 'http://localhost:' + RUNNING_PORT } } }); //grunt.registerTask('server', ['build', 'connect:livereload', 'open', 'watch']); grunt.registerTask('build', ['less', 'concat', 'uglify']); grunt.registerTask('launch', ['wait', 'open']); grunt.registerTask('default', ['build', 'concurrent']); };
athieriot/crime-challenge
Gruntfile.js
JavaScript
mit
4,620
var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var User = require('../models/User'); passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { new User({ id: id}).fetch().then(function(user) { done(null, user); }); }); // Sign in with Email and Password passport.use(new LocalStrategy({ usernameField: 'email' }, function(email, password, done) { new User({ email: email }) .fetch() .then(function(user) { if (!user) { return done(null, false, { msg: 'The email address ' + email + ' is not associated with any account. ' + 'Double-check your email address and try again.' }); } user.comparePassword(password, function(err, isMatch) { if (!isMatch) { return done(null, false, { msg: 'Invalid email or password' }); } return done(null, user); }); }); }));
mikeghen/ibm-watson-nlu-demo
config/passport.js
JavaScript
mit
961
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M9.64 7.64c.23-.5.36-1.05.36-1.64 0-2.21-1.79-4-4-4S2 3.79 2 6s1.79 4 4 4c.59 0 1.14-.13 1.64-.36L10 12l-2.36 2.36C7.14 14.13 6.59 14 6 14c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4c0-.59-.13-1.14-.36-1.64L12 14l7 7h3v-1L9.64 7.64zM6 8c-1.1 0-2-.89-2-2s.9-2 2-2 2 .89 2 2-.9 2-2 2zm0 12c-1.1 0-2-.89-2-2s.9-2 2-2 2 .89 2 2-.9 2-2 2zm6-7.5c-.28 0-.5-.22-.5-.5s.22-.5.5-.5.5.22.5.5-.22.5-.5.5zM19 3l-6 6 2 2 7-7V3h-3z" /> , 'ContentCutOutlined');
callemall/material-ui
packages/material-ui-icons/src/ContentCutOutlined.js
JavaScript
mit
568
const path = require('path') const fs = require('fs') const merge = require('webpack-merge') const chokidar = require('chokidar') const debounce = require('lodash.debounce') const { underline, green } = require('chalk') const appPaths = require('./app-paths') const { log, warn, fatal } = require('./helpers/logger') const extensionRunner = require('./app-extension/extensions-runner') const { needsAdditionalPolyfills } = require('./helpers/browsers-support') const appFilesValidations = require('./helpers/app-files-validations') const cssVariables = require('./helpers/css-variables') const getDevlandFile = require('./helpers/get-devland-file') const getPackageMajorVersion = require('./helpers/get-package-major-version') const transformAssetUrls = getDevlandFile('quasar/dist/transform-asset-urls.json') const urlRegex = /^http(s)?:\/\// function encode (obj) { return JSON.stringify(obj, (_, value) => { return typeof value === 'function' ? `/fn(${value.toString()})` : value }) } function formatPublicPath (path) { if (!path) { return '' } if (!path.endsWith('/')) { path = `${path}/` } if (urlRegex.test(path) === true) { return path } if (!path.startsWith('/')) { path = `/${path}` } return path } function formatRouterBase (publicPath) { if (!publicPath || !publicPath.startsWith('http')) { return publicPath } const match = publicPath.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/) return formatPublicPath(match[5] || '') } function parseAssetProperty (prefix) { return asset => { if (typeof asset === 'string') { return { path: asset[0] === '~' ? asset.substring(1) : prefix + `/${asset}` } } return { ...asset, path: typeof asset.path === 'string' ? (asset.path[0] === '~' ? asset.path.substring(1) : prefix + `/${asset.path}`) : asset.path } } } function getUniqueArray (original) { return Array.from(new Set(original)) } function uniquePathFilter (value, index, self) { return self.map(obj => obj.path).indexOf(value.path) === index } function uniqueRegexFilter (value, index, self) { return self.map(regex => regex.toString()).indexOf(value.toString()) === index } /* * this.quasarConf - Compiled Object from quasar.conf.js * this.webpackConf - Webpack config(s) */ class QuasarConfFile { constructor (ctx, opts = {}) { this.ctx = ctx this.opts = opts this.filename = appPaths.resolve.app('quasar.conf.js') this.pkg = require(appPaths.resolve.app('package.json')) this.watch = opts.onBuildChange || opts.onAppChange if (this.watch) { // Start watching for quasar.config.js changes chokidar .watch(this.filename, { watchers: { chokidar: { ignoreInitial: true } } }) .on('change', debounce(async () => { console.log() log(`quasar.conf.js changed`) try { await this.prepare() } catch (e) { if (e.message !== 'NETWORK_ERROR') { console.error(e) warn(`quasar.conf.js has JS errors. Please fix them then save file again.\n`) } return } await this.compile() if (this.webpackConfChanged === true) { opts.onBuildChange() } else { opts.onAppChange() } }, 1000)) if (this.ctx.mode.ssr) { const SsrExtension = require('./ssr/ssr-extension') if (!SsrExtension.isValid()) { process.exit(1) } chokidar .watch(appPaths.ssrDir, { watchers: { chokidar: { ignoreInitial: true } } }) .on('change', debounce(async () => { console.log() log(`src-ssr/* changed`) SsrExtension.deleteCache() if (SsrExtension.isValid()) { // trigger build update opts.onBuildChange() } else { warn(`[FAIL] Please fix the error then save the file so we can continue.`) } }, 1000)) } } } async prepare () { log(`Reading quasar.conf.js`) let quasarConfigFunction if (fs.existsSync(this.filename)) { delete require.cache[this.filename] quasarConfigFunction = require(this.filename) } else { fatal(`[FAIL] Could not load quasar.conf.js config file`) } const initialConf = await quasarConfigFunction(this.ctx) const cfg = merge({ ctx: this.ctx, css: [], boot: [], vendor: { add: [], remove: [] }, build: { transpileDependencies: [], transformAssetUrls: {}, stylusLoaderOptions: {}, sassLoaderOptions: {}, scssLoaderOptions: {}, lessLoaderOptions: {}, env: {}, uglifyOptions: { compress: {}, mangle: {} } }, devServer: {}, animations: [], extras: [], sourceFiles: {}, ssr: { componentCache: {} }, pwa: { workboxOptions: {}, manifest: { icons: [] }, metaVariables: {} }, electron: { unPackagedInstallParams: [], packager: {}, builder: {} }, cordova: {}, capacitor: { capacitorCliPreparationParams: [] }, bin: {}, bex: { builder: { directories: {} } }, htmlVariables: {} }, initialConf) if (cfg.framework === void 0) { cfg.framework = { importStrategy: 'auto' } } else if (cfg.framework === 'all') { cfg.framework = { importStrategy: 'all' } } if (cfg.animations === 'all') { cfg.animations = require('./helpers/animations') } if (!cfg.framework.plugins) { cfg.framework.plugins = [] } if (!cfg.framework.config) { cfg.framework.config = {} } if (!cfg.framework.components) { cfg.framework.components = [] } if (!cfg.framework.directives) { cfg.framework.directives = [] } if (this.ctx.dev) { if (this.opts.host) { cfg.devServer.host = this.opts.host } else if (!cfg.devServer.host) { cfg.devServer.host = '0.0.0.0' } if (this.opts.port) { cfg.devServer.port = this.opts.port } else if (!cfg.devServer.port) { cfg.devServer.port = 8080 } if ( this.address && this.address.from.host === cfg.devServer.host && this.address.from.port === cfg.devServer.port ) { cfg.devServer.host = this.address.to.host cfg.devServer.port = this.address.to.port } else { const addr = { host: cfg.devServer.host, port: cfg.devServer.port } const to = this.opts.onAddress !== void 0 ? await this.opts.onAddress(addr) : addr // if network error while running if (to === null) { throw new Error('NETWORK_ERROR') } cfg.devServer = merge(cfg.devServer, to) this.address = { from: addr, to: { host: cfg.devServer.host, port: cfg.devServer.port } } } } this.sourceCfg = cfg } async compile () { let cfg = this.sourceCfg await extensionRunner.runHook('extendQuasarConf', async hook => { log(`Extension(${hook.api.extId}): Extending quasar.conf...`) await hook.fn(cfg, hook.api) }) // if watching for changes, // then determine the type (webpack related or not) if (this.watch) { const newConfigSnapshot = [ cfg.build ? encode(cfg.build) : '', cfg.ssr ? cfg.ssr.pwa : '', cfg.framework ? cfg.framework.importStrategy + cfg.framework.autoImportComponentCase : '', cfg.devServer ? encode(cfg.devServer) : '', cfg.pwa ? encode(cfg.pwa) : '', cfg.electron ? encode(cfg.electron) : '', cfg.bex ? encode(cfg.bex) : '', cfg.htmlVariables ? encode(cfg.htmlVariables) : '' ].join('') if (this.oldConfigSnapshot) { this.webpackConfChanged = newConfigSnapshot !== this.oldConfigSnapshot } this.oldConfigSnapshot = newConfigSnapshot } // make sure these exist cfg.__rootDefines = {} cfg.__needsAppMountHook = false cfg.__vueDevtools = false cfg.supportTS = cfg.supportTS || false if (cfg.vendor.disable !== true) { cfg.vendor.add = cfg.vendor.add.length > 0 ? new RegExp(cfg.vendor.add.filter(v => v).join('|')) : void 0 cfg.vendor.remove = cfg.vendor.remove.length > 0 ? new RegExp(cfg.vendor.remove.filter(v => v).join('|')) : void 0 } if (cfg.css.length > 0) { cfg.css = cfg.css.filter(_ => _) .map(parseAssetProperty('src/css')) .filter(asset => asset.path) .filter(uniquePathFilter) } if (cfg.boot.length > 0) { cfg.boot = cfg.boot.filter(_ => _) .map(parseAssetProperty('boot')) .filter(asset => asset.path) .filter(uniquePathFilter) } if (cfg.extras.length > 0) { cfg.extras = getUniqueArray(cfg.extras) } if (cfg.animations.length > 0) { cfg.animations = getUniqueArray(cfg.animations) } if (['all', 'auto'].includes(cfg.framework.importStrategy) === false) { cfg.framework.importStrategy = 'auto' } if (cfg.framework.importStrategy === 'auto') { if (!['kebab', 'pascal', 'combined'].includes(cfg.framework.autoImportComponentCase)) { cfg.framework.autoImportComponentCase = 'kebab' } } // special case where a component can be designated for a framework > config prop if (cfg.framework.importStrategy === 'auto' && cfg.framework.config && cfg.framework.config.loading) { const component = cfg.framework.config.loading.spinner // Is a component and is a QComponent if (component !== void 0 && /^(Q[A-Z]|q-)/.test(component) === true) { cfg.framework.components.push(component) } } cfg.framework.components = getUniqueArray(cfg.framework.components) cfg.framework.directives = getUniqueArray(cfg.framework.directives) cfg.framework.plugins = getUniqueArray(cfg.framework.plugins) cfg.build = merge({ transformAssetUrls: Object.assign({ video: ['src', 'poster'], source: 'src', img: 'src', image: ['xlink:href', 'href'], use: ['xlink:href', 'href'] }, transformAssetUrls), showProgress: true, scopeHoisting: true, productName: this.pkg.productName, productDescription: this.pkg.description, extractCSS: this.ctx.prod, sourceMap: this.ctx.dev, minify: this.ctx.prod && this.ctx.mode.bex !== true, distDir: path.join('dist', this.ctx.modeName), htmlFilename: 'index.html', ssrPwaHtmlFilename: 'offline.html', // do NOT use index.html as name! // will mess up SSR vueRouterMode: 'hash', forceDevPublicPath: false, transpile: true, // transpileDependencies: [], // leaving here for completeness devtool: this.ctx.dev ? '#cheap-module-eval-source-map' : '#source-map', // env: {}, // leaving here for completeness uglifyOptions: { compress: { // turn off flags with small gains to speed up minification arrows: false, collapse_vars: false, // 0.3kb comparisons: false, computed_props: false, hoist_funs: false, hoist_props: false, hoist_vars: false, inline: false, loops: false, negate_iife: false, properties: false, reduce_funcs: false, reduce_vars: false, switches: false, toplevel: false, typeofs: false, // a few flags with noticable gains/speed ratio // numbers based on out of the box vendor bundle booleans: true, // 0.7kb if_return: true, // 0.4kb sequences: true, // 0.7kb unused: true, // 2.3kb // required features to drop conditional branches conditionals: true, dead_code: true, evaluate: true }, mangle: { safari10: true } } }, cfg.build) if (cfg.build.transpile === true) { cfg.build.transpileDependencies = cfg.build.transpileDependencies.filter(uniqueRegexFilter) cfg.__supportsIE = cfg.build.transpile === true && needsAdditionalPolyfills(this.ctx) const type = cfg.__supportsIE === true ? ' - includes IE11 support' : '' cfg.__transpileBanner = green(`yes (Babel)${type}`) log(`Transpiling JS (Babel active)${type}`) } else { cfg.__supportsIE = false cfg.__transpileBanner = 'no' log(underline('Not transpiling JS')) } cfg.__loadingBar = cfg.framework.importStrategy === 'all' || cfg.framework.plugins.includes('LoadingBar') cfg.__meta = cfg.framework.importStrategy === 'all' || cfg.framework.plugins.includes('Meta') if (this.ctx.dev || this.ctx.debug) { Object.assign(cfg.build, { minify: false, gzip: false }) } if (this.ctx.dev) { cfg.build.extractCSS = false } if (this.ctx.debug) { cfg.build.sourceMap = true } if (this.ctx.mode.ssr) { Object.assign(cfg.build, { vueRouterMode: 'history', gzip: false }) } else if (this.ctx.mode.cordova || this.ctx.mode.capacitor || this.ctx.mode.electron || this.ctx.mode.bex) { Object.assign(cfg.build, { htmlFilename: 'index.html', vueRouterMode: 'hash', gzip: false }) } if (!path.isAbsolute(cfg.build.distDir)) { cfg.build.distDir = appPaths.resolve.app(cfg.build.distDir) } if (this.ctx.mode.cordova || this.ctx.mode.capacitor) { cfg.build.packagedDistDir = path.join(cfg.build.distDir, this.ctx.targetName) } if (this.ctx.mode.cordova || this.ctx.mode.capacitor) { cfg.build.distDir = appPaths.resolve[this.ctx.modeName]('www') } else if (this.ctx.mode.electron || this.ctx.mode.bex) { cfg.build.packagedDistDir = cfg.build.distDir cfg.build.distDir = path.join(cfg.build.distDir, 'UnPackaged') } cfg.build.publicPath = cfg.build.publicPath && ['spa', 'pwa', 'ssr'].includes(this.ctx.modeName) ? formatPublicPath(cfg.build.publicPath) : (cfg.build.vueRouterMode === 'hash' ? '' : '/') /* careful if you configure the following; make sure that you really know what you are doing */ cfg.build.vueRouterBase = cfg.build.vueRouterBase !== void 0 ? cfg.build.vueRouterBase : formatRouterBase(cfg.build.publicPath) /* careful if you configure the following; make sure that you really know what you are doing */ cfg.build.appBase = cfg.build.appBase !== void 0 ? cfg.build.appBase : cfg.build.publicPath cfg.sourceFiles = merge({ rootComponent: 'src/App.vue', router: 'src/router/index', store: 'src/store/index', indexHtmlTemplate: 'src/index.template.html', registerServiceWorker: 'src-pwa/register-service-worker.js', serviceWorker: 'src-pwa/custom-service-worker.js', electronMainDev: 'src-electron/main-process/electron-main.dev.js', electronMainProd: 'src-electron/main-process/electron-main.js', ssrServerIndex: 'src-ssr/index.js' }, cfg.sourceFiles) appFilesValidations(cfg) // do we got vuex? const storePath = appPaths.resolve.app(cfg.sourceFiles.store) cfg.store = ( fs.existsSync(storePath) || fs.existsSync(storePath + '.js') || fs.existsSync(storePath + '.ts') ) // make sure we have preFetch in config cfg.preFetch = cfg.preFetch || false if (this.ctx.mode.capacitor & cfg.capacitor.capacitorCliPreparationParams.length === 0) { cfg.capacitor.capacitorCliPreparationParams = [ 'sync', this.ctx.targetName ] } if (this.ctx.mode.ssr) { cfg.ssr = merge({ pwa: false, manualHydration: false, componentCache: { max: 1000, maxAge: 1000 * 60 * 15 } }, cfg.ssr) cfg.ssr.debug = this.ctx.debug cfg.ssr.__templateOpts = JSON.stringify({ ...cfg.ssr, publicPath: cfg.build.publicPath }, null, 2) cfg.ssr.__templateFlags = { meta: cfg.__meta } const file = appPaths.resolve.app(cfg.sourceFiles.ssrServerIndex) cfg.ssr.__dir = path.dirname(file) cfg.ssr.__index = path.basename(file) if (cfg.ssr.pwa) { await require('./mode/install-missing')('pwa') } this.ctx.mode.pwa = cfg.ctx.mode.pwa = cfg.ssr.pwa !== false } if (this.ctx.dev) { const originalBefore = cfg.devServer.before const openInEditor = require('launch-editor-middleware') delete cfg.devServer.before cfg.devServer = merge({ publicPath: cfg.build.publicPath, hot: true, inline: true, overlay: true, quiet: true, noInfo: true, disableHostCheck: true, compress: true, open: true }, this.ctx.mode.ssr === true ? {} : { historyApiFallback: cfg.build.vueRouterMode === 'history' ? { index: `${cfg.build.publicPath || '/'}${cfg.build.htmlFilename}` } : false, index: cfg.build.htmlFilename }, cfg.devServer, { contentBase: false, watchContentBase: false, before: (app, server, compiler) => { if (!this.ctx.mode.ssr) { const express = require('express') if (cfg.build.ignorePublicFolder !== true) { app.use((cfg.build.publicPath || '/'), express.static(appPaths.resolve.app('public'), { maxAge: 0 })) } if (this.ctx.mode.cordova) { const folder = appPaths.resolve.cordova(`platforms/${this.ctx.targetName}/platform_www`) app.use('/', express.static(folder, { maxAge: 0 })) } } app.use('/__open-in-editor', openInEditor(void 0, appPaths.appDir)) originalBefore && originalBefore(app, server, compiler) } }) if (this.ctx.vueDevtools === true || cfg.devServer.vueDevtools === true) { cfg.__needsAppMountHook = true cfg.__vueDevtools = { host: cfg.devServer.host === '0.0.0.0' ? 'localhost' : cfg.devServer.host, port: 8098 } } // make sure the prop is not supplied to webpack dev server if (cfg.devServer.hasOwnProperty('vueDevtools')) { delete cfg.devServer.vueDevtools } if (this.ctx.mode.cordova || this.ctx.mode.capacitor || this.ctx.mode.electron) { cfg.devServer.open = false if (this.ctx.mode.electron) { cfg.devServer.https = false } } if (cfg.devServer.open) { const isMinimalTerminal = require('./helpers/is-minimal-terminal') if (isMinimalTerminal) { cfg.devServer.open = false } } if (cfg.devServer.open) { cfg.__devServer = { open: !!cfg.devServer.open, openOptions: cfg.devServer.open !== true ? cfg.devServer.open : false } cfg.devServer.open = false } else { cfg.__devServer = {} } } if (cfg.build.gzip) { let gzip = cfg.build.gzip === true ? {} : cfg.build.gzip let ext = ['js', 'css'] if (gzip.extensions) { ext = gzip.extensions delete gzip.extensions } cfg.build.gzip = merge({ filename: '[path].gz[query]', algorithm: 'gzip', test: new RegExp('\\.(' + ext.join('|') + ')$'), threshold: 10240, minRatio: 0.8 }, gzip) } if (this.ctx.mode.pwa) { cfg.pwa = merge({ workboxPluginMode: 'GenerateSW', workboxOptions: {}, useCredentials: false, manifest: { name: this.pkg.productName || this.pkg.name || 'Quasar App', short_name: this.pkg.name || 'quasar-pwa', description: this.pkg.description, display: 'standalone', start_url: '.' }, metaVariables: { appleMobileWebAppCapable: 'yes', appleMobileWebAppStatusBarStyle: 'default', appleTouchIcon120: 'icons/apple-icon-120x120.png', appleTouchIcon152: 'icons/apple-icon-152x152.png', appleTouchIcon167: 'icons/apple-icon-167x167.png', appleTouchIcon180: 'icons/apple-icon-180x180.png', appleSafariPinnedTab: 'icons/safari-pinned-tab.svg', msapplicationTileImage: 'icons/ms-icon-144x144.png', msapplicationTileColor: '#000000' } }, cfg.pwa) if (cfg.pwa.manifest.icons.length === 0) { warn() warn(`PWA manifest in quasar.conf.js > pwa > manifest is missing "icons" prop.\n`) process.exit(1) } if (!['GenerateSW', 'InjectManifest'].includes(cfg.pwa.workboxPluginMode)) { warn() warn(`Workbox webpack plugin mode "${cfg.pwa.workboxPluginMode}" is invalid.`) warn(`Valid Workbox modes are: GenerateSW, InjectManifest\n`) process.exit(1) } cfg.pwa.manifest.icons = cfg.pwa.manifest.icons.map(icon => { if (urlRegex.test(icon.src) === false) { icon.src = `${cfg.build.publicPath}${icon.src}` } return icon }) } if (this.ctx.dev) { const host = cfg.devServer.host === '0.0.0.0' ? 'localhost' : cfg.devServer.host const urlPath = cfg.build.vueRouterMode === 'hash' ? (cfg.build.htmlFilename !== 'index.html' ? (cfg.build.publicPath ? '' : '/') + cfg.build.htmlFilename : '') : '' cfg.build.APP_URL = `http${cfg.devServer.https ? 's' : ''}://${host}:${cfg.devServer.port}${cfg.build.publicPath}${urlPath}` } else if (this.ctx.mode.cordova || this.ctx.mode.capacitor || this.ctx.mode.bex) { cfg.build.APP_URL = 'index.html' } else if (this.ctx.mode.electron) { cfg.__rootDefines[`process.env.APP_URL`] = `"file://" + __dirname + "/index.html"` } Object.assign(cfg.build.env, { NODE_ENV: this.ctx.prod ? 'production' : 'development', CLIENT: true, SERVER: false, DEV: this.ctx.dev, PROD: this.ctx.prod, DEBUGGING: this.ctx.debug || this.ctx.dev, MODE: this.ctx.modeName, VUE_ROUTER_MODE: cfg.build.vueRouterMode, VUE_ROUTER_BASE: cfg.build.vueRouterBase, APP_URL: cfg.build.APP_URL }) if (this.ctx.mode.pwa) { cfg.build.env.SERVICE_WORKER_FILE = `${cfg.build.publicPath}service-worker.js` } if (this.ctx.mode.electron) { if (this.ctx.dev) { cfg.electron = merge({ nodeIntegration: true }, cfg.electron) if (cfg.build.ignorePublicFolder !== true) { cfg.__rootDefines.__statics = `"${appPaths.resolve.app('public').replace(/\\/g, '\\\\')}"` } } else { const bundler = require('./electron/bundler') cfg.electron = merge({ nodeIntegration: true, packager: { asar: true, icon: appPaths.resolve.electron('icons/icon'), overwrite: true }, builder: { appId: 'quasar-app', productName: this.pkg.productName || this.pkg.name || 'Quasar App', directories: { buildResources: appPaths.resolve.electron('') } } }, cfg.electron, { packager: { dir: cfg.build.distDir, out: cfg.build.packagedDistDir }, builder: { directories: { app: cfg.build.distDir, output: path.join(cfg.build.packagedDistDir, 'Packaged') } } }) if (cfg.ctx.bundlerName) { cfg.electron.bundler = cfg.ctx.bundlerName } else if (!cfg.electron.bundler) { cfg.electron.bundler = bundler.getDefaultName() } if (this.opts.argv !== void 0) { const { ensureElectronArgv } = require('./helpers/ensure-argv') ensureElectronArgv(cfg.electron.bundler, this.opts.argv) } if (cfg.electron.bundler === 'packager') { if (cfg.ctx.targetName) { cfg.electron.packager.platform = cfg.ctx.targetName } if (cfg.ctx.archName) { cfg.electron.packager.arch = cfg.ctx.archName } } else { cfg.electron.builder = { config: cfg.electron.builder } if (cfg.ctx.targetName === 'mac' || cfg.ctx.targetName === 'darwin' || cfg.ctx.targetName === 'all') { cfg.electron.builder.mac = [] } if (cfg.ctx.targetName === 'linux' || cfg.ctx.targetName === 'all') { cfg.electron.builder.linux = [] } if (cfg.ctx.targetName === 'win' || cfg.ctx.targetName === 'win32' || cfg.ctx.targetName === 'all') { cfg.electron.builder.win = [] } if (cfg.ctx.archName) { cfg.electron.builder[cfg.ctx.archName] = true } if (cfg.ctx.publish) { cfg.electron.builder.publish = cfg.ctx.publish } bundler.ensureBuilderCompatibility() } bundler.ensureInstall(cfg.electron.bundler) } } else if (this.ctx.mode.bex) { cfg.bex = merge(cfg.bex, { builder: { directories: { input: cfg.build.distDir, output: path.join(cfg.build.packagedDistDir, 'Packaged') } } }) } cfg.htmlVariables = merge({ ctx: cfg.ctx, process: { env: cfg.build.env }, productName: cfg.build.productName, productDescription: cfg.build.productDescription }, cfg.htmlVariables) cfg.__html = { minifyOptions: cfg.build.minify ? { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true, collapseBooleanAttributes: true, removeScriptTypeAttributes: true // more options: // https://github.com/kangax/html-minifier#options-quick-reference } : false } // used by .quasar entry templates cfg.__versions = {} cfg.__css = { quasarSrcExt: cssVariables.quasarSrcExt } if (this.ctx.mode.capacitor) { const { capVersion } = require('./capacitor/cap-cli') cfg.__versions.capacitor = capVersion const getCapPluginVersion = capVersion <= 2 ? () => true : name => { const version = getPackageMajorVersion(name, appPaths.capacitorDir) return version === void 0 ? false : version || true } Object.assign(cfg.__versions, { capacitor: capVersion, capacitorPluginApp: getCapPluginVersion('@capacitor/app'), capacitorPluginSplashscreen: getCapPluginVersion('@capacitor/splash-screen') }) } else if (this.ctx.mode.pwa) { cfg.__versions.workboxWebpackPlugin = getPackageMajorVersion('workbox-webpack-plugin') } if (this.ctx.mode.capacitor && cfg.__versions.capacitorPluginSplashscreen && cfg.capacitor.hideSplashscreen !== false) { cfg.__needsAppMountHook = true } this.quasarConf = cfg if (this.webpackConfChanged !== false) { this.webpackConf = await require('./webpack')(cfg) } } } module.exports = QuasarConfFile
pdanpdan/quasar
app/lib/quasar-conf-file.js
JavaScript
mit
27,984
'use strict'; var React = require('react/addons'); var PureRenderMixin = React.addons.PureRenderMixin; var DownloadOverlayOption = React.createFactory(require('./DownloadOverlayOption')); var gruntify = require('./util').gruntify; var DOM = React.DOM, div = DOM.div, form = DOM.form, button = DOM.button, input = DOM.input, ul = DOM.ul, li = DOM.li; var DownloadOverlay = React.createClass({ mixins: [PureRenderMixin], getInitialState: function() { return {}; }, toggleTextarea: function(elem) { this.setState({expanded: elem}); }, render: function() { var props = this.props; var state = this.state; var config = props.config; var hasFlash = Modernizr.flash && !Modernizr.flash.blocked; var codepen = this.buildCodePen(); return div({className: 'downloadOverlay', onClick: this.toggleOverlay}, div({ref: 'container', className: 'downloadOverlay-container'}, ul({className: 'downloadOverlay-options'}, DownloadOverlayOption({ title: 'Build', expanded: state.expanded, content: props.buildContent, toggleTextarea: this.toggleTextarea, hasFlash: hasFlash, type: 'text/javascript', filename: 'modernizr-custom.js', updateAction: props.updateAction, key: 'build' }), DownloadOverlayOption({ title: 'Command Line Config', expanded: state.expanded, content: JSON.stringify(config, 0, 2), toggleTextarea: this.toggleTextarea, hasFlash: hasFlash, type: 'application/json', filename: 'modernizr-config.json', path: '/download/config', updateAction: props.updateAction, key: 'config' }), DownloadOverlayOption({ title: 'Grunt Config', expanded: state.expanded, content: gruntify(config, props.allDetects), toggleTextarea: this.toggleTextarea, hasFlash: hasFlash, type: 'application/json', filename: 'grunt-config.json', path: '/download/gruntconfig', updateAction: props.updateAction, key: 'grunt' }), li({ key: 'codepen' }, form({ action: 'https://codepen.io/pen/define', method: 'POST' }, input({ type: 'hidden', name: 'data', value: codepen }), button({className: 'fakelink'}, 'Open build on codepen.io') ) ) ) ) ); }, toggleOverlay: function(e) { var container = this.refs.container.getDOMNode(); if (!container.contains(e.target)) { this.props.toggle(false); } }, buildCodePen: function() { var data = { title: 'modernizr.custom.js', description: 'This is generated via modernizr.com/download', html: '<h1>Modernizr build auto generated</h1><p><a href="' + location.href + '">Build hash</a></p>', css: 'ul{-webkit-column-count: 3;-moz-column-count: 3;column-count: 3;}li{color:green}', js: this.props.buildContent }; // multiclasses features are joined with a _, so we do this splitting and joining // to flatten the array into a list of individual classes var features = location.search.slice(1).split('&')[0].split('_').join('-').split('-'); var _ul = document.createElement('ul'); _.forEach(features, function(feature) { data.css += '.no-' + feature + ' li.'+ feature + '{ color: red; }'; var _li = document.createElement('li'); _li.className = _li.innerHTML = feature; _ul.appendChild(_li); }); data.html = _ul.outerHTML; return JSON.stringify(data); } }); module.exports = DownloadOverlay;
Modernizr/modernizr-neue
frontend/js/download/DownloadOverlay.js
JavaScript
mit
3,906
const EventEmitter = require('events'); const FSM = require('../../gamelib/components/FSM.js'); const fsm = { stop: {}, move: { onUpdate(dt) { this.owner.move(dt); } }, capture: { }, destroy: { } }; class BoxItem extends EventEmitter { static create(parent, data) { var obj = new this(parent, data); return obj; } constructor(parent, data) { super() this._parent = parent; this.x = data.x || 0; this.y = data.y || 0; this.speed = data.speed || 100; this.angle = data.angle || 0; var rad = this.angle * Math.PI / 180; this.speedX = this.speed * Math.cos(rad); this.speedY = this.speed * Math.sin(rad); for (var i in data) { if (!(i in this)) { this[i] = data[i]; } } this.fsm = new FSM(this, fsm); } get parent() { return this._parent; } get state() { return this.fsm.state; } set state(v) { this.fsm.state = v; } get parent() { return this._parent; } move(dt) { this.x += this.speedX * dt; this.y += this.speedY * dt; this.emit('move', this.x, this.y); } destroy() { this.state = 'destroy'; this.off(); this.parent.destroyItem(this); } update(dt) { this.fsm.onUpdate(dt); } } module.exports = BoxItem;
goodzsq/cocos_template
src/samples/games/BoxItem.js
JavaScript
mit
1,269
var gulp = require('gulp'); var install = require("gulp-install"); // Install npm packages module.exports = function installNpmPackages() { return gulp .src('./package.json') .pipe(install({noOptional: true})); };
croquet-australia/croquet-australia-logging
build/tasks/installNpmPackages.js
JavaScript
mit
236
/* ======================================================================== * DOM-based Routing * Based on http://goo.gl/EUTi53 by Paul Irish * * Only fires on body classes that match. If a body class contains a dash, * replace the dash with an underscore when adding it to the object below. * * .noConflict() * The routing is enclosed within an anonymous function so that you can * always reference jQuery with $, even when in .noConflict() mode. * ======================================================================== */ (function($) { // Use this variable to set up the common and page specific functions. If you // rename this variable, you will also need to rename the namespace below. var Sage = { // All pages 'common': { init: function() { // JavaScript to be fired on all pages }, finalize: function() { // JavaScript to be fired on all pages, after page specific JS is fired } }, // Home page 'home': { init: function() { // JavaScript to be fired on the home page }, finalize: function() { // JavaScript to be fired on the home page, after the init JS $('.carousel').owlCarousel({ loop: true, items: 1, autoplay: true, dots: false, animateIn: 'bounceInRight', animateOut: 'bounceOutLeft' }); } }, // About us page, note the change from about-us to about_us. 'about_us': { init: function() { // JavaScript to be fired on the about us page } } }; // The routing fires all common scripts, followed by the page specific scripts. // Add additional events for more control over timing e.g. a finalize event var UTIL = { fire: function(func, funcname, args) { var fire; var namespace = Sage; funcname = (funcname === undefined) ? 'init' : funcname; fire = func !== ''; fire = fire && namespace[func]; fire = fire && typeof namespace[func][funcname] === 'function'; if (fire) { namespace[func][funcname](args); } }, loadEvents: function() { // Fire common init JS UTIL.fire('common'); // Fire page-specific init JS, and then finalize JS $.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) { UTIL.fire(classnm); UTIL.fire(classnm, 'finalize'); }); // Fire common finalize JS UTIL.fire('common', 'finalize'); } }; // Load Events $(document).ready(UTIL.loadEvents); })(jQuery); // Fully reference jQuery after this point.
wab/collectifdanse
site/web/app/themes/cdrm/assets/scripts/main.js
JavaScript
mit
2,638
'use strict'; var glob = require('glob'); var JasmineRunner = require('jasmine'); var path = require('path'); // require('es6-shim/es6-shim.js'); require('zone.js/dist/zone-node.js'); require('zone.js/dist/long-stack-trace-zone.js'); require('zone.js/dist/async-test.js'); require('reflect-metadata/Reflect'); var jrunner = new JasmineRunner(); // Tun on full stack traces in errors to help debugging Error.stackTraceLimit = Infinity; jrunner.jasmine.DEFAULT_TIMEOUT_INTERVAL = 100; // Support passing multiple globs var globsIndex = process.argv.indexOf('--'); var args; if (globsIndex < 0) { args = [process.argv[2]]; } else { args = process.argv.slice(globsIndex + 1); } var specFiles = args.map(function(globstr) { return glob.sync(globstr); }) .reduce(function(specFiles, paths) { return specFiles.concat(paths); }, []); jasmine.DEFAULT_TIMEOUT_INTERVAL = 100; jrunner.configureDefaultReporter({showColors: process.argv.indexOf('--no-color') === -1}); jrunner.onComplete(function(passed) { process.exit(passed ? 0 : 1); }); jrunner.projectBaseDir = path.resolve(__dirname, '../../'); jrunner.specDir = ''; jrunner.addSpecFiles(specFiles); require('./test-cjs-main.js'); require('zone.js/dist/jasmine-patch.js'); jrunner.execute();
robertmesserle/angular
tools/cjs-jasmine/index.js
JavaScript
mit
1,269
import React from 'react'; import {Icon} from '../iconography'; import classnames from 'classnames'; import PropTypes from 'prop-types'; export class Input extends React.Component { static propTypes = { size: PropTypes.string, icon: PropTypes.string, innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]) }; componentDidMount() { require('../../css/inputs'); } render() { const {size, icon, innerRef, ...props} = this.props; const input = (<input {...{ ...props, ref: innerRef, className: classnames(props.className, { 'input-sm': ['sm', 'small'].indexOf(size) !== -1, 'input-lg': ['lg', 'large'].indexOf(size) !== -1 }) }} />); if (!icon) return input; return ( <div className="input-icon-container"> {input} <Icon {...{src: icon}}/> </div> ); } }
pivotal-cf/pivotal-ui
src/react/inputs/input.js
JavaScript
mit
886
var $newInputRow = `<div class="row"> <div class="form-group col-md-3"> <input type="text" class="form-control"> </div> <div class="form-group col-md-4"> <input type="url" class="form-control"> </div> <div class="form-group col-md-2"> <input type="number" class="form-control" min="1"> </div> <div class="form-group col-md-3"> <button class="btn btn-outline-warning"><i class="fa fa-pencil"></i></button> <button class="btn btn-outline-danger"><i class="fa fa-trash"></i></button> <button class="btn btn-outline-success"><i class="fa fa-star"></i></button> </div> </div>`; listStoredFeeds(); $('.btn-outline-danger').on('click', deleteFeed); function listStoredFeeds() { $('#allFeeds').empty(); $.each(localStorage, function (key, value) { $('#allFeeds').append($newInputRow); $('.row:last').children()[0].getElementsByTagName('input')[0].value = JSON.parse(value).name; $('.row:last').children()[1].getElementsByTagName('input')[0].value = JSON.parse(value).url; $('.row:last').children()[2].getElementsByTagName('input')[0].value = JSON.parse(value).counter; }); } function addNewFeedToStorage() { var feedObject = { name: $nameInput.val(), url: $urlInput.val(), counter: $counterInput.val(), isFavourite: false }; if (localStorage.getItem($nameInput.val()) === null) { localStorage.setItem($nameInput.val(), JSON.stringify(feedObject)); alert("New feed is successfully stored!"); listStoredFeeds(); } else { alert("Feed already exists with the given name!"); } } function deleteFeed() { var $chosenFeed = $(this).parent().siblings()[0].getElementsByTagName('input')[0].value; $($(this).parent().parent()).remove(); localStorage.removeItem($chosenFeed); }
DLevai94/CoolNews
js/GetAndSetFeeds.js
JavaScript
mit
2,121
define(["exports", "aurelia-path"], function (exports, _aureliaPath) { "use strict"; var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _inherits = function (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 _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); }; var relativeToFile = _aureliaPath.relativeToFile; function register(lookup, name, resource, type) { if (!name) { return; } var existing = lookup[name]; if (existing) { if (existing != resource) { throw new Error("Attempted to register " + type + " when one with the same name already exists. Name: " + name + "."); } return; } lookup[name] = resource; } var ResourceRegistry = exports.ResourceRegistry = (function () { function ResourceRegistry() { this.attributes = {}; this.elements = {}; this.valueConverters = {}; this.attributeMap = {}; this.baseResourceUrl = ""; } _prototypeProperties(ResourceRegistry, null, { registerElement: { value: function registerElement(tagName, behavior) { register(this.elements, tagName, behavior, "an Element"); }, writable: true, configurable: true }, getElement: { value: function getElement(tagName) { return this.elements[tagName]; }, writable: true, configurable: true }, registerAttribute: { value: function registerAttribute(attribute, behavior, knownAttribute) { this.attributeMap[attribute] = knownAttribute; register(this.attributes, attribute, behavior, "an Attribute"); }, writable: true, configurable: true }, getAttribute: { value: function getAttribute(attribute) { return this.attributes[attribute]; }, writable: true, configurable: true }, registerValueConverter: { value: function registerValueConverter(name, valueConverter) { register(this.valueConverters, name, valueConverter, "a ValueConverter"); }, writable: true, configurable: true }, getValueConverter: { value: function getValueConverter(name) { return this.valueConverters[name]; }, writable: true, configurable: true } }); return ResourceRegistry; })(); var ViewResources = exports.ViewResources = (function (ResourceRegistry) { function ViewResources(parent, viewUrl) { _get(Object.getPrototypeOf(ViewResources.prototype), "constructor", this).call(this); this.parent = parent; this.viewUrl = viewUrl; this.valueConverterLookupFunction = this.getValueConverter.bind(this); } _inherits(ViewResources, ResourceRegistry); _prototypeProperties(ViewResources, null, { relativeToView: { value: function relativeToView(path) { return relativeToFile(path, this.viewUrl); }, writable: true, configurable: true }, getElement: { value: function getElement(tagName) { return this.elements[tagName] || this.parent.getElement(tagName); }, writable: true, configurable: true }, mapAttribute: { value: function mapAttribute(attribute) { return this.attributeMap[attribute] || this.parent.attributeMap[attribute]; }, writable: true, configurable: true }, getAttribute: { value: function getAttribute(attribute) { return this.attributes[attribute] || this.parent.getAttribute(attribute); }, writable: true, configurable: true }, getValueConverter: { value: function getValueConverter(name) { return this.valueConverters[name] || this.parent.getValueConverter(name); }, writable: true, configurable: true } }); return ViewResources; })(ResourceRegistry); exports.__esModule = true; });
behzad88/templating
dist/amd/resource-registry.js
JavaScript
mit
4,972
'use strict' /* * Каждый раз при загрузке расширение возвращает бадж в его "дефолтное" состояние */ var extension = userBrowser.browserAction extension.setBadgeBackgroundColor({ color: [100, 100, 100, 1] }) extension.setBadgeText({ text: '' }) /* * Настройка радио */ var getRadioSrc = () => `https://listen${$currentPoint.mr24.server()}.${domain.mr24}/${$currentPoint.mr24.port()}` var radio = new Audio(), volume if (!$ls.get('aw_chr_radioVol')) { volume = 50; $ls.set('aw_chr_radioVol', volume) } else { volume = $ls.get('aw_chr_radioVol') } radio.preload = 'none' radio.volume = $ls.get('aw_chr_radioVol')/100 radio.toggle = function() { if (radio.paused) { radio.src = getRadioSrc() radio.play() extension.setBadgeText({text: (userBrowserName == 'opera') ? 'play' : '\u23F5'}) } else { radio.src = '' extension.setBadgeText({text: ''}) } } radio.toPoint = point => { if (!Object.keys(points).includes(point)) { return } let _this = radio, storageRadioOnPauseItemName = 'aw_chr_radioOnPause' $ls.set(storageRadioOnPauseItemName, _this.paused) $ls.set(storageCurrentPointItemName, point) _this.src = getRadioSrc() if ($ls.get(storageRadioOnPauseItemName) == 'false') { _this.load() _this.play() } $ls.rm(storageRadioOnPauseItemName) } /* * Обработчики событий */ userBrowser.runtime.onMessage.addListener((mes, sender, sendResponse) => { switch (mes.cmd) { case 'toggle': radio.toggle() sendResponse({'result': radio.paused}); break case 'status': sendResponse({'result': radio.paused}); break case 'getVol': sendResponse({'result': volume}); break case 'setVol': volume = mes.volume radio.volume = volume/100 break case 'changePoint': radio.toPoint(mes.point); break } }) userBrowser.alarms.onAlarm.addListener(alarm => { getData(API.anime_sched).then(resolve => checkSched(resolve, 'anime')) })
tehcojam/aw_chrome
source/js/background.js
JavaScript
mit
1,990
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Slide = void 0; const core_browser_1 = require("@bldr/core-browser"); const markdown_to_html_1 = require("@bldr/markdown-to-html"); const master_collection_1 = require("./master-collection"); /** * Meta informations can be added to each slide. All properties are possibly * undefined. */ class SlideMetaData { constructor(raw) { this.raw = raw; this.id = this.cutAndConvert('id'); this.title = this.cutAndConvert('title'); this.description = this.cutAndConvert('description'); this.source = this.cutAndConvert('source'); } cutAndConvert(property) { const value = this.raw.cut(property); if (value != null) { return markdown_to_html_1.convertMarkdownToHtml(value); } } } /** * A slide. */ class Slide { constructor(rawData) { const raw = new core_browser_1.RawDataObject(rawData); this.meta = new SlideMetaData(raw); this.rawData = rawData; this.no = 0; this.level = 0; this.slides = []; this.master = master_collection_1.masterCollection.findMaster(rawData); this.props = this.master.normalizeProps(raw.cut(this.master.name)); this.master.detectUnkownProps(this.props); this.master.convertMarkdownToHtml(this.props); this.master.validateUris(this.props); this.mediaUris = this.master.resolveMediaUris(this.props); this.optionalMediaUris = this.master.resolveOptionalMediaUris(this.props); } } exports.Slide = Slide;
JosefFriedrich-nodejs/baldr
src/lib/browser/lamp-core/dist/node/slide.js
JavaScript
mit
1,610
import React from 'react'; import { StyleSheet, Text, TouchableHighlight, TouchableOpacity, View, } from 'react-native'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import Icon from 'react-native-vector-icons/MaterialIcons'; import moment from 'moment-timezone'; import { getCompareToStartDate, getCompareToEndDate } from '../utils/compareToDate'; import * as dateRangeActions from '../actions/dateRange'; import tracker from '../utils/tracker'; moment.tz.setDefault('America/Los_Angeles'); const styles = StyleSheet.create({ container: { height: 50, flexDirection: 'row', alignItems: 'center', backgroundColor: '#FAFAFA', borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: '#E0E0E0', }, displayBlock: { flex: 6, flexDirection: 'row', padding: 10, alignItems: 'center', }, icon: { height: 40, width: 40, borderRadius: 20, justifyContent: 'center', alignItems: 'center', }, text: { fontSize: 14, }, compareToText: { fontSize: 12, color: '#424242', }, }); const RangePicker = (props) => { const { startDate, endDate, rangeType, isCompareTo, setPreviousDateRange, setNextDateRange, navigation } = props; let rangeShowAs; if (startDate && endDate) { let startYearShowAs = `, ${moment(startDate).year()}`; let endYearShowAs = `, ${moment(endDate).year()}`; if (moment(startDate).year() === moment().year() || moment(startDate).year() === moment(endDate).year()) { startYearShowAs = ''; } if (moment(endDate).year() === moment().year()) { endYearShowAs = ''; } if (moment(startDate).format('L') === moment(endDate).format('L')) { rangeShowAs = `${moment(endDate).format('ddd, MMM DD')}${endYearShowAs}`; } else { rangeShowAs = `${moment(startDate).format('MMM DD')}${startYearShowAs} - ${moment(endDate).format('MMM DD')}${endYearShowAs}`; } } let compareToRangeShowAs; if (isCompareTo) { const compareToStartDate = getCompareToStartDate(startDate, endDate, rangeType); const compareToEndDate = getCompareToEndDate(startDate, endDate, rangeType); let compareToStartYearShowAs = `, ${moment(startDate).year()}`; let compareToEndYearShowAs = `, ${moment(endDate).year()}`; if (moment(compareToStartDate).year() === moment().year() || moment(compareToStartDate).year() === moment(compareToEndDate).year()) { compareToStartYearShowAs = ''; } if (moment(compareToEndDate).year() === moment().year()) { compareToEndYearShowAs = ''; } if (moment(compareToStartDate).format('L') === moment(compareToEndDate).format('L')) { compareToRangeShowAs = `${moment(compareToEndDate).format('ddd, MMM DD')}${compareToEndYearShowAs}`; } else { compareToRangeShowAs = `${moment(compareToStartDate).format('MMM DD')}${compareToStartYearShowAs} - ${moment(compareToEndDate).format('MMM DD')}${compareToEndYearShowAs}`; } } return (<View style={styles.container}> <TouchableOpacity style={styles.displayBlock} onPress={() => { navigation.navigate('DateSettings'); tracker.logEvent('view-date-settings', { category: 'user-event', component: 'range-picker' }); }} > <View> <Text style={styles.text}>{rangeShowAs}</Text> {isCompareTo && <Text style={styles.compareToText}>vs. {compareToRangeShowAs}</Text>} </View> </TouchableOpacity> <TouchableHighlight underlayColor="#EEEEEE" style={styles.icon} onPress={() => { setPreviousDateRange(); tracker.logEvent('go-previous-date-range', { category: 'user-event', component: 'range-picker', value: rangeType }); }} > <Icon name="chevron-left" size={24} color="gray" /> </TouchableHighlight> <TouchableHighlight underlayColor="#EEEEEE" style={styles.icon} onPress={() => { setNextDateRange(); tracker.logEvent('go-next-date-range', { category: 'user-event', component: 'range-picker', value: rangeType }); }} > <Icon name="chevron-right" size={24} color="gray" /> </TouchableHighlight> <TouchableHighlight underlayColor="#EEEEEE" style={styles.icon} onPress={() => { navigation.navigate('DateSettings'); tracker.logEvent('view-date-settings', { category: 'user-event', component: 'range-picker' }); }} > <Icon name="tune" size={20} color="gray" /> </TouchableHighlight> </View>); }; RangePicker.defaultProps = { startDate: null, endDate: null, isCompareTo: false, }; RangePicker.propTypes = { startDate: React.PropTypes.object, endDate: React.PropTypes.object, rangeType: React.PropTypes.string.isRequired, isCompareTo: React.PropTypes.bool, setPreviousDateRange: React.PropTypes.func.isRequired, setNextDateRange: React.PropTypes.func.isRequired, navigation: React.PropTypes.object.isRequired, }; const mapStateToProps = state => ({ startDate: state.dateRange.startDate, endDate: state.dateRange.endDate, rangeType: state.dateRange.rangeType, isCompareTo: state.dateRange.isCompareTo, }); export default connect( mapStateToProps, dispatch => bindActionCreators(dateRangeActions, dispatch), )(RangePicker);
7kfpun/AudienceNetworkReactNative
app/components/RangePicker.js
JavaScript
mit
5,320
import React, { Component } from 'react'; // Utils import WeatherAPIUtils from '../utils/WeatherAPIUtils'; class WeatherForecastTemp extends Component { render() { // Set the temperature colors: let highColor = WeatherAPIUtils.getTempColor(this.props.high); let lowColor = WeatherAPIUtils.getTempColor(this.props.low); // Return the html: return ( <div> <span style={{color: highColor}}>{this.props.high}</span> • <span style={{color: lowColor}}>{this.props.low}</span> </div> ); } } export default WeatherForecastTemp;
danesparza/Dashboard
src/components/WeatherForecastTemp.react.js
JavaScript
mit
590
var assert = require('chai').assert; var sinon = require('sinon'); var Flux = require('flux'); var dispatcher = new Flux.Dispatcher(); var Store = require('./index.js')(dispatcher); describe('FluxStore', function() { it('Creates an empty store', function() { var store = new Store(); assert.deepEqual(store.getState(), {}); }); it('getState() returns a copy of state', function() { var store = new Store(); store.setState({ arr: [] }); var state1 = store.getState(); var state2 = store.getState(); assert.notEqual(state1.arr, state2.arr); }); it('getInitialState() returns an initial state', function() { var store = new Store({ foo: 'bar' }); store.setState({ foo: 'baz' }); assert.equal(store.getState().foo, 'baz'); assert.equal(store.getInitialState().foo, 'bar'); }); it('reset() sets the initial state', function() { var store = new Store({ foo: 'bar' }); store.setState({ foo: 'baz' }); store.reset(); assert.equal(store.getState().foo, 'bar'); }); it('getToken() returns dispatcher token', function() { var Store = require('./index')({ register: function() { return 'foo'; } }); var store = new Store(); assert.equal(store.getToken(), 'foo'); }); describe('reducer()', function() { beforeEach(function() { this.store = new Store({ foo: 'bar', aaa: 'bbb' }); this.spy = sinon.spy(function(state, action) { state.foo = action.foo; return state; }); this.store.reducer('FOO', this.spy); dispatcher.dispatch({ _name: 'FOO', foo: 'baz' }); }); it('Calls the reducer on specific action', function() { assert.ok(this.spy.calledOnce); }); it('Called with current state as a first arg', function() { var state = this.spy.getCall(0).args[0]; assert.equal(state.aaa, 'bbb'); }); it('Called with action as a second arg', function() { var action = this.spy.getCall(0).args[1]; assert.equal(action._name, 'FOO'); }); it('Changes the state when returned from reducer', function() { assert.equal(this.store.getState().foo, 'baz'); }); it('Does not change state when falsy value returned', function() { var spy = sinon.spy(function(state) { state.aaa = 'xxx'; return false; }); this.store.reducer('AAA', spy); dispatcher.dispatch({ actionName: 'AAA' }); assert.ok(spy.calledOnce); assert.equal(this.store.getState().aaa, 'bbb'); }); }); it('method() add a instence method', function() { var store = new Store({ foo: 'bar' }); store.method('getFoo', function() { return this.getState().foo; }); assert.equal(store.getFoo(), 'bar'); }); describe('Store.create() creates the store in "one go"', function() { beforeEach(function() { this.store = Store.create({ foo: 'bar' }, { 'FOO': function(state) { state.foo = 'baz'; return state; } }, { getFoo: function() { return this.getState().foo; } }); }); it('Has correct initial state', function() { assert.equal(this.store.getState().foo, 'bar'); }); it('Has correct reducers', function() { dispatcher.dispatch({ actionName: 'FOO' }); assert.equal(this.store.getState().foo, 'baz'); }); it('Has correct methods', function() { assert.equal(this.store.getFoo(), 'bar'); }); }); });
pwlmaciejewski/fluxstore
test.js
JavaScript
mit
3,649
const { sum, forEach } = require('../sum') test('adds 1 + 2 to equals 3', () => { expect(sum(1, 2)).toEqual(3) }) test('object assigenment', () => { const data = { one: 1 } data['two'] = 2 expect(data).toEqual({ one: 1, two: 2 }) }) test('zero', () => { const z = 0 expect(z).not.toBeNull() expect(z).toBeDefined() expect(z).not.toBeUndefined() expect(z).not.toBeTruthy() expect(z).toBeFalsy() }) test('adding floating point numbers', () => { const value = 0.1 + 0.2 expect(value).not.toBe(0.3) expect(value).toBeCloseTo(0.3) }) test('mock', () => { const mockCb = jest.fn() forEach([0, 1], mockCb) expect(mockCb.mock.calls.length).toBe(2) })
imuntil/nodejs
Test/Jest/start/__test__/sum.test.js
JavaScript
mit
677
App.SearchFormComponent = Ember.Component.extend({ hasValue: function () { return !!this.get('keywords'); }.property('keywords'), didInsertElement: function () { this.set('$search', this.$().find('#search')); }, observeFocus: function () { if (this.get('isFocused')) { this.get('$search').focus(); } }.observes('isFocused'), actions: { lookup: function () { this.get('$search').blur(); this.sendAction('action', this.get('keywords')); }, cancel: function () { this.sendAction('cancel'); }, activate: function () { this.set('isActive', true); }, deactivate: function () { this.set('isActive', false); } } });
Igor10k/infigames
app/components/search-form.js
JavaScript
mit
661
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nls from './../../../fillers/vscode-nls.js'; import * as languageFacts from '../languageFacts/facts.js'; import * as nodes from '../parser/cssNodes.js'; import { union } from '../utils/arrays.js'; import { Rules, Settings } from './lintRules.js'; import calculateBoxModel, { Element } from './lintUtil.js'; var localize = nls.loadMessageBundle(); var NodesByRootMap = /** @class */ (function () { function NodesByRootMap() { this.data = {}; } NodesByRootMap.prototype.add = function (root, name, node) { var entry = this.data[root]; if (!entry) { entry = { nodes: [], names: [] }; this.data[root] = entry; } entry.names.push(name); if (node) { entry.nodes.push(node); } }; return NodesByRootMap; }()); var LintVisitor = /** @class */ (function () { function LintVisitor(document, settings, cssDataManager) { var _this = this; this.cssDataManager = cssDataManager; this.warnings = []; this.settings = settings; this.documentText = document.getText(); this.keyframes = new NodesByRootMap(); this.validProperties = {}; var properties = settings.getSetting(Settings.ValidProperties); if (Array.isArray(properties)) { properties.forEach(function (p) { if (typeof p === 'string') { var name = p.trim().toLowerCase(); if (name.length) { _this.validProperties[name] = true; } } }); } } LintVisitor.entries = function (node, document, settings, cssDataManager, entryFilter) { var visitor = new LintVisitor(document, settings, cssDataManager); node.acceptVisitor(visitor); visitor.completeValidations(); return visitor.getEntries(entryFilter); }; LintVisitor.prototype.isValidPropertyDeclaration = function (element) { var propertyName = element.fullPropertyName; return this.validProperties[propertyName]; }; LintVisitor.prototype.fetch = function (input, s) { var elements = []; for (var _i = 0, input_1 = input; _i < input_1.length; _i++) { var curr = input_1[_i]; if (curr.fullPropertyName === s) { elements.push(curr); } } return elements; }; LintVisitor.prototype.fetchWithValue = function (input, s, v) { var elements = []; for (var _i = 0, input_2 = input; _i < input_2.length; _i++) { var inputElement = input_2[_i]; if (inputElement.fullPropertyName === s) { var expression = inputElement.node.getValue(); if (expression && this.findValueInExpression(expression, v)) { elements.push(inputElement); } } } return elements; }; LintVisitor.prototype.findValueInExpression = function (expression, v) { var found = false; expression.accept(function (node) { if (node.type === nodes.NodeType.Identifier && node.matches(v)) { found = true; } return !found; }); return found; }; LintVisitor.prototype.getEntries = function (filter) { if (filter === void 0) { filter = (nodes.Level.Warning | nodes.Level.Error); } return this.warnings.filter(function (entry) { return (entry.getLevel() & filter) !== 0; }); }; LintVisitor.prototype.addEntry = function (node, rule, details) { var entry = new nodes.Marker(node, rule, this.settings.getRule(rule), details); this.warnings.push(entry); }; LintVisitor.prototype.getMissingNames = function (expected, actual) { var expectedClone = expected.slice(0); // clone for (var i = 0; i < actual.length; i++) { var k = expectedClone.indexOf(actual[i]); if (k !== -1) { expectedClone[k] = null; } } var result = null; for (var i = 0; i < expectedClone.length; i++) { var curr = expectedClone[i]; if (curr) { if (result === null) { result = localize('namelist.single', "'{0}'", curr); } else { result = localize('namelist.concatenated', "{0}, '{1}'", result, curr); } } } return result; }; LintVisitor.prototype.visitNode = function (node) { switch (node.type) { case nodes.NodeType.UnknownAtRule: return this.visitUnknownAtRule(node); case nodes.NodeType.Keyframe: return this.visitKeyframe(node); case nodes.NodeType.FontFace: return this.visitFontFace(node); case nodes.NodeType.Ruleset: return this.visitRuleSet(node); case nodes.NodeType.SimpleSelector: return this.visitSimpleSelector(node); case nodes.NodeType.Function: return this.visitFunction(node); case nodes.NodeType.NumericValue: return this.visitNumericValue(node); case nodes.NodeType.Import: return this.visitImport(node); case nodes.NodeType.HexColorValue: return this.visitHexColorValue(node); case nodes.NodeType.Prio: return this.visitPrio(node); case nodes.NodeType.IdentifierSelector: return this.visitIdentifierSelector(node); } return true; }; LintVisitor.prototype.completeValidations = function () { this.validateKeyframes(); }; LintVisitor.prototype.visitUnknownAtRule = function (node) { var atRuleName = node.getChild(0); if (!atRuleName) { return false; } var atDirective = this.cssDataManager.getAtDirective(atRuleName.getText()); if (atDirective) { return false; } this.addEntry(atRuleName, Rules.UnknownAtRules, "Unknown at rule " + atRuleName.getText()); return true; }; LintVisitor.prototype.visitKeyframe = function (node) { var keyword = node.getKeyword(); if (!keyword) { return false; } var text = keyword.getText(); this.keyframes.add(node.getName(), text, (text !== '@keyframes') ? keyword : null); return true; }; LintVisitor.prototype.validateKeyframes = function () { // @keyframe and it's vendor specific alternatives // @keyframe should be included var expected = ['@-webkit-keyframes', '@-moz-keyframes', '@-o-keyframes']; for (var name in this.keyframes.data) { var actual = this.keyframes.data[name].names; var needsStandard = (actual.indexOf('@keyframes') === -1); if (!needsStandard && actual.length === 1) { continue; // only the non-vendor specific keyword is used, that's fine, no warning } var missingVendorSpecific = this.getMissingNames(expected, actual); if (missingVendorSpecific || needsStandard) { for (var _i = 0, _a = this.keyframes.data[name].nodes; _i < _a.length; _i++) { var node = _a[_i]; if (needsStandard) { var message = localize('keyframes.standardrule.missing', "Always define standard rule '@keyframes' when defining keyframes."); this.addEntry(node, Rules.IncludeStandardPropertyWhenUsingVendorPrefix, message); } if (missingVendorSpecific) { var message = localize('keyframes.vendorspecific.missing', "Always include all vendor specific rules: Missing: {0}", missingVendorSpecific); this.addEntry(node, Rules.AllVendorPrefixes, message); } } } } return true; }; LintVisitor.prototype.visitSimpleSelector = function (node) { ///////////////////////////////////////////////////////////// // Lint - The universal selector (*) is known to be slow. ///////////////////////////////////////////////////////////// var firstChar = this.documentText.charAt(node.offset); if (node.length === 1 && firstChar === '*') { this.addEntry(node, Rules.UniversalSelector); } return true; }; LintVisitor.prototype.visitIdentifierSelector = function (node) { ///////////////////////////////////////////////////////////// // Lint - Avoid id selectors ///////////////////////////////////////////////////////////// this.addEntry(node, Rules.AvoidIdSelector); return true; }; LintVisitor.prototype.visitImport = function (node) { ///////////////////////////////////////////////////////////// // Lint - Import statements shouldn't be used, because they aren't offering parallel downloads. ///////////////////////////////////////////////////////////// this.addEntry(node, Rules.ImportStatemement); return true; }; LintVisitor.prototype.visitRuleSet = function (node) { ///////////////////////////////////////////////////////////// // Lint - Don't use empty rulesets. ///////////////////////////////////////////////////////////// var declarations = node.getDeclarations(); if (!declarations) { // syntax error return false; } if (!declarations.hasChildren()) { this.addEntry(node.getSelectors(), Rules.EmptyRuleSet); } var propertyTable = []; for (var _i = 0, _a = declarations.getChildren(); _i < _a.length; _i++) { var element = _a[_i]; if (element instanceof nodes.Declaration) { propertyTable.push(new Element(element)); } } ///////////////////////////////////////////////////////////// // the rule warns when it finds: // width being used with border, border-left, border-right, padding, padding-left, or padding-right // height being used with border, border-top, border-bottom, padding, padding-top, or padding-bottom // No error when box-sizing property is specified, as it assumes the user knows what he's doing. // see https://github.com/CSSLint/csslint/wiki/Beware-of-box-model-size ///////////////////////////////////////////////////////////// var boxModel = calculateBoxModel(propertyTable); if (boxModel.width) { var properties = []; if (boxModel.right.value) { properties = union(properties, boxModel.right.properties); } if (boxModel.left.value) { properties = union(properties, boxModel.left.properties); } if (properties.length !== 0) { for (var _b = 0, properties_1 = properties; _b < properties_1.length; _b++) { var item = properties_1[_b]; this.addEntry(item.node, Rules.BewareOfBoxModelSize); } this.addEntry(boxModel.width.node, Rules.BewareOfBoxModelSize); } } if (boxModel.height) { var properties = []; if (boxModel.top.value) { properties = union(properties, boxModel.top.properties); } if (boxModel.bottom.value) { properties = union(properties, boxModel.bottom.properties); } if (properties.length !== 0) { for (var _c = 0, properties_2 = properties; _c < properties_2.length; _c++) { var item = properties_2[_c]; this.addEntry(item.node, Rules.BewareOfBoxModelSize); } this.addEntry(boxModel.height.node, Rules.BewareOfBoxModelSize); } } ///////////////////////////////////////////////////////////// // Properties ignored due to display ///////////////////////////////////////////////////////////// // With 'display: inline-block', 'float' has no effect var displayElems = this.fetchWithValue(propertyTable, 'display', 'inline-block'); if (displayElems.length > 0) { var elem = this.fetch(propertyTable, 'float'); for (var index = 0; index < elem.length; index++) { var node_1 = elem[index].node; var value = node_1.getValue(); if (value && !value.matches('none')) { this.addEntry(node_1, Rules.PropertyIgnoredDueToDisplay, localize('rule.propertyIgnoredDueToDisplayInlineBlock', "inline-block is ignored due to the float. If 'float' has a value other than 'none', the box is floated and 'display' is treated as 'block'")); } } } // With 'display: block', 'vertical-align' has no effect displayElems = this.fetchWithValue(propertyTable, 'display', 'block'); if (displayElems.length > 0) { var elem = this.fetch(propertyTable, 'vertical-align'); for (var index = 0; index < elem.length; index++) { this.addEntry(elem[index].node, Rules.PropertyIgnoredDueToDisplay, localize('rule.propertyIgnoredDueToDisplayBlock', "Property is ignored due to the display. With 'display: block', vertical-align should not be used.")); } } ///////////////////////////////////////////////////////////// // Avoid 'float' ///////////////////////////////////////////////////////////// var elements = this.fetch(propertyTable, 'float'); for (var index = 0; index < elements.length; index++) { var element = elements[index]; if (!this.isValidPropertyDeclaration(element)) { this.addEntry(element.node, Rules.AvoidFloat); } } ///////////////////////////////////////////////////////////// // Don't use duplicate declarations. ///////////////////////////////////////////////////////////// for (var i = 0; i < propertyTable.length; i++) { var element = propertyTable[i]; if (element.fullPropertyName !== 'background' && !this.validProperties[element.fullPropertyName]) { var value = element.node.getValue(); if (value && this.documentText.charAt(value.offset) !== '-') { var elements_1 = this.fetch(propertyTable, element.fullPropertyName); if (elements_1.length > 1) { for (var k = 0; k < elements_1.length; k++) { var value_1 = elements_1[k].node.getValue(); if (value_1 && this.documentText.charAt(value_1.offset) !== '-' && elements_1[k] !== element) { this.addEntry(element.node, Rules.DuplicateDeclarations); } } } } } } ///////////////////////////////////////////////////////////// // Unknown propery & When using a vendor-prefixed gradient, make sure to use them all. ///////////////////////////////////////////////////////////// var isExportBlock = node.getSelectors().matches(":export"); if (!isExportBlock) { var propertiesBySuffix = new NodesByRootMap(); var containsUnknowns = false; for (var _d = 0, propertyTable_1 = propertyTable; _d < propertyTable_1.length; _d++) { var element = propertyTable_1[_d]; var decl = element.node; if (this.isCSSDeclaration(decl)) { var name = element.fullPropertyName; var firstChar = name.charAt(0); if (firstChar === '-') { if (name.charAt(1) !== '-') { // avoid css variables if (!this.cssDataManager.isKnownProperty(name) && !this.validProperties[name]) { this.addEntry(decl.getProperty(), Rules.UnknownVendorSpecificProperty); } var nonPrefixedName = decl.getNonPrefixedPropertyName(); propertiesBySuffix.add(nonPrefixedName, name, decl.getProperty()); } } else { var fullName = name; if (firstChar === '*' || firstChar === '_') { this.addEntry(decl.getProperty(), Rules.IEStarHack); name = name.substr(1); } // _property and *property might be contributed via custom data if (!this.cssDataManager.isKnownProperty(fullName) && !this.cssDataManager.isKnownProperty(name)) { if (!this.validProperties[name]) { this.addEntry(decl.getProperty(), Rules.UnknownProperty, localize('property.unknownproperty.detailed', "Unknown property: '{0}'", decl.getFullPropertyName())); } } propertiesBySuffix.add(name, name, null); // don't pass the node as we don't show errors on the standard } } else { containsUnknowns = true; } } if (!containsUnknowns) { // don't perform this test if there are for (var suffix in propertiesBySuffix.data) { var entry = propertiesBySuffix.data[suffix]; var actual = entry.names; var needsStandard = this.cssDataManager.isStandardProperty(suffix) && (actual.indexOf(suffix) === -1); if (!needsStandard && actual.length === 1) { continue; // only the non-vendor specific rule is used, that's fine, no warning } var expected = []; for (var i = 0, len = LintVisitor.prefixes.length; i < len; i++) { var prefix = LintVisitor.prefixes[i]; if (this.cssDataManager.isStandardProperty(prefix + suffix)) { expected.push(prefix + suffix); } } var missingVendorSpecific = this.getMissingNames(expected, actual); if (missingVendorSpecific || needsStandard) { for (var _e = 0, _f = entry.nodes; _e < _f.length; _e++) { var node_2 = _f[_e]; if (needsStandard) { var message = localize('property.standard.missing', "Also define the standard property '{0}' for compatibility", suffix); this.addEntry(node_2, Rules.IncludeStandardPropertyWhenUsingVendorPrefix, message); } if (missingVendorSpecific) { var message = localize('property.vendorspecific.missing', "Always include all vendor specific properties: Missing: {0}", missingVendorSpecific); this.addEntry(node_2, Rules.AllVendorPrefixes, message); } } } } } } return true; }; LintVisitor.prototype.visitPrio = function (node) { ///////////////////////////////////////////////////////////// // Don't use !important ///////////////////////////////////////////////////////////// this.addEntry(node, Rules.AvoidImportant); return true; }; LintVisitor.prototype.visitNumericValue = function (node) { ///////////////////////////////////////////////////////////// // 0 has no following unit ///////////////////////////////////////////////////////////// var funcDecl = node.findParent(nodes.NodeType.Function); if (funcDecl && funcDecl.getName() === 'calc') { return true; } var decl = node.findParent(nodes.NodeType.Declaration); if (decl) { var declValue = decl.getValue(); if (declValue) { var value = node.getValue(); if (!value.unit || languageFacts.units.length.indexOf(value.unit.toLowerCase()) === -1) { return true; } if (parseFloat(value.value) === 0.0 && !!value.unit && !this.validProperties[decl.getFullPropertyName()]) { this.addEntry(node, Rules.ZeroWithUnit); } } } return true; }; LintVisitor.prototype.visitFontFace = function (node) { var declarations = node.getDeclarations(); if (!declarations) { // syntax error return false; } var definesSrc = false, definesFontFamily = false; var containsUnknowns = false; for (var _i = 0, _a = declarations.getChildren(); _i < _a.length; _i++) { var node_3 = _a[_i]; if (this.isCSSDeclaration(node_3)) { var name = node_3.getProperty().getName().toLowerCase(); if (name === 'src') { definesSrc = true; } if (name === 'font-family') { definesFontFamily = true; } } else { containsUnknowns = true; } } if (!containsUnknowns && (!definesSrc || !definesFontFamily)) { this.addEntry(node, Rules.RequiredPropertiesForFontFace); } return true; }; LintVisitor.prototype.isCSSDeclaration = function (node) { if (node instanceof nodes.Declaration) { if (!node.getValue()) { return false; } var property = node.getProperty(); if (!property) { return false; } var identifier = property.getIdentifier(); if (!identifier || identifier.containsInterpolation()) { return false; } return true; } return false; }; LintVisitor.prototype.visitHexColorValue = function (node) { // Rule: #eeff0011 or #eeff00 or #ef01 or #ef0 var length = node.length; if (length !== 9 && length !== 7 && length !== 5 && length !== 4) { this.addEntry(node, Rules.HexColorLength); } return false; }; LintVisitor.prototype.visitFunction = function (node) { var fnName = node.getName().toLowerCase(); var expectedAttrCount = -1; var actualAttrCount = 0; switch (fnName) { case 'rgb(': case 'hsl(': expectedAttrCount = 3; break; case 'rgba(': case 'hsla(': expectedAttrCount = 4; break; } if (expectedAttrCount !== -1) { node.getArguments().accept(function (n) { if (n instanceof nodes.BinaryExpression) { actualAttrCount += 1; return false; } return true; }); if (actualAttrCount !== expectedAttrCount) { this.addEntry(node, Rules.ArgsInColorFunction); } } return true; }; LintVisitor.prefixes = [ '-ms-', '-moz-', '-o-', '-webkit-', // Quite common // '-xv-', '-atsc-', '-wap-', '-khtml-', 'mso-', 'prince-', '-ah-', '-hp-', '-ro-', '-rim-', '-tc-' // Quite un-common ]; return LintVisitor; }()); export { LintVisitor };
TeamSPoon/logicmoo_workspace
packs_web/swish/web/node_modules/monaco-editor/esm/vs/language/css/_deps/vscode-css-languageservice/services/lint.js
JavaScript
mit
24,668
const r = require('./db'); function seedDB () { r.db('ironman').table_list().run() .then(clearDB) .then(createModels); } // This won't work if there are multiple dbs function clearDB (tables) { for (let table of tables) { return r.table_drop(table).run(); } } function createModels() { return r.tableCreate('users').run(); } module.exports = seedDB;
dcurletti/KnowledgeScout
server/db/seed.js
JavaScript
mit
377
import minimatch from 'minimatch'; import path from 'path'; import pkgUp from 'pkg-up'; function getEntryPoint(context) { const pkgPath = pkgUp.sync(context.getFilename()); try { return require.resolve(path.dirname(pkgPath)); } catch (error) { // Assume the package has no entrypoint (e.g. CLI packages) // in which case require.resolve would throw. return null; } } module.exports = { meta: { type: 'problem', docs: { description: 'Disallow import statements with module.exports', category: 'Best Practices', recommended: true, }, fixable: 'code', schema: [ { 'type': 'object', 'properties': { 'exceptions': { 'type': 'array' }, }, 'additionalProperties': false, }, ], }, create(context) { const importDeclarations = []; const entryPoint = getEntryPoint(context); const options = context.options[0] || {}; let alreadyReported = false; function report(node) { const fileName = context.getFilename(); const isEntryPoint = entryPoint === fileName; const isIdentifier = node.object.type === 'Identifier'; const hasKeywords = (/^(module|exports)$/).test(node.object.name); const isException = options.exceptions && options.exceptions.some(glob => minimatch(fileName, glob)); if (isIdentifier && hasKeywords && !isEntryPoint && !isException) { importDeclarations.forEach(importDeclaration => { context.report({ node: importDeclaration, message: `Cannot use import declarations in modules that export using ` + `CommonJS (module.exports = 'foo' or exports.bar = 'hi')`, }); }); alreadyReported = true; } } return { ImportDeclaration(node) { importDeclarations.push(node); }, MemberExpression(node) { if (!alreadyReported) { report(node); } }, }; }, };
benmosher/eslint-plugin-import
src/rules/no-import-module-exports.js
JavaScript
mit
2,001
// # Custom Middleware // The following custom middleware functions are all unit testable, and have accompanying unit tests in // middleware_spec.js var _ = require('lodash'), express = require('express'), busboy = require('./ghost-busboy'), config = require('../config'), path = require('path'), api = require('../api'), expressServer, ONE_HOUR_MS = 60 * 60 * 1000, ONE_YEAR_MS = 365 * 24 * ONE_HOUR_MS; function isBlackListedFileType(file) { var blackListedFileTypes = ['.hbs', '.md', '.json'], ext = path.extname(file); return _.contains(blackListedFileTypes, ext); } function cacheServer(server) { expressServer = server; } var middleware = { // ### Authenticate Middleware // authentication has to be done for /ghost/* routes with // exceptions for signin, signout, signup, forgotten, reset only // api and frontend use different authentication mechanisms atm authenticate: function (req, res, next) { var noAuthNeeded = [ '/ghost/signin/', '/ghost/signout/', '/ghost/signup/', '/ghost/forgotten/', '/ghost/reset/', '/ghost/ember/', '/ghost/ember/signin' ], subPath; // SubPath is the url path starting after any default subdirectories // it is stripped of anything after the two levels `/ghost/.*?/` as the reset link has an argument subPath = req.path.substring(config().paths.subdir.length); /*jslint regexp:true, unparam:true*/ subPath = subPath.replace(/^(\/.*?\/.*?\/)(.*)?/, function (match, a) { return a; }); if (res.isAdmin) { if (subPath.indexOf('/ghost/api/') === 0) { return middleware.authAPI(req, res, next); } if (noAuthNeeded.indexOf(subPath) < 0) { return middleware.auth(req, res, next); } } next(); }, // ### Auth Middleware // Authenticate a request by redirecting to login if not logged in. // We strip /ghost/ out of the redirect parameter for neatness auth: function (req, res, next) { if (!req.session.user) { var subPath = req.path.substring(config().paths.subdir.length), reqPath = subPath.replace(/^\/ghost\/?/gi, ''), redirect = '', msg; return api.notifications.browse().then(function (notifications) { if (reqPath !== '') { msg = { type: 'error', message: 'Please Sign In', status: 'passive' }; // let's only add the notification once if (!_.contains(_.pluck(notifications, 'id'), 'failedauth')) { api.notifications.add(msg); } redirect = '?r=' + encodeURIComponent(reqPath); } if (subPath.indexOf('/ember') > -1) { return res.redirect(config().paths.subdir + '/ghost/ember/signin'); } return res.redirect(config().paths.subdir + '/ghost/signin/' + redirect); }); } next(); }, // ## AuthApi Middleware // Authenticate a request to the API by responding with a 401 and json error details authAPI: function (req, res, next) { if (!req.session.user) { res.json(401, { error: 'Please sign in' }); return; } next(); }, // Check if we're logged in, and if so, redirect people back to dashboard // Login and signup forms in particular redirectToDashboard: function (req, res, next) { if (req.session && req.session.user) { return res.redirect(config().paths.subdir + '/ghost/'); } next(); }, // While we're here, let's clean up on aisle 5 // That being ghost.notifications, and let's remove the passives from there // plus the local messages, as they have already been added at this point // otherwise they'd appear one too many times // ToDo: Remove once ember handles passive notifications. cleanNotifications: function (req, res, next) { /*jslint unparam:true*/ api.notifications.browse().then(function (notifications) { _.each(notifications.notifications, function (notification) { if (notification.status === 'passive') { api.notifications.destroy(notification); } }); next(); }); }, // ### CacheControl Middleware // provide sensible cache control headers cacheControl: function (options) { /*jslint unparam:true*/ var profiles = { 'public': 'public, max-age=0', 'private': 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0' }, output; if (_.isString(options) && profiles.hasOwnProperty(options)) { output = profiles[options]; } return function cacheControlHeaders(req, res, next) { if (output) { res.set({'Cache-Control': output}); } next(); }; }, // ### whenEnabled Middleware // Selectively use middleware // From https://github.com/senchalabs/connect/issues/676#issuecomment-9569658 whenEnabled: function (setting, fn) { return function settingEnabled(req, res, next) { // Set from server/middleware/index.js for now if (expressServer.enabled(setting)) { fn(req, res, next); } else { next(); } }; }, staticTheme: function () { return function blackListStatic(req, res, next) { if (isBlackListedFileType(req.url)) { return next(); } return middleware.forwardToExpressStatic(req, res, next); }; }, // to allow unit testing forwardToExpressStatic: function (req, res, next) { api.settings.read({context: {internal: true}, key: 'activeTheme'}).then(function (response) { var activeTheme = response.settings[0]; express['static'](path.join(config().paths.themePath, activeTheme.value), {maxAge: ONE_YEAR_MS})(req, res, next); }); }, conditionalCSRF: function (req, res, next) { var csrf = express.csrf(); // CSRF is needed for admin only if (res.isAdmin) { csrf(req, res, next); return; } next(); }, busboy: busboy }; module.exports = middleware; module.exports.cacheServer = cacheServer;
potherca-contrib/Ghost
core/server/middleware/middleware.js
JavaScript
mit
6,851
(function(plugin){ if ( typeof require === "function" && typeof exports === "object" && typeof module === "object" ) { // NodeJS module.exports = plugin; } else if ( typeof define === "function" && define.amd ) { // AMD define(function () { return plugin; }); } else { // Other environment (usually <script> tag): plug in to global chai instance directly. chai.use(plugin); } }(function(chai, utils){ chai.datetime = chai.datetime || {}; function asDate(date) { return (date instanceof Date) ? date : new Date(date); } function padNumber(num, length) { var ret = '' + num; var i = ret.length; if (!isFinite(length)) { length = 2; } for (i; i < length; i++) { ret = '0' + ret; } return ret; } chai.datetime.getFormattedTimezone = function(timezoneInMinutes) { var tz = Math.abs(timezoneInMinutes); var hours = Math.floor(tz / 60); var minutes = tz % 60; var isAheadOfUtc = timezoneInMinutes <= 0; return (isAheadOfUtc ? '+' : '-') + padNumber(hours) + ':' + padNumber(minutes); } chai.datetime.formatDate = function(date) { return asDate(date).toDateString(); }; chai.datetime.formatTime = function(time) { return time.toDateString() + ' ' + padNumber(time.getHours()) + ':' + padNumber(time.getMinutes()) + ':' + padNumber(time.getSeconds()) + '.' + padNumber(time.getMilliseconds(), 3) + ' (' + chai.datetime.getFormattedTimezone(time.getTimezoneOffset()) + ')'; }; chai.datetime.equalTime = function(actual, expected) { return actual.getTime() == expected.getTime(); }; chai.datetime.equalDate = function(actual, expected) { return actual.toDateString() === asDate(expected).toDateString(); }; var dateWithoutTime = function(date) { return new Date(date.getFullYear(), date.getMonth(), date.getDate()); } chai.datetime.beforeDate = function(actual, expected) { return chai.datetime.beforeTime(dateWithoutTime(actual), dateWithoutTime(expected)); }; chai.datetime.afterDate = function(actual, expected) { return chai.datetime.afterTime(dateWithoutTime(actual), dateWithoutTime(expected)); }; chai.datetime.beforeTime = function(actual, expected) { return actual.getTime() < expected.getTime(); }; chai.datetime.afterTime = function(actual, expected) { return actual.getTime() > expected.getTime(); }; chai.Assertion.addChainableMethod('equalTime', function(expected) { var actual = this._obj; return this.assert( chai.datetime.equalTime(expected, actual), 'expected ' + this._obj + ' to equal ' + expected, 'expected ' + this._obj + ' to not equal ' + expected, expected.toString(), actual.toString() ); }); chai.Assertion.addChainableMethod('equalDate', function(expected) { var expectedDate = chai.datetime.formatDate(expected), actualDate = chai.datetime.formatDate(this._obj); return this.assert( chai.datetime.equalDate(this._obj, expected), 'expected ' + actualDate + ' to equal ' + expectedDate, 'expected ' + actualDate + ' to not equal ' + expectedDate ); }); chai.Assertion.addChainableMethod('beforeDate', function(expected) { var actual = this._obj; this.assert( chai.datetime.beforeDate(actual, expected), 'expected ' + chai.datetime.formatDate(actual) + ' to be before ' + chai.datetime.formatDate(expected), 'expected ' + chai.datetime.formatDate(actual) + ' not to be before ' + chai.datetime.formatDate(expected) ); }); chai.Assertion.addChainableMethod('afterDate', function(expected) { var actual = this._obj; this.assert( chai.datetime.afterDate(actual, expected), 'expected ' + chai.datetime.formatDate(actual) + ' to be after ' + chai.datetime.formatDate(expected), 'expected ' + chai.datetime.formatDate(actual) + ' not to be after ' + chai.datetime.formatDate(expected) ); }); chai.Assertion.addChainableMethod('beforeTime', function(expected) { var actual = this._obj; this.assert( chai.datetime.beforeTime(actual, expected), 'expected ' + chai.datetime.formatTime(actual) + ' to be before ' + chai.datetime.formatTime(expected), 'expected ' + chai.datetime.formatTime(actual) + ' not to be before ' + chai.datetime.formatTime(expected) ); }); chai.Assertion.addChainableMethod('afterTime', function(expected) { var actual = this._obj; this.assert( chai.datetime.afterTime(actual, expected), 'expected ' + chai.datetime.formatTime(actual) + ' to be after ' + chai.datetime.formatTime(expected), 'expected ' + chai.datetime.formatTime(actual) + ' not to be after ' + chai.datetime.formatTime(expected) ); }); // Asserts var assert = chai.assert; assert.equalDate = function(val, exp, msg) { new chai.Assertion(val, msg).to.be.equalDate(exp); }; assert.notEqualDate = function(val, exp, msg) { new chai.Assertion(val, msg).to.not.be.equalDate(exp); }; assert.beforeDate = function(val, exp, msg) { new chai.Assertion(val, msg).to.be.beforeDate(exp); }; assert.notBeforeDate = function(val, exp, msg) { new chai.Assertion(val, msg).to.not.be.beforeDate(exp); }; assert.afterDate = function(val, exp, msg) { new chai.Assertion(val, msg).to.be.afterDate(exp); }; assert.notAfterDate = function(val, exp, msg) { new chai.Assertion(val, msg).not.to.be.afterDate(exp); }; assert.equalTime = function(val, exp, msg) { new chai.Assertion(val, msg).to.be.equalTime(exp); }; assert.notEqualTime = function(val, exp, msg) { new chai.Assertion(val, msg).to.not.be.equalTime(exp); }; assert.beforeTime = function(val, exp, msg) { new chai.Assertion(val, msg).to.be.beforeTime(exp); }; assert.notBeforeTime = function(val, exp, msg) { new chai.Assertion(val, msg).not.to.be.beforeTime(exp); }; assert.afterTime = function(val, exp, msg) { new chai.Assertion(val, msg).to.be.afterTime(exp); }; assert.notAfterTime = function(val, exp, msg) { new chai.Assertion(val, msg).to.not.be.afterTime(exp); }; }));
FluxAugur/chai-datetime
chai-datetime.js
JavaScript
mit
6,277
'use strict' import CACodingProxy from './CACodingProxy' import CGPoint from '../CoreGraphics/CGPoint' import CGRect from '../CoreGraphics/CGRect' import CGSize from '../CoreGraphics/CGSize' /** * * @access public * @extends {CACodingProxy} * */ export default class LKNSValueCodingProxy extends CACodingProxy { /** * */ static initWithCoder(coder) { //console.log('LKNSValueCodingProxy: ' + JSON.stringify(Object.keys(coder._refObj), null, 2)) const obj = coder._refObj const kind = obj.kind switch(kind) { case 0: { // CGPoint (x, y) return new CGPoint(obj.x, obj.y) } case 1: { // CGSize (width, height) return new CGSize(obj.width, obj.height) } case 2: { // CGRect (x, y, width, height) const point = new CGPoint(obj.x, obj.y) const size = new CGSize(obj.width, obj.height) return new CGRect(point, size) } case 3: { // CATransform3D (m11, m12, ..., m44) break } case 4: { // CAPoint3D (x, y, z) return new CGPoint(obj.x, obj.y) } case 5: { // CADoublePoint (x, y) return new CGPoint(obj.x, obj.y) } case 6: { // CADoubleSize (width, height) return new CGSize(obj.width, obj.height) } case 7: { // CADoubleRect (x, y, width, height) const point = new CGPoint(obj.x, obj.y) const size = new CGSize(obj.width, obj.height) return new CGRect(point, size) } case 8: { // CAColorMatrix (m11, ..., m15, m21, ..., m45) break } } throw new Error('LKNSValueCodingProxy unsupported type: ' + kind) } /** * constructor * @access public * @constructor */ constructor() { super() } }
magicien/JSceneKit
src/js/QuartzCore/LKNSValueCodingProxy.js
JavaScript
mit
1,758
//= require angular //= require angular-ui-router //= require angular-resource //= require angular-rails-templates //= require chart.js/dist/Chart.js //= require angular-chart.js/dist/angular-chart.js //= require_tree .
tejbans/expensio
app/assets/javascripts/application.js
JavaScript
mit
219
'use strict'; exports.__esModule = true; var _curry2 = require('fj-curry'); var bind = function bind(context, fn) { return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return fn.apply(context, args); }; }; exports['default'] = _curry2.curry2(bind); module.exports = exports['default']; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGV4LmVzNiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7O3NCQUF1QixVQUFVOztBQUVqQyxJQUFJLElBQUksR0FBRyxjQUFDLE9BQU8sRUFBRSxFQUFFLEVBQUs7QUFDMUIsU0FBTztzQ0FBSSxJQUFJO0FBQUosVUFBSTs7O1dBQUssRUFBRSxDQUFDLEtBQUssQ0FBQyxPQUFPLEVBQUUsSUFBSSxDQUFDO0dBQUEsQ0FBQztDQUM3QyxDQUFDOztxQkFFYSxRQU5OLE1BQU0sQ0FNTyxJQUFJLENBQUMiLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgeyBjdXJyeTIgfSBmcm9tICdmai1jdXJyeSc7XG5cbmxldCBiaW5kID0gKGNvbnRleHQsIGZuKSA9PiB7XG4gIHJldHVybiAoLi4uYXJncykgPT4gZm4uYXBwbHkoY29udGV4dCwgYXJncyk7XG59O1xuXG5leHBvcnQgZGVmYXVsdCBjdXJyeTIoYmluZCk7XG4iXSwic291cmNlUm9vdCI6Ii9zb3VyY2UvIn0=
fp-js/fj-bind
index.js
JavaScript
mit
1,083
/** * @callback Phaser.Sound.Types.EachActiveSoundCallback * @since 3.0.0 * * @param {Phaser.Sound.BaseSoundManager} manager - The SoundManager * @param {Phaser.Sound.BaseSound} sound - The current active Sound * @param {number} index - The index of the current active Sound * @param {Phaser.Sound.BaseSound[]} sounds - All sounds */
englercj/phaser
src/sound/typedefs/EachActiveSoundCallback.js
JavaScript
mit
342
/** * author: Storm * date: 2017/03/31 */ import col from './col.vue'; export default col;
wenyejie/trading-tiger
src/components/col/index.js
JavaScript
mit
95
'use strict' const Sequelize = require('sequelize') module.exports = db => db.define('products', { name: { type: Sequelize.STRING, allowNull: false, validate: { notEmpty: true, } }, category: { type: Sequelize.STRING, allowNull: false }, price: { type: Sequelize.INTEGER, allowNull: false, validate: { min: 0 } }, images: { type: Sequelize.ARRAY(Sequelize.STRING), }, color: { type: Sequelize.ARRAY(Sequelize.STRING), allowNull: false }, size: { type: Sequelize.ARRAY(Sequelize.STRING), allowNull: false }, quantity: { type: Sequelize.INTEGER, validate: { isInt: true, min: 0 } }, reviewStars: { type: Sequelize.DECIMAL(2, 1) }, description: { type: Sequelize.TEXT, allowNull: false } }) module.exports.associations = (Product, { Review }) => { Product.hasMany(Review) }
GraceShopper/LisasBikes
db/models/product.js
JavaScript
mit
921
var dir_b2f33c71d4aa5e7af42a1ca61ff5af1b = [ [ "ogregraphics", "dir_b044d5385d7e8df2e7c9615f57d442dc.html", "dir_b044d5385d7e8df2e7c9615f57d442dc" ] ];
HATtrick-games/ICT312
html/html/dir_b2f33c71d4aa5e7af42a1ca61ff5af1b.js
JavaScript
mit
155
var uuid = require('node-uuid'); var Q = require('q'); var _ = require('lodash'); var config = require('../../config'); var couchHelper = require('../../lib/couch.helper'); var db = require('../../lib/dbconnect')(config); var type = "report"; var joiHelper = require('../../lib/joi.helper'); module.exports = { add_report: add_report, get_reports_by_type: get_reports_by_type, get_reports_by_time: get_reports_by_time }; function add_report(reportType, entry, operation) { entry.reportType = reportType; entry.operation = operation; entry.timestamp = new Date(); entry.type = type; if(reportType === "product") { entry.product_id = entry.id; entry.product_rev = entry.rev; } else { entry.user_id = entry.id; entry.user_rev = entry.rev; } delete entry.id; delete entry.rev; var q = Q.defer(); db.insert(entry, uuid.v1(), function(err, variable) { if (err) { q.reject({ error: 'Something is wrong.' }); } else { q.resolve(); } }); return q.promise; } function get_reports_by_type(type) { var q = Q.defer(); var query = {include_docs: true}; db.view('report', 'getAllReports', query, function(err, body) { if (err) { q.reject(err); return; } var obj = []; var body = couchHelper.onlyDocs(body); for(var i = 0; i < body.length; i++) { if(body[i].reportType === type) { obj.push(body[i]); } } q.resolve(obj); }); return q.promise; } function get_reports_by_time(from, to, type) { var q = Q.defer(); var query = {include_docs: true}; db.view('report', 'getAllReports', query, function(err, body) { if (err) { q.reject(err); return; } var obj = []; var body = couchHelper.onlyDocs(body); for(var i = 0; i < body.length; i++) { var compare = new Date(body[i].timestamp.substring(0, 10).split("-").reverse().join("-")).getTime() / 1000; if(compare >= from && compare <= to && body[i].reportType === type) { obj.push(body[i]); } } q.resolve(obj); }); return q.promise; }
FFNascimento/sportsnow
features/report/reportModel.js
JavaScript
mit
2,292
/*! @Name: SI @Info: Sivona.js的命名空间,以及新画布的构造函数 @Type: Namespace & Method @Params: - id {string} 画布插入位置 - w {number} 画布宽度(可选 默认为浏览器窗口宽度) - h {number} 画布高度(可选 默认为浏览器窗口高度) - t {number} 画布位置top值 - l {number} 画布位置left值 @Return: - {instance} Paper对象的实例 @Usage: | var paper = SI('div1', 100, 200); | paper.rect(...); */ var SI = function(id, w, h, t, l){ return new SI.Paper(id, w, h, t, l); }, _uniqId = 0;
x6doooo/Sivona.js
src/sivona.init.js
JavaScript
mit
621
var cli = require ('./cli-no-color'); exports.create = function () { return cli.create({ colorize: false, hideValid: true }); };
sdolard/node-jsrevival
lib/reporter/cli-hide-valid-no-color.js
JavaScript
mit
139
'use strict' // app // external modules var express = require('express') var ejs = require('ejs') var passport = require('passport') var methodOverride = require('method-override') var cookieParser = require('cookie-parser') var compression = require('compression') var session = require('express-session') var SequelizeStore = require('connect-session-sequelize')(session.Store) var fs = require('fs') var path = require('path') var morgan = require('morgan') var passportSocketIo = require('passport.socketio') var helmet = require('helmet') var i18n = require('i18n') var flash = require('connect-flash') // core var config = require('./lib/config') var logger = require('./lib/logger') var response = require('./lib/response') var models = require('./lib/models') // generate front-end constants by template var constpath = path.join(__dirname, './public/js/lib/common/constant.ejs') var data = { domain: config.domain, urlpath: config.urlpath, debug: config.debug, version: config.version, GOOGLE_API_KEY: config.google.clientSecret, GOOGLE_CLIENT_ID: config.google.clientID, DROPBOX_APP_KEY: config.dropbox.clientSecret } ejs.renderFile(constpath, data, {}, function (err, str) { if (err) throw new Error(err) fs.writeFileSync(path.join(__dirname, './public/build/constant.js'), str) }) // server setup var app = express() var server = null if (config.usessl) { var ca = (function () { var i, len, results results = [] for (i = 0, len = config.sslcapath.length; i < len; i++) { results.push(fs.readFileSync(config.sslcapath[i], 'utf8')) } return results })() var options = { key: fs.readFileSync(config.sslkeypath, 'utf8'), cert: fs.readFileSync(config.sslcertpath, 'utf8'), ca: ca, dhparam: fs.readFileSync(config.dhparampath, 'utf8'), requestCert: false, rejectUnauthorized: false } server = require('https').createServer(options, app) } else { server = require('http').createServer(app) } // logger app.use(morgan('combined', { 'stream': logger })) // socket io var io = require('socket.io')(server) io.engine.ws = new (require('uws').Server)({ noServer: true, perMessageDeflate: false }) // others var realtime = require('./lib/realtime.js') // assign socket io to realtime realtime.io = io // methodOverride app.use(methodOverride('_method')) // session store var sessionStore = new SequelizeStore({ db: models.sequelize }) // compression app.use(compression()) // use hsts to tell https users stick to this app.use(helmet.hsts({ maxAge: 31536000 * 1000, // 365 days includeSubdomains: true, preload: true })) i18n.configure({ locales: ['en', 'zh', 'fr', 'de', 'ja', 'es', 'ca', 'el', 'pt', 'it', 'tr', 'ru', 'nl', 'hr', 'pl', 'uk', 'hi', 'sv', 'eo', 'da'], cookie: 'locale', directory: path.join(__dirname, '/locales') }) app.use(cookieParser()) app.use(i18n.init) // routes without sessions // static files app.use('/', express.static(path.join(__dirname, '/public'), { maxAge: config.staticcachetime })) // session app.use(session({ name: config.sessionname, secret: config.sessionsecret, resave: false, // don't save session if unmodified saveUninitialized: true, // always create session to ensure the origin rolling: true, // reset maxAge on every response cookie: { maxAge: config.sessionlife }, store: sessionStore })) // session resumption var tlsSessionStore = {} server.on('newSession', function (id, data, cb) { tlsSessionStore[id.toString('hex')] = data cb() }) server.on('resumeSession', function (id, cb) { cb(null, tlsSessionStore[id.toString('hex')] || null) }) // middleware which blocks requests when we're too busy app.use(require('./lib/web/middleware/tooBusy')) app.use(flash()) // passport app.use(passport.initialize()) app.use(passport.session()) // check uri is valid before going further app.use(require('./lib/web/middleware/checkURIValid')) // redirect url without trailing slashes app.use(require('./lib/web/middleware/redirectWithoutTrailingSlashes')) // routes need sessions // template files app.set('views', path.join(__dirname, '/public/views')) // set render engine app.engine('ejs', ejs.renderFile) // set view engine app.set('view engine', 'ejs') app.use(require('./lib/web/baseRouter')) app.use(require('./lib/web/statusRouter')) app.use(require('./lib/web/auth')) app.use(require('./lib/web/historyRouter')) app.use(require('./lib/web/userRouter')) app.use(require('./lib/web/imageRouter')) app.use(require('./lib/web/noteRouter')) // response not found if no any route matxches app.get('*', function (req, res) { response.errorNotFound(res) }) // socket.io secure io.use(realtime.secure) // socket.io auth io.use(passportSocketIo.authorize({ cookieParser: cookieParser, key: config.sessionname, secret: config.sessionsecret, store: sessionStore, success: realtime.onAuthorizeSuccess, fail: realtime.onAuthorizeFail })) // socket.io heartbeat io.set('heartbeat interval', config.heartbeatinterval) io.set('heartbeat timeout', config.heartbeattimeout) // socket.io connection io.sockets.on('connection', realtime.connection) // listen function startListen () { server.listen(config.port, function () { var schema = config.usessl ? 'HTTPS' : 'HTTP' logger.info('%s Server listening at port %d', schema, config.port) realtime.maintenance = false }) } // sync db then start listen models.sequelize.sync().then(function () { // check if realtime is ready if (realtime.isReady()) { models.Revision.checkAllNotesRevision(function (err, notes) { if (err) throw new Error(err) if (!notes || notes.length <= 0) return startListen() }) } else { throw new Error('server still not ready after db synced') } }) // log uncaught exception process.on('uncaughtException', function (err) { logger.error('An uncaught exception has occured.') logger.error(err) logger.error('Process will exit now.') process.exit(1) }) // install exit handler function handleTermSignals () { logger.info('hackmd has been killed by signal, try to exit gracefully...') realtime.maintenance = true // disconnect all socket.io clients Object.keys(io.sockets.sockets).forEach(function (key) { var socket = io.sockets.sockets[key] // notify client server going into maintenance status socket.emit('maintenance') setTimeout(function () { socket.disconnect(true) }, 0) }) var checkCleanTimer = setInterval(function () { if (realtime.isReady()) { models.Revision.checkAllNotesRevision(function (err, notes) { if (err) return logger.error(err) if (!notes || notes.length <= 0) { clearInterval(checkCleanTimer) return process.exit(0) } }) } }, 100) } process.on('SIGINT', handleTermSignals) process.on('SIGTERM', handleTermSignals) process.on('SIGQUIT', handleTermSignals)
ironhack/hackmd
app.js
JavaScript
mit
6,908
"use strict"; var exports = module.exports = {}; var express = require('express'); var router = express.Router(); var passport = require('passport'); var XingStrategy = require('passport-xing').Strategy; var session = require('express-session'); var loginRequired = require("../middleware/loginRequired"); const config = require("../config.js"); const winston = require("winston"); //XING API keys var XING_API_KEY = config.XING_CONFIG.consumerKey; var XING_SECRET_KEY = config.XING_CONFIG.consumerSecret; // Passport session setup. // To support persistent login sessions, Passport needs to be able to // serialize users into and deserialize users out of the session. Typically, // this will be as simple as storing the user ID when serializing, and finding // the user by ID when deserializing. However, since this example does not // have a database of user records, the complete Xing profile is // serialized and deserialized. passport.serializeUser(function (user, done) { done(null, user); }); passport.deserializeUser(function (obj, done) { done(null, obj); }); // Use the XingStrategy within Passport. // Strategies in passport require a `verify` function, which accept // credentials (in this case, a token, tokenSecret, and Xing profile), and // invoke a callback with a user object. passport.use(new XingStrategy({ consumerKey: XING_API_KEY, consumerSecret: XING_SECRET_KEY, callbackURL: "http://localhost:" + config.LISTEN_PORT + "/xing/auth/xing/callback", state: "abc" }, function (token, tokenSecret, profile, done) { // asynchronous verification, for effect... process.nextTick(function () { // To keep the example simple, the user's Xing profile is returned to // represent the logged-in user. In a typical application, you would want // to associate the Xing account with a user record in your database, // and return that user instead. winston.info(JSON.stringify(profile)); winston.info(profile.displayName); winston.info(profile.resourceTags); console.log("xing token: " + token); console.log("xing tokenSecret: " + tokenSecret); return done(null, false);// profile); //1. user + serviceUserId exists -> no problem //2. no user -> no problem //3. user but no serviceUserId -> !?!?!? }); } )); router.get('/', loginRequired, function (req, res) { winston.info("xing /"); res.render('linkedService/xing', {user: req.user}); }); router.get('/account', loginRequired, function (req, res) { winston.info("xing /account"); winston.info(req.getAllInfo()); res.render('linkedService/xing', {user: req.user}); }); router.get('/login', loginRequired, function (req, res) { winston.info("xing /login"); res.render('linkedService/xing', {user: req.user}); }); // GET /auth/xing // Use passport.authenticate() as route middleware to authenticate the // request. The first step in Xing authentication will involve // redirecting the user to xing.com. After authorization, Xing will // redirect the user back to this application at /auth/xing/callback router.get('/auth/xing', loginRequired, passport.authenticate('xing'), function (req, res) { winston.info("xing /auth/xing"); // The request will be redirected to Xing for authentication, so this // function will not be called. }); // GET /auth/xing/callback // Use passport.authenticate() as route middleware to authenticate the // request. If authentication fails, the user will be redirected back to the // login page. Otherwise, the primary route function function will be called, // which, in this example, will redirect the user to the home page. router.get('/auth/xing/callback', function (req, res) { console.log("adada"); }); router.get('/logout', loginRequired, function (req, res) { req.logout(); res.redirect('/'); }); // Simple route middleware to ensure user is authenticated. // Use this route middleware on any resource that needs to be protected. If // the request is authenticated (typically via a persistent login session), // the request will proceed. Otherwise, the user will be redirected to the // login page. function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('linkedService/xing'); } module.exports = router;
ScJa/projectr
web/app/linkedServices/xing.js
JavaScript
mit
4,546
(function() { 'use strict'; angular.module('engine.app', [ 'ngStorage', 'engine.app.render', 'engine.app.authorisation', 'engine.app.directives', 'engine.app.services' ]); })();
team-codetown/Arren-Drifter
src/engine/app/appModule.js
JavaScript
mit
231
(function () { "use strict"; angular.module('endo') .controller("EventController", EventController); function EventController(Event) { var vm = this; vm.mouseenter = function () { vm.hover = true; }; vm.mouseleave = function () { vm.hover = false; }; vm.remove = function (ev) { console.log(ev); Event.remove(ev); }; } })();
enzosv/encal
src/js/calendar/EventController.js
JavaScript
mit
360
// Regular expression that matches all symbols in the `Deseret` script as per Unicode v4.1.0: /\uD801[\uDC00-\uDC4F]/;
mathiasbynens/unicode-data
4.1.0/scripts/Deseret-regex.js
JavaScript
mit
118
'use strict'; define(['angular'], function (ng) { //get module definations var module = ng.module(APP_MODULES.AUTH.name); //attached all recipies of angular module.config([ '$controllerProvider', '$compileProvider', '$filterProvider', '$provide', function ($controllerProvider, $compileProvider, $filterProvider, $provide) { // lazy controller, directive and service module.controller = $controllerProvider.register; module.directive = $compileProvider.directive; module.filter = $filterProvider.register; module.factory = $provide.factory; module.service = $provide.service; module.constant = $provide.constant; module.value = $provide.value; } ]); });
mdshohelrana/AngularJSArchitecture
src/app/auth/auth.config.js
JavaScript
mit
800
/* * getobject * https://github.com/cowboy/node-getobject * * Copyright (c) 2013 "Cowboy" Ben Alman * Licensed under the MIT license. */ 'use strict'; var getobject = module.exports = {}; // Split strings on dot, but only if dot isn't preceded by a backslash. Since // JavaScript doesn't support lookbehinds, use a placeholder for "\.", split // on dot, then replace the placeholder character with a dot. function getParts(str) { return str.replace(/\\\./g, '\uffff').split('.').map(function(s) { return s.replace(/\uffff/g, '.'); }); } // Get the value of a deeply-nested property exist in an object. getobject.get = function(obj, parts, create) { if (typeof parts === 'string') { parts = getParts(parts); } var part; while (typeof obj === 'object' && obj && parts.length) { part = parts.shift(); if (!(part in obj) && create) { obj[part] = {}; } obj = obj[part]; } return obj; }; // Set a deeply-nested property in an object, creating intermediary objects // as we go. getobject.set = function(obj, parts, value) { parts = getParts(parts); if (parts.includes('__proto__')) { // do not allow setting of __proto__. See CVE-2020-28282. return; } var prop = parts.pop(); obj = getobject.get(obj, parts, true); if (obj && typeof obj === 'object') { return (obj[prop] = value); } }; // Does a deeply-nested property exist in an object? getobject.exists = function(obj, parts) { parts = getParts(parts); var prop = parts.pop(); obj = getobject.get(obj, parts); return typeof obj === 'object' && obj && prop in obj; };
cowboy/node-getobject
lib/getobject.js
JavaScript
mit
1,610
jQuery(function () { jsKeyboard.init("virtualKeyboard"); //first input focus var $firstInput =jQuery(':input').first().focus(); jsKeyboard.currentElement = $firstInput; jsKeyboard.currentElementCursorPosition = 0; });
solgenomics/sgn
js/source/legacy/main.js
JavaScript
mit
274
$(function () { var domId = '#poll-options' // controlls the limits the of poll options $(domId).on('cocoon:after-insert', function () { checkToHideOrShowAddLink() }) $(domId).on('cocoon:after-remove', function () { checkToHideOrShowAddLink() }) checkToHideOrShowAddLink() function checkToHideOrShowAddLink () { if ($(domId + ' .nested-fields').length <= 2) { $(domId + ' a.remove_fields').hide() } else { $(domId + ' a.remove_fields').show() } if ($(domId + ' .nested-fields').length >= 10) { $(domId + ' a.add_fields').hide() } else { $(domId + ' a.add_fields').show() } } })
cyclestreets/cyclescape
app/assets/javascripts/cocoon_fields.js
JavaScript
mit
656
(function(init){ // deps if ( typeof module === 'object' && module && typeof module.exports === 'object' ) { // node module.exports = init( require('./include/jquery'), require('./include/jquery-ui'), require('./parser'), require('./log').log ); } else if ( typeof define === 'function' && define.amd ) { // "amd" (require.js) define( ['jquery', 'jquery-ui', './parser', './log'], function ($, jqueryui, parser, log) { return init($, jqueryui, parser, log.log); }); } })(function($, jqueryui, parser, log){ // init var _config = {}; var configroot = 'rex-config'; var configlabels = ['rex-ordering', 'rex-primaries']; var load = function loadconfig(tree) { for(var i = 0; i < configlabels.length; i++) { _config[configlabels[i]] = []; } if( tree[configroot] ) { loadconfiginner(tree[configroot]); } else { loadconfiginner(tree); } }; var loadconfiginner = function loadconfiginner(tree) { if( tree instanceof Array ) { for( var i = 0; i < tree.length; i++ ) { loadconfiginner(tree[i]); } return; } if( tree instanceof Object ) { for( var key in tree ) { if( $.inArray(key, configlabels) > -1) { _config[key] = tree[key]; delete tree[key]; } else { loadconfiginner(tree[key]); } } } }; var getconfig = function getconfig() { return $.extend(true, {}, _config); }; var forkey = function forkey(key) { return _config[key]; }; return { // interface 'load' : load, 'get' : getconfig, 'forkey' : forkey, 'configroot' : configroot, }; });
ibiwan/drects-node
public/config.js
JavaScript
mit
2,215
import { assign, merge } from 'lodash'; import { transform } from '@babel/core'; import ESNextTestFileCompiler from './compiler'; import { TestFileParserBase } from '../../test-file-parser-base'; const TOKEN_TYPE = { Identifier: 'Identifier', PropertyAccessExpression: 'MemberExpression', CallExpression: 'CallExpression', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateLiteral: 'TemplateLiteral', StringLiteral: 'StringLiteral', ArrowFunctionExpression: 'ArrowFunctionExpression', FunctionExpression: 'FunctionExpression', ExpressionStatement: 'ExpressionStatement', ReturnStatement: 'ReturnStatement', FunctionDeclaration: 'FunctionDeclaration', VariableStatement: 'VariableStatement', VariableDeclaration: 'VariableDeclaration', ObjectLiteralExpression: 'ObjectExpression' }; export class EsNextTestFileParser extends TestFileParserBase { constructor () { super(TOKEN_TYPE); } static getTagStrValue (exp) { //NOTE: we set <computed name> if template literal has at least one computed substring ${...} return exp.expressions.length ? EsNextTestFileParser.formatComputedName(exp.loc.start.line) : exp.quasis[0].value.raw; } isAsyncFn (token) { return token.async || token.generator; } getTokenType (token) { return token.type; } getRValue (token) { return token.declarations[0].init; } getStringValue (token) { const stringTypes = [this.tokenType.StringLiteral, this.tokenType.TemplateLiteral, this.tokenType.Identifier]; if (stringTypes.indexOf(token.type) > -1) return this.formatFnArg(token); return null; } getFunctionBody (token) { return token.body && token.body.body ? token.body.body : []; } getCalleeToken (token) { return token.callee; } getMemberFnName (token) { return token.callee.property.name; } formatFnData (name, value, token, meta = [{}]) { return { fnName: name, value: value, loc: token.loc, start: token.start, end: token.end, meta: merge({}, ...meta) }; } getKeyValue (prop) { const { key, value } = prop; return { key: key.name || this.formatFnArg(key), value: this.getStringValue(value) }; } analyzeMemberExp (token) { let exp = token; const tokenType = this.tokenType; const callStack = [exp]; while (exp.type !== tokenType.Identifier) { if (exp.type === tokenType.CallExpression) exp = exp.callee; else if (exp.type === tokenType.PropertyAccessExpression) exp = exp.object; else if (exp.type === tokenType.TaggedTemplateExpression) exp = exp.tag; else return null; if (exp.type !== tokenType.Identifier) callStack.push(exp); } if (!this.isApiFn(exp.name)) return null; const meta = this.getMetaInfo(callStack.slice()); let parentExp = callStack.pop(); if (parentExp.type === tokenType.CallExpression) return this.formatFnData(exp.name, this.formatFnArg(parentExp.arguments[0]), token, meta); if (parentExp.type === tokenType.TaggedTemplateExpression) return this.formatFnData(exp.name, EsNextTestFileParser.getTagStrValue(parentExp.quasi), token, meta); if (parentExp.type === tokenType.PropertyAccessExpression) { while (parentExp) { if (parentExp.type === tokenType.CallExpression && parentExp.callee) { const calleeType = parentExp.callee.type; const calleeMemberFn = parentExp.callee.property && parentExp.callee.property.name; if (this.checkExpDefineTargetName(calleeType, calleeMemberFn)) return this.formatFnData(exp.name, this.formatFnArg(parentExp.arguments[0]), token, meta); } if (parentExp.type === tokenType.TaggedTemplateExpression && parentExp.tag) { const tagType = parentExp.tag.type; const tagMemberFn = parentExp.tag.property && parentExp.tag.property.name; if (this.checkExpDefineTargetName(tagType, tagMemberFn)) return this.formatFnData(exp.name, EsNextTestFileParser.getTagStrValue(parentExp.quasi), token, meta); } parentExp = callStack.pop(); } } return null; } formatFnArg (arg) { if (arg.type === this.tokenType.Identifier) return EsNextTestFileParser.formatComputedName(arg.loc.start.line); if (arg.type === this.tokenType.TemplateLiteral) return EsNextTestFileParser.getTagStrValue(arg); if (arg.type === this.tokenType.StringLiteral) return arg.value; return null; } getFnCall (token) { if (!this.isApiFn(token.callee.name)) return null; return this.formatFnData(token.callee.name, this.formatFnArg(token.arguments[0]), token); } getTaggedTemplateExp (token) { return this.formatFnData(token.tag.name, EsNextTestFileParser.getTagStrValue(token.quasi), token); } analyzeFnCall (token) { const tokenType = this.tokenType; if (token.type === tokenType.PropertyAccessExpression) return this.analyzeMemberExp(token); if (token.type === tokenType.CallExpression) { const calleeType = token.callee.type; if (calleeType === tokenType.PropertyAccessExpression || calleeType === tokenType.CallExpression) return this.analyzeMemberExp(token); if (calleeType === tokenType.FunctionExpression || calleeType === tokenType.ArrowFunctionExpression) return this.collectTestCafeCalls(token.callee.body.body); return this.getFnCall(token); } if (token.type === tokenType.TaggedTemplateExpression) { if (token.tag.type === tokenType.PropertyAccessExpression) return this.analyzeMemberExp(token); return this.getTaggedTemplateExp(token); } return null; } parse (code) { const compilerOptions = ESNextTestFileCompiler.getBabelOptions(null, code); delete compilerOptions.filename; const opts = assign(compilerOptions, { ast: true }); const ast = transform(code, opts).ast; return this.analyze(ast.program.body); } } const parser = new EsNextTestFileParser(); export const getTestList = parser.getTestList.bind(parser); export const getTestListFromCode = parser.getTestListFromCode.bind(parser);
AndreyBelym/testcafe
src/compiler/test-file/formats/es-next/get-test-list.js
JavaScript
mit
7,015
'use strict'; /*global require*/ /************************************************************************ ## Modules in Scriptcraft ScriptCraft has a simple module loading system. In ScriptCraft, files and modules are in one-to-one correspondence. As an example, foo.js loads the module circle.js in the same directory. *ScriptCraft now uses the same module system as Node.js - see [Node.js Modules][njsmod] for more details.* [njsmod]: http://nodejs.org/api/modules.html The contents of foo.js: ```javascript var circle = require('./circle.js'); console.log( 'The area of a circle of radius 4 is ' + circle.area(4)); ``` The contents of circle.js: ```javascript var PI = Math.PI; exports.area = function (r) { return PI * r * r; }; exports.circumference = function (r) { return 2 * PI * r; }; ``` The module circle.js has exported the functions area() and circumference(). To add functions and objects to the root of your module, you can add them to the special exports object. Variables local to the module will be private, as though the module was wrapped in a function. In this example the variable PI is private to circle.js. If you want the root of your module's export to be a function (such as a constructor) or if you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports instead of exports. ## Module Loading When the ScriptCraft Java plugin is first installed, a new `scriptcraft` subdirectory is created. If your minecraft server directory is called 'mcserver' then the new subdirectories will be ... * mcserver/scriptcraft/ * mcserver/scriptcraft/plugins * mcserver/scriptcraft/modules * mcserver/scriptcraft/lib ... The `plugins`, `modules` and `lib` directories each serve a different purpose. ### The plugins directory At server startup the ScriptCraft Java plugin is loaded and begins automatically loading and executing all of the modules (javascript files with the extension `.js`) it finds in the `scriptcraft/plugins` directory. All modules in the plugins directory are automatically loaded into the `global` namespace. What this means is that anything a module in the `plugins` directory exports becomes a global variable. For example, if you have a module greeting.js in the plugins directory.... ```javascript exports.greet = function(player) { echo(player, 'Hello ' + player.name); }; ``` ... then `greet` becomes a global function and can be used at the in-game (or server) command prompt like so... /js greet(self) ... This differs from how modules (in NodeJS and commonJS environments) normally work. If you want your module to be exported globally, put it in the `plugins` directory. If you don't want your module to be exported globally but only want it to be used by other modules, then put it in the `modules` directory instead. If you've used previous versions of ScriptCraft and have put your custom javascript modules in the `js-plugins` directory, then put them in the `scriptcraft/plugins` directory. To summarise, modules in this directory are ... * Automatically loaded and run at server startup. * Anything exported by modules becomes a global variable. ### The modules directory The module directory is where you should place your modules if you don't want to export globally. In javascript, it's considered best practice not to have too many global variables, so if you want to develop modules for others to use, or want to develop more complex mods then your modules should be placed in the `modules` directory. *Modules in the `modules` directory are not automatically loaded at startup*, instead, they are loaded and used by other modules/plugins using the standard `require()` function. This is the key difference between modules in the `plugins` directory and modules in the `modules` directory. Modules in the `plugins` directory are automatically loaded and exported in to the global namespace at server startup, modules in the `modules` directory are not. ### The lib directory Modules in the `lib` directory are for use by ScriptCraft and some core functions for use by module and plugin developers are also provided. The `lib` directory is for internal use by ScriptCraft. Modules in this directory are not automatically loaded nor are they globally exported. ### plugins sub-directories As of December 24 2013, the `scriptcraft/plugins` directory has the following sub-directories... * drone - Contains the drone module and drone extensions. Drone was the first scriptcraft module. * mini-games - Contains mini-games * arrows - The arrows module - Changes the behaviour of Arrows: Explosive, Fireworks, Teleportation etc. * signs - The signs module (includes example signs) - create interactive signs. * chat - The chat plugin/module * alias - The alias plugin/module - for creating custom aliases for commonly-used commands. * home - The home module - for setting homes and visiting other homes. ## Global variables There are a couple of special javascript variables available in ScriptCraft... ### __plugin variable The ScriptCraft JavaPlugin object. ### server variable The Minecraft Server object ### self variable The current player. (Note - this value should not be used in multi-threaded scripts or event-handling code - it's not thread-safe). This variable is only safe to use at the in-game prompt and should *never* be used in modules. For example you can use it here... /js console.log(self.name) ... but not in any javascript module you create yourself or in any event handling code. `self` is a temporary short-lived variable which only exists in the context of the in-game or server command prompts. ### config variable ScriptCraft configuration - this object is loaded and saved at startup/shutdown. ### events variable The events object is used to add new event handlers to Minecraft. ## Module variables The following variables are available only within the context of Modules. (not available at in-game prompt). ### &#95;&#95;filename variable The current file - this variable is only relevant from within the context of a Javascript module. ### &#95;&#95;dirname variable The current directory - this variable is only relevant from within the context of a Javascript module. ## Global functions ScripCraft provides some global functions which can be used by all plugins/modules... ### echo function The `echo()` function displays a message on the in-game screen. #### Example /js echo( self, 'Hello World') For programmers familiar with Javascript web programming, an `alert` function is also provided. `alert` works exactly the same as `echo` e.g. `alert( self, 'Hello World')`. ### require() function ScriptCraft's `require()` function is used to load modules. The `require()` function takes a module name as a parameter and will try to load the named module. #### Parameters * modulename - The name of the module to be loaded. Can be one of the following... - A relative file path (with or without `.js` suffix) - An absolute file path (with or without `.js` suffix) - A relative directory path (uses node.js rules for directories) - An absolute directory path (uses node.js rules for directories) - A name of the form `'events'` - in which case the `lib` directory and `modules` directories are searched for the module. #### Return require() will return the loaded module's exports. ### scload() function #### No longer recommended for use by Plugin/Module developers (deprecated) scload() should only be used to load .json data. #### Parameters * filename - The name of the file to load. * warnOnFileNotFound (optional - default: false) - warn if the file was not found. #### Returns scload() will return the result of the last statement evaluated in the file. #### Example scload("myFile.js"); // loads a javascript file and evaluates it. var myData = scload("myData.json"); // loads a javascript file and evaluates it - eval'd contents are returned. ##### myData.json contents... { players: { walterh: { h: ["jsp home {1}"], sunny:["time set 0", "weather clear"] } } } ### scsave() function The scsave() function saves an in-memory javascript object to a specified file. Under the hood, scsave() uses JSON (specifically json2.js) to save the object. There will usually be no need to call this function directly - If you want to have a javascript object automatically loaded at startup and saved on shutdown then use the `persist()` module. The `persist()` module uses scsave and scload under the hood. Any in-memory object saved using the `scsave()` function can later be restored using the `scload()` function. #### Parameters * objectToSave : The object you want to save. * filename : The name of the file you want to save it to. #### Example ```javascript var myObject = { name: 'John Doe', aliases: ['John Ray', 'John Mee'], date_of_birth: '1982/01/31' }; scsave(myObject, 'johndoe.json'); ``` ##### johndoe.json contents... { "name": "John Doe", "aliases": ["John Ray", "John Mee"], "date_of_birth": "1982/01/31" }; ### plugin() function #### Update April 2015 The `plugin()` function is deprecated. Please refer to [Anatomy of a ScriptCraft Plugin][anatomy] for an up-to-date step-by-step guide to creating a plugin which uses persistence (loading and saving data). #### Deprecated The `plugin()` function should be used to declare a javascript module whose state you want to have managed by ScriptCraft - that is - a Module whose state will be loaded at start up and saved at shut down. A plugin is just a regular javascript object whose state is managed by ScriptCraft. The only member of the plugin which whose persistence is managed by Scriptcraft is `store` - this special member will be automatically saved at shutdown and loaded at startup by ScriptCraft. This makes it easier to write plugins which need to persist data. #### Parameters * pluginName (String) : The name of the plugin - this becomes a global variable. * pluginDefinition (Object) : The various functions and members of the plugin object. * isPersistent (boolean - optional) : Specifies whether or not the plugin/object state should be loaded and saved by ScriptCraft. #### Example See chat/color.js for an example of a simple plugin - one which lets players choose a default chat color. See also [Anatomy of a ScriptCraft Plugin][anatomy]. [anatomy]: ./Anatomy-of-a-Plugin.md ### command() function The `command()` function is used to expose javascript functions for use by non-operators (regular players). Only operators should be allowed use raw javascript using the `/js ` command because it is too powerful for use by regular players and can be easily abused. However, the `/jsp ` command lets you (the operator / server administrator / plugin author) safely expose javascript functions for use by players. #### Parameters * commandFunction: The named javascript function which will be invoked when the command is invoked by a player. The name of the function will be used as the command name so name this function accordingly. The callback function in turn takes 2 parameters... * params : An Array of type String - the list of parameters passed to the command. * sender : The [CommandSender][bukcs] object that invoked the command (this is usually a Player object but can be a Block ([BlockCommandSender][bukbcs]). * options (Array|Function - optional) : An array of command options/parameters which the player can supply (It's useful to supply an array so that Tab-Completion works for the `/jsp ` commands. If a function is supplied instead of an array then the function will be invoked at TAB-completion time and should return an array of strings. * intercepts (boolean - optional) : Indicates whether this command can intercept Tab-Completion of the `/jsp ` command - advanced usage - see alias/alias.js for example. #### Example // javascript code function boo( params, sender) { echo( sender, params[0] ); } command( boo ); # in-game execution /jsp boo Hi! > Hi! To use a callback for options (TAB-Completion) ... var utils = require('utils'); function boo( params, sender ) { var receiver = server.getPlayer( params[0] ); if ( receiver ){ echo( receiver, sender.name + ' says boo!'); } } command( boo, utils.playerNames ); See chat/colors.js or alias/alias.js or homes/homes.js for more examples of how to use the `command()` function. ### setTimeout() function This function mimics the setTimeout() function used in browser-based javascript. However, the function will only accept a function reference, not a string of javascript code. Where setTimeout() in the browser returns a numeric value which can be subsequently passed to clearTimeout(), This implementation returns an object which can be subsequently passed to ScriptCraft's own clearTimeout() implementation. If Node.js supports setTimeout() then it's probably good for ScriptCraft to support it too. #### Example ```javascript // // start a storm in 5 seconds // setTimeout( function() { var world = server.worlds.get(0); world.setStorm(true); }, 5000); ``` ### clearTimeout() function A scriptcraft implementation of clearTimeout(). ### setInterval() function This function mimics the setInterval() function used in browser-based javascript. However, the function will only accept a function reference, not a string of javascript code. Where setInterval() in the browser returns a numeric value which can be subsequently passed to clearInterval(), This implementation returns an object which can be subsequently passed to ScriptCraft's own clearInterval() implementation. ### clearInterval() function A scriptcraft implementation of clearInterval(). ### refresh() function The refresh() function can be used to only reload the ScriptCraft plugin (it's like the `reload` command except it only reloads ScriptCraft). The refresh() function will ... 1. Disable the ScriptCraft plugin. 2. Unload all event listeners associated with the ScriptCraft plugin. 3. Cancel all timed tasks (created by `setInterval` & `setTimeout`) 3. Enable the ScriptCraft plugin. ... refresh() can be used during development to reload only scriptcraft javascript files. See [issue #69][issue69] for more information. By default, if `self` is defined at runtime, it checks, whether `self` is server operator, otherwise fails with message. This behavivor can be modified using `skipOpCheck` parameter (useful, if you are doing some custom premission checks before calling this function). #### Parameters * skipOpCheck (boolean - optional) : If true, the function won't check if `self` is server operator. [issue69]: https://github.com/walterhiggins/ScriptCraft/issues/69 ### addUnloadHandler() function The addUnloadHandler() function takes a callback function as a parameter. The callback will be called when the ScriptCraft plugin is unloaded (usually as a result of a a `reload` command or server shutdown). This function provides a way for ScriptCraft modules to do any required cleanup/housekeeping just prior to the ScriptCraft Plugin unloading. ### isOp() function This function takes a single parameter and returns true if it's an operator or has operator-level privileges. ***/ /* wph 20130124 - make self, plugin and server public - these are far more useful now that tab-complete works. */ var global = this; var server; global.nashorn = typeof Java !== 'undefined'; /* private implementation */ var __onDisableImpl; function __onDisable ( __engine, __plugin ) { __onDisableImpl( __engine, __plugin); } function __onEnable ( __engine, __plugin, __script ) { function _echo( ) { var sender, msg; if (arguments.length == 2){ sender = arguments[0]; msg = arguments[1]; } else { if ( typeof self == 'undefined' ) { return; } sender = self; msg = arguments[0]; } if (__plugin.canary){ sender.message( msg ); } else { sender.sendMessage( msg ); } } // end echo() function _canonize( file ) { return '' + file.getCanonicalPath().replaceAll( '\\\\', '/' ); } /* Save a javascript object to a file (saves using JSON notation) */ function _save( objToSave, filename ) { var objectToStr = null, f, out; try { objectToStr = JSON.stringify( objToSave, null, 2 ); } catch( e ) { console.error( 'ERROR: ' + e.getMessage() + ' while saving ' + filename ); return; } f = (filename instanceof File) ? filename : new File(filename); out = new PrintWriter(new FileWriter(f)); out.println( objectToStr ); out.close(); } function _loadJSON( filename ){ var result = null, file = filename, r, reader, br, contents; if ( !( filename instanceof File ) ) { file = new File(filename); } var canonizedFilename = _canonize( file ); if ( file.exists() ) { reader = new FileReader( file ); br = new BufferedReader( reader ); contents = ''; try { while ( (r = br.readLine()) !== null ) { contents += r + '\n'; } result = JSON.parse(contents); } catch ( e ) { logError('Error evaluating ' + canonizedFilename + ', ' + e ); } finally { try { reader.close(); } catch ( re ) { // fail silently on reader close error } } } return result; } /* Load the contents of the file and evaluate as javascript */ function _load( filename, warnOnFileNotFound ) { var result = null, file = filename, r, parent, reader, br, code, wrappedCode; if ( !( filename instanceof File ) ) { file = new File(filename); } var canonizedFilename = _canonize( file ); if ( file.exists() ) { reader = new FileReader( file ); br = new BufferedReader( reader ); code = ''; try { while ( (r = br.readLine()) !== null ) { code += r + '\n'; } wrappedCode = '(' + code + ')'; result = __engine.eval( wrappedCode ); // issue #103 avoid side-effects of || operator on Mac Rhino } catch ( e ) { logError('Error evaluating ' + canonizedFilename + ', ' + e ); } finally { try { reader.close(); } catch ( re ) { // fail silently on reader close error } } } else { if ( warnOnFileNotFound ) { logWarn(canonizedFilename + ' not found' ); } } return result; } // end _load() function _isOp( sender ){ if (__plugin.canary){ return sender.receiverType.name() == 'SERVER' || Canary.ops().isOpped(sender); } else { return sender.op; } } function _refresh( skipOpCheck ) { if (!skipOpCheck && typeof self !== 'undefined') { if (!_isOp(self)) return echo(self, 'Only operators can refresh()'); } if (__plugin.canary){ var pluginName = __plugin.name; Canary.manager().disablePlugin( pluginName ); Canary.manager().enablePlugin( pluginName ); } else { __plugin.pluginLoader.disablePlugin( __plugin ); org.bukkit.event.HandlerList["unregisterAll(org.bukkit.plugin.Plugin)"]( __plugin ); server.scheduler.cancelTasks( __plugin ); __plugin.pluginLoader.enablePlugin( __plugin ); } } // end _refresh() function _onDisable( evt ) { // save config _save( global.config, new File( jsPluginsRootDir, 'data/global-config.json' ) ); _runUnloadHandlers(); } function _addUnloadHandler( f ) { unloadHandlers.push( f ); } function _runUnloadHandlers() { for ( var i = 0; i < unloadHandlers.length; i++ ) { unloadHandlers[i]( ); } } function __onCommand() { var jsArgs = [], i = 0, jsResult, result, cmdName, sender, args, cmd, label, fnBody; if ( __plugin.canary ) { sender = arguments[0]; args = arguments[1]; cmdName = (''+args[0]).toLowerCase().replace(/^\//,''); for ( i = 1; i < args.length ; i++ ) { jsArgs.push( '' + args[i] ); } } else { sender = arguments[0]; cmd = arguments[1]; label = arguments[2]; args = arguments[3]; cmdName = ( '' + cmd.name ).toLowerCase(); for ( ; i < args.length ; i++ ) { jsArgs.push( '' + args[i] ); } } result = false; if (cmdName == 'js') { result = true; fnBody = jsArgs.join(' '); global.self = sender; global.__engine = __engine; try { // cannot rely on native eval in jre7 and jre8 // because ... // js var hearts // js hearts // ... throws an execption ('hearts' is not defined). vars are not sticky in native eval . // jsResult = __engine.eval( fnBody ); if ( typeof jsResult != 'undefined' ) { if ( jsResult == null) { // engine eval will return null even if the result should be undefined // this can be confusing so I think it's better to omit output for this case // sender.sendMessage('(null)'); } else { try { if ( isJavaObject(jsResult) || typeof jsResult === 'function') { echo(sender, jsResult); } else { var replacer = function replacer(key, value){ return this[key] instanceof java.lang.Object ? '' + this[key] : value; }; echo(sender, JSON.stringify( jsResult, replacer, 2) ); } } catch ( displayError ) { logError('Error while trying to display result: ' + jsResult + ', Error: '+ displayError) ; } } } } catch ( e ) { logError( 'Error while trying to evaluate javascript: ' + fnBody + ', Error: '+ e ); echo( sender, 'Error while trying to evaluate javascript: ' + fnBody + ', Error: '+ e ); throw e; } finally { /* wph 20140312 don't delete self on nashorn until https://bugs.openjdk.java.net/browse/JDK-8034055 is fixed */ if ( !nashorn ) { delete global.self; delete global.__engine; } } } if ( cmdName == 'jsp' ) { cmdModule.exec( jsArgs, sender ); result = true; } return result; } // end __onCommand() function var Bukkit = null; var Canary = null; var logger = null; if (__plugin.canary){ Canary = Packages.net.canarymod.Canary; server = Canary.server; logger = __plugin.logman; } else { Bukkit = Packages.org.bukkit.Bukkit; server = Bukkit.server; logger = __plugin.logger; } function logError(msg){ __plugin.canary ? logger.error( msg ) : logger.severe( msg ); } function logWarn(msg){ __plugin.canary ? logger.warn( msg ) : logger.warning( msg ); } var File = java.io.File, FileReader = java.io.FileReader, BufferedReader = java.io.BufferedReader, PrintWriter = java.io.PrintWriter, FileWriter = java.io.FileWriter, // assumes scriptcraft.js is in mcserver/plugins/scriptcraft/lib directory jsPluginsRootDir = __script.parentFile.parentFile, jsPluginsRootDirName = _canonize(jsPluginsRootDir), unloadHandlers = []; /* make sure eval is present: it's present on JRE 6, 7, and 8 on Linux */ if ( typeof eval == 'undefined' ) { global.eval = function( str ) { return __engine.eval( str ); }; } /* now that load is defined, use it to load a global config object */ var configFile = new File(jsPluginsRootDir, 'data/'); configFile.mkdirs(); configFile = new File(configFile,'global-config.json'); var config = _load( configFile ); if ( !config ) { config = { verbose: false }; } global.config = config; global.__plugin = __plugin; /* wph 20131229 Issue #103 JSON is not bundled with javax.scripting / Rhino on Mac. */ (function(){ var jsonFileReader = new FileReader( new File( jsPluginsRootDirName + '/lib/json2.js' ) ); var jsonLoaded = __engine['eval(java.io.Reader)']( jsonFileReader ); }()); global.addUnloadHandler = _addUnloadHandler; global.refresh = _refresh; global.echo = _echo; global.alert = _echo; global.scload = _load; global.scsave = _save; global.scloadJSON = _loadJSON; global.isOp = _isOp; var configRequire = _load( jsPluginsRootDirName + '/lib/require.js', true ); /* setup paths to search for modules */ var modulePaths = [ jsPluginsRootDirName + '/lib/', jsPluginsRootDirName + '/modules/' ]; if ( config.verbose ) { logger.info( 'Setting up CommonJS-style module system. Root Directory: ' + jsPluginsRootDirName ); logger.info( 'Module paths: ' + JSON.stringify(modulePaths) ); } var requireHooks = { loading: function( path ) { if ( config.verbose ) { logger.info( 'loading ' + path ); } }, loaded: function( path ) { if ( config.verbose ) { logger.info( 'loaded ' + path ); } } }; global.require = configRequire( jsPluginsRootDirName, modulePaths, requireHooks, function( code ) { return __engine.eval( code ); } ); var testJSPatch = require('js-patch')( global ); var console = require('console')(logger); global.console = console; testJSPatch(console); /* setup persistence */ require('persistence')( jsPluginsRootDir, global ); var isJavaObject = require('java-utils').isJavaObject; var cmdModule = require('command'); global.command = cmdModule.command; var plugins = require('plugin'); global.__onTabComplete = require('tabcomplete'); global.plugin = plugins.plugin; var events = require('events'); // wph 20131226 - make events global as it is used by many plugins/modules global.events = events; if (__plugin.canary) { // canary plugin doesn't get to handle its own plugin disable event } else { events.pluginDisable(_onDisable); } __onDisableImpl = _onDisable; global.__onCommand = __onCommand; plugins.autoload( global, new File(jsPluginsRootDir,'plugins') ); require('legacy-check')(jsPluginsRootDir); }
bgon/BlocklyCraft
src/main/js/lib/scriptcraft.js
JavaScript
mit
27,355
'use strict' const tape = require('tape') const cullKeywords = require('./_index.js') const expected = { keywords: ['MTV', 'Quick', 'fox', 'jumps', 'quack', 'quiz', 'zephyrs'], keyphrases: ['Alex Trebek\'s fun TV quiz game', 'Junk MTV quiz', 'MTV ax quiz prog', 'Quick', 'fox'] } const format = array => array.map(key => key.replace('\'', '').split(' ').join('-')) var string = ` The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex. Waltz, bad, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz. How quickly daft jumping zebras vex. Two driven jocks help fax my big quiz. Quick, Baz, get my woven flax jodhpurs! "Now fax quiz Jack!" my brave ghost pled. Five quacking zephyrs jolt my wax bed. Flummoxed by job, kvetching W. zaps Iraq. Cozy sphinx waves quart jug of bad milk. A very bad quack might jinx zippy fowls. Few quips galvanized the mock jury box. Quick brown dogs jump over the lazy fox. The jay, pig, fox, zebra, and my wolves quack! Blowzy red vixens fight for a quick jump. Joaquin Phoenix was gazed by MTV for luck. A wizard’s job is to vex chumps quickly in fog. Watch "Jeopardy!", Alex Trebek's fun TV quiz game . Woven silk pyjamas exchanged for blue quartz. Brawny gods just ` tape('cull-keywords', test => { /* * Should Error */ /* Using promises */ cullKeywords('', 'format').then(test.notOk).catch(err => { test.ok(err instanceof Error) test.ok(err.message, 'Expected `string` as first argument.') }) cullKeywords('').then(test.notOk).catch(err => { test.ok(err instanceof Error) test.ok(err.message, 'Expected `string` as first argument.') }) /* Using callbacks */ cullKeywords('', 'format', (err, res) => { test.notOk(res) test.ok(err instanceof Error) test.ok(err.message, 'Expected `string` as first argument.') }) cullKeywords('', (err, res) => { test.notOk(res) test.ok(err instanceof Error) test.ok(err.message, 'Expected `string` as first argument.') }) /** * Should return results */ /* Using promises */ cullKeywords(string).then(res => { test.ok(res) test.deepEqual(res.keyphrases, expected.keyphrases) test.deepEqual(res.keywords, expected.keywords) }).catch(test.notOk) cullKeywords(string, {keyphrases: true, keywords: true}).then(res => { test.ok(res) test.deepEqual(res.keyphrases, expected.keyphrases) test.deepEqual(res.keywords, expected.keywords) }).catch(test.notOk) cullKeywords(string, 'keyphrases').then(res => { test.ok(res) test.deepEqual(res.keyphrases, expected.keyphrases) }) cullKeywords(string, 'keywords').then(res => { test.ok(res) test.deepEqual(res.keywords, expected.keywords) }) cullKeywords(string, 'format').then(res => { test.ok(res) test.deepEqual(res.keyphrases, format(expected.keyphrases)) test.deepEqual(res.keywords, format(expected.keywords)) }).catch(test.notOk) cullKeywords(string, {keyphrases: true, keywords: true, format: true}).then(res => { test.ok(res) test.deepEqual(res.keyphrases, format(expected.keyphrases)) test.deepEqual(res.keywords, format(expected.keywords)) }).catch(test.notOk) cullKeywords(string, {keyphrases: true, format: true}).then(res => { test.ok(res) test.deepEqual(res.keyphrases, format(expected.keyphrases)) }) cullKeywords(string, {keywords: true, format: true}).then(res => { test.ok(res) test.deepEqual(res.keywords, format(expected.keywords)) }) test.ok(typeof cullKeywords.doop === 'function') test.ok(cullKeywords.doop.name === 'doop') test.notOk(cullKeywords.doop()) test.end() })
mrzmmr/cull-keywords
test.js
JavaScript
mit
3,897
define(['loglevel', 'i18n', 'can', 'settings', 'app/partial/navbar'], function (log, i18n, can, settings, Navbar) { /** * A set for general purpose utilities. * @author dorajistyle * @module util */ var SPACE_REGEX = /^\s*|\s\s+\n*|\s+$/g, INVALID_USER_NAME_REGEX = /[^a-zA-Z0-9\-.]+/gi, NON_DIGIT = /\D/g; var messages = new Array(); return { /** * @param {string} name of param. * @returns {string} return param value. * @example <caption> * var lang =util.getParam('lang'); * </caption> */ getParam: function (name) { var value = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href); return value != null ? value[1] : undefined; }, /** * Check user's browser that less than IE8. * @returns {*|jQuery} */ isLessThanIE8: function () { return $('html').hasClass('lt-ie8'); }, /** * stringify JSON if browser greater than IE7. * @param obj * @returns {*} */ stringify: function (obj) { if(this.isLessThanIE8()) return i18n.t('util.stringify.notSupport'); return JSON.stringify(obj); }, /* Get encoded Current URL * @returns {string} */ getCurrentURL: function() { return window.location.href; }, /** * Get Current host * @returns {string} */ getCurrentHost: function() { var host = window.location.protocol+'//'+window.location.host; return host; }, /** * Get static root from Settings * @returns {string} */ getStaticPath: function() { return settings.staticPath; }, /** * Get id data from event target. * @param ev * @returns {*} */ getId: function (ev) { return this.getData(ev, 'id'); }, /** * Get data from event target. * @param ev * @param name * @returns {*|jQuery} */ getData: function(ev, name) { return $(ev.target).data(name); }, /** * Init array. * @param arr */ initArray: function (arr) { if(arr == undefined) { arr = {}; } }, /** * Clear array. * @param arr */ clearArray: function (arr) { arr.splice(0, arr.length); }, /** * Set canjs observe array data. * @param arr * @param data */ setArray: function(arr, data) { arr.attr(new can.List(data).attr()); //old versions set Array // arr.attr(data.attr()); }, /** * Set canjs observe object data. * @param obj * @param data */ setObject: function(obj, data) { if(can.isEmptyObject(obj)){ obj = data; } else { obj.attr(data.attr()); } }, /** * Concat canjs observed array. * @param arr * @param data */ concatArray: function (arr, data) { if(arr != undefined) { if(data != undefined) { arr.attr(arr.attr().concat(data.attr())); } } }, /** * refresh canjs paginate array. * @param arr * @param data */ refreshPaginate: function (arr, data) { arr.attr('hasPrev',data.hasPrev); arr.attr('hasNext',data.hasNext); arr.attr('prevPage',data.currentPage-1); arr.attr('nextPage',data.currentPage+1); }, /** * Refresh canjs observed array. * @param arr * @param data */ refreshArray: function (arr, data) { if(arr == undefined) { this.initArray(arr); } if(arr != undefined) { this.logDebug('array','not null'); this.clearArray(arr); if(data != undefined) { this.logDebug('array','not null'); this.setArray(arr, data); } } }, /** * Refresh canjs observed object. * @param obj * @param data */ refreshObject: function (obj, data) { if(obj != undefined) { // obj.length = 0; if(data != undefined) { this.setObject(obj, data); } } }, /** * Refresh page title to h1#pageTitle's content. */ refreshTitle: function() { var $pageTitle = document.getElementById('pageTitle'); var title = ''; if($pageTitle != null) title = $pageTitle.innerHTML + ' - '; document.title = title + i18n.t('service.name'); }, refreshMeta: function() { var $pageTitle = document.getElementById('pageTitle'), $pageDescription = $('#pageDescription'); var title = '', description = '', serviceName = '', serviceUrl = ''; serviceName = i18n.t('service.name'); serviceUrl = this.getCurrentURL(); if($pageTitle != null) { title = $pageTitle.innerHTML + ' - '; } title = this.truncate70(title + serviceName); document.title = title; if($pageDescription != null) { description = $pageDescription.text(); } description = this.truncate150(description); var meta = '<title>'+title+'</title>'+ '<meta name="description" content="'+description+'" />'+ '<meta property="og:title" content="'+title+'" />'+ '<meta property="og:description" content="'+description+'" />'+ '<meta property="og:type" content="article">'+ '<meta property="og:url" content="'+serviceUrl+'">'+ '<meta property="og:site_name" content="'+serviceName+'">'+ '<meta name="twitter:card" content="'+description+'">'+ '<meta name="twitter:url" content="'+serviceUrl+'">'+ '<meta name="twitter:title" content="'+title+'">'+ '<meta name="twitter:description" content="'+description+'">'+ '<meta itemprop="name" content="'+title+'">'+ '<meta itemprop="description" content="'+description+'">'; var $head = $('head'); $($head.find('title')).remove(); $($head.find('meta[name="description"]')).remove(); $($head.find('meta[property*="og:"]')).remove(); $($head.find('meta[name*="twitter:"]')).remove(); $($head.find('meta[itemprop]')).remove(); $head.prepend(meta); }, /** * Set wrapper information of control. * @param control * @param wrapperName */ setWrapperInfo: function (control, wrapperName) { var $wrapper = $('#'+wrapperName); control.wrapper = $wrapper.html(); control.wrapperId = $wrapper.prop('id'); control.wrapperClass = $wrapper.prop('class'); }, /** * Replace wrapper information of control. * @param control * @param wrapperName */ replaceWrapper: function (control, wrapperName) { var $wrapper = $('#'+wrapperName); $wrapper.replaceWith('<div id="'+control.wrapperId+'" class="'+control.wrapperClass+'">'+control.wrapper+'</div>'); }, /** * Allocate the view if view is undefined. * @param router * @param allocate */ allocate: function (router, control) { if(control === undefined || control.element === null ) router.allocate(); }, /** * Enable javascript logger. * */ enableLog: function () { log.enableAll(); }, /** * Disable javascript logger. * */ disableLog: function () { log.disableAll(); }, /** * Disables all logging below the given level. * @param level * @private */ setLogLevel: function (level) { log.setLevel(level); }, /** * Log trace level message into console. * It works only after enable logger. {@link module:util/enableLog} * @param target * @param msg */ logTrace: function (target, msg) { log.trace(target + ' : ', msg); }, /** * Log debug level message into console. * It works only after enable logger. {@link module:util/enableLog} * @param target * @param msg */ logDebug: function (target, msg) { log.debug(target + ' : ', msg); }, /** * Log info level message into console. * It works only after enable logger. {@link module:util/enableLog} * @param target * @param msg */ logInfo: function (target, msg) { log.info(target + ' : ', msg); }, /** * Log warn level message into console. * It works only after enable logger. {@link module:util/enableLog} * @param target * @param msg */ logWarn: function (target, msg) { log.warn(target + ' : ', msg); }, /** * Log error level message into console. * It works only after enable logger. {@link module:util/enableLog} * @param target * @param msg */ logError: function (target, msg) { log.error(target + ' : ', msg); }, /** * Log JSON object as debug level message into console. * It works only after enable logger. {@link module:util/enableLog} * @param target * @param obj JSON object */ logJson: function (target, obj) { log.debug(target + ' : ', this.stringify(obj)); }, /** * show message popup. * @param msg * @param type */ showMessage: function (msg, type) { if(msg != undefined && msg.length > 0) { var $msgBox = $('#message' + type); $msgBox.html(msg); $msgBox.fadeIn(200).removeClass('uk-hidden').delay(500).fadeOut(800); this.logDebug("showMessage",msg); } }, /** * show warning message. * @param msg */ showWarningMsg: function (msg) { this.showMessage(msg, 'AlertWarning'); }, /** * show error message. * @param msg */ showErrorMsg: function (msg) { this.showMessage(msg, 'AlertError'); }, /** * show info message. * @param msg */ showInfoMsg: function (msg) { this.showMessage(msg, 'AlertInfo'); }, /** * show success message. * @param msg */ showSuccessMsg: function (msg) { this.showMessage(msg, 'AlertSuccess'); }, /** * Put message into message array. * @param msg */ putMessage: function (msg) { messages[messages.length] = msg; }, /** * Show messages that putted before. */ showMessages: function () { this.showWarningMsg(messages.join('<br/>')); this.clearMessages(); }, /** * Get messages that was placed before. */ getMessages: function () { var msg = ""; if(messages.length > 0) { msg = messages.join('<br/>'); this.clearMessages(); } return msg; }, /** * Clear message array. */ clearMessages: function () { messages.length = 0; }, /** * DEPRECATED * Return Template engine for typeahead * @returns {{}} */ // getEngine: function () { // var Stache = {}; // Stache.compile = function (template) { // var compile = can.view.stache(template), // render = { // render: function (ctx) { // return compile.render(ctx); // } // }; // return render; // }; // return Stache; // }, /** * Compile Template for typeahead * @returns {{}} */ compileTemplate: function (template) { var compile = can.view.stache(template); return compile; }, /** * Refresh app div. * @param target * @param name */ getFreshApp: function (){ return this.getFreshDiv('app'); }, /** * Refresh div. * @param name * @returns {HTMLElement} */ getFreshDiv: function (name){ $('#'+name).replaceWith('<div id="'+name+'"></div>'); return $('#'+name); }, /** * handle http status codes. * @param xhr */ handleStatus: function (xhr, message, changeRoute) { var util = this; util.logError('response code', xhr.status); switch (xhr.status) { case 200: // OK break; case 201: // Created break; case 304: // Not Modified break; case 400: // Bad Request // $(settings.appDivId).html(can.view('views_partial_error_stache', {})); // can.route.attr({'route': ''}, true); break; case 401: // Unauthorized// Navbar.load(); if(changeRoute) { util.showErrorMsg(message+i18n.t('error.loginPlease')); $(settings.appDivId).html(can.view('views_partial_error_stache', {})); can.route.attr({'route': 'login'}, true); } else { util.showErrorMsg(message); } break; case 403: // Forbidden // Navbar.load(); util.showMsgAndChangeRoute(message, changeRoute, 'login'); break; case 404: // Not Found util.showMsgAndChangeRoute(message, changeRoute, ''); break; // case 405: // // request method not supported by that resource // break; // case 409: // // request could not be processed because of conflict // break; case 500: // Internal Server Error util.showMsgAndChangeRoute(message, changeRoute, ''); // $(settings.appDivId).html(can.view('views_partial_error_stache', {})); break; default: util.showMsgAndChangeRoute(message, changeRoute, ''); } }, /** * show error message and change route. * @param message * @param changeRoute * @param route */ showMsgAndChangeRoute: function (message, changeRoute, route) { this.showErrorMsg(message); if(changeRoute) { $(settings.appDivId).html(can.view('views_partial_error_stache', {})); can.route.attr({'route': ''}, true); } }, /** * show error message and handle status. * @param xhr * @param message */ handleStatusWithErrorMsg: function (xhr, message) { if(message != undefined && message.length > 0) { message = message + "\n<br\>"; } this.handleStatus(xhr, message); }, /** * show error message and handle status. * @param xhr */ handleError: function (xhr) { var message = i18n.t(xhr.responseJSON.messageType); this.handleStatusWithErrorMsg(xhr, message); }, /** * delete cookie * @param name * @returns {*} */ deleteCookie: function (name) { document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; }, /** * compare two values and return boolean. * @param first * @param second * @returns {boolean} */ compare: function(first, second) { return first == second; }, /** * compare two values and return true when first value is less than second. * @param first * @param second * @returns {boolean} */ lessThanSecond: function(first, second) { return first < second; }, /** * compare two values and return true when first value is greater than second. * @param first * @param second * @returns {boolean} */ greaterThanSecond: function(first, second) { return first > second; }, /* empty the element. * @param element */ empty: function (element) { var child; while (child = element.lastChild) { element.removeChild(child); //clear } }, /** * Trim the string. * @returns trimedStr * @param str */ trim: function(str) { return str.replace(SPACE_REGEX,''); }, /** * Strip non numeric characters of the string. * @returns stripped str * @param str */ strip: function(str) { return str.replace(NON_DIGIT,''); }, /** * Truncate the string. * @param str */ truncate: function(str, limit) { // return str; if(str != undefined) { if(str.length > limit) { return this.trim(str).substr(0, limit-1)+'...'; } } return str; }, /** * Truncate the string with default limit 40. * @param str * @returns {*} */ truncate40: function(str) { return this.truncate(str, 40); }, /** * Truncate the string with default limit 70. * @param str * @returns {*} */ truncate70: function(str) { return this.truncate(str, 70); }, /** * Truncate the string with default limit 150. * @param str * @returns {*} */ truncate150: function(str) { return this.truncate(str, 150); }, /** * replace / to blank * @param str * @returns {*|XML|string|void} */ slashToBlank: function (str) { return str.replace(/\//gi,''); }, /** * Correct username. * @param username * @returns {*|XML|string|void} */ correctUserName: function (username) { if(username.length > 16) { username = username.substring(0,16); } var correctedName = username.replace(INVALID_USER_NAME_REGEX,'0'); return correctedName; }, /** * sets focus on top of the page */ setFocusOnTop: function() { window.scrollTo(0,0); } }; });
tka/goyangi
frontend/canjs/static/js/app/lib/util.js
JavaScript
mit
20,407
// This file acts as the project entry point. // This is to compensate the fact that phaser is not modular. // NOTE: ES2015 import statements cannot be used here. It's an ugly fix, but it's the best I could find. window.PIXI = require('custom-PIXI'); window.p2 = require('p2'); window.Phaser = require('phaser'); // Bootstrap the game. const Bootstrap = require('./Bootstrap'); new Bootstrap.default();
jberube/rainblowed
src/js/index.js
JavaScript
mit
405
import React from 'react'; import ReactDOM from 'react-dom'; import {Router, Route, browserHistory} from 'react-router'; import {Hello} from './app/hello'; import './index.scss'; ReactDOM.render( <Router history={browserHistory}> <Route path="/" component={Hello}/> </Router>, document.getElementById('root') );
XingMeansOK/gallery-by-react
src/index.js
JavaScript
mit
325
"use strict"; const printf = require("./utils/printf"); const LEVELS = require("./levels"); /** * Produce log records. It could not be created manually, * always use LoggerFactory instance to create loggers. * * @param {function} onLogCallback factory, holding this logger * @param {string} name name of this logger * @param {Object} context Set of keys, which will be auto-added to each record * @class */ class Logger { constructor(onLogCallback, name, context) { this._onLogCallback = onLogCallback; this._name = name; this._context = context; } /** * Create log record with given level and arguments. * Usually not used. * * @param {number} level Log level * @param {Array} args Arguments * @private */ log(level, args) { const err = args.length > 0 && args[args.length - 1] instanceof Error ? args.pop() : undefined; const record = { logger: this._name, level: level, levelname: LEVELS[level], args: args, timestamp: Date.now(), err: err, message: printf(args), context: this._context }; this._onLogCallback(record); } /** * Creates new Logger with the same name, factory but with given context. * Every property and value of context will be added to log record. This * can be usefull for json logging * * @param {Object} context * @return {Logger} new logger with given context */ with(context) { // fool check if (typeof context !== "object" || context == null) { throw new Error("`context` must be an Object instance"); } return new Logger(this._onLogCallback, this._name, context); } /** * Create log record with level TRACE. If first argument is string, it is used as message format, like console.log do. * Supported modifiers %s, %d, %j, %%. If you want to output error, it must be one among all arguments and be last. * * @param {...*} args Any arguments. Error must be one and last. * @example * * logger.trace('User entered %s', userInput); * * logger.error('Error happen while sending email', err); */ trace(...args) { this.log(LEVELS.TRACE, args); } /** * Create log record with level DEBUG. If first argument is string, it is used as message format, like console.log do. * Supported modifiers %s, %d, %j, %%. If you want to output error, it must be one among all arguments and be last. * * @param {...*} args Any arguments. Error must be one and last. * @example * * logger.trace('User entered %s', userInput); * * logger.error('Error happen while sending email', err); */ debug(...args) { this.log(LEVELS.DEBUG, args); } /** * Create log record with level INFO. If first argument is string, it is used as message format, like console.log do. * Supported modifiers %s, %d, %j, %%. If you want to output error, it must be one among all arguments and be last. * * @param {...*} args Any arguments. Error must be one and last. * @example * * logger.trace('User entered %s', userInput); * * logger.error('Error happen while sending email', err); */ info(...args) { this.log(LEVELS.INFO, args); } /** * Create log record with level WARN. If first argument is string, it is used as message format, like console.log do. * Supported modifiers %s, %d, %j, %%. If you want to output error, it must be one among all arguments and be last. * * @param {...*} args Any arguments. Error must be one and last. * @example * * logger.trace('User entered %s', userInput); * * logger.error('Error happen while sending email', err); */ warn(...args) { this.log(LEVELS.WARN, args); } /** * Create log record with level ERROR. If first argument is string, it is used as message format, like console.log do. * Supported modifiers %s, %d, %j, %%. If you want to output error, it must be one among all arguments and be last. * * @param {...*} args Any arguments. Error must be one and last. * @example * * logger.trace('User entered %s', userInput); * * logger.error('Error happen while sending email', err); */ error(...args) { this.log(LEVELS.ERROR, args); } } module.exports = Logger;
btd/huzzah
logger.js
JavaScript
mit
4,272
/* @flow */ export { default as AttributeSelector, AttributeSelectorAttribute, AttributeSelectorMatcher, AttributeSelectorValue, AttributeSelectorWithMatcher, } from './AttributeSelector'; export { default as ClassSelector } from './ClassSelector'; export { default as Combinator } from './Combinator'; export { default as HashSelector } from './HashSelector'; export { default as Identifier } from './Identifier'; export { default as Literal } from './Literal'; export { default as NamespacePrefix } from './NamespacePrefix'; export { default as Node } from './Node'; export { default as NumberLiteral } from './NumberLiteral'; export { default as PseudoSelector, CallExpression, PseudoClassSelector, PseudoElementSelector, } from './PseudoSelector'; export { default as Selector } from './Selector'; export { default as SelectorList } from './SelectorList'; export { default as SimpleSelector } from './SimpleSelector'; export { default as SimpleSelectorList } from './SimpleSelectorList'; export { default as StringLiteral } from './StringLiteral'; export { default as TypeSelector } from './TypeSelector'; export { default as UniversalSelector } from './UniversalSelector'; export type NodeType = string;
clentfort/another-selector-parser
src/util/nodes/index.js
JavaScript
mit
1,228
// Production override config
Twilio-org/open-data-notifications
config/production.js
JavaScript
mit
30
/* generated from Designfiles Public by generate_data_designfles */ require ('frameworks.rainbow.generic'); /*! LOAD: frameworks.rainbow.generic !*/ /** * PHP patterns * * @author Craig Campbell * @version 1.0.8 */ Rainbow.extend('php', [ { 'name': 'support', 'pattern': /\becho\b/g }, { 'matches': { 1: 'variable.dollar-sign', 2: 'variable' }, 'pattern': /(\$)(\w+)\b/g }, { 'name': 'constant.language', 'pattern': /true|false|null/ig }, { 'name': 'constant', 'pattern': /\b[A-Z0-9_]{2,}\b/g }, { 'name': 'keyword.dot', 'pattern': /\./g }, { 'name': 'keyword', 'pattern': /\b(die|end(for(each)?|switch|if)|case|require(_once)?|include(_once)?)(?=\(|\b)/g }, { 'matches': { 1: 'keyword', 2: { 'name': 'support.class', 'pattern': /\w+/g } }, 'pattern': /(instanceof)\s([^\$].*?)(\)|;)/g }, /** * these are the top 50 most used PHP functions * found from running a script and checking the frequency of each function * over a bunch of popular PHP frameworks then combining the results */ { 'matches': { 1: 'support.function' }, 'pattern': /\b(array(_key_exists|_merge|_keys|_shift)?|isset|count|empty|unset|printf|is_(array|string|numeric|object)|sprintf|each|date|time|substr|pos|str(len|pos|tolower|_replace|totime)?|ord|trim|in_array|implode|end|preg_match|explode|fmod|define|link|list|get_class|serialize|file|sort|mail|dir|idate|log|intval|header|chr|function_exists|dirname|preg_replace|file_exists)(?=\()/g }, { 'name': 'variable.language.php-tag', 'pattern': /(&lt;\?(php)?|\?&gt;)/g }, { 'matches': { 1: 'keyword.namespace', 2: { 'name': 'support.namespace', 'pattern': /\w+/g } }, 'pattern': /\b(namespace|use)\s(.*?);/g }, { 'matches': { 1: 'storage.modifier', 2: 'storage.class', 3: 'entity.name.class', 4: 'storage.modifier.extends', 5: 'entity.other.inherited-class', 6: 'storage.modifier.extends', 7: 'entity.other.inherited-class' }, 'pattern': /\b(abstract|final)?\s?(class|interface|trait)\s(\w+)(\sextends\s)?([\w\\]*)?(\simplements\s)?([\w\\]*)?\s?\{?(\n|\})/g }, { 'name': 'keyword.static', 'pattern': /self::|static::/g }, { 'matches': { 1: 'storage.function', 2: 'support.magic' }, 'pattern': /(function)\s(__.*?)(?=\()/g }, { 'matches': { 1: 'keyword.new', 2: { 'name': 'support.class', 'pattern': /\w+/g } }, 'pattern': /\b(new)\s([^\$].*?)(?=\)|\(|;)/g }, { 'matches': { 1: { 'name': 'support.class', 'pattern': /\w+/g }, 2: 'keyword.static' }, 'pattern': /([\w\\]*?)(::)(?=\b|\$)/g }, { 'matches': { 2: { 'name': 'support.class', 'pattern': /\w+/g } }, 'pattern': /(\(|,\s?)([\w\\]*?)(?=\s\$)/g } ]);
WebHare/designfiles
frameworks.rainbow.php/frameworks.rainbow.php.js
JavaScript
mit
3,484
var mongoose = require('mongoose'), db_url = 'localhost/prueba1'; db = mongoose.createConnection(db_url); var schema_Usuario = require('./Model/Usuario.js'); Usuario = db.model('Usuario', schema_Usuario); var schema_Registro = require('./Model/Registro.js'); Registro = db.model('Registro', schema_Registro); var schema_Prestamo = require('./Model/Prestamo.js'); Prestamo = db.model('Prestamo', schema_Prestamo); var schema_Item = require('./Model/Item.js'); Item = db.model('Item', schema_Item); var schema_Elemento = require('./Model/Elemento.js'); Elemento = db.model('Elemento', schema_Elemento); console.log((db)); module.exports=db; module.exports=mongoose;
azorlandoaz/Reto-2
db.js
JavaScript
mit
670
const path = require('path'); const fs = require('fs-extra'); const colors = require('colors'); const mustache = require('mustache'); const validator = require('validator'); const json = require('json-update'); const semver = require('semver'); const config = require('config'); const homePath = require('home-path'); const request = require('superagent'); const archiver = require('archiver'); const tmp = require('tmp-promise'); const AdmZip = require('adm-zip'); const chalk = require('chalk'); const columns = require('cli-columns'); const inquirer = require('inquirer'); const klawSync = require('klaw-sync'); const HttpStatus = require('http-status-codes'); const dir = require('../lib/node-dir'); const TemplateManager = require('./templateManager'); const Generator = require('./generator'); const Deploy = require('./command/deploy'); const Compose = require('./command/compose'); const Generate = require('./command/generate'); const Clean = require('./command/clean'); const Push = require('./command/push'); const Clone = require('./command/clone'); const Pull = require('./command/pull'); class CLI { constructor(program, version) { this.program = program; this.version = version; this.currentLocation = process.cwd(); this.snapdevFolder = this.currentLocation; this.templateFolder = path.join(this.snapdevFolder, 'templates'); this.starterFolder = path.normalize(path.join(__dirname, '..', 'starters')); this.distFolder = path.join(this.snapdevFolder, 'dist'); this.modelsFolder = path.join(this.snapdevFolder, 'models'); this.headFolder = path.join(this.snapdevFolder, '.head'); this.snapdevHome = path.join(homePath(), config.homeFolder); this.credentialFile = path.join(this.snapdevHome, 'credentials'); // console.log(colors.yellow('Home folder: ' + this.snapdevHome)); // rules this.shortTemplateNameRule = '^[a-z][a-z0-9-_]*$'; this.fullTemplateNameRule = '^[a-z][a-z0-9-_]*[/][a-z0-9-_]*$'; // starters this.starterModelFile = path.join(this.starterFolder, 'model.json'); this.starterSchemaFile = path.join(this.starterFolder, 'schema.json'); this.starterSnapdevFile = path.join(this.starterFolder, 'snapdev.json'); this.starterAppComposeFile = path.join(this.starterFolder, 'app-compose.yml'); this.starterTemplateJsonFile = path.join(this.starterFolder, 'template.json'); this.starterReadMeFile = path.join(this.starterFolder, 'README.md'); this.starterSampleTemplateFile = path.join(this.starterFolder, '{{titlecase}}.java.txt'); this.mustacheModel = { version: this.version, }; // API this.snapdevHost = config.snapdevHost; this.usersAPI = config.snapdevHost + config.apiv1 + config.usersAPI; this.templatesAPI = config.snapdevHost + config.apiv1 + config.templatesAPI; this.apiv1 = this.snapdevHost + config.apiv1; // Auth this.username = ''; this.token = ''; this.cred = null; } async model() { this.checkSnapdevRoot(); const { templateModelFolder } = await this.getTemplateContext(); if (this.program.pwd) { console.log(templateModelFolder); return true; } let modelList = []; const files = dir.files(templateModelFolder, { sync: true, }); if (!files) { modelList = []; } else { modelList = files.map((f) => f.replace(path.join(templateModelFolder, '/'), '')); } if (modelList.length === 0) { console.log(colors.yellow('No models found')); } else { console.log(columns(modelList)); } return true; } async update() { this.checkSnapdevRoot(); const { templateSrcFolder } = await this.getTemplateContext(); let hasAction = false; /** ============================ */ // ext /** ============================ */ if (this.program.ext) { hasAction = true; const filterFn = (item) => { const basename = path.basename(item.path); const ret = basename === '.' || basename[0] !== '.'; // console.log(ret, item.path); return ret; }; try { console.log('Root:', templateSrcFolder); const paths = klawSync(templateSrcFolder, { nodir: true, filter: filterFn, }); const files = paths.map((p) => p.path); console.log('File count:', files.length); for (let index = 0; index < files.length; index++) { const file = files[index]; // console.log('File:', file); if (path.extname(file) !== '.sd') { const newFile = `${file}.sd`; await fs.move(file, newFile); console.log('Updated:', newFile); } } console.log(); console.log('Done.'); // console.dir(files); } catch (err) { console.log(colors.yellow('Unable to update extensions:'), err.message); process.exit(1); } } return hasAction; } async preReset() { const { branch } = await this.getTemplateContext(); this.program.template = branch; if (this.program.force !== undefined && this.program.force) { // user add --force } else { this.program.force = true; const input = await inquirer.prompt([ { type: 'confirm', name: 'canReset', message: `Are you sure you want to reset '${branch}' to the latest online version`, }, ]); if (!input.canReset) { process.exit(1); } } } async reset() { // check snapdev root this.checkSnapdevRoot(); await this.preReset(); await this.clone(false); return true; } async preDelete() { const templateName = this.program.template; const input = await inquirer.prompt([ { type: 'confirm', name: 'canDelete', message: `Are you sure you want to delete ${templateName}`, }, ]); if (!input.canDelete) { process.exit(1); } } async delete() { const templateName = this.program.template; if (!this.program.force) { await this.preDelete(); } // find remote template if (this.program.remote) { if (!this.isValidFullTemplateName(templateName)) { console.log(colors.yellow('Please specify the full template name i.e. <owner>/<template>')); process.exit(1); } await this.checkLogin(); try { await request .delete(`${this.templatesAPI}/${templateName.replace('/', '%2F')}`) .set('Authorization', `Bearer ${this.token}`) .send(); console.log('[Remote]', templateName, 'removed'); } catch (err) { if (err.status === HttpStatus.BAD_REQUEST) { console.log(colors.yellow('[Remote]', err.response.body.error.message)); } else if (err.status === HttpStatus.UNAUTHORIZED) { console.log(colors.yellow('Session expired')); this.program.force = true; await this.logout(); } else { console.log(colors.yellow('[Remote]', err.message)); } process.exit(1); } } this.checkSnapdevRoot(); // find local template const templateFolder = path.join(this.templateFolder, templateName); if (!fs.existsSync(templateFolder)) { console.log(colors.yellow('[Local]', 'Template not found')); process.exit(1); } else { // delete local template await fs.remove(templateFolder); console.log('[Local]', templateName, 'removed'); } return true; } async preDeregister() { const cred = await this.getCredentials(); const input = await inquirer.prompt([ { type: 'confirm', name: 'canDelete', message: `Are you sure you want to delete ${cred.username} account?`, }, ]); if (!input.canDelete) { process.exit(1); } } async deregister() { this.checkSnapdevRoot(); await this.checkLogin(); if (!this.program.force) { await this.preDeregister(); } try { await request.delete(`${this.usersAPI}/me`).set('Authorization', `Bearer ${this.token}`).send(); console.log('Account deleted'); } catch (err) { if (err.status === HttpStatus.BAD_REQUEST) { console.log(colors.yellow(err.response.body.error.message)); } else if (err.status === HttpStatus.UNAUTHORIZED) { console.log(colors.yellow('Session expired')); this.program.force = true; await this.logout(); } else { console.log(colors.yellow(err.message)); } process.exit(1); } return true; } async deploy() { const exec = new Deploy(this); return exec.execute(); } async compose() { const exec = new Compose(this); return exec.execute(); } async list() { console.log('Getting lists...'); console.log(''); console.log('=== Remote ==='); console.log(''); // check login const isLoggedIn = await this.checkLogin(false); let list = []; if (isLoggedIn) { // get the template list const cred = await this.getCredentials(); try { const response = await request .get(`${this.templatesAPI}/me`) .set('Authorization', `Bearer ${cred.token}`) .send(); list = response.body.data; } catch (err) { if (err.status === HttpStatus.BAD_REQUEST) { console.log(colors.yellow(err.response.body.error.message)); } else if (err.status === HttpStatus.UNAUTHORIZED) { console.log(colors.yellow('Session expired')); this.program.force = true; await this.logout(); } else { console.log(colors.yellow(err.message)); } process.exit(1); } } // show the list if (list.length === 0) { if (isLoggedIn) { console.log(colors.yellow('No remote templates found')); } else { console.log(colors.yellow('You must be logged in to see your remote templates')); } } else { const values = list.map((t) => { if (t.isPrivate) { return chalk.yellow(t.name); } return t.name; }); console.log(columns(values)); } console.log(''); console.log('=== Local ==='); console.log(''); let localList = []; this.checkSnapdevRoot(); // get list of local templates localList = TemplateManager.getLocalTemplates(this.templateFolder); // console.log(localList); // show list if (localList.length === 0) { console.log(colors.yellow('No local templates found')); } else { console.log(columns(localList)); } return true; } downloadZip(token, templateName, version, saveToFile) { return new Promise((resolve, reject) => { const stream = fs.createWriteStream(saveToFile); request .post(`${this.templatesAPI}/pull`) .set('Authorization', `Bearer ${token}`) .send({ name: templateName, version, }) .on('error', function (error) { reject(error); }) .pipe(stream) .on('finish', function () { resolve(); }); }); } async pull() { const exec = new Pull(this); return exec.execute(); } async clone(isPull) { const exec = new Clone(this, isPull); return exec.execute(); } extractZip(zipFile, distFolder) { const zip = new AdmZip(zipFile); zip.extractAllTo(distFolder, true); } zipDirectory(sourceDir, distZipFile) { const archive = archiver('zip', { zlib: { level: 9 } }); const stream = fs.createWriteStream(distZipFile); return new Promise((resolve, reject) => { archive .directory(sourceDir, false) .on('error', (err) => reject(err)) .pipe(stream); stream.on('close', () => resolve()); archive.finalize(); }); } getFilesizeInBytes(filename) { const stats = fs.statSync(filename); const fileSizeInBytes = stats.size; return fileSizeInBytes; } async push() { const exec = new Push(this); return exec.execute(); } async isLoggedIn() { const cred = await this.getCredentials(); if (cred) { if (cred.token !== '') { return true; } } return false; } async relogin() { console.log('Authenticating with existing credentials...'); // call get me API try { const cred = await this.getCredentials(); await request.get(`${this.usersAPI}/me`).set('Authorization', `Bearer ${cred.token}`).send(); console.log('Logged in as:', cred.username); console.log('Login Succeeded'); } catch (err) { if (err.status === HttpStatus.BAD_REQUEST) { console.log(colors.yellow(err.response.body.error.message)); process.exit(1); } else if (err.status === HttpStatus.UNAUTHORIZED) { console.log(colors.yellow('Session expired')); this.program.force = true; await this.logout(); await this.login(); } else { console.log(colors.yellow(err.message)); process.exit(1); } } return true; } async logout() { // call logout API console.log('Logging out...'); try { const cred = await this.getCredentials(); if (!this.program.local) { await request.post(`${this.usersAPI}/logout`).set('Authorization', `Bearer ${cred.token}`).send(); } await this.updateJSON(this.credentialFile, { username: '', token: '', }); console.log('Logged out!'); } catch (err) { if (this.program.force) { await this.updateJSON(this.credentialFile, { username: '', token: '', }); console.log('Logged out!'); } else { console.log(colors.yellow(err.message)); process.exit(1); } } return true; } async register() { console.log(''); let hasErrors = false; if (this.program.username === undefined || validator.isEmpty(this.program.username)) { console.log(colors.yellow('--username is required')); hasErrors = true; } if (!this.program.force) { if (this.program.password !== this.program.password2) { console.log(colors.yellow('Passwords mismatch')); hasErrors = true; } } else if (this.program.password === undefined || validator.isEmpty(this.program.password)) { console.log(colors.yellow('--password is required')); hasErrors = true; } if (this.program.email === undefined || !validator.isEmail(this.program.email)) { console.log(colors.yellow('--email is required')); hasErrors = true; } if (hasErrors) { process.exit(1); } // call sign up API try { await request.post(`${this.usersAPI}/signup`).send({ displayName: this.program.username, email: this.program.email, username: this.program.username, password: this.program.password, }); console.log('Account created'); } catch (err) { if (err.status === HttpStatus.BAD_REQUEST) { console.log(colors.yellow(err.response.body.error.message)); } else if (err.status === HttpStatus.UNAUTHORIZED) { console.log(colors.yellow('Session expired')); this.program.force = true; await this.logout(); } else { console.log(colors.yellow(err.message)); } process.exit(1); } return true; } async inputLogin() { console.log('Login with your snapdev username to push and clone templates from snapdev online repository'); const list = []; // console.log('usr', this.program.username); if (this.program.username === undefined) { list.push({ name: 'username', message: 'Username:', validate: function validateFirstName(value) { return value !== ''; }, }); } // console.log('pass', this.program.password); if (this.program.password === undefined) { list.push({ name: 'password', message: 'Password:', type: 'password', validate: function validateFirstName(value) { return value !== ''; }, }); } const input = await inquirer.prompt(list); if (this.program.username === undefined) { this.program.username = input.username; } if (this.program.password === undefined) { this.program.password = input.password; } } async login() { // use existing token if available const isLoggedIn = await this.isLoggedIn(); if (isLoggedIn) { return this.relogin(); } if (this.program.username && this.program.password) { // direct login } else { await this.inputLogin(); } console.log('Logging in...'); // console.log('Host:', config.snapdevAPI); // console.log('Username:', this.program.username); // console.log('Password:', this.program.password); // create a ~/.snapdev/credentials if (!fs.existsSync(this.snapdevHome)) { fs.mkdirSync(this.snapdevHome, { recursive: true }); } // call login API try { const response = await request.post(`${this.usersAPI}/login`).send({ username: this.program.username, password: this.program.password, }); await this.updateJSON(this.credentialFile, { username: this.program.username, token: response.body.data.token, }); console.log(`Logged in as: ${this.program.username}`); console.log('Login Succeeded'); } catch (err) { if (err.status === HttpStatus.BAD_REQUEST) { console.log(colors.yellow(err.response.body.error.message)); } else if (err.status === HttpStatus.UNAUTHORIZED) { console.log(colors.yellow('Session expired')); this.program.force = true; await this.logout(); } else { console.log(colors.yellow(err.message)); } process.exit(1); } return true; } init() { let projectFolder = this.currentLocation; // create project folder if specified if (this.program.project) { projectFolder = path.join(projectFolder, this.program.project); } // create snapdev folder if not found const snapdevFolder = path.join(projectFolder, 'snapdev'); if (!fs.existsSync(snapdevFolder)) { fs.mkdirSync(snapdevFolder, { recursive: true }); } // create head folder const headFolder = path.join(snapdevFolder, '.head'); if (!fs.existsSync(headFolder)) { fs.mkdirSync(headFolder, { recursive: true }); } // create models folder if not found const modelsFolder = path.join(snapdevFolder, 'models'); if (!fs.existsSync(modelsFolder)) { fs.mkdirSync(modelsFolder, { recursive: true }); } const newModelFile = path.join(modelsFolder, 'default.json'); // create templates folder if not found const templateFolder = path.join(snapdevFolder, 'templates'); if (!fs.existsSync(templateFolder)) { fs.mkdirSync(templateFolder, { recursive: true }); } // create snapdev file from a starter template const newSnapdevFile = path.join(snapdevFolder, 'snapdev.json'); this.copyStarter(this.starterSnapdevFile, newSnapdevFile, this.mustacheModel); const newAppComposeFile = path.join(snapdevFolder, 'app-compose.yml'); this.copyStarter(this.starterAppComposeFile, newAppComposeFile); this.copyStarter(this.starterModelFile, newModelFile); return true; } async status() { const cred = await this.getCredentials(); let username = ''; if (cred) { username = cred.username; } // get API version let apiVersion; try { const response = await request.get(`${this.apiv1}/version`).send(); apiVersion = response.body.version; } catch (e) { apiVersion = 'Network error'; } console.log('API endpoint:', config.snapdevHost); console.log('API version:', apiVersion); console.log('Logged in as:', username); this.checkSnapdevRoot(); const { branch, templateFolder, templateVersion, templatePrivate, templateTags, pushId, } = await this.getTemplateContext(false); if (branch === '') { console.log(colors.yellow('template.json not found')); } console.log('Template name:', branch); console.log('Template version:', templateVersion); console.log('Template tags:', templateTags.join(',')); console.log('Template acl:', templatePrivate ? 'private' : 'public'); console.log('Template root:', templateFolder); console.log('Last commit:', pushId); return true; } async tag() { this.checkSnapdevRoot(); let { templateFolder, username, templateJSONFile, branch, templateName } = await this.getTemplateContext(); /** ============================ */ // set version /** ============================ */ if (this.program.version !== undefined) { const { version } = this.program; if (semver.valid(version) === null) { console.log(colors.yellow('Invalid version number format. Please use the https://semver.org/ specification')); process.exit(1); } // update template.json // console.log(semver.clean(version),'$$$',version); const updated = await this.updateJSON(templateJSONFile, { version: semver.clean(version), }); if (updated) { console.log(branch, 'set to version', version); } } /** ============================ */ // set tags /** ============================ */ if (this.program.tags !== undefined) { const { tags } = this.program; if (validator.isEmpty(tags)) { console.log(colors.yellow('Invalid tag list')); process.exit(1); } const updated = await this.updateJSON(templateJSONFile, { tags: tags.split(','), }); if (updated) { console.log('Tags updated'); } } /** ============================ */ // set description /** ============================ */ if (this.program.description !== undefined) { const newDescription = this.program.description; if (validator.isEmpty(newDescription)) { console.log(colors.yellow('Invalid template description')); process.exit(1); } const updated = await this.updateJSON(templateJSONFile, { description: newDescription, }); if (updated) { console.log('Description updated'); } } /** ============================ */ // set name /** ============================ */ if (this.program.name !== undefined) { const newName = this.program.name; // make sure it's a short name if (!validator.matches(newName, this.shortTemplateNameRule)) { console.log(colors.yellow('Invalid template name')); process.exit(1); } let newBranch; if (branch.indexOf('/') > -1) { // has username const user = branch.split('/')[0]; newBranch = `${user}/${newName}`; } else { // no username newBranch = newName; } templateName = newName; const newTemplateLocation = path.join(this.templateFolder, newBranch); const oldTemplateLocation = templateFolder; // console.log('OLD BRANCH:', branch); // console.log('OLD LOCATION:', oldTemplateLocation); // console.log('NEW BRANCH:', newBranch); // console.log('NEW LOCATION:', newTemplateLocation); if (fs.existsSync(newTemplateLocation)) { console.log(colors.yellow('Template name already exists at that location', newTemplateLocation)); process.exit(1); } else { // fs.mkdirSync(newTemplateLocation, { recursive: true }); } // rename folder try { // move template into the user folder await fs.move(oldTemplateLocation, newTemplateLocation); console.log('From:', oldTemplateLocation); console.log('To:', newTemplateLocation); // update template context fields templateJSONFile = path.join(newTemplateLocation, 'template.json'); templateFolder = path.join(this.templateFolder, newBranch); await this.updateJSON(templateJSONFile, { name: newName, }); // update context branch await this.switchContextBranch(newBranch); branch = newBranch; } catch (err) { console.log(colors.yellow('Unable to rename template', err)); process.exit(1); } } /** ============================ */ // tag with a user /** ============================ */ if (this.program.user) { await this.checkLogin(); const valid = this.validUsername(username); if (valid) { if (branch.indexOf('/') > -1) { const currentBranch = branch; const newBranch = username.concat('/', templateName); if (currentBranch === newBranch) { /* already tagged */ console.log('Tagged', branch); } else { /** Create a copy of the template under the current user */ // console.log('Current branch:', currentBranch); // console.log('New branch:', newBranch); // create new branch const currentTemplateFolder = path.join(this.templateFolder, currentBranch); const newTemplateFolder = path.join(this.templateFolder, newBranch); // console.log('Current branch path:', currentTemplateFolder); // console.log('New branch path:', newTemplateFolder); if (!fs.existsSync(newTemplateFolder)) { fs.mkdirSync(newTemplateFolder, { recursive: true }); } await fs.copy(currentTemplateFolder, newTemplateFolder, { overwrite: false, }); console.log('Tagged', newBranch); // switch context await this.switchContextBranch(newBranch); } } else { // no user for template, move template into a user folder const userFolder = path.join(this.templateFolder, username); if (!fs.existsSync(userFolder)) { // user folder not found fs.mkdirSync(userFolder, { recursive: true }); } else { // user folder found } const newTemplateFolder = path.join(userFolder, branch); if (fs.existsSync(newTemplateFolder)) { console.log(colors.yellow('Tag destination already exists', newTemplateFolder)); process.exit(1); } try { // move template into the user folder await fs.move(templateFolder, newTemplateFolder); console.log('From:', templateFolder); console.log('To:', newTemplateFolder); // update context branch await this.switchContextBranch(`${username}/${branch}`); } catch (err) { console.log(colors.yellow('Unable to move template', err)); process.exit(1); } } } } /** ============================ */ // tag template as public or private /** ============================ */ // setting must take effect when pushing to online. if (this.program.private && this.program.public) { console.log(colors.yellow('Cannot use --private and --public at the same time')); process.exit(1); } if (this.program.private || this.program.public) { const isPrivate = this.program.private !== undefined; const updated = await this.updateJSON(templateJSONFile, { private: isPrivate, }); if (updated) { if (isPrivate) { console.log('Template marked as private'); } else { console.log('Template marked as public'); } } } return true; } async create() { this.checkSnapdevRoot(); // validate template name against short and full name let templateName; const programTemplate = this.program.template; if (programTemplate.indexOf('/') > -1) { // username/template-name if (!validator.matches(programTemplate, this.fullTemplateNameRule)) { console.log(colors.yellow('Invalid template name')); return false; } templateName = programTemplate; } else { // template-name if (!validator.matches(programTemplate, this.shortTemplateNameRule)) { console.log(colors.yellow('Invalid template name')); return false; } // prefix the template with the username const loggedIn = await this.isLoggedIn(); if (loggedIn) { const cred = await this.getCredentials(); templateName = `${cred.username}/${programTemplate}`; } else { templateName = programTemplate; } } // get new folder name const newTemplateFolder = path.join(this.templateFolder, templateName); const srcFolder = path.join(newTemplateFolder, 'src'); // make sure template folder does not exists if (fs.existsSync(srcFolder)) { console.log(colors.yellow('Template name already exists')); process.exit(1); } // create src folder fs.mkdirSync(srcFolder, { recursive: true }); // save template.json in the folder this.copyStarter(this.starterTemplateJsonFile, path.join(newTemplateFolder, 'template.json'), { name: templateName, version: '0.0.1', }); // save schema.json in the folder this.copyStarter(this.starterSchemaFile, path.join(newTemplateFolder, 'schema.json'), { name: templateName, }); // copy readme file // TODO: Render all the token values from the generator this.copyStarter(this.starterReadMeFile, path.join(newTemplateFolder, 'README.md'), { name: templateName, }); // copy template sample file this.copyStarter(this.starterSampleTemplateFile, path.join(srcFolder, '{{titlecase}}.java.txt'), null); // create models folder const modelFolder = path.join(newTemplateFolder, 'models'); if (!fs.existsSync(modelFolder)) { fs.mkdirSync(modelFolder, { recursive: true }); } // create sample models file this.copyStarter(this.starterModelFile, path.join(modelFolder, 'default.json')); // switch context await this.switchContextBranch(templateName); return true; } hasTemplate(templateName) { const newTemplateFolder = path.join(this.templateFolder, templateName); const srcFolder = path.join(newTemplateFolder, 'src'); return fs.existsSync(srcFolder); } async checkout() { this.checkSnapdevRoot(); // validate template name against short and full name let templateName; const programTemplate = this.program.template; if (programTemplate.indexOf('/') > -1) { // username/template-name if (!validator.matches(programTemplate, this.fullTemplateNameRule)) { console.log(colors.yellow('Invalid template name')); return false; } templateName = programTemplate; } else { // template-name if (!validator.matches(programTemplate, this.shortTemplateNameRule)) { console.log(colors.yellow('Invalid template name')); return false; } // if shorn name not found then append user if logged in and search for full template if (!this.hasTemplate(programTemplate)) { // console.log(colors.yellow('Template not found', programTemplate)); // check full name template const loggedIn = await this.isLoggedIn(); if (loggedIn) { const cred = await this.getCredentials(); templateName = `${cred.username}/${programTemplate}`; } else { templateName = programTemplate; } } else { // use short name templateName = programTemplate; } } // get new folder name // console.log(this.templateFolder, templateName); if (!this.hasTemplate(templateName)) { console.log(colors.yellow('Template not found', templateName)); process.exit(1); } // switch context await this.switchContextBranch(templateName); return true; } async switchContextBranch(branch) { const updated = await this.updateJSON('snapdev.json', { branch, }); if (updated) { console.log('Switched to', branch); } } async updateJSON(filename, jsonObject) { try { await json.update(filename, jsonObject); return true; } catch (error) { console.log(colors.yellow('Unable to modify json file:', filename, error)); } return false; } async setPushId(templateId, pushId) { // create head folder const headFolder = path.join(this.snapdevFolder, '.head'); if (!fs.existsSync(headFolder)) { fs.mkdirSync(headFolder, { recursive: true }); } if (!templateId || templateId === '') { console.log(colors.yellow('PushId not set')); process.exit(1); } const filename = path.join(headFolder, templateId); try { await json.update(filename, { pushId, }); return true; } catch (error) { console.log(colors.yellow('Unable to update file:', filename, error)); } return false; } async getPushId(templateId) { const headFolder = path.join(this.snapdevFolder, '.head'); if (!fs.existsSync(headFolder)) { fs.mkdirSync(headFolder, { recursive: true }); } if (!templateId || templateId === '') { return ''; } const filename = path.join(headFolder, templateId); try { if (!fs.existsSync(filename)) { await json.update(filename, {}); } const data = await json.load(filename); return data.pushId || ''; } catch (error) { console.log(colors.yellow('Unable to read file:', filename, error)); } return ''; } async readJSON(filename) { if (!fs.existsSync(filename)) { await json.update(filename, {}); } const data = await json.load(filename); return data; } async getCredentials() { if (fs.existsSync(this.credentialFile)) { const cred = await this.readJSON(this.credentialFile); return cred; } return null; } getShortTemplateName(templateName) { let shortName; if (templateName.indexOf('/') > -1) { // has username [, shortName] = templateName.split('/'); } else { // no username shortName = templateName; } return shortName; } async getTemplateContext(exit = true, readSchemaDef = false) { const snapdevData = await this.readJSON('snapdev.json'); const { branch } = snapdevData; const templateName = this.getShortTemplateName(branch); const cred = await this.getCredentials(); let username = ''; if (cred) { username = cred.username; } const templateFolder = path.join(this.templateFolder, branch); if (!fs.existsSync(path.join(templateFolder, 'template.json'))) { if (exit) { console.log(colors.yellow('template.json not found')); process.exit(1); } else { return { username, pushId: '', templateId: '', templateFolder: '', templateSrcFolder: '', templateVersion: '', templateJSONFile: '', branch: '', templateModelFolder: '', templateName: '', templatePrivate: true, templateTags: [], templateDescription: '', templateSchemaDef: {}, }; } } /// get template details const templateJSONFile = path.join(templateFolder, 'template.json'); const templateData = await this.readJSON(templateJSONFile); // console.log(templateData); const templateId = templateData.templateId || ''; const templateVersion = templateData.version || '0.0.1'; let templatePrivate = templateData.private; if (templatePrivate === undefined) { templatePrivate = true; } const templateTags = templateData.tags || ['base']; const templateDescription = templateData.description || ''; // get the schema data let templateSchemaDef; if (readSchemaDef) { const templateSchemaDefFile = path.join(templateFolder, 'schema.json'); let templateSchemaDefData; if (!fs.existsSync(templateSchemaDefFile)) { templateSchemaDefData = {}; } else { templateSchemaDefData = await this.readJSON(templateSchemaDefFile); } templateSchemaDef = templateSchemaDefData; } const templateSrcFolder = path.join(templateFolder, 'src'); const templateModelFolder = path.join(templateFolder, 'models'); if (!fs.existsSync(templateSrcFolder)) { console.log( colors.yellow( 'Invalid template context. Please use [snapdev checkout <template>] to switch to a valid template' ) ); process.exit(1); } const pushId = await this.getPushId(templateId); return { templateFolder, templateSrcFolder, templateModelFolder, templateName, templateVersion, templatePrivate, templateTags, templateJSONFile, username, branch, templateDescription, templateSchemaDef, pushId, templateId, }; } async add() { this.checkSnapdevRoot(); const { templateFolder } = await this.getTemplateContext(); // validate the file extension let newModelFile = path.join(templateFolder, 'models', this.program.model); const ext = path.extname(newModelFile); if (ext !== '.json') { if (ext !== '') { console.log(colors.yellow('Invalid file extension')); process.exit(1); } else { newModelFile += '.json'; } } // console.log('Creating Model:', newModelFile); // create the parent folder for the model.json const parentFolder = path.dirname(newModelFile); // console.log('parentFolder', parentFolder); if (!fs.existsSync(parentFolder)) { fs.mkdirSync(parentFolder, { recursive: true }); } // copy the file return this.copyStarter(this.starterModelFile, newModelFile); } clean() { const exec = new Clean(this); return exec.execute(); } async generate() { const exec = new Generate(this); return exec.execute(); } hasModelFile(modelFile) { return fs.existsSync(modelFile); } generateForModel(name, templateFolder, templateSrcFolder) { let modelName = name; const ext = path.extname(modelName); if (ext !== '.json' || ext === '') { modelName += '.json'; } // find the model file console.log('Model filename:', modelName); // location 1 let modelFile = path.join(this.snapdevFolder, 'models', modelName); let hasModel = this.hasModelFile(modelFile); if (!hasModel) { // location 2 modelFile = path.join(templateFolder, 'models', modelName); hasModel = this.hasModelFile(modelFile); if (!hasModel) { console.log(colors.yellow('Model filename not found')); process.exit(1); } } console.log('Model path:', modelFile); // generate code const generator = new Generator( templateSrcFolder, modelFile, this.distFolder, this.program.verbose, this.program.silent ); generator.generate(); } validUsername(username) { const usernameRule = '^[a-z][a-z0-9-_]*$'; if (!validator.matches(username, usernameRule)) { console.log(colors.yellow('Invalid username format')); return false; } return true; } inRoot() { const snapdevFile = path.join(this.currentLocation, 'snapdev.json'); return fs.existsSync(snapdevFile); } inTemplate() { const templateFile = path.join(this.currentLocation, 'template.json'); return fs.existsSync(templateFile); } async checkTagged(exit = true) { const { branch } = await this.getTemplateContext(); if (branch.indexOf('/') === -1) { console.log(colors.yellow('Please run [snapdev tag --user] to tag the template with the logged in user')); if (exit) { process.exit(1); } else { return false; } } return true; } async updateLogin() { this.cred = await this.getCredentials(); if (this.cred) { this.username = this.cred.username; this.token = this.cred.token; } else { this.username = ''; this.token = ''; } } async checkLogin(exit = true) { const loggedIn = await this.isLoggedIn(); if (!loggedIn) { if (exit) { console.log(colors.yellow('Please run [snapdev login] to log in')); process.exit(1); } else { await this.updateLogin(); return false; } } await this.updateLogin(); return true; } isValidFullTemplateName(templateName) { return validator.matches(templateName, this.fullTemplateNameRule); } isValidShortTemplateName(templateName) { return validator.matches(templateName, this.shortTemplateNameRule); } checkSnapdevRoot(exit = true) { if (!this.inRoot()) { if (exit) { console.log(colors.yellow('Working directory is not a snapdev workspace')); process.exit(1); } else { return false; } } return true; } checkTemplateRoot(exit = true) { if (!this.inTemplate()) { if (exit) { console.log(colors.yellow('Please run command from the template folder that has the template.json file')); process.exit(1); } else { return false; } } return true; } copyStarter(fromFile, toFile, mustacheModel = null) { // get starter model content const modelStarterData = fs.readFileSync(fromFile, 'utf8'); let mergedData; if (mustacheModel !== null) { mergedData = mustache.render(modelStarterData, mustacheModel); } else { mergedData = modelStarterData; } // create the new file if not found if (!fs.existsSync(toFile)) { try { fs.writeFileSync(toFile, mergedData); console.log('Created:', toFile); } catch (e) { console.log(colors.yellow('Unable to create file'), colors.yellow(e)); process.exit(1); } } else { console.log(colors.yellow('The specified file already exists')); process.exit(1); } return true; } async makeTempFile() { const o = await tmp.file(); // console.log(o); return o.path; } } module.exports = CLI;
tptshepo/snapdev
classes/CLI.js
JavaScript
mit
42,618
var elixir = require('laravel-elixir'); var paths = { jquery: 'vendor/bower_components/jquery/dist/jquery.js', bootstrap: 'vendor/bower_components/bootstrap-sass/assets/' }; /* |-------------------------------------------------------------------------- | Elixir Asset Management |-------------------------------------------------------------------------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your WordPlate application. By default, we are compiling the Sass | file for our application, as well as publishing vendor resources. | */ elixir.config.publicPath = 'public/themes/default/dist'; elixir.config.css.sass.folder = 'styles'; elixir.config.css.outputFolder = 'css'; elixir.config.js.folder = 'scripts'; elixir.config.js.outputFolder = 'js'; elixir(function (mix) { mix.sass('app.scss'); // Copy Bootstrap fonts mix.copy(paths.bootstrap + 'fonts', elixir.config.publicPath + '/fonts'); mix.scripts([ '../../../' + paths.jquery, '../../../' + paths.bootstrap + 'javascripts/bootstrap.js', 'app.js' ]); mix.copy(elixir.config.assetsPath + '/images', elixir.config.publicPath + '/images'); });
fieleman/wordplate
gulpfile.js
JavaScript
mit
1,182
// ------------------------------------------------------------------- // DHTML Window Widget- By Dynamic Drive, available at: http://www.dynamicdrive.com // v1.0: Script created Feb 15th, 07' // v1.01: Feb 21th, 07' (see changelog.txt) // v1.02: March 26th, 07' (see changelog.txt) // v1.03: May 5th, 07' (see changelog.txt) // v1.1: Oct 29th, 07' (see changelog.txt) // ------------------------------------------------------------------- var dhtmlwindow = { imagefiles: ['windowfiles/min.gif', 'windowfiles/close.gif', 'windowfiles/restore.gif', 'windowfiles/resize.gif'], //Path to 4 images used by script, in that order ajaxbustcache: true, //Bust caching when fetching a file via Ajax? ajaxloadinghtml: '<b>Loading Page. Please wait...</b>', //HTML to show while window fetches Ajax Content? minimizeorder: 0, zIndexvalue: 100, tobjects: [], //object to contain references to dhtml window divs, for cleanup purposes lastactivet: {}, //reference to last active DHTML window init: function(t) { var domwindow = document.createElement("div") //create dhtml window div domwindow.id = t domwindow.className = "dhtmlwindow" var domwindowdata = '' domwindowdata = '<div class="drag-handle">' domwindowdata += 'DHTML Window <div class="drag-controls"><img src="' + this.imagefiles[0] + '" title="Minimize" /><img src="' + this.imagefiles[1] + '" title="Close"/></div>' domwindowdata += '</div>' domwindowdata += '<div class="drag-contentarea"></div>' domwindowdata += '<div class="drag-statusarea"><div class="drag-resizearea" style="background: transparent url(' + this.imagefiles[3] + ') top right no-repeat;">&nbsp;</div></div>' domwindowdata += '</div>' domwindow.innerHTML = domwindowdata document.getElementById("dhtmlwindowholder").appendChild(domwindow) //this.zIndexvalue=(this.zIndexvalue)? this.zIndexvalue+1 : 100 //z-index value for DHTML window: starts at 0, increments whenever a window has focus var t = document.getElementById(t) var divs = t.getElementsByTagName("div") for (var i = 0; i < divs.length; i++) { //go through divs inside dhtml window and extract all those with class="drag-" prefix if (/drag-/.test(divs[i].className)) t[divs[i].className.replace(/drag-/, "")] = divs[i] //take out the "drag-" prefix for shorter access by name } //t.style.zIndex=this.zIndexvalue //set z-index of this dhtml window t.handle._parent = t //store back reference to dhtml window t.resizearea._parent = t //same t.controls._parent = t //same t.onclose = function() { return true } //custom event handler "onclose" t.onmousedown = function() { dhtmlwindow.setfocus(this) } //Increase z-index of window when focus is on it t.handle.onmousedown = dhtmlwindow.setupdrag //set up drag behavior when mouse down on handle div t.resizearea.onmousedown = dhtmlwindow.setupdrag //set up drag behavior when mouse down on resize div t.controls.onclick = dhtmlwindow.enablecontrols t.show = function() { dhtmlwindow.show(this) } //public function for showing dhtml window t.hide = function() { dhtmlwindow.hide(this) } //public function for hiding dhtml window t.close = function() { dhtmlwindow.close(this) } //public function for closing dhtml window (also empties DHTML window content) t.setSize = function(w, h) { dhtmlwindow.setSize(this, w, h) } //public function for setting window dimensions t.moveTo = function(x, y) { dhtmlwindow.moveTo(this, x, y) } //public function for moving dhtml window (relative to viewpoint) t.isResize = function(bol) { dhtmlwindow.isResize(this, bol) } //public function for specifying if window is resizable t.isScrolling = function(bol) { dhtmlwindow.isScrolling(this, bol) } //public function for specifying if window content contains scrollbars t.load = function(contenttype, contentsource, title) { dhtmlwindow.load(this, contenttype, contentsource, title) } //public function for loading content into window this.tobjects[this.tobjects.length] = t return t //return reference to dhtml window div }, open: function(t, contenttype, contentsource, title, attr, recalonload) { var d = dhtmlwindow //reference dhtml window object function getValue(Name) { var config = new RegExp(Name + "=([^,]+)", "i") //get name/value config pair (ie: width=400px,) return (config.test(attr)) ? parseInt(RegExp.$1) : 0 //return value portion (int), or 0 (false) if none found } if (document.getElementById(t) == null) //if window doesn't exist yet, create it t = this.init(t) //return reference to dhtml window div else t = document.getElementById(t) this.setfocus(t) t.setSize(getValue(("width")), (getValue("height"))) //Set dimensions of window var xpos = getValue("center") ? "middle" : getValue("left") //Get x coord of window var ypos = getValue("center") ? "middle" : getValue("top") //Get y coord of window //t.moveTo(xpos, ypos) //Position window if (typeof recalonload != "undefined" && recalonload == "recal" && this.scroll_top == 0) { //reposition window when page fully loads with updated window viewpoints? if (window.attachEvent && !window.opera) //In IE, add another 400 milisecs on page load (viewpoint properties may return 0 b4 then) this.addEvent(window, function() { setTimeout(function() { t.moveTo(xpos, ypos) }, 400) }, "load") else this.addEvent(window, function() { t.moveTo(xpos, ypos) }, "load") } t.isResize(getValue("resize")) //Set whether window is resizable t.isScrolling(getValue("scrolling")) //Set whether window should contain scrollbars t.style.visibility = "visible" t.style.display = "block" t.contentarea.style.display = "block" t.moveTo(xpos, ypos) //Position window t.load(contenttype, contentsource, title) if (t.state == "minimized" && t.controls.firstChild.title == "Restore") { //If window exists and is currently minimized? t.controls.firstChild.setAttribute("src", dhtmlwindow.imagefiles[0]) //Change "restore" icon within window interface to "minimize" icon t.controls.firstChild.setAttribute("title", "Minimize") t.state = "fullview" //indicate the state of the window as being "fullview" } return t }, setSize: function(t, w, h) { //set window size (min is 150px wide by 100px tall) t.style.width = Math.max(parseInt(w), 150) + "px" t.contentarea.style.height = Math.max(parseInt(h), 100) + "px" }, moveTo: function(t, x, y) { //move window. Position includes current viewpoint of document this.getviewpoint() //Get current viewpoint numbers t.style.left = (x == "middle") ? this.scroll_left + (this.docwidth - t.offsetWidth) / 2 + "px" : this.scroll_left + parseInt(x) + "px" //t.style.top=(y=="middle")? this.scroll_top+(this.docheight-t.offsetHeight)/2+"px" : this.scroll_top+parseInt(y)+"px" stanley t.style.top = 120 + "px"; t.style.zIndex = 102; }, isResize: function(t, bol) { //show or hide resize inteface (part of the status bar) t.statusarea.style.display = (bol) ? "block" : "none" t.resizeBool = (bol) ? 1 : 0 }, isScrolling: function(t, bol) { //set whether loaded content contains scrollbars t.contentarea.style.overflow = (bol) ? "auto" : "hidden" }, load: function(t, contenttype, contentsource, title) { //loads content into window plus set its title (3 content types: "inline", "iframe", or "ajax") if (t.isClosed) { alert("DHTML Window has been closed, so no window to load contents into. Open/Create the window again.") return } var contenttype = contenttype.toLowerCase() //convert string to lower case if (typeof title != "undefined") t.handle.firstChild.nodeValue = title if (contenttype == "inline") t.contentarea.innerHTML = contentsource else if (contenttype == "div") { var inlinedivref = document.getElementById(contentsource) t.contentarea.innerHTML = (inlinedivref.defaultHTML || inlinedivref.innerHTML) //Populate window with contents of inline div on page if (!inlinedivref.defaultHTML) inlinedivref.defaultHTML = inlinedivref.innerHTML //save HTML within inline DIV inlinedivref.innerHTML = "" //then, remove HTML within inline DIV (to prevent duplicate IDs, NAME attributes etc in contents of DHTML window inlinedivref.style.display = "none" //hide that div } else if (contenttype == "iframe") { t.contentarea.style.overflow = "hidden" //disable window scrollbars, as iframe already contains scrollbars if (!t.contentarea.firstChild || t.contentarea.firstChild.tagName != "IFRAME") //If iframe tag doesn't exist already, create it first t.contentarea.innerHTML = '<iframe src="" style="margin:0; padding:0; width:100%; height: 100%" name="_iframe-' + t.id + '"></iframe>' window.frames["_iframe-" + t.id].location.replace(contentsource) //set location of iframe window to specified URL } else if (contenttype == "ajax") { this.ajax_connect(contentsource, t) //populate window with external contents fetched via Ajax } t.contentarea.datatype = contenttype //store contenttype of current window for future reference }, setupdrag: function(e) { var d = dhtmlwindow //reference dhtml window object var t = this._parent //reference dhtml window div d.etarget = this //remember div mouse is currently held down on ("handle" or "resize" div) var e = window.event || e d.initmousex = e.clientX //store x position of mouse onmousedown d.initmousey = e.clientY d.initx = parseInt(t.offsetLeft) //store offset x of window div onmousedown d.inity = parseInt(t.offsetTop) d.width = parseInt(t.offsetWidth) //store width of window div d.contentheight = parseInt(t.contentarea.offsetHeight) //store height of window div's content div if (t.contentarea.datatype == "iframe") { //if content of this window div is "iframe" t.style.backgroundColor = "#F8F8F8" //colorize and hide content div (while window is being dragged) t.contentarea.style.visibility = "hidden" } document.onmousemove = d.getdistance //get distance travelled by mouse as it moves document.onmouseup = function() { if (t.contentarea.datatype == "iframe") { //restore color and visibility of content div onmouseup t.contentarea.style.backgroundColor = "white" t.contentarea.style.visibility = "visible" } d.stop() } return false }, getdistance: function(e) { var d = dhtmlwindow var etarget = d.etarget var e = window.event || e d.distancex = e.clientX - d.initmousex //horizontal distance travelled relative to starting point d.distancey = e.clientY - d.initmousey if (etarget.className == "drag-handle") //if target element is "handle" div d.move(etarget._parent, e) else if (etarget.className == "drag-resizearea") //if target element is "resize" div d.resize(etarget._parent, e) return false //cancel default dragging behavior }, getviewpoint: function() { //get window viewpoint numbers var ie = document.all && !window.opera var domclientWidth = document.documentElement && parseInt(document.documentElement.clientWidth) || 100000 //Preliminary doc width in non IE browsers this.standardbody = (document.compatMode == "CSS1Compat") ? document.documentElement : document.body //create reference to common "body" across doctypes this.scroll_top = (ie) ? this.standardbody.scrollTop : window.pageYOffset this.scroll_left = (ie) ? this.standardbody.scrollLeft : window.pageXOffset this.docwidth = (ie) ? this.standardbody.clientWidth : (/Safari/i.test(navigator.userAgent)) ? window.innerWidth : Math.min(domclientWidth, window.innerWidth - 16) this.docheight = (ie) ? this.standardbody.clientHeight : window.innerHeight }, rememberattrs: function(t) { //remember certain attributes of the window when it's minimized or closed, such as dimensions, position on page this.getviewpoint() //Get current window viewpoint numbers t.lastx = parseInt((t.style.left || t.offsetLeft)) - dhtmlwindow.scroll_left //store last known x coord of window just before minimizing t.lasty = parseInt((t.style.top || t.offsetTop)) - dhtmlwindow.scroll_top t.lastwidth = parseInt(t.style.width) //store last known width of window just before minimizing/ closing }, move: function(t, e) { t.style.left = dhtmlwindow.distancex + dhtmlwindow.initx + "px" t.style.top = dhtmlwindow.distancey + dhtmlwindow.inity + "px" }, resize: function(t, e) { t.style.width = Math.max(dhtmlwindow.width + dhtmlwindow.distancex, 150) + "px" t.contentarea.style.height = Math.max(dhtmlwindow.contentheight + dhtmlwindow.distancey, 100) + "px" }, enablecontrols: function(e) { var d = dhtmlwindow var sourceobj = window.event ? window.event.srcElement : e.target //Get element within "handle" div mouse is currently on (the controls) if (/Minimize/i.test(sourceobj.getAttribute("title"))) //if this is the "minimize" control d.minimize(sourceobj, this._parent) else if (/Restore/i.test(sourceobj.getAttribute("title"))) //if this is the "restore" control d.restore(sourceobj, this._parent) else if (/Close/i.test(sourceobj.getAttribute("title"))) //if this is the "close" control d.close(this._parent) return false }, minimize: function(button, t) { dhtmlwindow.rememberattrs(t) button.setAttribute("src", dhtmlwindow.imagefiles[2]) button.setAttribute("title", "Restore") t.state = "minimized" //indicate the state of the window as being "minimized" t.contentarea.style.display = "none" t.statusarea.style.display = "none" if (typeof t.minimizeorder == "undefined") { //stack order of minmized window on screen relative to any other minimized windows dhtmlwindow.minimizeorder++ //increment order t.minimizeorder = dhtmlwindow.minimizeorder } t.style.left = "10px" //left coord of minmized window t.style.width = "200px" var windowspacing = t.minimizeorder * 10 //spacing (gap) between each minmized window(s) t.style.top = dhtmlwindow.scroll_top + dhtmlwindow.docheight - (t.handle.offsetHeight * t.minimizeorder) - windowspacing + "px" }, restore: function(button, t) { dhtmlwindow.getviewpoint() button.setAttribute("src", dhtmlwindow.imagefiles[0]) button.setAttribute("title", "Minimize") t.state = "fullview" //indicate the state of the window as being "fullview" t.style.display = "block" t.contentarea.style.display = "block" if (t.resizeBool) //if this window is resizable, enable the resize icon t.statusarea.style.display = "block" t.style.left = parseInt(t.lastx) + dhtmlwindow.scroll_left + "px" //position window to last known x coord just before minimizing t.style.top = parseInt(t.lasty) + dhtmlwindow.scroll_top + "px" t.style.width = parseInt(t.lastwidth) + "px" }, close: function(t) { try { var closewinbol = t.onclose() } catch (err) { //In non IE browsers, all errors are caught, so just run the below var closewinbol = true } finally { //In IE, not all errors are caught, so check if variable isn't defined in IE in those cases if (typeof closewinbol == "undefined") { alert("An error has occured somwhere inside your \"onclose\" event handler") var closewinbol = true } } if (closewinbol) { //if custom event handler function returns true if (t.state != "minimized") //if this window isn't currently minimized dhtmlwindow.rememberattrs(t) //remember window's dimensions/position on the page before closing if (window.frames["_iframe-" + t.id]) //if this is an IFRAME DHTML window window.frames["_iframe-" + t.id].location.replace("about:blank") else t.contentarea.innerHTML = "" t.style.display = "none" t.isClosed = true //tell script this window is closed (for detection in t.show()) } return closewinbol }, setopacity: function(targetobject, value) { //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between) if (!targetobject) return if (targetobject.filters && targetobject.filters[0]) { //IE syntax if (typeof targetobject.filters[0].opacity == "number") //IE6 targetobject.filters[0].opacity = value * 100 else //IE 5.5 targetobject.style.filter = "alpha(opacity=" + value * 100 + ")" } else if (typeof targetobject.style.MozOpacity != "undefined") //Old Mozilla syntax targetobject.style.MozOpacity = value else if (typeof targetobject.style.opacity != "undefined") //Standard opacity syntax targetobject.style.opacity = value }, setfocus: function(t) { //Sets focus to the currently active window this.zIndexvalue++ t.style.zIndex = this.zIndexvalue t.isClosed = false //tell script this window isn't closed (for detection in t.show()) this.setopacity(this.lastactivet.handle, 0.5) //unfocus last active window this.setopacity(t.handle, 1) //focus currently active window this.lastactivet = t //remember last active window }, show: function(t) { if (t.isClosed) { alert("DHTML Window has been closed, so nothing to show. Open/Create the window again.") return } if (t.lastx) //If there exists previously stored information such as last x position on window attributes (meaning it's been minimized or closed) dhtmlwindow.restore(t.controls.firstChild, t) //restore the window using that info else t.style.display = "block" this.setfocus(t) t.state = "fullview" //indicate the state of the window as being "fullview" }, hide: function(t) { t.style.display = "none" }, ajax_connect: function(url, t) { var page_request = false var bustcacheparameter = "" if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc page_request = new XMLHttpRequest() else if (window.ActiveXObject) { // if IE6 or below try { page_request = new ActiveXObject("Msxml2.XMLHTTP") } catch (e) { try { page_request = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { } } } else return false t.contentarea.innerHTML = this.ajaxloadinghtml page_request.onreadystatechange = function() { dhtmlwindow.ajax_loadpage(page_request, t) } if (this.ajaxbustcache) //if bust caching of external page bustcacheparameter = (url.indexOf("?") != -1) ? "&" + new Date().getTime() : "?" + new Date().getTime() page_request.open('GET', url + bustcacheparameter, true) page_request.send(null) }, ajax_loadpage: function(page_request, t) { if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1)) { t.contentarea.innerHTML = page_request.responseText } }, stop: function() { dhtmlwindow.etarget = null //clean up document.onmousemove = null document.onmouseup = null }, addEvent: function(target, functionref, tasktype) { //assign a function to execute to an event handler (ie: onunload) var tasktype = (window.addEventListener) ? tasktype : "on" + tasktype if (target.addEventListener) target.addEventListener(tasktype, functionref, false) else if (target.attachEvent) target.attachEvent(tasktype, functionref) }, cleanup: function() { for (var i = 0; i < dhtmlwindow.tobjects.length; i++) { dhtmlwindow.tobjects[i].handle._parent = dhtmlwindow.tobjects[i].resizearea._parent = dhtmlwindow.tobjects[i].controls._parent = null } window.onload = null } } //End dhtmlwindow object document.write('<div id="dhtmlwindowholder"><span style="display:none">.</span></div>') //container that holds all dhtml window divs on page window.onunload=dhtmlwindow.cleanup
nyandikadon/Chat-Application
WebMessenger/windowfiles/dhtmlwindow.js
JavaScript
mit
21,483
(function($) { $.fn.listswap = function(options) { var settings = $.extend({ truncate : false, height : null, is_scroll : false, label_add : 'Add', label_remove : 'Remove', add_class : null, rtl : false, }, options); var i = 1; var wrapper = this.parent(); var destination_search = ''; var source_search = ''; var rand = Math.floor( (Math.random() * 999999) + 1 ); var div_id = "#listboxswap_" + rand; var div_id_ = "listboxswap_" + rand; var div_class_ = ''; var rtl_class_ = ''; (settings.rtl === true) ? rtl_class_ = ' rtl' : rtl_class_; (settings.add_class) ? div_class_ = ' ' + settings.add_class : div_class_; $(this).wrapAll("<div id='" + div_id_ + "' class='listboxswap" + rtl_class_ + div_class_ + "'></div>"); wrapper = $(div_id + '.listboxswap'); if(this.size() != 2) { var warning = '<p>You must choose a <strong>source select list</strong> and a <strong>destination select list</strong> only.</p>'; $(this.parent()).append(warning); return; } var source_select_id = this[0].id; var destination_select_id = this[1].id; this.each( function() { console.log(wrapper[0]); var class_name = ''; var select_id = $(this)[0].id; var listbox_id = 'listbox_' + select_id + '_wrapper'; var parent_wrapper = wrapper[0]; var parent_element = '<div id="' + listbox_id + '"></div>'; var options_count = $(div_id + " #" + select_id + " > option").length; var truncate_class = ''; var round_class = ''; create_element(parent_wrapper, parent_element); (settings.truncate) ? truncate_class = ' class="truncate"' : truncate_class; (i % 2 !== 0) ? class_name = 'source_wrapper' : class_name = 'destination_wrapper'; $('#' + listbox_id).addClass(class_name); if($(this).attr('data-text')) { var text_data = '<p' + truncate_class + '>' + $(this).attr('data-text') + '</p>'; $(div_id + ' .' + class_name).append(text_data); } if($(this).attr('data-search')) { var search_data = '<div class="listbox_search">' + '<input type="text" id="search_listbox" name="search_listbox" value="'+ $(this).attr('data-search') + '" />' + '<span class="clear"></span>' + '</div>'; $(div_id + ' .' + class_name).append(search_data); if(!$(this).attr('data-text')){ $(div_id + ' .listbox_search').addClass('listbox_round_class'); } } create_element('div#' + listbox_id, '<ul></ul>'); if(!$(this).attr('data-text') && !$(this).attr('data-search')){ $(div_id + ' .source_wrapper ul, ' + div_id + ' .destination_wrapper ul').addClass('listbox_round_class'); } $(div_id + " #" + select_id + " > option").each(function() { var value = this.value; var label = this.text; var wrapper = 'div#' + listbox_id; var element = '<li class="listbox_option" data-value="' + value + '"><span' + truncate_class + '>' + label + '</span></li>'; $(div_id + ' ' + wrapper + ' ul').append(element); }); (i % 2 !== 0) ? source_search = $(this).attr('data-search') : destination_search = $(this).attr('data-search'); i++; }); if(settings.height) { $(div_id + ' .source_wrapper ul, ' + div_id + ' .destination_wrapper ul').css('height', settings.height); } if(settings.is_scroll === true) { $(div_id + ' .source_wrapper ul, ' + div_id + ' .destination_wrapper ul').css('overflow-y', 'scroll'); } $(this).css('display','none'); $(this).css('visibility','hidden'); var controls = '<div class="listbox_controls">' + '<ul>' + '<li class="add"><span class="arrow"></span><span class="label">' + settings.label_add + '</span></li>' + '<li class="remove"><span class="arrow"></span><span class="label">' + settings.label_remove + '</span></li>' + '</ul>' + '</div>'; $(controls).insertAfter( div_id + " .source_wrapper" ); $(div_id).append('<div class="listbox_clear"></div>'); $(div_id + ' .source_wrapper .listbox_option, ' + div_id + ' .destination_wrapper .listbox_option').click(function() { $(this).toggleClass('selected'); }); $(div_id + ' .listbox_controls .add').click(function() { $(div_id + ' .source_wrapper .listbox_option.selected').each(function() { add_remove_handler($(this), div_id + ' .destination_wrapper ul', source_select_id, destination_select_id); }); refresh_list(); }); $(div_id + ' .listbox_controls .remove').click(function() { $(div_id + ' .destination_wrapper .listbox_option.selected').each(function() { add_remove_handler($(this), div_id + ' .source_wrapper ul', destination_select_id, source_select_id); }); refresh_list(); }); if (source_search) { var search_selector = div_id + ' .source_wrapper'; search_filter(search_selector); reset_search_input(search_selector, source_select_id); clear_button(search_selector); } if (destination_search) { var search_selector = div_id + ' .destination_wrapper'; search_filter(search_selector); reset_search_input(search_selector, destination_select_id); clear_button(search_selector); } refresh_list(); function add_remove_handler(target, destination, select_1, select_2) { var selected_options = target.clone(true); var data_value = target.attr('data-value'); var text = target[0].textContent; $(selected_options).removeClass('selected'); $(destination).append(selected_options); $(div_id + " select#" + select_1 + " option[value='" + data_value + "']").remove(); $(div_id + " select#" + select_2).append($("<option></option>").attr("value",data_value).text(text)); target.remove(); } function create_element(wrapper, element) { return $(element).appendTo(wrapper); } function search_filter (selector) { $(selector + ' .listbox_search input#search_listbox').keyup(function(){ remove_selection(selector); var val = $(this).val().toString().toLowerCase(); $(selector + ' ul > li').each(function(){ var text = $(this).text().toString().toLowerCase(); (text.indexOf(val) != -1) ? $(this).show() : $(this).hide(); if( $(this).hasClass('even') ) $(this).removeClass('even'); if( $(this).hasClass('odd') ) $(this).removeClass('odd'); }); if(!val) refresh_list(); }); } function reset_search_input(search_selector, select_id) { $(search_selector + ' .listbox_search input#search_listbox').focus(function(){ var val = $(this).val().toString().toLowerCase(); var data_search = $(div_id + ' select#' + select_id).attr('data-search').toString().toLowerCase(); if(val == data_search) $(this).val(''); }); $(search_selector + ' .listbox_search input#search_listbox').blur(function(){ var val = $(this).val().toString().toLowerCase(); var data_search = $(div_id + ' select#' + select_id).attr('data-search').toString(); if(val == '') $(this).val(data_search); }); } function clear_button (selector) { $(selector + ' .listbox_search .clear').click(function() { $(selector + ' .listbox_search input#search_listbox').val(''); $(selector + ' .listbox_search input#search_listbox').focus(); $(selector + ' ul > li').each(function(){ $(this).show(); }); refresh_list(); }); } function remove_selection(selector) { $(selector + ' li.listbox_option').each(function() { if( $(this).hasClass('selected') ) $(this).removeClass('selected'); }); } function refresh_list() { $(div_id + ' .source_wrapper li.listbox_option, .listboxswap .destination_wrapper li.listbox_option').each(function() { if( $(this).hasClass('even') ) $(this).removeClass('even'); if( $(this).hasClass('odd') ) $(this).removeClass('odd'); }); $(div_id + ' .source_wrapper li.listbox_option').filter( ":even" ).addClass('even'); $(div_id + ' .source_wrapper li.listbox_option').filter( ":odd" ).addClass('odd'); $(div_id + ' .destination_wrapper li.listbox_option').filter( ":even" ).addClass('even'); $(div_id + ' .destination_wrapper li.listbox_option').filter( ":odd" ).addClass('odd'); } } }(jQuery));
phedde/listSwap
jquery.listswap.js
JavaScript
mit
8,236
//a civilization handles everything that change on race like ship-layout or troops per population function humanCivilization(){ //load the needed images this.arrayImages = new Array(); //troops this.arrayImages["troopRedSmall"] = new Image(); this.arrayImages["troopRedSmall"].src = "../Images/troopRedSmall.png" this.arrayImages["troopBlueSmall"] = new Image(); this.arrayImages["troopBlueSmall"].src = "../Images/troopBlueSmall.png" this.getTroopImage = function(arrayTroop){ //fit the image if(arrayTroop["player"] == 0){//player1 is blue and player2 is red var strImageId = "troopRedSmall"; }else{ var strImageId = "troopBlueSmall"; } return this.arrayImages[strImageId]; } }
EyeBook888/Themis
both/civilizations.js
JavaScript
mit
754
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _desc, _value, _class; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; } var middle = require('../dist/middle.js').default; var mdeco = require('../dist/middle.js').decorator; var Dragon = (_class = function () { function Dragon() { _classCallCheck(this, Dragon); this.txt = 'am class'; } _createClass(Dragon, [{ key: 'drag', value: function drag(x, y) { console.log('drag', this && this.txt); var zzz = this || {}; return zzz.txt + ' tadaaa ' + x + y; } }]); return Dragon; }(), (_applyDecoratedDescriptor(_class.prototype, 'drag', [mdeco], Object.getOwnPropertyDescriptor(_class.prototype, 'drag'), _class.prototype)), _class); // console.log( 'Dragon', Dragon ) Dragon.prototype.drag.use(function (next, x, y) { console.log('proto.drag.use', this && this.txt); return next(x, y); }); var dragn = new Dragon(); dragn.txt = 'am instance'; dragn.drag.use(function (next, x, y) { console.log('drag.use', this && this.txt); return next(x, y); }, dragn); var x = dragn.drag(1, 2);
luckylooke/middle
src/babelOutput.js
JavaScript
mit
2,465
import React from 'react'; const VideoListItem = (props)=>{ const video = props.videos; const onVideoSelect = props.onVideoSelect; const imageUrl = video.snippet.thumbnails.default.url; return( <li onClick={()=> onVideoSelect(video)} className="list-group-item"> <div className="video-list media"> <div className="media-left"> <img className="media-object" src={imageUrl}/> </div> </div> <div className="media-body"> <div className="media-heading"> {video.snippet.title} </div> </div> </li> ); }; export default VideoListItem;
bournecreative/react-video-search
src/components/video_list_item.js
JavaScript
mit
625
/** * @jsx React.DOM */ /* not used but thats how you can use touch events * */ //React.initializeTouchEvents(true); /* not used but thats how you can use animation and other transition goodies * */ //var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; /** * we will use yes for true * we will use no for false * * React has some built ins that rely on state being true/false like classSet() * and these will not work with yes/no but can easily be modified / reproduced * * this single app uses the yes/no var so if you want you can switch back to true/false * * */ var yes = 'yes', no = 'no'; //var yes = true, no = false; /* bootstrap components * */ var Flash = ReactBootstrap.Alert; var Btn = ReactBootstrap.Button; var Modal = ReactBootstrap.Modal; /* create the container object * */ var snowUI = {}; /* create flash message * */ snowUI.SnowpiFlash = React.createClass({displayName: 'SnowpiFlash', getInitialState: function() { return { isVisible: true }; }, getDefaultProps: function() { return ({showclass:'info'}); }, render: function() { console.log(this.props); if(!this.state.isVisible) return null; var message = this.props.message ? this.props.message : this.props.children; return ( Flash({bsStyle: this.props.showclass, onDismiss: this.dismissFlash}, React.DOM.p(null, message) ) ); }, dismissFlash: function() { this.setState({isVisible: false}); } }); /* my little man component * simple example * */ snowUI.SnowpiMan = React.createClass({displayName: 'SnowpiMan', getDefaultProps: function() { return ({divstyle:{float:'right',}}); }, render: function() { return this.transferPropsTo( React.DOM.div({style: this.props.divstyle, dangerouslySetInnerHTML: {__html: snowtext.logoman}}) ); } }); //wallet select snowUI.walletSelect = React.createClass({displayName: 'walletSelect', componentDidMount: function() { var _this = this $("#walletselect").selectbox({ onChange: function (val, inst) { _this.props.route(val) }, effect: "fade" }); }, render: function() { var wallets; if(this.props.section === snowPath.wallet.substring(1)) { var _df = (this.props.wallet) ? snowPath.wallet + '/' + this.props.wallet : snowPath.wallet; } else { var _df = this.props.section; } return this.transferPropsTo( React.DOM.div({className: "list"}, React.DOM.div({className: "walletmsg", style: {display:'none'}}), React.DOM.select({onChange: this.route, id: "walletselect", defaultValue: _df}, wallets, React.DOM.optgroup(null), React.DOM.option({value: snowPath.wallet}, "list wallets"), React.DOM.option({value: snowPath.receive}, "receive coins"), React.DOM.option({value: snowPath.settings}, "settings"), React.DOM.option({value: snowPath.inq}, "inquisive queue") ) ) ); } }); var UI = React.createClass({displayName: 'UI', getInitialState: function() { /** * initialize the app * the plan is to keep only active references in root state. * we should use props for the fill outs * */ return { section:snowPath.wallet, moon:false, wallet:false, }; }, componentWillReceiveProps: function(nextProps) { /** * should be a mimic of initial * * */ console.log('UI nextProps',nextProps) if(nextProps.section)this.setState({section:nextProps.section}); if(nextProps.moon)this.setState({moon:nextProps.moon}); if(nextProps.wallet)this.setState({wallet:nextProps.wallet}); return false; }, changeTheme: function() { var mbody = $('body'); if(mbody.hasClass('themeable-snowcoinslight')==true) { mbody.removeClass('themeable-snowcoinslight'); } else { mbody.addClass('themeable-snowcoinslight'); } }, route: function(route) { bone.router.navigate(snowPath.root + route, {trigger:true}); }, render: function() { return this.transferPropsTo( React.DOM.div(null, React.DOM.div({id: "snowpi-body"}, React.DOM.div({id: "walletbarspyhelper", style: {display:'block'}}), React.DOM.div({id: "walletbar", className: "affix"}, React.DOM.div({className: "wallet"}, React.DOM.div({className: "button-group"}, Btn({bsStyle: "link", 'data-toggle': "dropdown", className: "dropdown-toggle"}, snowtext.menu.menu.name), React.DOM.ul({className: "dropdown-menu", role: "menu"}, React.DOM.li({className: "nav-item-add"}, " ", React.DOM.a({onClick: this.route(snowPath.wallet + '/new')}, snowtext.menu.plus.name)), React.DOM.li({className: "nav-item-home"}, " ", React.DOM.a({onClick: this.route(snowPath.wallet)}, snowtext.menu.list.name)), React.DOM.li({className: "nav-item-receive"}, React.DOM.a({onClick: this.route(snowPath.receive)}, snowtext.menu.receive.name)), React.DOM.li({className: "nav-item-settings"}, React.DOM.a({onClick: this.route(snowPath.settings)}, snowtext.menu.settings.name)), React.DOM.li({className: "divider"}), React.DOM.li({className: "nav-item-snowcat"}), React.DOM.li({className: "divider"}), React.DOM.li(null, React.DOM.div(null, React.DOM.div({onClick: this.changeTheme, className: "walletmenuspan changetheme bstooltip", title: "Switch between the light and dark theme", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, React.DOM.span({className: "glyphicon glyphicon-adjust"})), React.DOM.div({className: "walletmenuspan bstooltip", title: "inquisive queue", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, " ", React.DOM.a({className: "nav-item-inq"})), React.DOM.div({className: "walletmenuspan bstooltip", title: "Logout", 'data-toggle': "tooltip", 'data-placement': "right", 'data-container': "body"}, " ", React.DOM.a({href: "/signout"}, " ", React.DOM.span({className: "glyphicon glyphicon-log-out"}))), React.DOM.div({className: "clearfix"}) ) ) ) ) ), snowUI.walletSelect({route: this.route, section: this.state.section, wallet: this.state.wallet}), React.DOM.div({className: "logo"}, React.DOM.a({title: "inquisive.io snowcoins build info", 'data-container': "body", 'data-placement': "bottom", 'data-toggle': "tooltip", className: "walletbar-logo"})) ), React.DOM.div({className: "container-fluid"}, React.DOM.div({id: "menuspy", className: "dogemenu col-xs-1 col-md-2", 'data-spy': "affix", 'data-offset-top': "0"} ), React.DOM.div({id: "menuspyhelper", className: "dogemenu col-xs-1 col-md-2"}), React.DOM.div({className: "dogeboard col-xs-11 col-md-10"}, snowUI.AppInfo(null) ) ) /* end snowpi-body */ ) ) ); } }); //app info snowUI.AppInfo = React.createClass({displayName: 'AppInfo', render: function() { return ( React.DOM.div({id: "easter-egg", style: {display:'none'}}, React.DOM.div(null, React.DOM.div({className: "blocks col-xs-offset-1 col-xs-10 col-md-offset-1 col-md-5 col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.h4(null, "Get Snowcoins"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-11"}, React.DOM.a({href: "https://github.com/inquisive/snowcoins", target: "_blank"}, "GitHub / Installation")), React.DOM.div({className: "col-sm-offset-1 col-sm-11"}, " ", React.DOM.a({href: "https://github.com/inquisive/snowcoins/latest.zip", target: "_blank"}, "Download zip"), " | ", React.DOM.a({href: "https://github.com/inquisive/snowcoins/latest.tar.gz", target: "_blank"}, "Download gz")) ), React.DOM.h4(null, "Built With"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://nodejs.org", target: "_blank"}, "nodejs")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://keystonejs.com", target: "_blank"}, "KeystoneJS")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://getbootstrap.com/", target: "_blank"}, "Bootstrap")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://github.com/countable/node-dogecoin", target: "_blank"}, "node-dogecoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://mongoosejs.com/", target: "_blank"}, "mongoose")) ), React.DOM.h4(null, "Donate"), React.DOM.div({className: "row"}, React.DOM.div({title: "iq", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, "iq: ", React.DOM.a({href: "https://inquisive.com/iq/snowkeeper", target: "_blank"}, "snowkeeper")), React.DOM.div({title: "Dogecoin", className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://snow.snowpi.org/share/dogecoin", target: "_blank"}, "Ðogecoin")), React.DOM.div({title: "Bitcoin", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "https://snow.snowpi.org/share/bitcoin", target: "_blank"}, "Bitcoin")), React.DOM.div({title: "Litecoin", className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://snow.snowpi.org/share/litecoin", target: "_blank"}, "Litecoin")), React.DOM.div({title: "Darkcoin", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "https://snow.snowpi.org/share/darkcoin", target: "_blank"}, "Darkcoin")) ) ), React.DOM.div({className: "blocks col-xs-offset-1 col-xs-10 col-md-offset-1 col-md-5 col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.h4(null, "Digital Coin Wallets"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://dogecoin.com", target: "_blank"}, "dogecoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://bitcoin.org", target: "_blank"}, "bitcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://litecoin.org", target: "_blank"}, "litecoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://vertcoin.org", target: "_blank"}, "vertcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://octocoin.org", target: "_blank"}, "888")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://auroracoin.org", target: "_blank"}, "auroracoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://blackcoin.co", target: "_blank"}, "blackcoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://digibyte.co", target: "_blank"}, "digibyte")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://digitalcoin.co", target: "_blank"}, "digitalcoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://darkcoin.io", target: "_blank"}, "darkcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://maxcoin.co.uk", target: "_blank"}, "maxcoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://mintcoin.co", target: "_blank"}, "mintcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://einsteinium.org", target: "_blank"}, "einsteinium")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://peercoin.net", target: "_blank"}, "peercoin ")) ), React.DOM.h4(null, "Links"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://reddit.com/r/snowcoins", target: "_blank"}, "/r/snowcoins")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://reddit.com/r/dogecoin", target: "_blank"}, "/r/dogecoin")) ) ), React.DOM.div({className: "clearfix"}) ) ) ); } });
inquisive/wallet-manager
public/js/.module-cache/64e44a4ec59266c8ee9369ec48b99df69b1144d1.js
JavaScript
mit
12,511
module.exports = function(grunt) { grunt.initConfig({ qunit: { all: ['test/index.html'] }, watch: { js: { files: ['**/*.js'], tasks: ['qunit'], options: { spawn: false, }, }, coffee: { files: ['**/*.md'], tasks: ['coffee'], options: { spawn: false, }, }, }, coffee: { compile: { files: { 'reab.js': 'README.md', 'test/tests.js': 'test/tests.md', } }, }, concurrent: { dev: { tasks: ['watch:js', 'watch:coffee'], options: { logConcurrentOutput: true } } } }); grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-coffee'); grunt.loadNpmTasks('grunt-concurrent'); grunt.registerTask('test', ['qunit']); grunt.registerTask('test:watch', ['watch:js']); grunt.registerTask('coff', ['coffee']); grunt.registerTask('coff:watch', ['watch:coffee']); grunt.registerTask('dev', ['concurrent:dev']); };
Horsed/reab
Gruntfile.js
JavaScript
mit
1,126
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, brackets, $ */ define(function (require, exports, module) { "use strict"; // Brackets modules var MultiRangeInlineEditor = brackets.getModule("editor/MultiRangeInlineEditor").MultiRangeInlineEditor, FileIndexManager = brackets.getModule("project/FileIndexManager"), EditorManager = brackets.getModule("editor/EditorManager"), JSUtils = brackets.getModule("language/JSUtils"), PerfUtils = brackets.getModule("utils/PerfUtils"); /** * Return the token string that is at the specified position. * * @param hostEditor {!Editor} editor * @param {!{line:Number, ch:Number}} pos * @return {String} token string at the specified position */ function _getFunctionName(hostEditor, pos) { var token = hostEditor._codeMirror.getTokenAt(pos); // If the pos is at the beginning of a name, token will be the // preceding whitespace or dot. In that case, try the next pos. if (token.string.trim().length === 0 || token.string === ".") { token = hostEditor._codeMirror.getTokenAt({line: pos.line, ch: pos.ch + 1}); } // Return valid function expressions only (function call or reference) if (!((token.type === "variable") || (token.type === "variable-2") || (token.type === "property"))) { return null; } return token.string; } /** * @private * For unit and performance tests. Allows lookup by function name instead of editor offset * without constructing an inline editor. * * @param {!string} functionName * @return {$.Promise} a promise that will be resolved with an array of function offset information */ function _findInProject(functionName) { var result = new $.Deferred(); FileIndexManager.getFileInfoList("all") .done(function (fileInfos) { PerfUtils.markStart(PerfUtils.JAVASCRIPT_FIND_FUNCTION); JSUtils.findMatchingFunctions(functionName, fileInfos) .done(function (functions) { PerfUtils.addMeasurement(PerfUtils.JAVASCRIPT_FIND_FUNCTION); result.resolve(functions); }) .fail(function () { PerfUtils.finalizeMeasurement(PerfUtils.JAVASCRIPT_FIND_FUNCTION); result.reject(); }); }) .fail(function () { result.reject(); }); return result.promise(); } /** * @private * For unit and performance tests. Allows lookup by function name instead of editor offset . * * @param {!Editor} hostEditor * @param {!string} functionName * @return {$.Promise} a promise that will be resolved with an InlineWidget * or null if we're not going to provide anything. */ function _createInlineEditor(hostEditor, functionName) { var result = new $.Deferred(); PerfUtils.markStart(PerfUtils.JAVASCRIPT_INLINE_CREATE); _findInProject(functionName).done(function (functions) { if (functions && functions.length > 0) { var jsInlineEditor = new MultiRangeInlineEditor(functions); jsInlineEditor.load(hostEditor); PerfUtils.addMeasurement(PerfUtils.JAVASCRIPT_INLINE_CREATE); result.resolve(jsInlineEditor); } else { // No matching functions were found PerfUtils.addMeasurement(PerfUtils.JAVASCRIPT_INLINE_CREATE); result.reject(); } }).fail(function () { PerfUtils.finalizeMeasurement(PerfUtils.JAVASCRIPT_INLINE_CREATE); result.reject(); }); return result.promise(); } /** * This function is registered with EditorManager as an inline editor provider. It creates an inline editor * when the cursor is on a JavaScript function name, finds all functions that match the name * and shows (one/all of them) in an inline editor. * * @param {!Editor} editor * @param {!{line:Number, ch:Number}} pos * @return {$.Promise} a promise that will be resolved with an InlineWidget * or null if we're not going to provide anything. */ function javaScriptFunctionProvider(hostEditor, pos) { // Only provide a JavaScript editor when cursor is in JavaScript content if (hostEditor.getModeForSelection() !== "javascript") { return null; } // Only provide JavaScript editor if the selection is within a single line var sel = hostEditor.getSelection(); if (sel.start.line !== sel.end.line) { return null; } // Always use the selection start for determining the function name. The pos // parameter is usually the selection end. var functionName = _getFunctionName(hostEditor, sel.start); if (!functionName) { return null; } return _createInlineEditor(hostEditor, functionName); } // init EditorManager.registerInlineEditProvider(javaScriptFunctionProvider); PerfUtils.createPerfMeasurement("JAVASCRIPT_INLINE_CREATE", "JavaScript Inline Editor Creation"); PerfUtils.createPerfMeasurement("JAVASCRIPT_FIND_FUNCTION", "JavaScript Find Function"); // for unit tests only exports.javaScriptFunctionProvider = javaScriptFunctionProvider; exports._createInlineEditor = _createInlineEditor; exports._findInProject = _findInProject; });
L0g1k/quickfire-old
src/extensions/default/JavaScriptQuickEdit/main.js
JavaScript
mit
7,152
import React from 'react'; import { cleanup, fireEvent, render, findAllByTestId, waitForElement } from '@testing-library/react'; import Actions from '../../src/back-office/components/Actions'; describe('Click some actions', () => { // automatically unmount and cleanup DOM after the test is finished. afterEach(cleanup); it('calls you back', async () => { const callback = jest.fn(); const { container } = render( <Actions onAction={callback}/> ); const data = await waitForElement(() => findAllByTestId(container, 'actions')); (await data).forEach(e => fireEvent.click(e)); const calls = callback.mock.calls; expect(calls.length).toEqual(3); expect(calls[0][0]).toEqual('info'); expect(calls[1][0]).toEqual('edit'); expect(calls[2][0]).toEqual('delete'); }); });
mihailgaberov/es6-bingo-game
back-office-tests/__tests__/Actions.test.js
JavaScript
mit
826
var test = require('tape') var path = require('path') var fs = require('fs') var rimraf = require('rimraf') var debug = require('debug') var makeGit = require('../') var temp = path.join(__dirname, 'tmp') var repoName = 'testRepo' var workTree = path.join(temp, repoName) var cloneName = 'cloneRepo' var cloneTree = path.join(temp, cloneName) var git var clone test('ensure clean directory', function(t) { if (fs.existsSync(temp)) { rimraf(temp, function(err) { t.error(err, 'tmp dir removed') t.end() }) } else { t.pass('no temp dir exists') t.end() } }) test('create git object', function(t) { t.plan(1) git = makeGit(workTree) t.pass('git instance created') }) test('init test repo', function(t) { t.plan(1) git.init(function(err, stdout, stderr) { t.error(err, 'initialzed test repo') debug(stdout) debug(stderr) }) }) test('run a string command', function(t) { t.plan(1) git('status', function(err, stdout, stderr) { t.error(err, 'string command sucessfully run') debug(stdout) debug(stderr) }) }) test('run a file command', function(t) { t.plan(1) git(['status'], function(err, stdout, stderr) { t.error(err, 'array command sucessfully run') debug(stdout) debug(stderr) }) }) test('run a string command w/ options', function(t) { t.plan(1) git('status', { timeout: 1500 }, function(err, stdout, stderr) { t.error(err, 'string command sucessfully run') debug(stdout) debug(stderr) }) }) test('run a file command w/ options', function(t) { t.plan(1) git(['status'], { timeout: 15000 }, function(err, stdout, stderr) { t.error(err, 'array command sucessfully run') debug(stdout) debug(stderr) }) }) test('clone testRepo', function(t) { t.plan(1) clone = makeGit(cloneTree) clone.clone(workTree, function(err, stdout, stderr) { t.error(err, 'repo cloned') debug(stdout) debug(stderr) }) }) test('clean up', function(t) { t.plan(1) rimraf(temp, function(err) { t.error(err, 'tests cleaned up') }) })
bcomnes/quick-gits
test/index.js
JavaScript
mit
2,103
var searchData= [ ['g_5fesame',['g_esame',['../structesame__t.html#a7f75496c6ec081c2b8983f61084281a1',1,'esame_t']]], ['g_5fultimo_5favvio',['g_ultimo_avvio',['../structesame__t.html#ab3272815de95113194244da692604433',1,'esame_t']]], ['gg_5fripasso',['gg_ripasso',['../structesame__t.html#a1f8c3466614a7d45deaf5825144700a8',1,'esame_t']]], ['gg_5fstudio_5fsett',['gg_studio_sett',['../structesame__t.html#ac60ccede2db07fdb96f9a3030f589dbf',1,'esame_t']]], ['giorni_5fripasso_5fmodificato',['giorni_ripasso_modificato',['../base__handlers_8cpp.html#a614a9b0f253230db42496a8d42f3c2b4',1,'base_handlers.cpp']]], ['giorno_5fcliccato',['giorno_cliccato',['../base__handlers_8cpp.html#a1d12123750ca6e58d67e2d11c52c00a5',1,'base_handlers.cpp']]], ['gtk_5fbutton_5fchiudi',['GTK_BUTTON_CHIUDI',['../flashcards__handlers_8cpp.html#a06fc87d81c62e9abb8790b6e5713c55bae91293c00f7d174f1344a6a86ee050d3',1,'flashcards_handlers.cpp']]] ];
rohmable/CStudy
doc/html/search/all_6.js
JavaScript
mit
938
$(document).ready(function() { var win = $(window), body = $('body').hasClass('home'), navigation = $('.navigation'), slider = $('.featured-slider-home'), slider_content = $('.featured-slider-home__content'), limit = 400; var bodyPadding = function() { $('body').css({ 'padding-top' : navigation.outerHeight()}); } var selectPicker = function() { $('.cart__resume-table__product-quantity.selectpicker').selectpicker({ style: 'btn-link item_refresh', size: 5 }); }; var isMobile = function() { return ( win.width() < 768 ? true : false ); } var changeColspan = function() { if(win.width() < 421) { $('.search-page__table--thead-th').attr('colspan', 1); } else { $('.search-page__table--thead-th').attr('colspan', 2); } } var isSmallMobile = function() { return ( win.width() < 320 ? true : false ); } var setHeightElement = function(boxArray, tallestElement) { for(var i = 0; i < boxArray.length; i++){ $(boxArray[i]).css({'height' : tallestElement +'px' }); } boxArray = []; } var getSidebarWidth = function() { return $('.sidebar__sidebar-container').width(); } var setSidebarWidth = function() { $('.sidebar__sidebar').css({'width': getSidebarWidth() }); } setSidebarWidth(); var alignHeights = function (){ if(!isSmallMobile()) { var tallestElement = 0, currentElementHeight = 0, boxArray = [], container = $('.symmetrical-container'), boxArray = container.children('.symmetrical'); for(var i = 0; i < boxArray.length; i++){ $(boxArray[i]).css({'height' : 'auto'}); currentElementHeight = $(boxArray[i]).outerHeight(); if(currentElementHeight > tallestElement){ tallestElement = currentElementHeight; } } setTimeout(setHeightElement(boxArray, tallestElement), 200); } else { $('.symmetrical').css({'height' : 'auto'}); } } var updateIcon = function() { $(".footer__menu").each(function() { var status = $(this).hasClass( "footer__menu--close"); if(status) { $(this).find('.mdi').removeClass('mdi-chevron-up'); $(this).find('.mdi').addClass('mdi-chevron-down'); } else { $(this).find('.mdi').removeClass('mdi-chevron-down'); $(this).find('.mdi').addClass('mdi-chevron-up'); } }); }; var updateMenu = function(element, status, menu){ $(element).parents('footer__menu'); $('.footer').find('.footer__menu').addClass('footer__menu--close'); if(status) { $(menu).removeClass('footer__menu--close').fadeIn(); } else { $(menu).addClass('footer__menu--close').fadeIn(); } updateIcon(); }; $('.footer__section-icon > .mdi').click(function(event) { event.preventDefault(); var element = $(this); var menu = $(element).closest(".footer__menu"); var status = menu.hasClass( "footer__menu--close"); updateMenu(element, status, menu); }); $.validate({ }); bodyPadding(); updateIcon(); changeColspan(); selectPicker(); var doParallax = function(element){ var banner = $(element); if(body && banner.length) { var initPosition = 0; var distance = banner.offset().top - win.scrollTop(); var positionY = distance/6; if(isMobile()) { banner.css('backgroundPosition', '0 '+ '0'); } else { banner.css('backgroundPosition', '50% '+ positionY + 'px'); } } } win.on('scroll', function() { doParallax('.featured-banner-home'); doParallax('.featured-banner-second-home'); if(win.width() > 768) { var st = $(this).scrollTop(); var navbanner = $('.navbanner') || false; slider_content.css({ 'opacity' : (1 - st/limit), 'position':'relative', 'top' : (st/2) }); if(win.scrollTop() > navigation.outerHeight()) { navigation.addClass('navigation-scrolled'); navbanner.addClass('nav-hidde').removeClass('nav-show'); } else { navigation.removeClass('navigation-scrolled'); navbanner.removeClass('nav-hidde').addClass('nav-show'); } } }); $('.main-slider').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: true, prevArrow: $('.prev'), nextArrow: $('.next'), speed: 2000, autoplay: true, autoplaySpeed: 3000, fade: true, }); alignHeights(); $(window).resize(function() { // swap_logo(); bodyPadding(); alignHeights(); setSidebarWidth(); changeColspan(); }); var setCategoryMenu = function () { $('.sidebar__sidebar-submenu').slideDown(); } setCategoryMenu(); $(".sidebar__sidebar-list-toggle").click(function(e){ e.preventDefault(); var isActive = $(this).next('.sidebar__sidebar-submenu').hasClass('active'); if(!isActive) { $(this).children(".mdi").addClass('mdi-chevron-up'); $(this).children(".mdi").removeClass('mdi-chevron-down'); $(this).next(".sidebar__sidebar-submenu").slideDown(); $(this).next(".sidebar__sidebar-submenu").addClass('active'); } else { $(this).children('.mdi').removeClass('mdi-chevron-up'); $(this).children('.mdi').addClass('mdi-chevron-down'); $(this).next(".sidebar__sidebar-submenu").slideUp(); $(this).next(".sidebar__sidebar-submenu").removeClass('active'); } }); var $adminBar = $('#admin-bar-iframe'); if ($adminBar.length) { $('body').css({ position: 'initial' }); $('#top-navbar').css({ position: 'relative' }); $('.navbar.navbar-fixed-top.navigation').css({ 'margin-top': '40px' }); } });
carlosvazquez/gourmet-theme
src/assets/app.js
JavaScript
mit
5,645
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ var TAG_TILE_MAP = 1; //------------------------------------------------------------------ // // TileDemo // //------------------------------------------------------------------ var TileDemo = cc.Layer.extend({ ctor:function () { this._super(); cc.associateWithNative(this, cc.Layer); this.init(); // 'browser' can use touches or mouse. // The benefit of using 'touches' in a browser, is that it works both with mouse events or touches events var t = cc.config.platform; if (t == 'browser' || t == 'mobile') { this.setTouchEnabled(true); } else if (t == 'desktop') { this.setMouseEnabled(true); } }, title:function () { return "No title"; }, subtitle:function () { return "drag the screen"; }, onEnter:function () { //this.m_label.setString(this.title().toString()); //this.m_subtitle.setString(this.subtitle().toString()); this._super(); var s = director.getWinSize(); // add title and subtitle var title = this.title(); var label = cc.LabelTTF.create(title, "Arial", 28); this.addChild(label, 1); label.setPosition(cc.p(s.width / 2, s.height - 50)); var strSubtitle = this.subtitle(); if (strSubtitle) { var l = cc.LabelTTF.create(strSubtitle, "Thonburi", 16); this.addChild(l, 1); l.setPosition(cc.p(s.width / 2, s.height - 80)); } // add menu var item1 = cc.MenuItemImage.create(s_pathB1, s_pathB2, this.onBackCallback, this); var item2 = cc.MenuItemImage.create(s_pathR1, s_pathR2, this.onRestartCallback, this); var item3 = cc.MenuItemImage.create(s_pathF1, s_pathF2, this.onNextCallback, this); var menu = cc.Menu.create(item1, item2, item3); menu.setPosition(0, 0); item1.setPosition(s.width / 2 - 100, 30); item2.setPosition(s.width / 2, 30); item3.setPosition(s.width / 2 + 100, 30); this.addChild(menu, 1); }, onRestartCallback:function (sender) { var s = new TileMapTestScene(); s.addChild(restartTileMapTest()); director.replaceScene(s); }, onNextCallback:function (sender) { var s = new TileMapTestScene(); s.addChild(nextTileMapTest()); director.replaceScene(s); }, onBackCallback:function (sender) { var s = new TileMapTestScene(); s.addChild(previousTileMapTest()); director.replaceScene(s); }, onTouchesMoved:function (touches, event) { var touch = touches[0]; var delta = touch.getDelta(); var node = this.getChildByTag(TAG_TILE_MAP); var diff = cc.pAdd(delta, node.getPosition()); node.setPosition(diff); }, onMouseDragged:function (event) { var delta = event.getDelta(); var node = this.getChildByTag(TAG_TILE_MAP); var diff = cc.pAdd(delta, node.getPosition()); node.setPosition(diff); } }); var TileMapTest = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TileMapAtlas.create(s_tilesPng, s_levelMapTga, 16, 16); map.getTexture().setAntiAliasTexParameters(); var s = map.getContentSize(); cc.log("ContentSize: " + s.width + " " + s.height); map.releaseMap(); this.addChild(map, 0, TAG_TILE_MAP); map.setAnchorPoint(cc.p(0, 0.5)); var scale = cc.ScaleBy.create(4, 0.8); var scaleBack = scale.reverse(); var seq = cc.Sequence.create(scale, scaleBack); map.runAction(cc.RepeatForever.create(seq)); }, title:function () { return "TileMapAtlas"; } }); var TileMapEditTest = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TileMapAtlas.create(s_tilesPng, s_levelMapTga, 16, 16); // Create an Aliased Atlas map.getTexture().setAliasTexParameters(); var s = map.getContentSize(); cc.log("ContentSize: " + s.width + " " + s.height); // If you are not going to use the Map, you can free it now // [tilemap releaseMap); // And if you are going to use, it you can access the data with: this.schedule(this.updateMap, 0.2);//:@selector(updateMap:) interval:0.2f); this.addChild(map, 0, TAG_TILE_MAP); map.setAnchorPoint(cc.p(0, 0)); map.setPosition(cc.p(-20, -200)); }, title:function () { return "Editable TileMapAtlas"; }, updateMap:function (dt) { // IMPORTANT // The only limitation is that you cannot change an empty, or assign an empty tile to a tile // The value 0 not rendered so don't assign or change a tile with value 0 var tilemap = this.getChildByTag(TAG_TILE_MAP); // NEW since v0.7 var c = tilemap.getTileAt(cc.g(13, 21)); c.r++; c.r %= 50; if (c.r == 0) c.r = 1; // NEW since v0.7 tilemap.setTile(c, cc.g(13, 21)); } }); //------------------------------------------------------------------ // // TMXOrthoTest // //------------------------------------------------------------------ var TMXOrthoTest = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/orthogonal-test1.tmx"); this.addChild(map, 0, TAG_TILE_MAP); map.runAction(cc.ScaleBy.create(2, 0.5)); }, title:function () { return "TMX Ortho test"; } }); //------------------------------------------------------------------ // // TMXOrthoTest2 // //------------------------------------------------------------------ var TMXOrthoTest2 = TileDemo.extend({ ctor:function () { this._super(); // // Test orthogonal with 3d camera and anti-alias textures // // it should not flicker. No artifacts should appear // var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/orthogonal-test2.tmx"); this.addChild(map, 0, TAG_TILE_MAP); /*var x, y, z; map.getCamera().getEyeXYZ(x, y, z); map.getCamera().setEyeXYZ(x - 200, y, z + 300);*/ }, title:function () { return "TMX Orthogonal test 2"; }, onEnter:function () { this._super(); director.setProjection(cc.DIRECTOR_PROJECTION_3D); }, onExit:function () { this._super(); director.setProjection(cc.DIRECTOR_PROJECTION_2D); } }); //------------------------------------------------------------------ // // TMXOrthoTest3 // //------------------------------------------------------------------ var TMXOrthoTest3 = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/orthogonal-test3.tmx"); this.addChild(map, 0, TAG_TILE_MAP); map.setScale(0.2); map.setAnchorPoint(cc.p(0.5, 0.5)); }, title:function () { return "TMX anchorPoint test"; } }); //------------------------------------------------------------------ // // TMXOrthoTest4 // //------------------------------------------------------------------ var TMXOrthoTest4 = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/orthogonal-test4.tmx"); this.addChild(map, 0, TAG_TILE_MAP); map.setAnchorPoint(cc.p(0, 0)); var layer = map.getLayer("Layer 0"); var s = layer.getLayerSize(); var sprite; sprite = layer.getTileAt(cc.p(0, 0)); sprite.setScale(2); sprite = layer.getTileAt(cc.p(s.width - 1, 0)); sprite.setScale(2); sprite = layer.getTileAt(cc.p(0, s.height - 1)); sprite.setScale(2); sprite = layer.getTileAt(cc.p(s.width - 1, s.height - 1)); sprite.setScale(2); this.schedule(this.onRemoveSprite, 2); }, onRemoveSprite:function (dt) { this.unschedule(this.onRemoveSprite); var map = this.getChildByTag(TAG_TILE_MAP); var layer = map.getLayer("Layer 0"); var s = layer.getLayerSize(); var sprite = layer.getTileAt(cc.p(s.width - 1, 0)); layer.removeChild(sprite, true); }, title:function () { return "TMX width/height test"; } }); //------------------------------------------------------------------ // // TMXReadWriteTest // //------------------------------------------------------------------ var TMXReadWriteTest = TileDemo.extend({ gid:0, ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/orthogonal-test2.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s = map.getContentSize(); var layer = map.getLayer("Layer 0"); //layer.getTexture().setAntiAliasTexParameters(); map.setScale(1); var tile0 = layer.getTileAt(cc.p(1, 63)); var tile1 = layer.getTileAt(cc.p(2, 63)); var tile2 = layer.getTileAt(cc.p(3, 62));//cc.p(1,62)); var tile3 = layer.getTileAt(cc.p(2, 62)); tile0.setAnchorPoint(cc.p(0.5, 0.5)); tile1.setAnchorPoint(cc.p(0.5, 0.5)); tile2.setAnchorPoint(cc.p(0.5, 0.5)); tile3.setAnchorPoint(cc.p(0.5, 0.5)); var move = cc.MoveBy.create(0.5, cc.p(0, 160)); var rotate = cc.RotateBy.create(2, 360); var scale = cc.ScaleBy.create(2, 5); var opacity = cc.FadeOut.create(2); var fadein = cc.FadeIn.create(2); var scaleback = cc.ScaleTo.create(1, 1); var finish = cc.CallFunc.create(this.onRemoveSprite); // 'this' is optional. Since it is not used, it is not passed. var seq0 = cc.Sequence.create(move, rotate, scale, opacity, fadein, scaleback, finish); tile0.runAction(seq0); tile1.runAction(seq0.copy()); tile2.runAction(seq0.copy()); tile3.runAction(seq0.copy()); this.gid = layer.getTileGIDAt(cc.p(0, 63)); this.schedule(this.updateCol, 2.0); this.schedule(this.repaintWithGID, 2.0); this.schedule(this.removeTiles, 1.0); this.gid2 = 0; }, onRemoveSprite:function (sender) { var p = sender.getParent(); if (p) { p.removeChild(sender, true); } }, updateCol:function (dt) { var map = this.getChildByTag(TAG_TILE_MAP); var layer = map.getChildByTag(0); var s = layer.getLayerSize(); for (var y = 0; y < s.height; y++) { layer.setTileGID(this.gid2, cc.p(3, y)); } this.gid2 = (this.gid2 + 1) % 80; }, repaintWithGID:function (dt) { var map = this.getChildByTag(TAG_TILE_MAP); var layer = map.getChildByTag(0); var s = layer.getLayerSize(); for (var x = 0; x < s.width; x++) { var y = s.height - 1; var tmpgid = layer.getTileGIDAt(cc.p(x, y)); layer.setTileGID(tmpgid + 1, cc.p(x, y)); } }, removeTiles:function (dt) { this.unschedule(this.removeTiles); var map = this.getChildByTag(TAG_TILE_MAP); var layer = map.getChildByTag(0); var s = layer.getLayerSize(); for (var y = 0; y < s.height; y++) { layer.removeTileAt(cc.p(5.0, y)); } }, title:function () { return "TMX Read/Write test"; } }); //------------------------------------------------------------------ // // TMXHexTest // //------------------------------------------------------------------ var TMXHexTest = TileDemo.extend({ ctor:function () { this._super(); var color = cc.LayerColor.create(cc.c4b(64, 64, 64, 255)); this.addChild(color, -1); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/hexa-test.tmx"); this.addChild(map, 0, TAG_TILE_MAP); }, title:function () { return "TMX Hex test"; } }); //------------------------------------------------------------------ // // TMXIsoTest // //------------------------------------------------------------------ var TMXIsoTest = TileDemo.extend({ ctor:function () { this._super(); var color = cc.LayerColor.create(cc.c4b(64, 64, 64, 255)); this.addChild(color, -1); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/iso-test.tmx"); this.addChild(map, 0, TAG_TILE_MAP); // move map to the center of the screen var ms = map.getMapSize(); var ts = map.getTileSize(); map.runAction(cc.MoveTo.create(1.0, cc.p(-ms.width * ts.width / 2, -ms.height * ts.height / 2))); }, title:function () { return "TMX Isometric test 0"; } }); //------------------------------------------------------------------ // // TMXIsoTest1 // //------------------------------------------------------------------ var TMXIsoTest1 = TileDemo.extend({ ctor:function () { this._super(); var color = cc.LayerColor.create(cc.c4b(64, 64, 64, 255)); this.addChild(color, -1); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/iso-test1.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s = map.getContentSize(); map.setAnchorPoint(cc.p(0.5, 0.5)); }, title:function () { return "TMX Isometric test + anchorPoint"; } }); //------------------------------------------------------------------ // // TMXIsoTest2 // //------------------------------------------------------------------ var TMXIsoTest2 = TileDemo.extend({ ctor:function () { this._super(); var color = cc.LayerColor.create(cc.c4b(64, 64, 64, 255)); this.addChild(color, -1); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/iso-test2.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s = map.getContentSize(); // move map to the center of the screen var ms = map.getMapSize(); var ts = map.getTileSize(); map.runAction(cc.MoveTo.create(1.0, cc.p(-ms.width * ts.width / 2, -ms.height * ts.height / 2))); }, title:function () { return "TMX Isometric test 2"; } }); //------------------------------------------------------------------ // // TMXUncompressedTest // //------------------------------------------------------------------ var TMXUncompressedTest = TileDemo.extend({ ctor:function () { this._super(); var color = cc.LayerColor.create(cc.c4b(64, 64, 64, 255)); this.addChild(color, -1); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/iso-test2-uncompressed.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s = map.getContentSize(); // move map to the center of the screen var ms = map.getMapSize(); var ts = map.getTileSize(); map.runAction(cc.MoveTo.create(1.0, cc.p(-ms.width * ts.width / 2, -ms.height * ts.height / 2))); // testing release map var childrenArray = map.getChildren(); var layer = null; for (var i = 0, len = childrenArray.length; i < len; i++) { layer = childrenArray[i]; if (!layer) break; layer.releaseMap(); } }, title:function () { return "TMX Uncompressed test"; } }); //------------------------------------------------------------------ // // TMXTilesetTest // //------------------------------------------------------------------ var TMXTilesetTest = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/orthogonal-test5.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s = map.getContentSize(); /*var layer; layer = map.getLayer("Layer 0"); layer.getTexture().setAntiAliasTexParameters(); layer = map.getLayer("Layer 1"); layer.getTexture().setAntiAliasTexParameters(); layer = map.getLayer("Layer 2"); layer.getTexture().setAntiAliasTexParameters();*/ }, title:function () { return "TMX Tileset test"; } }); //------------------------------------------------------------------ // // TMXOrthoObjectsTest // //------------------------------------------------------------------ var TMXOrthoObjectsTest = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/ortho-objects.tmx"); this.addChild(map, -1, TAG_TILE_MAP); var s = map.getContentSize(); var group = map.getObjectGroup("Object Group 1"); var array = group.getObjects(); var dict; for (var i = 0, len = array.length; i < len; i++) { dict = array[i]; if (!dict) break; for (var k in dict) { cc.log(k + ' = ' + dict[k]); } } }, onEnter:function(){ this._super(); this.setAnchorPoint(cc.p(0, 0)); }, draw:function () { var map = this.getChildByTag(TAG_TILE_MAP); var group = map.getObjectGroup("Object Group 1"); var objects = group.getObjects(); for (var i = 0; i < objects.length; i++) { var dict = objects[i]; if (!dict) break; var x = dict["x"]; var y = dict["y"]; var width = dict["width"]; var height = dict["height"]; cc.renderContext.lineWidth = 3; cc.renderContext.strokeStyle = "#ffffff"; cc.drawingUtil.drawLine(cc.p(x, y), cc.p((x + width), y)); cc.drawingUtil.drawLine(cc.p((x + width), y), cc.p((x + width), (y + height))); cc.drawingUtil.drawLine(cc.p((x + width), (y + height)), cc.p(x, (y + height))); cc.drawingUtil.drawLine(cc.p(x, (y + height)), cc.p(x, y)); cc.renderContext.lineWidth = 1; } }, title:function () { return "TMX Ortho object test"; }, subtitle:function () { return "You should see a white box around the 3 platforms"; } }); //------------------------------------------------------------------ // // TMXIsoObjectsTest // //------------------------------------------------------------------ var TMXIsoObjectsTest = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/iso-test-objectgroup.tmx"); this.addChild(map, -1, TAG_TILE_MAP); var s = map.getContentSize(); var group = map.getObjectGroup("Object Group 1"); var array = group.getObjects(); var dict; for (var i = 0, len = array.length; i < len; i++) { dict = array[i]; if (!dict) break; for (var k in dict) { cc.log(k + ' = ' + dict[k]); } } }, onEnter:function(){ this._super(); this.setAnchorPoint(cc.p(0, 0)); }, title:function () { return "TMX Iso object test"; }, draw:function (ctx) { var map = this.getChildByTag(TAG_TILE_MAP); var group = map.getObjectGroup("Object Group 1"); var objects = group.getObjects(); var dict; for (var i = 0, len = objects.length; i < len; i++) { dict = objects[i]; if (!dict) break; var x = dict["x"]; var y = dict["y"]; var width = dict["width"]; var height = dict["height"]; cc.renderContext.lineWidth = 3; cc.renderContext.strokeStyle = "#ffffff"; cc.drawingUtil.drawLine(cc.p(x, y), cc.p(x + width, y)); cc.drawingUtil.drawLine(cc.p(x + width, y), cc.p(x + width, y + height)); cc.drawingUtil.drawLine(cc.p(x + width, y + height), cc.p(x, y + height)); cc.drawingUtil.drawLine(cc.p(x, y + height), cc.p(x, y)); cc.renderContext.lineWidth = 1; } }, subtitle:function () { return "You need to parse them manually. See bug #810"; } }); //------------------------------------------------------------------ // // TMXResizeTest // //------------------------------------------------------------------ var TMXResizeTest = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/orthogonal-test5.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s = map.getContentSize(); var layer; layer = map.getLayer("Layer 0"); var ls = layer.getLayerSize(); for (var y = 0; y < ls.height; y++) { for (var x = 0; x < ls.width; x++) { layer.setTileGID(1, cc.p(x, y)); } } }, title:function () { return "TMX resize test"; }, subtitle:function () { return "Should not crash. Testing issue #740"; } }); //------------------------------------------------------------------ // // TMXIsoZorder // //------------------------------------------------------------------ var TMXIsoZorder = TileDemo.extend({ tamara:null, ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/iso-test-zorder.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s = map.getContentSize(); map.setPosition(cc.p(-s.width / 2, 0)); this.tamara = cc.Sprite.create(s_pathSister1); map.addChild(this.tamara, map.getChildren().length); var mapWidth = map.getMapSize().width * map.getTileSize().width; this.tamara.setPosition(mapWidth / 2, 0); this.tamara.setAnchorPoint(cc.p(0.5, 0)); var move = cc.MoveBy.create(10, cc.pMult(cc.p(300, 250), 1)); var back = move.reverse(); var seq = cc.Sequence.create(move, back); this.tamara.runAction(cc.RepeatForever.create(seq)); this.schedule(this.repositionSprite); }, title:function () { return "TMX Iso Zorder"; }, subtitle:function () { return "Sprite should hide behind the trees"; }, onExit:function () { this.unschedule(this.repositionSprite); this._super(); }, repositionSprite:function (dt) { var p = this.tamara.getPosition(); var map = this.getChildByTag(TAG_TILE_MAP); // there are only 4 layers. (grass and 3 trees layers) // if tamara < 48, z=4 // if tamara < 96, z=3 // if tamara < 144, z=2 var newZ = 4 - (p.y / 48); newZ = parseInt(Math.max(newZ, 0), 10); map.reorderChild(this.tamara, newZ); } }); //------------------------------------------------------------------ // // TMXOrthoZorder // //------------------------------------------------------------------ var TMXOrthoZorder = TileDemo.extend({ tamara:null, ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/orthogonal-test-zorder.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s = map.getContentSize(); this.tamara = cc.Sprite.create(s_pathSister1); map.addChild(this.tamara, map.getChildren().length, TAG_TILE_MAP); this.tamara.setAnchorPoint(cc.p(0.5, 0)); var move = cc.MoveBy.create(10, cc.pMult(cc.p(400, 450), 1)); var back = move.reverse(); var seq = cc.Sequence.create(move, back); this.tamara.runAction(cc.RepeatForever.create(seq)); this.schedule(this.repositionSprite); }, title:function () { return "TMX Ortho Zorder"; }, subtitle:function () { return "Sprite should hide behind the trees"; }, repositionSprite:function (dt) { var p = this.tamara.getPosition(); var map = this.getChildByTag(TAG_TILE_MAP); // there are only 4 layers. (grass and 3 trees layers) // if tamara < 81, z=4 // if tamara < 162, z=3 // if tamara < 243,z=2 // -10: customization for this particular sample var newZ = 4 - ((p.y - 10) / 81); newZ = Math.max(newZ, 0); map.reorderChild(this.tamara, newZ); } }); //------------------------------------------------------------------ // // TMXIsoVertexZ // //------------------------------------------------------------------ var TMXIsoVertexZ = TileDemo.extend({ tamara:null, tamara1:null, ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/iso-test-vertexz.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s = map.getContentSize(); map.setPosition(cc.p(-s.width / 2, 0)); // because I'm lazy, I'm reusing a tile as an sprite, but since this method uses vertexZ, you // can use any cc.Sprite and it will work OK. var layer = map.getLayer("Trees"); this.tamara = layer.getTileAt(cc.p(29, 29)); var move = cc.MoveBy.create(10, cc.pMult(cc.p(300, 250), 1)); var back = move.reverse(); var seq = cc.Sequence.create(move, back); this.tamara.runAction(cc.RepeatForever.create(seq)); this.scheduleUpdate(); }, title:function () { return "TMX Iso VertexZ"; }, subtitle:function () { return "Sprite should hide behind the trees"; }, onEnter:function () { this._super(); // TIP: 2d projection should be used director.setProjection(cc.DIRECTOR_PROJECTION_2D); }, onExit:function () { // At exit use any other projection. // director.setProjection:cc.DIRECTOR_PROJECTION_3D); this._super(); }, update:function (dt) { // tile height is 64x32 // map size: 30x30 var p = this.tamara.getPosition(); var z = -( (p.y + 32) / 16); this.tamara.setVertexZ(z); } }); //------------------------------------------------------------------ // // TMXOrthoVertexZ // //------------------------------------------------------------------ var TMXOrthoVertexZ = TileDemo.extend({ tamara:null, ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/orthogonal-test-vertexz.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s = map.getContentSize(); // because I'm lazy, I'm reusing a tile as an sprite, but since this method uses vertexZ, you // can use any cc.Sprite and it will work OK. var layer = map.getLayer("trees"); this.tamara = layer.getTileAt(cc.p(0, 11)); cc.log("vertexZ: " + this.tamara.getVertexZ()); var move = cc.MoveBy.create(10, cc.pMult(cc.p(400, 450), 1)); var back = move.reverse(); var seq = cc.Sequence.create(move, back); this.tamara.runAction(cc.RepeatForever.create(seq)); this.scheduleUpdate(); cc.log("DEPTH BUFFER MUST EXIST IN ORDER"); }, title:function () { return "TMX Ortho vertexZ"; }, subtitle:function () { return "Sprite should hide behind the trees"; }, onEnter:function () { this._super(); // TIP: 2d projection should be used director.setProjection(cc.DIRECTOR_PROJECTION_2D); }, onExit:function () { // At exit use any other projection. // director.setProjection:cc.DIRECTOR_PROJECTION_3D); this._super(); }, update:function (dt) { // tile height is 101x81 // map size: 12x12 var p = this.tamara.getPosition(); this.tamara.setVertexZ(-( (p.y + 81) / 81)); } }); //------------------------------------------------------------------ // // TMXIsoMoveLayer // //------------------------------------------------------------------ var TMXIsoMoveLayer = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/iso-test-movelayer.tmx"); this.addChild(map, 0, TAG_TILE_MAP); map.setPosition(cc.p(-700, -50)); var s = map.getContentSize(); }, title:function () { return "TMX Iso Move Layer"; }, subtitle:function () { return "Trees should be horizontally aligned"; } }); //------------------------------------------------------------------ // // TMXOrthoMoveLayer // //------------------------------------------------------------------ var TMXOrthoMoveLayer = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/orthogonal-test-movelayer.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s = map.getContentSize(); }, title:function () { return "TMX Ortho Move Layer"; }, subtitle:function () { return "Trees should be horizontally aligned"; } }); //------------------------------------------------------------------ // // TMXTilePropertyTest // //------------------------------------------------------------------ var TMXTilePropertyTest = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/ortho-tile-property.tmx"); this.addChild(map, 0, TAG_TILE_MAP); if (cc.config.platform == 'browser') { for (var i = 1; i <= 20; i++) { cc.log("GID:" + i + ", Properties:" + JSON.stringify(map.propertiesForGID(i))); } } else { cc.log("Test not supported on JSB"); } }, title:function () { return "TMX Tile Property Test"; }, subtitle:function () { return "In the console you should see tile properties"; } }); //------------------------------------------------------------------ // // TMXOrthoFlipTest // //------------------------------------------------------------------ var TMXOrthoFlipTest = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/ortho-rotation-test.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s = map.getContentSize(); cc.log("ContentSize:" + s.width + "," + s.height); var action = cc.ScaleBy.create(2, 0.5); map.runAction(action); }, title:function () { return "TMX tile flip test"; } }); //------------------------------------------------------------------ // // TMXOrthoFlipRunTimeTest // //------------------------------------------------------------------ var TMXOrthoFlipRunTimeTest = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/ortho-rotation-test.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s = map.getContentSize(); cc.log("ContentSize:" + s.width + "," + s.height); var action = cc.ScaleBy.create(2, 0.5); map.runAction(action); this.schedule(this.onFlipIt, 1); }, title:function () { return "TMX tile flip run time test"; }, subtitle:function () { return "in 2 sec bottom left tiles will flip"; }, onFlipIt:function () { var map = this.getChildByTag(TAG_TILE_MAP); var layer = map.getLayer("Layer 0"); /*// CGPoint tileCoord = ccp(1,10); // ccTMXTileFlags flags; // uint32_t GID = [layer tileGIDAt:tileCoord withFlags:&flags]; // // Vertical // if( flags & kCCTMXTileVerticalFlag ) // flags &= ~kCCTMXTileVerticalFlag; // else // flags |= kCCTMXTileVerticalFlag; // [layer setTileGID:GID at:tileCoord withFlags:flags]; // tileCoord = ccp(1,8); // GID = [layer tileGIDAt:tileCoord withFlags:&flags]; // // Vertical // if( flags & kCCTMXTileVerticalFlag ) // flags &= ~kCCTMXTileVerticalFlag; // else // flags |= kCCTMXTileVerticalFlag; // [layer setTileGID:GID at:tileCoord withFlags:flags]; // tileCoord = ccp(2,8); // GID = [layer tileGIDAt:tileCoord withFlags:&flags]; // // Horizontal // if( flags & kCCTMXTileHorizontalFlag ) // flags &= ~kCCTMXTileHorizontalFlag; // else // flags |= kCCTMXTileHorizontalFlag; // [layer setTileGID:GID at:tileCoord withFlags:flags];*/ //blue diamond var tileCoord = cc.p(1, 10); var flags = layer.getTileFlagsAt(tileCoord); var GID = layer.getTileGIDAt(tileCoord); // Vertical if ((flags & cc.TMX_TILE_VERTICAL_FLAG) >>> 0) { flags = (flags & ~cc.TMX_TILE_VERTICAL_FLAG >>> 0) >>> 0; } else { flags = (flags | cc.TMX_TILE_VERTICAL_FLAG) >>> 0; } layer.setTileGID(GID, tileCoord, flags); tileCoord = cc.p(1, 8); flags = layer.getTileFlagsAt(tileCoord); GID = layer.getTileGIDAt(tileCoord); // Vertical if ((flags & cc.TMX_TILE_VERTICAL_FLAG) >>> 0) flags = (flags & ~cc.TMX_TILE_VERTICAL_FLAG >>> 0) >>> 0; else flags = (flags | cc.TMX_TILE_VERTICAL_FLAG) >>> 0; layer.setTileGID(GID, tileCoord, flags); tileCoord = cc.p(2, 8); flags = layer.getTileFlagsAt(tileCoord); GID = layer.getTileGIDAt(tileCoord); // Horizontal if ((flags & cc.TMX_TILE_HORIZONTAL_FLAG) >>> 0) flags = (flags & ~cc.TMX_TILE_HORIZONTAL_FLAG >>> 0) >>> 0; else flags = (flags | cc.TMX_TILE_HORIZONTAL_FLAG) >>> 0; layer.setTileGID(GID, tileCoord, flags); } }); //------------------------------------------------------------------ // // TMXOrthoFromXMLTest // //------------------------------------------------------------------ var TMXOrthoFromXMLTest = TileDemo.extend({ init:function () { this._super(); cc.log("Test not available"); }, title:function () { return "TMX created from XML test"; }, subtitle:function () { return "Test not available"; } }); //------------------------------------------------------------------ // // TMXBug987 // //------------------------------------------------------------------ var TMXBug987 = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/orthogonal-test6.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var s1 = map.getContentSize(); cc.log("ContentSize:" + s1.width + "," + s1.height); var childs = map.getChildren(); var node = null; for (var i = 0, len = childs.length; i < len; i++) { node = childs[i]; if (!node) break; //node.getTexture().setAntiAliasTexParameters(); } map.setAnchorPoint(cc.p(0, 0)); var layer = map.getLayer("Tile Layer 1"); layer.setTileGID(3, cc.p(2, 2)); }, title:function () { return "TMX Bug 987"; }, subtitle:function () { return "You should see an square"; } }); //------------------------------------------------------------------ // // TMXBug787 // //------------------------------------------------------------------ var TMXBug787 = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/iso-test-bug787.tmx"); this.addChild(map, 0, TAG_TILE_MAP); map.setScale(0.25); }, title:function () { return "TMX Bug 787"; }, subtitle:function () { return "You should see a map"; } }); var TMXGIDObjectsTest = TileDemo.extend({ ctor:function () { this._super(); var map = cc.TMXTiledMap.create(s_resprefix + "TileMaps/test-object-layer.tmx"); this.addChild(map, -1, TAG_TILE_MAP); var s = map.getContentSize(); cc.log("ContentSize:" + s.width + "," + s.height); cc.log("---. Iterating over all the group objets"); var group = map.getObjectGroup("Object Layer 1"); var array = group.getObjects(); var dict; for (var i = 0, len = array.length; i < len; i++) { dict = array[i]; if (!dict) break; for (var k in dict) { cc.log(k + ' = ' + dict[k]); } } }, title:function () { return "TMX GID objects"; }, subtitle:function () { return "Tiles are created from an object group"; }, draw:function () { var map = this.getChildByTag(TAG_TILE_MAP); var group = map.getObjectGroup("Object Layer 1"); var array = group.getObjects(); var dict; for (var i = 0, len = array.length; i < len; i++) { dict = array[i]; if (!dict) break; var x = dict["x"]; var y = dict["y"]; var width = dict["width"]; var height = dict["height"]; cc.renderContext.lineWidth = 3; cc.renderContext.strokeStyle = "#ffffff"; cc.drawingUtil.drawLine(cc.p(x, y), cc.p(x + width, y)); cc.drawingUtil.drawLine(cc.p(x + width, y), cc.p(x + width, y + height)); cc.drawingUtil.drawLine(cc.p(x + width, y + height), cc.p(x, y + height)); cc.drawingUtil.drawLine(cc.p(x, y + height), cc.p(x, y)); cc.renderContext.lineWidth = 1; } } }); var TileMapTestScene = TestScene.extend({ runThisTest:function () { sceneIdx = -1; var layer = nextTileMapTest(); this.addChild(layer); director.replaceScene(this); } }); // // Flow control // var arrayOfTileMapTest = [ TMXOrthoTest, TMXOrthoTest2, TMXOrthoTest3, TMXOrthoTest4, TMXReadWriteTest, TMXHexTest, TMXIsoTest, TMXIsoTest1, TMXIsoTest2, TMXUncompressedTest, TMXTilesetTest, TMXOrthoObjectsTest, TMXIsoObjectsTest, TMXResizeTest, TMXIsoZorder, TMXOrthoZorder, TMXIsoVertexZ, TMXOrthoVertexZ, TMXIsoMoveLayer, TMXOrthoMoveLayer, TMXTilePropertyTest, TMXOrthoFlipTest, TMXOrthoFlipRunTimeTest, TMXOrthoFromXMLTest, TMXBug987, TMXBug787, TMXGIDObjectsTest ]; var nextTileMapTest = function () { sceneIdx++; sceneIdx = sceneIdx % arrayOfTileMapTest.length; return new arrayOfTileMapTest[sceneIdx](); }; var previousTileMapTest = function () { sceneIdx--; if (sceneIdx < 0) sceneIdx += arrayOfTileMapTest.length; return new arrayOfTileMapTest[sceneIdx](); }; var restartTileMapTest = function () { return new arrayOfTileMapTest[sceneIdx](); };
zhwsh00/DirectFire-android
cocos2d-2.1beta3-x-2.1.0/samples/TestJavascript/cocos2d-js-tests/tests/TileMapTest/TileMapTest.js
JavaScript
mit
40,284
import Controller from '@ember/controller'; import { action } from '@ember/object'; import { task, timeout } from 'ember-concurrency'; export default class FooController extends Controller { isShowingButton = false; @task *showButtonSoon() { this.set('isShowingButton', false); yield timeout(200); this.set('isShowingButton', true); } value = 0; @action setValue() { this.set('value', 123); } }
machty/ember-concurrency
tests/dummy/app/testing-ergo/foo/controller.js
JavaScript
mit
428
/** * jquery.dlmenu.js v1.0.1 * http://www.codrops.com * * Licensed under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Copyright 2013, Codrops * http://www.codrops.com * * Modified by Michael Rose */ ;( function( $, window, undefined ) { 'use strict'; // global var Modernizr = window.Modernizr, $body = $( 'body' ); $.DLMenu = function( options, element ) { this.$el = $( element ); this._init( options ); }; // the options $.DLMenu.defaults = { // classes for the animation effects animationClasses : { classin : 'dl-animate-in-1', classout : 'dl-animate-out-1' }, // callback: click a link that has a sub menu // el is the link element (li); name is the level name onLevelClick : function( el, name ) { return false; }, // callback: click a link that does not have a sub menu // el is the link element (li); ev is the event obj onLinkClick : function( el, ev ) { return false; } }; $.DLMenu.prototype = { _init : function( options ) { // options this.options = $.extend( true, {}, $.DLMenu.defaults, options ); // cache some elements and initialize some variables this._config(); var animEndEventNames = { 'WebkitAnimation' : 'webkitAnimationEnd', 'OAnimation' : 'oAnimationEnd', 'msAnimation' : 'MSAnimationEnd', 'animation' : 'animationend' }, transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd', 'MozTransition' : 'transitionend', 'OTransition' : 'oTransitionEnd', 'msTransition' : 'MSTransitionEnd', 'transition' : 'transitionend' }; // animation end event name this.animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ] + '.dlmenu'; // transition end event name this.transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ] + '.dlmenu', // support for css animations and css transitions this.supportAnimations = Modernizr.cssanimations, this.supportTransitions = Modernizr.csstransitions; this._initEvents(); }, _config : function() { this.open = false; this.$menuwrapper = $( '#dl-menu' ); this.$trigger = this.$el.children( '.dl-trigger' ); this.$menu = this.$el.children( 'ul.dl-menu' ); this.$menuitems = this.$menu.find( 'li:not(.dl-back)' ); this.$el.find( 'ul.dl-submenu' ).prepend( '<li class="dl-back"><a href="#">back</a></li>' ); this.$back = this.$menu.find( 'li.dl-back' ); }, _initEvents : function() { var self = this; var submenu_anim_position = "absolute"; var submenu_anim_top = "50px"; var submenu_anim_width = "100%" this.$trigger.on( 'click.dlmenu', function() { if( self.open ) { self._closeMenu(); } else { self._openMenu(); } return false; } ); this.$menuitems.on( 'click.dlmenu', function( event ) { event.stopPropagation(); var $item = $(this), $submenu = $item.children( 'ul.dl-submenu' ); if( $submenu.length > 0 ) { var $flyin = $submenu.clone().css({ opacity: 0, margin: 0 position: submenu_anim_position, top: submenu_anim_top, width: submenu_anim_width }).insertAfter( self.$menu ), onAnimationEndFn = function() { self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.classout ).addClass( 'dl-subview' ); $item.addClass( 'dl-subviewopen' ).parents( '.dl-subviewopen:first' ).removeClass( 'dl-subviewopen' ).addClass( 'dl-subview' ); $flyin.remove(); }; setTimeout( function() { $flyin.addClass( self.options.animationClasses.classin ); self.$menu.addClass( self.options.animationClasses.classout ); if( self.supportAnimations ) { self.$menu.on( self.animEndEventName, onAnimationEndFn ); } else { onAnimationEndFn.call(); } self.options.onLevelClick( $item, $item.children( 'a:first' ).text() ); } ); return false; } else { self.options.onLinkClick( $item, event ); } } ); this.$back.on( 'click.dlmenu', function( event ) { var $this = $( this ), $submenu = $this.parents( 'ul.dl-submenu:first' ), $item = $submenu.parent(), $flyin = $submenu.clone().css({ position: submenu_anim_position, top: submenu_anim_top, width: submenu_anim_width }).insertAfter( self.$menu ); var onAnimationEndFn = function() { self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.classin ); $flyin.remove(); }; setTimeout( function() { $flyin.addClass( self.options.animationClasses.classout ); self.$menu.addClass( self.options.animationClasses.classin ); if( self.supportAnimations ) { self.$menu.on( self.animEndEventName, onAnimationEndFn ); } else { onAnimationEndFn.call(); } $item.removeClass( 'dl-subviewopen' ); var $subview = $this.parents( '.dl-subview:first' ); if( $subview.is( 'li' ) ) { $subview.addClass( 'dl-subviewopen' ); } $subview.removeClass( 'dl-subview' ); } ); return false; } ); }, closeMenu : function() { if( this.open ) { this._closeMenu(); } }, _closeMenu : function() { var self = this, onTransitionEndFn = function() { self.$menu.off( self.transEndEventName ); self._resetMenu(); }; this.$menuwrapper.removeClass( 'dl-menuopen' ); this.$menu.removeClass( 'dl-menuopen' ); this.$menu.addClass( 'dl-menu-toggle' ); this.$trigger.removeClass( 'dl-active' ); if( this.supportTransitions ) { this.$menu.on( this.transEndEventName, onTransitionEndFn ); } else { onTransitionEndFn.call(); } this.open = false; }, openMenu : function() { if( !this.open ) { this._openMenu(); } }, _openMenu : function() { var self = this; // clicking somewhere else makes the menu close $body.off( 'click' ).on( 'click.dlmenu', function() { self._closeMenu() ; } ); this.$menuwrapper.addClass( 'dl-menuopen' ); this.$menu.addClass( 'dl-menuopen dl-menu-toggle' ).on( this.transEndEventName, function() { $( this ).removeClass( 'dl-menu-toggle' ); } ); this.$trigger.addClass( 'dl-active' ); this.open = true; }, // resets the menu to its original state (first level of options) _resetMenu : function() { this.$menu.removeClass( 'dl-subview' ); this.$menuitems.removeClass( 'dl-subview dl-subviewopen' ); } }; var logError = function( message ) { if ( window.console ) { window.console.error( message ); } }; $.fn.dlmenu = function( options ) { if ( typeof options === 'string' ) { var args = Array.prototype.slice.call( arguments, 1 ); this.each(function() { var instance = $.data( this, 'dlmenu' ); if ( !instance ) { logError( "cannot call methods on dlmenu prior to initialization; " + "attempted to call method '" + options + "'" ); return; } if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) { logError( "no such method '" + options + "' for dlmenu instance" ); return; } instance[ options ].apply( instance, args ); }); } else { this.each(function() { var instance = $.data( this, 'dlmenu' ); if ( instance ) { instance._init(); } else { instance = $.data( this, 'dlmenu', new $.DLMenu( options, this ) ); } }); } return this; }; } )( jQuery, window );
dldx/hpstr-hugo-theme
static/js/plugins/jquery.dlmenu.js
JavaScript
mit
7,535
export default function routerConfig($stateProvider, $urlRouterProvider) { 'ngInject'; $stateProvider .state('player', { url: 'player', templateUrl: '/modules/championship/player/create/create-player.html', controlller: 'PlayerController', controllerAs: 'player' }) .state('club', { url: 'club', templateUrl: '/modules/championship/club/list-club.html', controller: 'ClubController', ControllerAs: 'club', }) }
roenfa/ChampionshipsProject
src/client/modules/championship/championship.routes.js
JavaScript
mit
446
// // Site / Model / Peony Flare // 'use strict'; // Dependencies var log = require('bows')('PeonyFlare'); var App = require('ampersand-app'); var State = require('ampersand-state'); var Utils = require('../base/utils'); // App State // -------------------------------------------------- var PeonyFlare = State.extend({ props: { parent: 'object', layer: 'number', x: 'number', y: 'number', angleDegrees: 'number', }, derived: { angleRadians: { deps: ['angleDegrees'], fn: function() { return Utils.GetRadians(this.angleDegrees); } }, accelerationFactor: { cache: false, fn: function() { var layerOrder = (this.parent.layerCount - this.layer + 1); return 1 - ((layerOrder-1) * 0.15); } }, speed: { deps: ['accelerationFactor'], cache: false, fn: function() { return this.parent.velocity * this.accelerationFactor; } }, }, collections: { }, children: { }, binding: { }, events: { }, initialize: function() { //log('initialize()'); // Init this.x = this.parent.x; this.y = this.parent.y; // Bindings this.listenTo(this.parent, 'change:age', this._parentAgeChangeHandler.bind(this)); }, // Event Handlers ---------------- _parentAgeChangeHandler: function() { if(!this.parent.isPreExisting) { //log('seed ID:', this.parent._id, 'layerCount:', this.layerCount, 'accFactor:', this.accelerationFactor); this.x = (this.speed * Math.cos(this.angleRadians) * this.parent.age) + this.parent.x; this.y = (this.speed * Math.sin(this.angleRadians) * this.parent.age) + this.parent.y; } }, // Private Methods ---------------- // Public Methods ---------------- isCollided: function(player) { return Utils.IsCircleCircleColliding( {x: this.x, y: this.y, r: this.parent.size}, {x: player.x, y: player.y, r: player.size * (1-this.parent.collusionTolerance)} ); }, draw: function(context) { if(!this.parent.isPreExisting) { context.beginPath(); context.arc(this.x, this.y, this.parent.size, 0, 2*Math.PI, false); context.globalAlpha = this.parent.alpha; context.fillStyle = this.parent.colour; context.fill(); } }, }); // Exports // -------------------------------------------------- module.exports = PeonyFlare;
rockacola/hanabi
src/scripts/models/peony-flare.js
JavaScript
mit
2,700
/* * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ 'use strict' var test = require('tap').test var proxyquire = require('proxyquire') var dnsMock = require('./dns-mock')() proxyquire('../aResolver', {dns: dnsMock.systemStub, 'dns-socket': dnsMock.dnsErrorSocketStub}) var concordant = require('../index') test('test error lookup with system dns', function (t) { process.env.DNS_MODE = 'A' dnsMock.setErrorA(false) var conc = concordant() conc.dns.resolve('badrecord.testns.svc.cluster.local', function (err, results) { t.notequal(null, err, 'test error condition on bad lookup') t.equal(err, 'ENODATA', 'test that error is no data from dns') t.end() }) }) test('test error lookup with direct dns', function (t) { process.env.DNS_MODE = 'A' process.env.DNS_PORT = 53053 process.env.DNS_HOST = '127.0.0.1' dnsMock.setErrorSRV(false) dnsMock.setErrorA(true) var conc = concordant() dnsMock.start(function () { conc.dns.resolve('service1.testns.svc.cluster.local', function (err, results) { t.notequal(null, err, 'test error condition on bad lookup') t.equal(err, 'force error on A', 'test that error is no data from dns') dnsMock.stop() t.end() }) }) })
apparatus/concordant
test/a.errors.test.js
JavaScript
mit
1,911
/* * This file is part of NectarJS * Copyright (c) 2017 - 2020 Adrien THIERRY * http://nectarjs.com - https://seraum.com/ * * sources : https://github.com/nectarjs/nectarjs * * NectarJS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NectarJS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NectarJS. If not, see <http://www.gnu.org/licenses/>. * */ "!_ffi_include njs_thread_lib/thread.h"; var _Thread = { run: __Nectar_NATIVE_THREAD_RUN, lock: __Nectar_NATIVE_LOCK_GUARD, waitForAll: __Nectar_NATIVE_WAIT_FOR_ALL, }; module.exports = _Thread;
seraum/nectarjs
nectar_modules/Thread/index.js
JavaScript
mit
1,029
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react' import { connect } from 'react-redux' import { createSelector } from 'reselect' import { IntlProvider } from 'react-intl' import { makeSelectLocale } from './selectors' export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ) } } LanguageProvider.propTypes = { locale: React.PropTypes.string, messages: React.PropTypes.object, children: React.PropTypes.element.isRequired, } const mapStateToProps = createSelector( makeSelectLocale(), locale => ({ locale }) ) function mapDispatchToProps(dispatch) { return { dispatch, } } export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider)
Jan-Jan/react-hackathon-boilerplate
app/containers/LanguageProvider/index.js
JavaScript
mit
1,116
const lineHeight = 24; const userListWidth = 200; const smallScreen = 600; export function findBreakpoints(blocks) { const breakpoints = []; let length = 0; for (let j = 0; j < blocks.length; j++) { const {text} = blocks[j]; for (let i = 0; i < text.length; i++) { const char = text.charAt(i); if (char === ' ') { breakpoints.push({ end: length + i, next: length + i + 1 }); } else if (i !== text.length - 1 && (char === '-' || char === '?')) { breakpoints.push({ end: length + i + 1, next: length + i + 1 }); } } length += text.length; } return [breakpoints, length]; } export function messageHeight( message, wrapWidth, charWidth, indent = 0, windowWidth ) { let pad = (6 + (message.from ? message.from.length + 1 : 0)) * charWidth; let height = lineHeight + 8; if (message.channel && windowWidth > smallScreen) { wrapWidth -= userListWidth; } if (pad + message.length * charWidth < wrapWidth) { return height; } const breaks = message.breakpoints; let prevBreak = 0; let prevPos = 0; for (let i = 0; i < breaks.length; i++) { if (pad + (breaks[i].end - prevBreak) * charWidth >= wrapWidth) { prevBreak = prevPos; pad = indent; height += lineHeight; } prevPos = breaks[i].next; } if (pad + (message.length - prevBreak) * charWidth >= wrapWidth) { height += lineHeight; } return height; }
khlieng/dispatch
client/js/utils/messageHeight.js
JavaScript
mit
1,450
(function($) { $.fn.canvasEdit = function(options) { var settings = $.extend({ mousePressed: false, lastX: '', lastY: '', mouse: { x: 0, y: 0 }, startMouse: { x: 0, y: 0 }, lastMouse: { x: 0, y: 0 }, $textarea: '', ctx: '', canvas: '', $canvas: '', tmpTxtCtn: '', gd: {}, shifted: false, ctrlDown: false, cPushArray: [''], cStep: -1, width: 1024, height: 768 }, options); init = function() { render(); drawing(); initTools(); } _manageCursor = function() { if (settings.gd.pushIt == true) { if (settings.$canvas.hasClass(settings.gd.lastTool)) { settings.$canvas.removeClass(settings.gd.lastTool); } if (!settings.$canvas.hasClass(settings.gd.tool)) { settings.$canvas.addClass(settings.gd.tool); } } else { if (settings.$canvas.hasClass(settings.gd.lastTool)) { settings.$canvas.removeClass(settings.gd.lastTool); } if (settings.$canvas.hasClass(settings.gd.tool)) { settings.$canvas.removeClass(settings.gd.tool); } } return true; }; _writeText = function(value) { var x = Math.min(settings.mouse.x, settings.startMouse.x), y = Math.min(settings.mouse.y, settings.startMouse.y), lines = value.split('\n'), processed_lines = []; settings.ctx.fillStyle = settings.gd.color; settings.ctx.font = settings.gd.fontSize + "px arial"; settings.ctx.textBaseline = "top"; for (var i = 0; i < lines.length; i++) { var chars = lines[i].length; for (var j = 0; j < chars; j++) { var text_node = document.createTextNode(lines[i][j]); settings.tmpTxtCtn.appendChild(text_node); settings.tmpTxtCtn.style.position = 'absolute'; settings.tmpTxtCtn.style.visibility = 'hidden'; settings.tmpTxtCtn.style.display = 'block'; var width = settings.tmpTxtCtn.offsetWidth; var height = settings.tmpTxtCtn.offsetHeight; settings.tmpTxtCtn.style.position = ''; settings.tmpTxtCtn.style.visibility = ''; settings.tmpTxtCtn.style.display = 'none'; if (width > parseInt(settings.$textarea.width())) { break; } } processed_lines.push(settings.tmpTxtCtn.textContent); settings.tmpTxtCtn.innerHTML = ''; } for (var n = 0; n < processed_lines.length; n++) { var processed_line = processed_lines[n]; settings.ctx.fillText( processed_line, parseInt(settings.$textarea.position().left), parseInt(settings.$textarea.position().top) + n * parseInt(settings.gd.fontSize) ); } _cPush(); } _undoRedoBtnActivity = function() { var redo = document.getElementById("draw-redo-ico"), undo = document.getElementById("draw-undo-ico"); if (settings.cStep < settings.cPushArray.length - 1) { $(redo).removeClass("inactive"); } else { $(redo).addClass("inactive"); } if (settings.cStep > 0) { $(undo).removeClass("inactive"); } else { $(undo).addClass("inactive"); } }; _cPush = function() { settings.cStep++; if (settings.cStep < settings.cPushArray.length) { settings.cPushArray.length = settings.cStep; } settings.cPushArray.push(document.getElementById('screenshot-canvas').toDataURL()); _undoRedoBtnActivity(); }; _draw = function(x, y, isDown) { if (isDown) { settings.ctx.beginPath(); settings.ctx.globalCompositeOperation = "source-over"; settings.ctx.strokeStyle = settings.gd.color; settings.ctx.lineWidth = settings.gd.toolSize; settings.ctx.lineJoin = "round"; settings.ctx.moveTo(settings.lastX, settings.lastY); settings.ctx.lineTo(x, y); settings.ctx.closePath(); settings.ctx.stroke(); } settings.lastX = x; settings.lastY = y; } _drawFromMemory = function() { var canvasPic = new Image(); canvasPic.src = settings.cPushArray[settings.cStep]; canvasPic.onload = function() { settings.ctx.drawImage(canvasPic, 0, 0, canvasPic.width, canvasPic.height); } } _erase = function(x, y, isDown) { if (isDown) { settings.ctx.beginPath(); settings.ctx.globalCompositeOperation = "destination-out"; settings.ctx.strokeStyle = "rgba(0,0,0,1)"; settings.ctx.lineWidth = settings.gd.toolSize; settings.ctx.lineJoin = "round"; settings.ctx.moveTo(settings.lastX, settings.lastY); settings.ctx.lineTo(x, y); settings.ctx.closePath(); settings.ctx.stroke(); } settings.lastX = x; settings.lastY = y; } _invisibleCanvas = function(e, _this) { var type = e; settings.mouseX = e.clientX; settings.mouseY = e.clientY; el; document.getElementById('screenshot-canvas').style.display = "none"; el = document.elementFromPoint(mouseX, mouseY); _this.css("cursor", $(el).css("cursor")); document.getElementById('screenshot-canvas').style.display = "block"; $(el).trigger(type); e.preventDefault(); e.stopPropagation(); return false; }; _toggleInvisibleCanvas = function(className) { if (!settings.$canvas.is(":visible")) { settings.$canvas.show(); } settings.gd.pushIt = true; settings.$canvas.attr("contentEditable", "true") settings.$canvas[0].contentEditable = true; }; _adjustTextArea = function() { var xx = Math.min(settings.mouse.x, settings.startMouse.x); yy = Math.min(settings.mouse.y, settings.startMouse.y), settings.width = Math.abs(settings.mouse.x - settings.startMouse.x), settings.height = Math.abs(settings.mouse.y - settings.startMouse.y); settings.$textarea.css({ top: yy + 'px', left: xx + 'px', width: settings.width + 'px', height: settings.height + 'px', color: settings.gd.color, "font-size": settings.gd.fontSize + "px", display: 'block' }); } _cUndo = function(toStart) { if (toStart) { settings.cStep = 0; settings.ctx.clearRect(0, 0, settings.width, settings.height); _drawFromMemory(); } else { if (settings.cStep > 0) { settings.cStep--; settings.ctx.clearRect(0, 0, settings.width, settings.height); _drawFromMemory(); } } _undoRedoBtnActivity(); } _undoRedoBtnActivity = function() { var redo = document.getElementById("draw-redo-ico"), undo = document.getElementById("draw-undo-ico"); if (settings.cStep < settings.cPushArray.length - 1) { $(redo).removeClass("inactive"); } else { $(redo).addClass("inactive"); } if (settings.cStep > 0) { $(undo).removeClass("inactive"); } else { $(undo).addClass("inactive"); } }; _clearAll = function() { settings.cPushArray = ['']; settings.cStep = 0; settings.ctx.clearRect(0, 0, settings.width, settings.height); settings.cPushArray.push(document.getElementById('screenshot-canvas').toDataURL()); _undoRedoBtnActivity(); } _cRedo = function(toEnd) { if (toEnd) { settings.cStep = settings.cPushArray.length - 1; settings.ctx.clearRect(0, 0, settings.width, settings.height); _drawFromMemory(); } else { if (settings.cStep < settings.cPushArray.length - 1) { settings.cStep++; settings.ctx.clearRect(0, 0, settings.width, settings.height); _drawFromMemory(); } } _undoRedoBtnActivity(); } drawing = function() { settings.$canvas = $('#screenshot-canvas'); canvas = document.getElementById('screenshot-canvas'); settings.ctx = canvas.getContext("2d"); settings.tmpTxtCtn = document.getElementById('comment'); settings.$textarea = $('#text-input'); canvas.width = settings.width; canvas.height = settings.height; settings.gd.tool = 'marker'; settings.gd.lastTool = settings.gd.tool; settings.gd.toolSize = 2; settings.gd.fontSize = 12; settings.gd.color = $('.active-color').attr('id'); _toggleInvisibleCanvas($('#toggle-drawing').attr("class")); settings.$textarea.bind("focus", function(e) { settings.$canvas.one("mousedown touchstart", function() { if (settings.$textarea.val().length > 0) { _writeText(settings.$textarea.val()); } settings.$textarea.val("").hide().css("z-index", 0); }); }); settings.$canvas.bind("mousedown touchstart", function(e) { settings.mousePressed = true; settings.lastX = e.pageX - $(this).offset().left; settings.lastY = e.pageY - $(this).offset().top; if (settings.gd.pushIt == true) { if (settings.gd.tool == 'marker') { _draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true); } if (settings.gd.tool == 'eraser') { _erase(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true); } } if (settings.gd.pushIt == false) { _invisibleCanvas(e, $(this)); } if ($(".multi-item-menu").is(":visible")) { $(".multi-item-menu").fadeOut(400); } if ($("#draw-colors-pallet").is(":visible")) { $("#draw-colors-pallet").fadeOut(400); } if (settings.gd.tool == 'text') { settings.mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX; settings.mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY; settings.startMouse.x = settings.mouse.x; settings.startMouse.y = settings.mouse.y; } }); settings.$canvas.bind("mousemove touchmove", function(e) { if (settings.mousePressed == true && settings.gd.pushIt == true) { if (settings.gd.tool == 'marker') { _draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true); } if (settings.gd.tool == 'eraser') { _erase(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true); } if (settings.gd.tool == 'text') { settings.mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX; settings.mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY; _adjustTextArea(); } } if (settings.gd.pushIt == false) { var x = e.pageX, y = e.pageY; settings.mousePressed = false; if (x !== settings.lastX || y !== settings.lastY) { _invisibleCanvas(e, $(this)); } settings.lastX = x; settings.lastY = y; } }); settings.$canvas.bind("mouseleave mouseup touchend touchcancel", function(e) { if (settings.mousePressed == true && settings.gd.pushIt == true) { if (settings.gd.tool !== 'text') { _cPush(); } if (settings.$textarea.is(":visible")) { settings.$textarea.focus().css({ "z-index": 10 }); } } settings.mousePressed = false; }); settings.$canvas.bind("mouseenter", function(e) { _manageCursor(); }); $('#draw-undo-ico').click(function() { _cUndo(); }).mousedown(function(e) { clearTimeout(this.downTimer); this.downTimer = setTimeout(function() { _cUndo(true); }, 1400); }).mouseup(function(e) { clearTimeout(this.downTimer); }); $('#draw-redo-ico').click(function() { _cRedo(); }).mousedown(function(e) { clearTimeout(this.downTimer); this.downTimer = setTimeout(function() { _cRedo(true); }, 1500); }).mouseup(function(e) { clearTimeout(this.downTimer); }); settings.$canvas.keydown(function(e) { var ctrlKey = 17, yKey = 89, zKey = 90, mKey = 109, eKey = 101, tKey = 116; e = e || window.event settings.ctrlDown = e.ctrlKey || e.metaKey if (settings.ctrlDown && e.keyCode == zKey) { _cUndo(); } if (settings.ctrlDown && e.keyCode == yKey) { _cRedo(); } }).keyup(function(e) { var ctrlKey = 17, yKey = 89, zKey = 90; e = e || window.event if (e.keyCode == ctrlKey) { settings.ctrlDown = false; } }); _cPush(); } render = function() { textarea = document.createElement('textarea'); textarea.setAttribute('id', "text-input"); document.body.appendChild(textarea); div = document.createElement('div'); div.setAttribute('id', 'comment'); div.setAttribute('class', 'hide'); document.body.appendChild(div); tools = document.createElement('div'); tools.setAttribute('id', 'draw-tools-block'); panel = document.createElement('div'); panel.setAttribute('class', 'draw-panel-title'); panel.innerHTML = 'Panel'; tools.appendChild(panel); draw_marker_ico = document.createElement('div'); draw_marker_ico.setAttribute('class', 'draw-tool-ico ion-edit active-tool'); draw_marker_ico.setAttribute('id', 'draw-marker-ico'); tools.appendChild(draw_marker_ico); draw_eraser_ico = document.createElement('div'); draw_eraser_ico.setAttribute('class', 'draw-tool-ico ion-ios-trash-outline'); draw_eraser_ico.setAttribute('id', 'draw-trash-ico'); tools.appendChild(draw_eraser_ico); draw_text_ico = document.createElement('div'); draw_text_ico.setAttribute('class', 'draw-tool-ico ion-android-textsms'); draw_text_ico.setAttribute('id', 'draw-text-ico'); tools.appendChild(draw_text_ico); draw_colors_ico = document.createElement('div'); draw_colors_ico.setAttribute('class', 'draw-tool-ico ion-android-color-palette'); draw_colors_ico.setAttribute('id', 'draw-colors-ico'); tools.appendChild(draw_colors_ico); draw_colors_pallet = document.createElement('div'); draw_colors_pallet.setAttribute('id', 'draw-colors-pallet'); tools.appendChild(draw_colors_pallet); draw_undo_ico = document.createElement('div'); draw_undo_ico.setAttribute('class', 'draw-tool-ico ion-reply'); draw_undo_ico.setAttribute('id', 'draw-undo-ico'); tools.appendChild(draw_undo_ico); draw_redo_ico = document.createElement('div'); draw_redo_ico.setAttribute('class', 'draw-tool-ico ion-forward'); draw_redo_ico.setAttribute('id', 'draw-redo-ico'); tools.appendChild(draw_redo_ico); document.body.appendChild(tools); } initTools = function() { var colorArray = ['#C0C0C0', '#808080', '#000000', '#FF0000', '#800000', '#FFFF00', '#808000', '#008000', '#00FFFF', '#008080', '#0000FF', '#000080', '#FF00FF', '#800080']; toggleDrawing = $('#toggle-drawing'); toolsContainer = $('#draw-tools-block'); markerIco = $('#draw-marker-ico'); trashIco = $('#draw-trash-ico'); eraserIco = $('#draw-eraser-ico'); TextIco = $('#draw-text-ico'); colorsIco = $('#draw-colors-ico'); colorPallet = $("#draw-colors-pallet"); $.each(colorArray, function(index, value) { var active = ''; if (index == 2) { active = " active-color"; } $('<span />', { id: value, class: "pallet-colors" + active, style: 'background-color:' + value + ';' }) .attr("data-color", value) .click(function() { $('.active-color').removeClass('active-color'); $(this).addClass('active-color'); settings.gd.color = value; settings.$textarea.css({ color: settings.gd.color, "font-size": settings.gd.fontSize + "px" }); $('.active-tool').click(); if (settings.$textarea.is(":visible")) { settings.$textarea.focus(); } }) .appendTo(colorPallet); }); colorsIco.click(function() { colorPallet.fadeToggle(400); }); $('.draw-tool-ico').click(function() { var $this = $(this), id = this.id; if (id !== "draw-colors-ico" && id !== "draw-undo-ico" && id !== "draw-redo-ico") { if (colorPallet.is(":visible")) { colorPallet.fadeOut(400); } if (!$this.hasClass("active-tool")) { $(".active-tool").removeClass("active-tool"); $this.toggleClass("active-tool"); } } if (id !== "draw-text-ico" && id !== "draw-colors-ico" && settings.$textarea.is(":visible")) { settings.$textarea.val("").hide().css("z-index", 0); } }); markerIco.click(function() { settings.gd.lastTool = settings.gd.tool; settings.gd.tool = "marker"; settings.gd.toolSize = 2; _manageCursor(); }); eraserIco.click(function() { settings.gd.lastTool = settings.gd.tool; settings.gd.tool = "eraser"; settings.gd.toolSize = 15; _manageCursor(); }); trashIco.click(function() { _clearAll(); }); TextIco.click(function() { settings.gd.lastTool = settings.gd.tool; settings.gd.tool = "text"; _manageCursor(); }); return true; }; return this.each(init); }; })(jQuery);
null-none/canvasEditor
canvas-editor.js
JavaScript
mit
16,334
var application = require("application"); application.mainModule = "app/views/main"; application.start();
burkeholland/instapop
app/app/app.js
JavaScript
mit
106
import React from 'react'; import { View, StyleSheet, } from 'react-native'; import { Header } from '../modules/header'; import { RemindersInput } from '../modules/remindersInput'; import { RemindersList } from '../modules/remindersList'; export default function(props, { reminders, editing }) { return ( <View style={ styles.component }> <Header /> <RemindersInput reminder={ editing } saveReminder={ this.handleReminderSave } /> <RemindersList reminders={ reminders } editReminder={ this.handleReminderEdit } removeReminder={ this.handleReminderRemove } /> </View> ); } const styles = StyleSheet.create({ component: { flex: 1, backgroundColor: '#FCFBFC', }, });
kuzzmi/rmndrz
src/app/AppRenderer.native.js
JavaScript
mit
872
version https://git-lfs.github.com/spec/v1 oid sha256:8a5d82bc2f6efdb3c3d38f6b62e27092573ff30d789f696115d4feb65fa9d73d size 3259
yogeshsaroya/new-cdnjs
ajax/libs/angular-strap/2.1.1/modules/popover.js
JavaScript
mit
129
import actionTypes from './actionTypes'; export default { submitConsoleRequest: (endpointId, responseBody, response, error) => { return { type: actionTypes.SUBMIT_DONE, endpointId: endpointId, apiResponse: { body: responseBody, status: response ? response.statusCode.toString() : '', statusMessage: error ? error.message : response.statusMessage || '' } }; }, queryParamChanged: (newValue, paramName, endpointId) => { return { type: actionTypes.QUERY_STRING_CHANGED, newValue: newValue, paramName: paramName, endpointId: endpointId }; }, pathParamChanged: (newValue, paramName, endpointId) => { return { type: actionTypes.PATH_PARAM_CHANGED, newValue: newValue, paramName: paramName, endpointId: endpointId }; }, postBodyInputChanged: (endpointId, paramName, newValue) => { return { type: actionTypes.POST_BODY_CHANGED, newValue: newValue, postBodyParamName: paramName, endpointId: endpointId }; }, addItemToPostbodyCollection: (paramName, endpointId, itemSchema) => { return { type: actionTypes.ADD_ITEM_TO_POST_BODY_COLLECTION, postBodyParamName: paramName, endpointId: endpointId, itemSchema: itemSchema }; }, removePostbodyCollectionItem: (paramName, endpointId) => { return { type: actionTypes.REMOVE_ITEM_FROM_POST_BODY_COLLECTION, postBodyParamName: paramName, endpointId: endpointId }; }, fillConsoleSampleData: (endpointId) => { return { type: actionTypes.FILL_REQUEST_SAMPLE_DATA, endpointId: endpointId }; }, updateAuthKey: (keyName, e) => { return { type: actionTypes.AUTH_KEY_CHANGED, inputVal: e.target.value, keyName: keyName }; }, resetConsole: (endpointId) => { return { type: actionTypes.RESET_CONSOLE, endpointId: endpointId }; } };
anyarms/developer-dot
dynamic/react/shared/actions.js
JavaScript
mit
2,277