text
stringlengths
2
6.14k
const clone = require('lodash/clone'); const testHelpers = require('@quoin/node-test-helpers'); const BasicTypes = require('./basic-types'); const expect = testHelpers.expect; describe("lib/core/basic-types", () => { it("should export an object", () => { expect(BasicTypes).to.be.an('object'); }); it("should expose known properties", () => { const aClone = clone(BasicTypes); testHelpers.verifyProperties(aClone, 'string', [ 'Boolean', 'Date', 'File', 'Password', 'Number', 'String', 'Text' ]); testHelpers.verifyProperties(aClone, 'function', [ 'defaultValue', 'isValid', 'typesCheck' ]); expect(aClone).to.deep.equal({}); }); describe("isValid()", () => { const isValid = BasicTypes.isValid; it("should accept 1 param", () => { expect(isValid).to.have.lengthOf(1); }); it("should recognize an existing type", () => { expect(isValid(BasicTypes.String)).to.be.true(); }); it("should not recognize an invalid type", () => { expect(isValid('foobar')).to.be.false(); }); }); });
import React from 'react'; import { storiesOf } from '@storybook/react'; import { linkTo, hrefTo } from '@storybook/addon-links'; import LinkTo from '@storybook/addon-links/react'; import { action } from '@storybook/addon-actions'; storiesOf('Addons|Links.Link', module) .add('First', () => <LinkTo story="Second">Go to Second</LinkTo>) .add('Second', () => <LinkTo story="First">Go to First</LinkTo>); storiesOf('Addons|Links.Button', module) .add('First', () => ( <button onClick={linkTo('Addons|Links.Button', 'Second')}>Go to "Second"</button> )) .add('Second', () => ( <button onClick={linkTo('Addons|Links.Button', 'First')}>Go to "First"</button> )); storiesOf('Addons|Links.Select', module) .add('Index', () => ( <select value="Index" onChange={linkTo('Addons|Links.Select', e => e.currentTarget.value)}> <option>Index</option> <option>First</option> <option>Second</option> <option>Third</option> </select> )) .add('First', () => <LinkTo story="Index">Go back</LinkTo>) .add('Second', () => <LinkTo story="Index">Go back</LinkTo>) .add('Third', () => <LinkTo story="Index">Go back</LinkTo>); storiesOf('Addons|Links.Href', module).add('log', () => { hrefTo('Addons|Links.Href', 'log').then(href => action('URL of this story')({ href })); return <span>See action logger</span>; }); storiesOf('Addons|Links.Scroll position', module) .addDecorator(story => ( <React.Fragment> <div style={{ marginBottom: '100vh' }}>Scroll down to see the link</div> {story()} </React.Fragment> )) .add('First', () => <LinkTo story="Second">Go to Second</LinkTo>) .add('Second', () => <LinkTo story="First">Go to First</LinkTo>);
'use strict'; var app = angular.module('Fablab'); app.controller('GlobalConfigurationEditController', function ($scope,$route, $location, ConfigurationService, NotificationService) { $scope.selected = {configuration: undefined}; $scope.loadConfiguration = function (id) { ConfigurationService.get(id, function (data) { $scope.configuration = data; }); }; $scope.save = function () { var configurationCurrent = angular.copy($scope.configuration); ConfigurationService.save(configurationCurrent, function (data) { $scope.configuration = data; NotificationService.notify("success", "configuration.notification.saved"); $route.reload(); $location.path("configurations"); }); }; } ); app.controller('ConfigurationEditController', function ($scope, $routeParams, $controller) { $controller('GlobalConfigurationEditController', {$scope: $scope}); $scope.newConfiguration = false; $scope.loadConfiguration($routeParams.id); } );
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; desc = parent = getter = undefined; _again = false; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } var _ResourceDecoratorJs = require("./ResourceDecorator.js"); var _ResourceDecoratorJs2 = _interopRequireDefault(_ResourceDecoratorJs); var _endpointsLoadedDataEndpointJs = require("../endpoints/LoadedDataEndpoint.js"); var _endpointsLoadedDataEndpointJs2 = _interopRequireDefault(_endpointsLoadedDataEndpointJs); var _transformersEmbeddedPropertyTransformerJs = require("../transformers/EmbeddedPropertyTransformer.js"); var _transformersEmbeddedPropertyTransformerJs2 = _interopRequireDefault(_transformersEmbeddedPropertyTransformerJs); var _endpointsPromiseEndpointJs = require("../endpoints/PromiseEndpoint.js"); var _endpointsPromiseEndpointJs2 = _interopRequireDefault(_endpointsPromiseEndpointJs); var _injectorJs = require("../injector.js"); var JsonPropertyDecorator = (function (_ResourceDecorator) { function JsonPropertyDecorator(loadedDataEndpointFactory, embeddedPropertyTransformerFactory, promiseEndpointFactory, name, path, value, options) { _classCallCheck(this, JsonPropertyDecorator); _get(Object.getPrototypeOf(JsonPropertyDecorator.prototype), "constructor", this).call(this, name); this.path = path; this.options = options || {}; this.loadedDataEndpointFactory = loadedDataEndpointFactory; this.embeddedPropertyTransformerFactory = embeddedPropertyTransformerFactory; this.promiseEndpointFactory = promiseEndpointFactory; this.value = value; } _inherits(JsonPropertyDecorator, _ResourceDecorator); _createClass(JsonPropertyDecorator, [{ key: "recordApply", value: function recordApply(target) { target.constructor.properties[this.name] = this.path; if (!target.hasOwnProperty(this.name)) { var afterSet = this.options.afterSet; var path = this.path; Object.defineProperty(target, this.name, { enumerable: true, configurable: true, get: function get() { return this.pathGet(path); }, set: function set(value) { var result = this.pathSet(path, value); if (afterSet) { afterSet.call(this); } return result; } }); } } }, { key: "resourceApply", value: function resourceApply(resource) { if (this.value !== undefined) { resource.setInitialValue(this.path, this.value); } this.recordApply(resource); } }, { key: "errorsApply", value: function errorsApply(errors) { this.recordApply(errors); } }, { key: "endpointFn", get: function () { if (!this._endpointFn) { var path = this.path; var promiseEndpointFactory = this.promiseEndpointFactory; var loadedDataEndpointFactory = this.loadedDataEndpointFactory; var embeddedPropertyTransformerFactory = this.embeddedPropertyTransformerFactory; this._endpointFn = function () { var _this = this; var uriParams = arguments[0] === undefined ? {} : arguments[0]; // 'this' in here = Endpoint var newPromise = function newPromise() { return _this.load().then(function (resource) { return loadedDataEndpointFactory(resource.self(), resource, [embeddedPropertyTransformerFactory(path)]); }); }; var newEndpoint = promiseEndpointFactory(newPromise); return newEndpoint; }; } return this._endpointFn; } }, { key: "endpointApply", value: function endpointApply(target) { this.addFunction(target, this.endpointFn); } }]); return JsonPropertyDecorator; })(_ResourceDecoratorJs2["default"]); exports["default"] = JsonPropertyDecorator; (0, _injectorJs.Inject)((0, _injectorJs.factory)(_endpointsLoadedDataEndpointJs2["default"]), (0, _injectorJs.factory)(_transformersEmbeddedPropertyTransformerJs2["default"]), (0, _injectorJs.factory)(_endpointsPromiseEndpointJs2["default"]))(JsonPropertyDecorator); module.exports = exports["default"];
var fs = require('fs'); fs.stat('/tmp', function(err, stats) { if (err) { console.error(err); return; } console.log(stats); });
var path = require('path'); var cmd = require('cmd-util'); var ast = cmd.ast; var iduri = cmd.iduri; exports.init = function(grunt) { var exports = {}; exports.jsConcat = function(fileObj, options) { var data = grunt.file.read(fileObj.src); var meta = ast.parseFirst(data); var records = grunt.option('concat-records'); if (grunt.util._.contains(records, meta.id)) { return ''; } records.push(meta.id); if (options.include === 'self') { return data; } var rv = meta.dependencies.map(function(dep) { if (dep.charAt(0) === '.') { var id = iduri.absolute(meta.id, dep); if (grunt.util._.contains(records, id)) { return ''; } records.push(id); var fpath = path.join(path.dirname(fileObj.src), dep); console.log('###', fpath); if (!/\.js$/.test(fpath)) fpath += '.js'; if (!grunt.file.exists(fpath)) { grunt.log.warn('##=>file ' + fpath + ' not found'); return ''; } return grunt.file.read(fpath); } else if ((/\.css$/.test(dep) && options.css2js) || options.include === 'all') { var fileInPaths; options.paths.some(function(basedir) { var fpath = path.join(basedir, dep); console.log('@@@', fpath); if (!/\.css$/.test(dep)) { fpath += '.js'; } if (grunt.file.exists(fpath)) { fileInPaths = fpath; return true; } }); if (!fileInPaths) { grunt.log.warn('@@=>file ' + dep + ' not found\n'+ fileInPaths +'\n'); } else { var data = grunt.file.read(fileInPaths); if (/\.css$/.test(dep)) { return options.css2js(data, dep); } return data; } } return ''; }).join(grunt.util.normalizelf(options.separator)); return [data, rv].join(grunt.util.normalizelf(options.separator)); }; return exports; };
'use strict'; angular.module('myApp.gear', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/gear', { templateUrl: 'gear/gear.html', controller: 'GearCtrl' }); }]) .controller('GearCtrl', ['$scope','$http', function($scope, $http) { $http.get('resources/data/gear.json'). success(function(data, status, headers, config) { $scope.content = data; }). error(function(data, status, headers, config) { // log error }); }]);
$("#btnAddButton").on('click', addButton); $("#btnRemoveButton").on('click', removeButton); $('#btnAddTrail').on('click', loadFiles); $(document).ready(function() { }); var counter = 0; function addButton(event) { if(counter >= 10){ alert("Only 10 textboxes are allowed"); return false; } var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter); var str = '<input id="inputPicture" type="file" name="addpic">' + '<input id="inputPictureLon" type="text" placeholder="lon" size="8">' + '<input id="inputPictureLat" type="text" placeholder="lat" size="8">' + '<input id="inputPictureAlt" type="text" placeholder="alt" size="8">' + '<input id="inputPictureTimestamp" type="text" placeholder="timestamp" size="8">' + '<input id="inputPictureName" type="text" placeholder="picturename" size="8">' + '<input id="inputPictureDescription" type="text" placeholder="description" size="8">'; newTextBoxDiv.after().html(str); newTextBoxDiv.appendTo("#TextBoxesGroup"); counter++; } function removeButton(event) { if (counter == 0) { alert("No more textbox to remove"); return false; } counter--; $("#TextBoxDiv" + counter).remove(); } var log = function(text) { var elem = document.getElementsByTagName('span')[1]; elem.innerHTML = text; elem.style.backgroundColor="yellow"; elem.style.color="black"; setTimeout(function() { document.getElementsByTagName('span')[1].innerHTML = ""; }, 60000); }; var picDataArray = []; var readers = []; var readerInd = 0; function loadFiles(event) { var elem; var file; picDataArray = []; readers = []; readerInd = 0; event.preventDefault(); if (window.File && window.FileReader && window.FileList && window.Blob) { //alert("File API supported.!"); for (var i=0; i<counter; i++) { readers[i] = new FileReader(); readers[i].onload = function(e) { if (e.target.error) { log("couldn't read file"); return; } picDataArray.push(btoa(e.target.result)); readerInd++; if (readerInd == counter) { sendTrail(); } }; var elem = document.getElementById('TextBoxDiv' + (i).toString()); var file = elem.children[0].files[0]; readers[i].readAsBinaryString(file); } if (counter == 0) { sendTrail(); } } else { alert('The File APIs are not fully supported in this browser.\nI will not send pictures'); sendTrail(); } } function sendTrail() { var obj; var locArray = []; var picArray = []; var coords = []; var lines = $('#textareaCoordinates').val().split('\n'); for (var i=0; i<lines.length; i++) { var words = lines[i].split(','); if (words.length == 4) { coords = []; for (var j=0; j<3; j++) { coords.push(parseFloat(words[j])); } obj = { 'timestamp': words[3], 'loc': { 'type': 'Point', 'coordinates': coords } }; locArray.push(obj); } } for (var i=0; i<counter; i++) { coords = []; coords.push($('#TextBoxDiv' + i + ' #inputPictureLon').val()); coords.push($('#TextBoxDiv' + i + ' #inputPictureLat').val()); coords.push($('#TextBoxDiv' + i + ' #inputPictureAlt').val()); obj = { 'timestamp': $('#TextBoxDiv' + i + ' #inputPictureTimestamp').val(), 'picturename': $('#TextBoxDiv' + i + ' #inputPictureName').val(), 'description': $('#TextBoxDiv' + i + ' #inputPictureDescription').val(), 'filename': $('#TextBoxDiv' + i + ' #inputPicture').val(), 'file': picDataArray[i], 'loc': { 'type': 'Point', 'coordinates': coords } }; picArray.push(obj); } var data = { 'newtrail' : [ { 'type': 'LocationCollection', 'locations': locArray }, { 'type': 'PictureCollection', 'pictures': picArray }, { 'type': 'TrailInfo', 'access': $('#inputAccess').val(), 'trailname': $('#inputTrailName').val(), 'description': $('#inputDescription').val(), 'date': $('#inputDate').val(), 'locationname': $('#inputLocationName').val() }, { 'type': 'UserInfo', 'username': $('#inputUsername').val(), 'password': $('#inputPassword').val(), } ] }; $.ajax({ type: 'POST', data: data, url: '/addtrail', dataType: 'JSON', success: function(res) { if (res.status == 'ok') { var elem = document.getElementsByTagName('span')[0]; elem.innerHTML = res.msg; elem.style.backgroundColor="blue"; elem.style.color="white"; setTimeout(function() { document.getElementsByTagName('span')[0].innerHTML = ""; }, 5000); } else { var elem = document.getElementsByTagName('span')[0]; elem.innerHTML = res.msg; elem.style.backgroundColor="red"; elem.style.color="white"; setTimeout(function() { document.getElementsByTagName('span')[0].innerHTML = ""; }, 5000); } }, error: function(xhr, textStatus) { alert("HTTP error code: " + xhr.status + " response:\n" + xhr.responseText); }, complete: function(xhr, textstatus) { } }); }
(function (window, document, angular, jQuery, undefined) { 'use strict'; angular.module('vissensePlayground') .controller('TrackSectionsDemoCtrl', [ '$window', '$document', '$scope', 'VisSense', function ($window, $document, $scope, VisSense) { $scope.scrollToElement = function (elementId) { jQuery('html, body').animate({ scrollTop: jQuery('#' + elementId).offset().top }, 500); }; var changeOpacityOnPercentageChangeOfElementWithId = function (elementId) { var sectionElement = jQuery('#' + elementId); var onChange = function (state) { var newValue = state.percentage; var oldValue = (state.previous.percentage || 0); var difference = newValue - oldValue; var duration = 500 * Math.max(difference, 0.25); // set the opacity to the actual visibility percentage var opacity = Math.max(newValue, 0.25); sectionElement.fadeTo(duration, opacity); }; var sectionMonitor = new VisSense(sectionElement[0]).monitor({ // update when user scrolls or resizes the page strategy: VisSense.VisMon.Strategy.EventStrategy({debounce: 50}), percentagechange: function (monitor) { onChange(monitor.state()); } }).start(); $scope.$on('$destroy', function () { sectionMonitor.stop(); }); }; changeOpacityOnPercentageChangeOfElementWithId('examples-section'); changeOpacityOnPercentageChangeOfElementWithId('demo-section'); changeOpacityOnPercentageChangeOfElementWithId('plugins-section'); }]); })(window, document, angular, jQuery);
"use strict"; const commonOptions = require("../common/common-options"); // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js module.exports = { bracketSpacing: commonOptions.bracketSpacing, singleQuote: commonOptions.singleQuote, proseWrap: commonOptions.proseWrap };
'use strict'; module.exports = config => [{ name: 'facebook-app_id', message: 'app id of facebook', store: true, when: require('./when')('facebook', config) }, { name: 'facebook_api-api_version', message: 'version of facebook api', store: true, when: require('./when')('facebook_api', config) }];
let prop, value, i, len; for (i = 0, len = myDiv.style.length; i < len; i++) { prop = myDiv.style[i]; // alternately, myDiv.style.item(i) value = myDiv.style.getPropertyCSSValue(prop); console.log(`prop: ${value.cssText} (${value.cssValueType})`); }
var albumId; var addPictures = function (result) { UserFBAlbums.update({id: albumId}, {$set: {'paging': result.paging}}); for (var i = 0; i < result.data.length; i++) { UserFBAlbums.update({id: albumId}, {$addToSet: {'pictures': result.data[i]}}); } IonLoading.hide(); }; Template.gallery.events({ 'click .loadNext': function () { IonLoading.show(); var next = UserFBAlbums.findOne({id: albumId}).paging.next; facebookApi.getNext(next, addPictures) }, 'click .thumb': function (e) { Meteor.call('TogglePicture', this.id, function (error, result) { if (error) { console.log(error.reason); } else if (!result) { IonPopup.alert({ title: 'Too many images!', template: 'You can only select up to five images.\n Please review your "Selected Photos" album, and remove some before adding more.', okText: 'Got It.' }); } }); } }); var pictures = []; Template.gallery.helpers({ pictures: function () { if (albumId) { pictures = UserFBAlbums.findOne({id: albumId}).pictures; } return pictures; }, photosSelected: function () { var selected = 0; if (Meteor.user()) { selected = Meteor.user().profile.facebookImageIds.length; } return '(' + selected + '/5)'; }, hasNext: function () { var album = UserFBAlbums.findOne({id: albumId}); if (album && album.paging) { return album.paging.next; } return false; } }); Template.gallery.rendered = function () { if (albumId) { if (!UserFBAlbums.findOne({id: albumId}).pictures) { IonLoading.show(); } this.autorun(function () { if (UserFBAlbums.findOne({id: albumId}).pictures) { IonLoading.hide(); } else if (Session.get('fbLoaded') && Meteor.userId()) { facebookApi.getPhotos({identifier: albumId}, function (result) { addPictures(result); }); } }.bind(this)); } }; Template.gallery.created = function () { albumId = Router.current().params._albumId; this.autorun(function () { this.subscription = Meteor.subscribe('user', Meteor.userId()); }.bind(this)); if (!albumId) { var images = Meteor.user().profile.facebookImageIds; for (var i = 0; i < images.length; i++) { pictures.push({id: images[i]}); } } };
var LiveStream = require('../') var SubLevel = require('level-sublevel') var db = SubLevel(require('level-test')()('test-level-live-stream')) var assert = require('assert') var i = 10 var j = 10 var k = 10 LiveStream(db, {tail: true}).on('data', function (data) { console.log(data) if(data.type === 'put') assert.equal(data.key, j--) }) LiveStream(db, {old: false}).on('data', function (data) { if(data.type === 'put') assert.equal(data.key, k--) }) var a = [] var int = setInterval(function () { var key = i + '' if(Math.random() < 0.2 && a.length) { var r = ~~(Math.random()*a.length) key = a[r] a.slice(r, 1) db.del(key, function (err) { assert(err == undefined) }) } else { a.push(key) db.put(key, new Date(), function(err) { assert(err == undefined) }) if(--i) return clearInterval(int) } }, 100)
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchIP } from '../../actions/fetchIP'; import { Snackbar } from 'react-toolbox'; import theme from './Snackbar.css'; class SnackbarComponent extends Component { constructor(props) { super(props); this.state = { active: false, message: '' }; this.handleSnackbarClick = this.handleSnackbarClick.bind(this); this.handleSnackbarTimeout = this.handleSnackbarTimeout.bind(this); } handleSnackbarClick = () => { this.setState({active: false}); }; handleSnackbarTimeout = () => { if (this._isMounted) { this.setState({active: false}); } this.props.fetchIP(); }; componentWillReceiveProps(props) { this.setState({ active: props.error, message: props.message }); } componentDidMount() { this._isMounted = true; } componentWillUnmount() { this._isMounted = false; } render() { return ( <section> <Snackbar theme={theme} action="Hide" active={this.props.weather.error} label={this.props.weather.message} timeout={1500} onClick={this.handleSnackbarClick} onTimeout={this.handleSnackbarTimeout} type="warning" /> </section> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchIP }, dispatch); } function mapStateToProps({ weather }) { return { weather }; } export default connect(mapStateToProps, mapDispatchToProps)(SnackbarComponent);
var util = require('util'); var bleno = require('bleno'); var BlenoPrimaryService = bleno.PrimaryService; var ParkCharacteristic = require('./parkCharacteristic'); function DeviceInformationService() { DeviceInformationService.super_.call(this, { uuid: 'ec00', characteristics: [ new ParkCharacteristic() ] }); } util.inherits(DeviceInformationService, BlenoPrimaryService); module.exports = DeviceInformationService;
const expect = require('chai').expect const includeMimeType = require('../src/file').includeMimeType const findInFile = require('../src/file').findInFile describe('file : includeMimeType', () => { it('MIME_TYPES_IGNORED contain this mime type', () => { expect(includeMimeType('test/directoryTest/file2.png')).to.be.true }) it('MIME_TYPES_IGNORED not contain this mime type', () => { expect(includeMimeType('test/directoryTest/file1.js')).to.be.false }) }) describe('file : findInFile', () => { it('will some results (string)', () => { const results = findInFile('foo', 'test/directoryTest/file1.js') expect(results).to.be.eql({ 1: [5], 2: [12], 3: [5, 18] }) }) it('will some results (regExp)', () => { const results = findInFile(/foo/, 'test/directoryTest/file1.js') expect(results).to.be.eql({ 1: [5], 2: [12], 3: [5, 18] }) }) it('will nothing (string)', () => { const results = findInFile('nothing', 'test/directoryTest/file1.js') expect(results).to.be.eql({}) }) it('will nothing (regExp)', () => { const results = findInFile(/nothing/, 'test/directoryTest/file1.js') expect(results).to.be.eql({}) }) })
var fs = require('fs'); var assert = require('assert'); var JSZip = require('jszip'); var path = require('path') var compareWorkbooks = require('./util/compareworkbooks.js') var excelbuilder = require('..'); describe('It generates a simple workbook', function () { it('generates a ZIP file we can save', function (done) { var workbook = excelbuilder.createWorkbook(); var table = [ [1, 2, "", 4, 5], [2, 4, null, 16, 20], [1, 4, NaN, 16, 25], [4, 8, undefined, 16, 20] ] var sheet1 = workbook.createSheet('sheet1', table[0].length, table.length); table.forEach(function (row, rowIdx) { row.forEach(function (val, colIdx) { sheet1.set(colIdx + 1, rowIdx + 1, val) }) }) workbook.generate(function (err, zip) { if (err) throw err; zip.generateAsync({type: "nodebuffer"}).then(function (buffer) { var OUTFILE = './test/out/example.xlsx'; fs.writeFile(OUTFILE, buffer, function (err) { console.log('open \"' + OUTFILE + "\""); compareWorkbooks('./test/files/example.xlsx', OUTFILE, function (err, result) { if (err) throw err; // assert(result) done(err); }); }); }); }); }); });
var Cat = require('../src/Cat'); require('chai').should(); describe('This should pass if mutated', function(){ it('yes it should', function(){ var name = Math.random(); true.should.equal(true); }); });
var today = new Date(); var birthday = new Date(1981, 1, 16); var age = today.getTime() - birthday.getTime(); alert(age); // alert(age / 1000 / 60 / 60 / 24/ 365.25);
/* * Datagrid.js */ function dg_send(url, grid, form, page, tamano, orderby, orderdirection) { var oForm = $("#"+form); var oGrid = $("#"+grid); var oLoader = $("#loader_"+grid); $('#Form_'+grid+'_page').val(page); $('#Form_'+grid+'_tamano').val(tamano); $('#Form_'+grid+'_orderby').val(orderby); $('#Form_'+grid+'_orderdirection').val(orderdirection); $(oLoader).width($(oGrid).width()) $(oLoader).height($(oGrid).height()) jQuery(oLoader).show(); $.ajax({ type: "POST", url: Routing.generate(url), data: ($(oForm).serialize()+'&datagrid='+grid), success: function(data){ data = data.replace(/^\s*|\s*$/g,""); $(oGrid).html(data); }, error: function(XMLHttpRequest, textStatus, errorThrown){ jQuery(oLoader).hide(); $("#dialog-modal").html("Error: "+XMLHttpRequest.status + ' ' + XMLHttpRequest.statusText); $("#dialog-modal").dialog("open"); } }); } function dg_delitem(urlreload, urldelete, grid, form, deletekey) { if (confirm("¿Está seguro que desea eliminar?")) { var oForm = $("#"+form); var oGrid = $("#"+grid); var oLoader = $("#loader_"+grid); $('#Form_'+grid+'_deletekey').val(deletekey); $(oLoader).width($(oGrid).width()) $(oLoader).height($(oGrid).height()) jQuery(oLoader).show(); $.ajax({ type: "POST", url: Routing.generate(urldelete), data: $(oForm).serialize(), success: function(data){ data = data.replace(/^\s*|\s*$/g,""); if(data == 'OK'){ dg_reload(urlreload, grid, form); }else{ jQuery(oLoader).hide(); $("#dialog-modal").html(data); $("#dialog-modal").dialog("open"); } }, error: function(XMLHttpRequest, textStatus, errorThrown){ jQuery(oLoader).hide(); $("#dialog-modal").html("Error: "+XMLHttpRequest.status + ' ' + XMLHttpRequest.statusText); $("#dialog-modal").dialog("open"); } }); } } function dg_reload(url, grid, form) { dg_send(url, grid, form, $('#Form_'+grid+'_page').val(), $('#Form_'+grid+'_tamano').val(), $('#Form_'+grid+'_orderby').val(), $('#Form_'+grid+'_orderdirection').val() ); }
"use strict"; exports.buttonEvent = function(id) { return function(cb) { return function() { var el = document.getElementById(id); el.addEventListener('click', function(ev) { cb(); }); } }; }; exports.keydownEvent = function(el) { return function(cb) { return function() { window.addEventListener('keydown', function(ev) { cb(ev)(); }); } }; }; exports.resizeEvent = function(cb) { return function() { var resizeDelay = 250; // ms delay before running resize logic var resizeTimeout = null; var throttled = function() { if (resizeTimeout) { clearTimeout(resizeTimeout); } resizeTimeout = setTimeout(function() { resizeTimeout = null; cb(exports.windowInnerSize())(); }, resizeDelay); }; window.addEventListener('resize', throttled, false); }; }; exports.windowInnerSize = function() { var w = window.innerWidth; var h = window.innerHeight; return { width: w, height: h }; }; exports.setWindow = function(k) { return function(v) { return function() { window[k] = v; }; }; }; exports.setElementContents = function(el) { return function(html) { return function() { el.innerHTML = html; }; }; }; var debugDivId = "debugDiv"; exports.initDebugDiv = function(radius) { return function() { var view = document.getElementById("browser"); var div = document.getElementById(debugDivId); if (!div) { div = document.createElement("div"); view.appendChild(div); } div.id = debugDivId; div.style['position'] = "relative"; div.style['left'] = "0.0"; div.style['top'] = "0.0"; div.style['border-radius'] = "50%"; div.style['width'] = (radius * 2.0) + "px"; div.style['height'] = (radius * 2.0) + "px"; div.style['z-index'] = "100"; div.style['backgroundColor'] = "red"; div.style['pointer-events'] = "none"; div.style['display'] = "inline-block"; div.style['visibility'] = "hidden"; div.dataset.radius = radius; return div; }; }; var getDebugDiv = function() { var div = document.getElementById(debugDivId); if (!div) { return initDebugDiv(10.0)(); } else { return div; } }; exports.setDebugDivVisibility = function(s) { return function() { var div = getDebugDiv(); div.style['visibility'] = s; }; }; exports.setDebugDivPoint = function(p) { return function() { var div = getDebugDiv(); var r = div.dataset.radius | 1.0; var x = p.x - r; var y = p.y - r * 2.0; // var y = p.y; div.style['left'] = x + "px"; div.style['top'] = y + "px"; }; };
window.appConf = { author: 'React Drive CMS', dashboardId: '1-on_GfmvaEcOk7HcWfKb8B6KFRv166RkLN2YmDEtDn4', sendContactMessageUrlId: 'AKfycbyL4vW1UWs4mskuDjLoLmf1Hjan1rTLEca6i2Hi2H_4CtKUN84d', shortname: 'easydrivecms', root: 'react-drive-cms', }
module.exports = flatten([ require("./base/dualfilter"), require("./base/filter"), require("./base/mirrorBlocks"), require("./base/overlayMask"), require("./base/split"), require("./base/splitMask"), require("./colourset/lerp"), require("./colourset/distinct"), require("./colourset/chunks"), require("./colourset/alpha"), require("./extras/swatch"), require("./extras/text"), require("./filter/bevel"), require("./filter/disolve"), require("./filter/roughen"), require("./filter/sharpen"), require("./filter/splash"), require("./lines/straight"), require("./lines/curve"), require("./lines/scribble"), require("./mask/halfmask"), require("./overlay/lines"), require("./overlay/network"), require("./overlay/shapes"), require("./overlay/sparkles"), require("./pallete/monochrome"), require("./pallete/hightlightAndMidtone"), require("./pallete/bicolor"), require("./pointset/static"), require("./pointset/linear"), require("./pointset/circular"), require("./pointset/grid"), require("./pointset/spiral"), require("./pointset/tree"), require("./shapes/polygon"), require("./shapes/stars"), require("./shapes/ring"), require("./shapes/circle"), require("./simple/blockColor"), require("./simple/blockOverlay"), require("./spacial/radial"), require("./spacial/chaos"), require("./spacial/linear"), require("./tiles/squares"), require("./tiles/triangles"), ]) function flatten( m ){ var retval = []; for ( var id in m ){ if ( m[id].push ){ retval = retval.concat(m[id]); }else{ retval.push(m[id]); } } return retval; }
'use strict'; angular.module('myApp').directive('loginDirective',function(){ return{ templateUrl:'partials/tpl/login.tpl.html' } });
function Rook(loc, isWhite, asset){ Piece.call(this, loc, isWhite, asset); this.name = "Rook"; } Rook.prototype = Object.create(Piece.prototype); Rook.prototype.constructor = Rook; Rook.prototype.getValidMoveSet = function(board) { var result = []; var currentX = this.loc.x+1; var currentY = this.loc.y; var currentSpeculation = new Point(currentX, currentY); //moving right while(board.inBounds(currentSpeculation) && !board.locOccupied(currentSpeculation)){ result.push(currentSpeculation); currentX += 1; currentSpeculation = new Point(currentX, currentY); } var cap = board.getPieceAt(currentSpeculation); if(cap){ if(cap.isWhite() !== this.white){ result.push(currentSpeculation); } } //moving left currentX = this.loc.x-1; currentY = this.loc.y; currentSpeculation = new Point(currentX, currentY); while(board.inBounds(currentSpeculation) && !board.locOccupied(currentSpeculation)){ result.push(currentSpeculation); currentX -= 1; currentSpeculation = new Point(currentX, currentY); } cap = board.getPieceAt(currentSpeculation); if(cap){ if(cap.isWhite() !== this.white){ result.push(currentSpeculation); } } //moving up currentX = this.loc.x; currentY = this.loc.y-1; currentSpeculation = new Point(currentX, currentY); while(board.inBounds(currentSpeculation) && !board.locOccupied(currentSpeculation)){ result.push(currentSpeculation); currentY -= 1; currentSpeculation = new Point(currentX, currentY); } cap = board.getPieceAt(currentSpeculation); if(cap){ if(cap.isWhite() !== this.white){ result.push(currentSpeculation); } } //moving down currentX = this.loc.x; currentY = this.loc.y+1; currentSpeculation = new Point(currentX, currentY); while(board.inBounds(currentSpeculation) && !board.locOccupied(currentSpeculation)){ result.push(currentSpeculation); currentY += 1; currentSpeculation = new Point(currentX, currentY); } cap = board.getPieceAt(currentSpeculation); if(cap){ if(cap.isWhite() !== this.white){ result.push(currentSpeculation); } } return result; };
var dir_72c031272133aec1d916095cf903ecf1 = [ [ "HTTP", "dir_7e5fd1ff9265fa651882e3ad4d93cc88.html", "dir_7e5fd1ff9265fa651882e3ad4d93cc88" ], [ "Module", "dir_10705d0e5b4538c0e815cbe3b6497638.html", "dir_10705d0e5b4538c0e815cbe3b6497638" ] ];
var flow = require('js-flow'), assert = require('assert'), tubes = require('evo-tubes'); describe('evo-states', function () { var TIMEOUT = 60000; var sandbox; beforeEach(function (done) { this.timeout(TIMEOUT); (sandbox = new tubes.Sandbox()) .add(new tubes.Environment({ nodes: 4 })) .add(new tubes.NeuronFactory()) .add(new tubes.Connector()) .add(new tubes.States()) .start(done); }); afterEach(function (done) { sandbox.cleanup(done); }); it('synchronize', function (done) { this.timeout(TIMEOUT); var connector = sandbox.res('evo-connector'); flow.steps() .next('clientsReady') .next(function (next) { flow.each([this.clients[0], this.clients[1]]) .keys() .do(function (index, client, next) { client.commit({ key: 'val' + index }, next); }) .run(next); }) .next(function (next) { this.waitForSync({ key: 'key' }, function (data, client, index) { return [0, 1].every(function (i) { var nodeVal = data.d[connector.clients[i].localId]; return nodeVal && nodeVal.d == 'val' + i; }); }, next); }) .with(sandbox.res('evo-states')) .run(done) }); });
/** * @authors JayChenFE * @date 2017-03-21 11:17:13 * @version $1.0$ */ /** * 主要核心逻辑入口 **/ const fs = require('fs'); const path = require('path'); const staticServer = require('./static-server'); class App { constructor() { } initServer() { //方便增加别的逻辑 //返回一个函数 return (request, response) => { let { url } = request; let body = staticServer(url); response.writeHead(200, 'resolve ok', { 'X-Powered-By': 'Node.js' }); response.end(body); // const staticPrefix = path.resolve(process.cwd(), 'public'); // let staticFun = url => { // if (url == '/') { // url = '/index.html'; // } // let _path = getPath(url); // // fs.readFile(_path, 'binary', (error, data) => { // // if (error) { // // data="NOT FOUND"; // // } // // response.end(data,'binary'); // // }); // fs.readFile(_path, (error, data) => { // if (error) { // data = `NOT FOUND ${error.stack}`; // } // response.end(data); // }); // }; // staticFun(url); // if (url == '/css/index.css') { // fs.readFile('./public/css/index.css', 'utf-8', (error, data) => { // response.end(data); // }); // } // if (url == '/js/index.js') { // fs.readFile('./public/js/index.js', 'utf-8', (error, data) => { // response.end(data); // }); // } // if (url == '/') { // //第一个路径相对的是process.cwd(); // fs.readFile('./public/index.html', 'utf-8', (error, data) => { // response.end(data); // }); // } }; } } module.exports = App;
define('controllers/menuController',['jqueryui'],function($){ $('#faq').dialog({ modal:true, autoOpen: false, height:window.innerHeight * 0.75, width:window.innerWidth * 0.75, draggable:false }); $('#faq-button').click(function(event){ $('#faq').dialog('open'); }); $('#signin').dialog({ modal:true, autoOpen: false, height:window.innerHeight * 0.75, width:window.innerWidth * 0.75, draggable:false }); $('#signin-button').click(function(event){ $('#signin').dialog('open'); }); $('#facebook-login').click(function(event){ $(document).trigger('facebook-login'); }); });
const _ = require("lodash"); const Path = require("path-parser"); const { URL } = require("url"); const mongoose = require("mongoose"); const requireSignIn = require("../middlewares/requireSignIn"); const requireCredits = require("../middlewares/requireCredits"); const Mailer = require("../services/Mailer"); const surveyTemplate = require("../services/templates/surveyTemplate"); const Survey = mongoose.model("surveys"); module.exports = app => { app.get("/api/surveys", requireSignIn, async (req, res) => { const surveys = await Survey.find({ _user: req.user.id }).select({ recipients: false }); res.send(surveys); }); app.get("/api/surveys/:surveyID/:choice", (req, res) => { res.send("Thank you for your response."); }); app.post("/api/surveys/webhooks", (req, res) => { const parsedURL = new Path("/api/surveys/:surveyID/:choice"); _.chain(req.body) .map(({ email, url }) => { //do not destructure because match can be null const match = parsedURL.test(new URL(url).pathname); if (match) { return { email, surveyID: match.surveyID, choice: match.choice }; } }) .compact() .uniqBy("email", "surveyID") .each(({ surveyID, email, choice }) => { Survey.updateOne( { _id: surveyID, recipients: { $elemMatch: { email: email, responded: false } } }, { $inc: { [choice]: 1 }, $set: { "recipients.$.responded": true }, lastResponded: new Date() } ).exec(); }) .value(); res.send({}); }); app.post("/api/surveys", requireSignIn, requireCredits, async (req, res) => { const { title, subject, body, recipients } = req.body; const survey = new Survey({ title, subject, body, recipients: recipients.split(",").map(email => ({ email: email.trim() })), _user: req.user.id, dateSent: Date.now() }); const mailer = new Mailer(survey, surveyTemplate(survey)); try { await mailer.send(); await survey.save(); req.user.credits -= 1; const user = await req.user.save(); res.send(user); } catch (err) { res.status(422).send(err); } }); };
#target "InDesign" #include "../datetimef.js" var today = new Date(2014, 2, 8, 13, 23, 46, 300); // => Sat Mar 08 2014 13:23:46 GMT+0900 var ret = []; var t = function(done, expect) { done_str = done; if (done === expect) { ret.push("[Passed]: return => " + expect); } else { ret.push("[Failed]: expect " + expect + ", but return => " + done); } } // tests t( datetimef(today)+"", Error("No Format")+""); t( datetimef(today, 123)+"", Error("No Format")+""); t( datetimef(today, ""), ""); t( datetimef(today, "%X"), "%X"); t( datetimef("today", "%Y")+"", Error("Not Date")+""); t( datetimef(today, "%Y"), "2014"); t( datetimef(today, "%y"), "14"); t( datetimef(today, "%m"), "03"); t( datetimef(today, "%B"), "March"); t( datetimef(today, "%b"), "Mar"); t( datetimef(today, "%d"), "08"); t( datetimef(today, "%e"), " 8"); t( datetimef(today, "%j"), "67"); t( datetimef(today, "%H"), "13"); t( datetimef(today, "%k"), "13"); t( datetimef(today, "%I"), "01"); t( datetimef(today, "%l"), " 1"); t( datetimef(today, "%p"), "PM"); t( datetimef(today, "%P"), "pm"); t( datetimef(today, "%M"), "23"); t( datetimef(today, "%S"), "46"); t( datetimef(today, "%L"), "300"); t( datetimef(today, "%z"), "-0900"); t( datetimef(today, "%A"), "Saturday"); t( datetimef(today, "%a"), "Sat"); t( datetimef(today, "%u"), "7"); t( datetimef(today, "%w"), "6"); t( datetimef(today, "%s"), "1394252626300"); t( datetimef(today, "%Y%m%d"), "20140308" ); t( datetimef(today, "%F"), "2014-03-08" ); t( datetimef(today, "%Y-%m"), "2014-03" ); t( datetimef(today, "%Y"), "2014" ); t( datetimef(today, "%Y%j"), "201467" ); t( datetimef(today, "%Y-%j"), "2014-67" ); t( datetimef(today, "%H%M%S"), "132346" ); t( datetimef(today, "%T"), "13:23:46" ); t( datetimef(today, "%H%M"), "1323" ); t( datetimef(today, "%H:%M"), "13:23" ); t( datetimef(today, "%H"), "13" ); t( datetimef(today, "%H%M%S,%L"), "132346,300" ); t( datetimef(today, "%T,%L"), "13:23:46,300" ); t( datetimef(today, "%H%M%S.%L"), "132346.300" ); t( datetimef(today, "%T.%L"), "13:23:46.300" ); t( datetimef(today, "%H%M%S%z"), "132346-0900" ); t( datetimef(today, "%Y%m%dT%H%M%S%z"), "20140308T132346-0900" ); t( datetimef(today, "%Y%jT%H%M%S%z"), "201467T132346-0900" ); t( datetimef(today, "%Y%m%dT%H%M"), "20140308T1323" ); t( datetimef(today, "%FT%R"), "2014-03-08T13:23" ); t( datetimef(today, "%Y%jT%H%MZ"), "201467T1323Z" ); t( datetimef(today, "%Y-%jT%RZ"), "2014-67T13:23Z" ); $.writeln(ret.join("\n")); /* toString,toSource [Passed]: return => エラー: No Format [Passed]: return => エラー: No Format [Passed]: return => [Passed]: return => %X [Passed]: return => エラー: Not Date [Passed]: return => 2014 [Passed]: return => 14 [Passed]: return => 03 [Passed]: return => March [Passed]: return => Mar [Passed]: return => 08 [Passed]: return =>  8 [Passed]: return => 67 [Passed]: return => 13 [Passed]: return => 13 [Passed]: return => 01 [Passed]: return =>  1 [Passed]: return => PM [Passed]: return => pm [Passed]: return => 23 [Passed]: return => 46 [Passed]: return => 300 [Passed]: return => -0900 [Passed]: return => Saturday [Passed]: return => Sat [Passed]: return => 7 [Passed]: return => 6 [Passed]: return => 1394252626300 [Passed]: return => 20140308 [Passed]: return => 2014-03-08 [Passed]: return => 2014-03 [Passed]: return => 2014 [Passed]: return => 201467 [Passed]: return => 2014-67 [Passed]: return => 132346 [Passed]: return => 13:23:46 [Passed]: return => 1323 [Passed]: return => 13:23 [Passed]: return => 13 [Passed]: return => 132346,300 [Passed]: return => 13:23:46,300 [Passed]: return => 132346.300 [Passed]: return => 13:23:46.300 [Passed]: return => 132346-0900 [Passed]: return => 20140308T132346-0900 [Passed]: return => 201467T132346-0900 [Passed]: return => 20140308T1323 [Passed]: return => 2014-03-08T13:23 [Passed]: return => 201467T1323Z [Passed]: return => 2014-67T13:23Z */
import { all } from 'redux-saga/effects'; import WatchUsers from 'sagas/users'; export default function *WatchSagas() { yield all([ WatchUsers() ]); }
//initialize Settings. zsi.init({ baseURL : base_url ,errorUpdateURL : base_url + "common/errors_update" ,sqlConsoleName : "runsql" ,excludeAjaxWatch : ["checkDataExist","employe_search_json"] }); //check cookie and load user menus. var userInfo = readCookie("userinfo"); if(userInfo){ if(isLocalStorageSupport()) { userInfo = JSON.parse(localStorage.getItem("userinfo")); var menuInfo = localStorage.getItem("menuInfo"); if(menuInfo){ displayMenu( JSON.parse(menuInfo)); } }else{ loadMenu(); loadUserInfo(); } }else{ loadMenu(); loadUserInfo(); } function isLocalStorageSupport(){ if(typeof(Storage) !== "undefined") return true; else return false; } function loadMenu(){ $.getJSON(base_url + "menu_types/getdata_json",function(data){ if(isLocalStorageSupport()) { localStorage.setItem("menuInfo", JSON.stringify(data)); } displayMenu(data); }); } function loadUserInfo(){ $.getJSON(base_url + "users/getuserinfo",function(data){ createCookie("userinfo", "*",1); localStorage.setItem("userinfo", JSON.stringify(data)); userInfo = data; }); } function displayMenu(data){ var nav = $("#navbar-main"); var m = '<ul class="nav navbar-nav">'; $.each(data,function(){ var mlength= this.subMenus.length; m += '<li class="dropdown">'; m += '<a data-toggle="dropdown" class="dropdown-toggle" href="#">' + this.name + ( mlength >0 ? '<span class="caret"></span>':'') + '</a>'; if(mlength>0){ m +='<ul class="dropdown-menu">'; $.each(this.subMenus,function(){ m +='<li><a href="' + base_url + this.url + '">' + this.name + '</a></li>'; }); m +='</ul>'; } m += '</>'; }); m +='<url>'; nav.append(m); }
var recLength = 0, recBuffers = [], sampleRate; this.onmessage = function(e){ switch(e.data.command){ case 'init': init(e.data.config); break; case 'record': record(e.data.buffer); break; case 'exportWAV': exportWAV(e.data.type); break; case 'getBuffer': getBuffer(); break; case 'clear': clear(); break; } }; function init(config){ sampleRate = config.sampleRate; } function record(inputBuffer){ var bufferL = inputBuffer[0]; var bufferR = inputBuffer[1]; var interleaved = interleave(bufferL, bufferR); recBuffers.push(interleaved); recLength += interleaved.length; } function exportWAV(type){ var buffer = mergeBuffers(recBuffers, recLength); var dataview = encodeWAV(buffer); var audioBlob = new Blob([dataview], { type: type }); this.postMessage(audioBlob); } function getBuffer() { var buffer = mergeBuffers(recBuffers, recLength) this.postMessage(buffer); } function clear(){ recLength = 0; recBuffers = []; } function mergeBuffers(recBuffers, recLength){ var result = new Float32Array(recLength); var offset = 0; for (var i = 0; i < recBuffers.length; i++){ result.set(recBuffers[i], offset); offset += recBuffers[i].length; } return result; } function interleave(inputL, inputR){ var length = inputL.length + inputR.length; var result = new Float32Array(length); var index = 0, inputIndex = 0; while (index < length){ result[index++] = inputL[inputIndex]; result[index++] = inputR[inputIndex]; inputIndex++; } return result; } function floatTo16BitPCM(output, offset, input){ for (var i = 0; i < input.length; i++, offset+=2){ var s = Math.max(-1, Math.min(1, input[i])); output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true); } } function writeString(view, offset, string){ for (var i = 0; i < string.length; i++){ view.setUint8(offset + i, string.charCodeAt(i)); } } function encodeWAV(samples){ var buffer = new ArrayBuffer(44 + samples.length * 2); var view = new DataView(buffer); /* RIFF identifier */ writeString(view, 0, 'RIFF'); /* file length */ view.setUint32(4, 32 + samples.length * 2, true); /* RIFF type */ writeString(view, 8, 'WAVE'); /* format chunk identifier */ writeString(view, 12, 'fmt '); /* format chunk length */ view.setUint32(16, 16, true); /* sample format (raw) */ view.setUint16(20, 1, true); /* channel count */ view.setUint16(22, 2, true); /* sample rate */ view.setUint32(24, sampleRate, true); /* byte rate (sample rate * block align) */ view.setUint32(28, sampleRate * 4, true); /* block align (channel count * bytes per sample) */ view.setUint16(32, 4, true); /* bits per sample */ view.setUint16(34, 16, true); /* data chunk identifier */ writeString(view, 36, 'data'); /* data chunk length */ view.setUint32(40, samples.length * 2, true); floatTo16BitPCM(view, 44, samples); return view; }
import React, {Component, PropTypes} from 'react'; import {View, ListView, Image, CameraRoll, TouchableHighlight, StyleSheet} from 'react-native'; import MessageDao from '../../dao/MessageDao'; import LoadingSpinner from '../common/LoadingSpinner'; import Icon from 'react-native-vector-icons/MaterialIcons'; import MediaRenderer from './MediaRenderer'; import {InteractionManager} from 'react-native'; import { Dimensions } from 'react-native'; class MediaGallery extends Component { constructor(props, context) { super(props, context); this.state = {mediasForThread: [], isLoading: true}; } componentDidMount(){ let threadId = this.props.threadId; InteractionManager.runAfterInteractions(() => { requestAnimationFrame(() => { this.openGalleryForThread(threadId); }); }); } reloadMedia(){ let threadId = this.props.threadId; this.openGalleryForThread(threadId); } openGalleryForThread(threadId){ let mediaResult = MessageDao.getMediasForThread(threadId); this.setState({ mediasForThread: mediaResult.mediasForThread, isLoading: false }); } render() { const {router} = this.props; let imagesDS = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2}); //let lotOfImages = []; //const images = this.state.mediasForThread; //lotOfImages = lotOfImages.concat(images, images, images); //imagesDS = imagesDS.cloneWithRows(lotOfImages); imagesDS = imagesDS.cloneWithRows(this.state.mediasForThread); if(this.state.isLoading){ return( <View style={[styles.loadingContainer]}> <LoadingSpinner size="large"/> </View> ); } else{ return ( <View style={[styles.container]}> <ListView contentContainerStyle={styles.imageGrid} enableEmptySections={true} dataSource={imagesDS} renderRow={(media) => this.renderMedia(media)} initialListSize={15} scrollRenderAheadDistance={500} pagingEnabled={true} pageSize={1} removeClippedSubviews={true} /> </View> ); } } renderMedia(media){ return( <TouchableHighlight onPress={() => this.openMediaViewer(media)}> <View> <MediaRenderer media={media} router={this.props.router} threadId={this.props.threadId} mediaViewerEnabled={true} mediaStyle={styles.image}/> </View> </TouchableHighlight> ); } openMediaViewer(media){ this.props.router.toMediaViewer({selectedMedia: media, threadId: this.props.threadId}); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'black', borderRadius: 4, borderWidth: 0.5, borderColor: '#d6d7da', paddingBottom: 10 }, loadingContainer:{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'black', height: Dimensions.get('window').height, width: Dimensions.get('window').width, }, image: { width: 100, height: 100, margin: 2, justifyContent: 'center', }, imageGrid: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-around', marginBottom: 50 }, }); MediaRenderer.propTypes = { router: PropTypes.object.isRequired, threadId: PropTypes.number.isRequired, }; export default MediaGallery;
+(function (factory) { if (typeof exports === 'undefined') { factory(webduino || {}); } else { module.exports = factory; } }(function (scope) { 'use strict'; // source: // https://raw.githubusercontent.com/twistdigital/es6-promisify/release/2.0.0/lib/promisify.js // Promise Context object constructor. function Context(resolve, reject, custom) { this.resolve = resolve; this.reject = reject; this.custom = custom; } // Default callback function - rejects on truthy error, otherwise resolves function callback(ctx, err, result) { if (typeof ctx.custom === 'function') { var cust = function () { // Bind the callback to itself, so the resolve and reject // properties that we bound are available to the callback. // Then we push it onto the end of the arguments array. return ctx.custom.apply(cust, arguments); }; cust.resolve = ctx.resolve; cust.reject = ctx.reject; cust.call(null, err, result); } else { if (err) { return ctx.reject(err); } ctx.resolve(result); } } function promisify(original, custom) { return function () { // Store original context var that = this, args = Array.prototype.slice.call(arguments); // Return the promisified function return new Promise(function (resolve, reject) { // Create a Context object var ctx = new Context(resolve, reject, custom); // Append the callback bound to the context args.push(callback.bind(null, ctx)); // Call the function original.apply(that, args); }); }; } scope.util.promisify = promisify; }));
import ContactList from './ContactList' export default ContactList
/*global module:false*/ module.exports = function(grunt) { // Load all tasks require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), meta: { banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= pkg.homepage ? "* " + pkg.homepage : "" %>' + '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + ' Licensed <%= pkg.licenses.map(function(license) { return license.type; }).join(", ") %> */' }, concat: { dist: { src: ['src/<%= pkg.name %>.js'], dest: 'dist/<%= pkg.name %>.js' } }, qunit: { files: ['test/**/*.html'] }, watch: { files: '<%= jshint.all %>', tasks: [ 'jshint', 'qunit', 'concat', 'uglify' ] }, jshint: { options: { jshintrc: '.jshintrc' }, all: ['src/**/*.js', 'test/**/*.js'] }, uglify: { options: { banner: '<%= meta.banner %>' }, dist: { src: ['<%= concat.dist.dest %>'], dest: 'dist/<%= pkg.name %>.min.js' } } }); // Register tasks grunt.registerTask('default', [ 'build' ]); grunt.registerTask('dev', [ 'build', 'watch' ]); grunt.registerTask('build', [ 'jshint', 'qunit', 'concat', 'uglify' ]); grunt.registerTask('test', [ 'jshint', 'qunit' ]); };
import { applyMiddleware, compose } from 'redux'; import history from './history'; import { routerMiddleware } from 'react-router-redux'; import thunk from 'redux-thunk'; export default compose( applyMiddleware(thunk, routerMiddleware(history)) );
import DateTimeCore from './DateTimeCore'; let DateTime = { mixins : [DateTimeCore], data : function () { return {}; }, methods : { _dtParseRelativeDatetimeToObj : function (val) { return this._dtcoreParseRelativeToObj('datetime', val); }, _dtIsRelativeDatetime : function (val) { return this._dtcoreIsRelative('datetime', val); }, _dtGetRelativeDatetime : function (relativeDate) { return this._dtcoreGetRelativeObj('datetime', relativeDate); } } }; export default DateTime;
if (!com) var com = {} if (!com.corejsf) { com.corejsf = { showProgress: function(data) { var inputId = data.source.id var progressbarId = inputId.substring(0, inputId.length - "name".length) + "pole"; if (data.status == "begin") Element.show(progressbarId); else if (data.status == "success") Element.hide(progressbarId); } } }
(function () { 'use strict'; angular.module('UserSearch') .controller('UserSearchController', ['searchService', UserSearchController]); function UserSearchController(searchService) { var self = this; self.user = {}; self.searchFilter = ''; self.showSpinner = true; init(); function init() { return searchService.getAllUserData().then(function (response) { if (response.data !== null) { self.userData = response; self.getUserDetails(0); self.showSpinner = false; } else { self.error = "Oops. Looks like we hit a snag, try reloading."; self.showSpinner = false; } }); } self.getUserDetails = function (index) { if (self.userData[index]) { self.user = self.userData[index]; } }; } })();
/** * Compiler configuration for outputting the comonent. */ /* eslint-disable */ var path = require('path') var webpack = require('webpack') module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', path.join(__dirname, '../src/index.jsx'), ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/' }, module: { loaders: [ { test: /\.jsx?$/, loaders: ['babel-loader'], include: path.join(__dirname, '../src') }, { test: /\.scss$/, loaders: ['style-loader', 'css-loader', 'sass-loader'] } ] } }
var mongoose = require('mongoose') , Schema = mongoose.Schema , ObjectId = Schema.ObjectId , relationships = require('../../index'); // require('mongoose-relationships'); /** * Blog Post Schema * "belongs to one author" */ var PostSchema = new Schema({ title : String , body : String , author : {type: ObjectId, ref: 'User'} }); /** * User Schema * "has many posts" */ var UserSchema = new Schema({ name : String , posts : [{type: ObjectId, ref: 'Post'}] }); /** * Attach the plugin to the schemas */ PostSchema.plugin(relationships, { belongsTo : "User" , through : "author" }); UserSchema.plugin(relationships, { hasMany : "Post" , through : "posts" }); /** * Register the models with Mongoose */ var Post = mongoose.model('Post', PostSchema) , User = mongoose.model('User', UserSchema); // Have fun here: var user = new User(); user.posts.create({ title: "Mongoose, now with added love through relationships!" }, function(err, user, post){ // user.posts.length === 1 // post.title === "Mongoose, now with added love through relationships!" }); // Using an `Array` user.posts.create([ { title: "Not too imaginative post title" } , { title: "... a tad more imaginative post title" } ], function(err, user, posts){ // user.posts.length === 3 // posts.length == 2 // posts[0] instanceof Post });
import {createSelector} from 'reselect' import usersSelector from 'usersSelector' const selectedUserIdSelector = (state) => state.selectedUserId export default createSelector( [usersSelector, selectedUserIdSelector], (users, selectedUserId) => users.get(selectedUserId) )
// (c) ammap.com | SVG (in JSON format) map of Libya - Low // areas: {id:"LY-WD"},{id:"LY-BU"},{id:"LY-DR"},{id:"LY-SR"},{id:"LY-BA"},{id:"LY-WA"},{id:"LY-JA"},{id:"LY-HZ"},{id:"LY-TB"},{id:"LY-MZ"},{id:"LY-ZA"},{id:"LY-NQ"},{id:"LY-JI"},{id:"LY-SB"},{id:"LY-MI"},{id:"LY-MQ"},{id:"LY-GT"},{id:"LY-WS"},{id:"LY-MB"},{id:"LY-KF"},{id:"LY-JU"},{id:"LY-NL"} AmCharts.maps.libyaLow={ "svg": { "defs": { "amcharts:ammap": { "projection":"mercator", "leftLongitude":"9.391466", "topLatitude":"33.1679793", "rightLongitude":"25.146954", "bottomLatitude":"19.5008125" } }, "g":{ "path":[ { "id":"LY-WD", "title":"Wadi al Hayaa", "d":"M236.97,352.67L188.1,345.8L105.65,404.02L106.9,441.29L145.18,439.93L234.51,402.37L245.18,378.51L236.97,352.67z" }, { "id":"LY-BU", "title":"Al Butnan", "d":"M790.67,297.68L790.32,232.14L775.94,177.43L791.36,142.24L784.01,109.12L799.48,90.55L790.69,72.49L703.58,57.71L689.36,141.4L694.05,295.25L790.67,297.68z" }, { "id":"LY-DR", "title":"Darnah", "d":"M703.58,57.71L696.27,32.47L639.88,16.11L636.44,113.04L646.24,122.59L689.36,141.4L703.58,57.71z" }, { "id":"LY-SR", "title":"Surt", "d":"M478.97,166.48L407.27,124.54L345.42,114.27L365.25,209.36L359.58,222.33L405.66,229.62L418.06,223.15L438.3,261.26L464.33,274.5L478.97,166.48z" }, { "id":"LY-BA", "title":"Benghazi", "d":"M606.3,127.57L601.08,97.76L567.51,95.48L557.53,74.82L568.89,37.08L536.87,73.09L547.02,116.47L569.78,129.22L606.3,127.57z" }, { "id":"LY-WA", "title":"Al Wahat", "d":"M606.3,127.57L569.78,129.22L547.02,116.47L541.73,140.25L520.58,163.52L496.89,172.65L478.97,166.48L464.33,274.5L498.21,283.36L498.09,359.23L790.67,357.18L790.67,297.68L694.05,295.25L689.36,141.4L646.24,122.59L626.34,125.78L606.3,127.57z" }, { "id":"LY-JA", "title":"Al Jabal al Akhdar", "d":"M639.88,16.11L608.21,24.06L626.34,125.78L646.24,122.59L636.44,113.04L639.88,16.11z" }, { "id":"LY-MJ", "title":"Al Marj", "d":"M608.21,24.06L568.89,37.08L557.53,74.82L567.51,95.48L601.08,97.76L606.3,127.57L626.34,125.78L608.21,24.06z" }, { "id":"LY-TB", "title":"Tripoli", "d":"M235.52,25.39L192.67,18.24L191.32,27.6L199.38,50.74L235.52,25.39z" }, { "id":"LY-JG", "title":"Al Jabal al Gharbi", "d":"M207.49,67.57L200.1,51.71L178.39,55.12L130.21,52.3L135.27,124.88L116.48,156.44L123.5,240.9L134.7,269.17L171.79,278.61L233.31,213.15L258.95,233.86L275.7,222.53L280.82,196.08L285.65,164.23L248.47,145.99L207.49,67.57z" }, { "id":"LY-ZA", "title":"Az Zawiyah", "d":"M191.32,27.6L192.67,18.24L165.98,22.13L130.21,52.3L178.39,55.12L191.32,27.6z" }, { "id":"LY-NQ", "title":"An Nuqat al Khams", "d":"M112.21,0L113.27,45.72L130.21,52.3L165.98,22.13L112.21,0z" }, { "id":"LY-JI", "title":"Al Jifarah", "d":"M199.38,50.74L191.32,27.6L178.39,55.12L200.1,51.71L199.38,50.74z" }, { "id":"LY-SB", "title":"Sabha", "d":"M328.23,319.08L291.61,324.15L259.02,350.19L236.97,352.67L245.18,378.51L234.51,402.37L259.18,395.1L279.48,373.62L352.59,355.71L328.23,319.08z" }, { "id":"LY-MI", "title":"Misratah", "d":"M345.42,114.27L314.06,92.6L301.74,51.03L275.87,43.83L271.38,72.5L243.96,62.12L207.49,67.57L248.47,145.99L285.65,164.23L280.82,196.08L325.45,223.19L359.58,222.33L365.25,209.36L345.42,114.27z" }, { "id":"LY-MQ", "title":"Murzuq", "d":"M498,416L449.47,395.09L409.49,413.29L385.86,407.05L352.53,368.64L352.59,355.71L279.48,373.62L259.18,395.1L234.51,402.37L145.18,439.93L106.9,441.29L110.31,509.32L135.56,553.87L211.75,572.39L248.7,603.18L337.76,557.86L498.9,644.09L498,416z" }, { "id":"LY-GT", "title":"Ghat", "d":"M105.65,404.02L92.16,335.26L32.98,313.53L22.41,343.44L31.22,379.55L6.29,409.86L36.84,453.56L38.05,479.97L49.54,495.47L110.31,509.32L106.9,441.29L105.65,404.02z" }, { "id":"LY-WS", "title":"Wadi ash Shati'", "d":"M258.95,233.86L233.31,213.15L171.79,278.61L134.7,269.17L103.09,272.05L82.24,254.85L58.63,267.48L27.74,267.82L32.98,313.53L92.16,335.26L105.65,404.02L188.1,345.8L236.97,352.67L259.02,350.19L291.61,324.15L328.23,319.08L332.41,298.68L317.85,290.94L289.05,294.93L286.08,279.91L259.09,252.9L258.95,233.86z" }, { "id":"LY-MB", "title":"Al Marqab", "d":"M275.87,43.83L235.52,25.39L199.38,50.74L200.1,51.71L207.49,67.57L243.96,62.12L271.38,72.5L275.87,43.83z" }, { "id":"LY-KF", "title":"Al Kufrah", "d":"M740.33,771.53L740.33,744.82L790.45,744.79L790.67,357.18L498.09,359.23L498,416L498.9,644.09L740.33,771.53z" }, { "id":"LY-JU", "title":"Al Jufrah", "d":"M359.58,222.33L325.45,223.19L280.82,196.08L275.7,222.53L258.95,233.86L259.09,252.9L286.08,279.91L289.05,294.93L317.85,290.94L332.41,298.68L328.23,319.08L352.59,355.71L352.53,368.64L385.86,407.05L409.49,413.29L449.47,395.09L498,416L498.09,359.23L498.21,283.36L464.33,274.5L438.3,261.26L418.06,223.15L405.66,229.62L359.58,222.33z" }, { "id":"LY-NL", "title":"Nalut", "d":"M130.21,52.3L113.27,45.72L49.73,89.52L41.79,104.37L46.11,145.4L29.96,167.38L0.52,181.25L19.71,210.79L27.74,267.82L58.63,267.48L82.24,254.85L103.09,272.05L134.7,269.17L123.5,240.9L116.48,156.44L135.27,124.88L130.21,52.3z" } ] } } };
/** * @license Highcharts JS v9.1.0 (2021-05-04) * @module highcharts/themes/high-contrast-light * @requires highcharts * * (c) 2009-2021 Highsoft AS * * License: www.highcharts.com/license */ 'use strict'; import '../../Extensions/Themes/HighContrastLight.js';
'use strict'; var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var yosay = require('yosay'); module.exports = yeoman.Base.extend({ prompting: function () { // Have Yeoman greet the user. this.log(yosay( 'Welcome to the stylish ' + chalk.red('generator-dev-cli') + ' generator!' )); var prompts = [{ type: 'list', name: 'environment', message: 'Please choose dev environment(jsPlugin):', choices: ['jsPlugin', 'react'], default: 'jsPlugin' }, { type: 'input', name: 'name', message: 'Your project name', default: this.appname // Default to current folder name }, { type: 'confirm', name: 'besure', message: 'Would you like to enable this option?', default: true }]; return this.prompt(prompts).then(function (props) { // To access props later use this.props.someAnswer; this.props = props; }.bind(this)); }, writing: function () { this.fs.copy( this.templatePath(this.props.environment), this.destinationPath(this.props.name), true ); this.fs.copy( this.templatePath(this.props.environment + '/.*'), this.destinationPath(this.props.name + '/'), true ); }, install: function () { } });
const { stripIndent } = require('common-tags') module.exports = function (widgetName) { return stripIndent` import { ${widgetName} } from 'react-widgets'; let people = listOfPeople(); <> <${widgetName} data={people} textField='fullName' groupBy='lastName' /> <${widgetName} data={people} textField='fullName' groupBy={person => person.fullName.length} /> </> ` }
module.exports = function(grunt) { grunt.initConfig({ sass: { // Task dist: { // Target files: { // Dictionary of files 'assets/stylesheets/styles.css': 'assets/stylesheets/src/styles.scss' , 'assets/stylesheets/smartphone.css': 'assets/stylesheets/src/smartphone.scss' } } }, watch: { css: { files: ['assets/stylesheets/src/*.scss'], tasks: ['sass', 'cssmin'] } }, cssmin: { target: { files: { 'assets/stylesheets/app.min.css': ['assets/stylesheets/styles.css', 'assets/stylesheets/smartphone.css'] } } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.registerTask('default', ['sass', 'cssmin', 'watch']); };
const test = require('tape'); const Mark = require('./../mark.js'); function stringArrayBuffer(str) { var buffer = new ArrayBuffer(str.length); var bytes = new Uint8Array(buffer); str.split('').forEach(function(str, i) { bytes[i] = str.charCodeAt(0); }); return buffer; } test('Stringify JSON object', function(assert) { assert.equal(Mark.stringify(Mark.parse(`{a:12.4, b:true, c:false, d:'str', e:null, g:1, h:[1,2,3], i:-12, j:[], k:{}, l:'', m:"", n:0, p:1e-2}`)), `{a:12.4 b:true c:false d:"str" e:null g:1 h:[1 2 3] i:-12 j:[] k:{} l:"" m:"" n:0 p:0.01}`, "Stringify JSON object"); assert.end() ; }); test('Stringify Mark object', function(assert) { assert.equal(Mark.stringify(Mark.parse('{obj}')), '{obj}', "Stringify {obj}"); assert.equal(Mark.stringify(Mark.parse('{div width:10}')), '{div width:10}', "Stringify {div width:10}"); assert.equal(Mark.stringify(Mark.parse('{div "text"}')), '{div "text"}', 'Stringify {div "text"}'); assert.equal(Mark.stringify(Mark.parse("{div 'text'}")), '{div "text"}', "Stringify {div 'text'}"); assert.equal(Mark.stringify(Mark.parse('{div {br}}')), '{div {br}}', "Stringify {div {br}}"); assert.equal(Mark.stringify(Mark.parse('{div width:null}')), '{div width:null}', "Stringify property with null value}"); // undefined value handling var t = {obj:undefined}; assert.equal(Mark.stringify(t), '{}', "Stringify undefined property"); assert.equal(Mark.stringify([1, null, undefined]), '[1 null null]', "Stringify undefined value in array"); // JSON inside Mark assert.equal(Mark.stringify(Mark.parse('{div {width:10}}')), '{div {width:10}}', "Stringify {div {width:10}}"); // stringify with identation assert.equal(Mark.stringify(Mark.parse('{div width:10 (!--comment--) "test" {br}}'), {space:' '}), '{div width:10 \n (!--comment--) \n "test" \n {br}\n}', "Stringify with identation"); // stringify omitting comma assert.equal(Mark.stringify(Mark.parse('{div width:10, height:"15px", margin:[5 10 10 5]}')), '{div width:10 height:"15px" margin:[5 10 10 5]}', "Stringify without comma"); // stringify base64 data assert.equal(Mark.stringify(stringArrayBuffer('Hello')), '[#SGVsbG8=]', "Stringify binary data 'hello'"); assert.equal(Mark.stringify(stringArrayBuffer('Hello worlds!')), '[#SGVsbG8gd29ybGRzIQ==]', "Stringify binary data 'Hello worlds!'"); var doc = Mark('doc', {mime:'text/html', data:stringArrayBuffer("<h1>Mark binary!</h1>")}); assert.equal(Mark.stringify(doc), '{doc mime:"text/html" data:[#PGgxPk1hcmsgYmluYXJ5ITwvaDE+]}', "Stringify nested binary data"); // stringify base85 data var bin = stringArrayBuffer('hello'); bin.encoding = 'a85'; assert.equal(Mark.stringify(bin), "[#~BOu!rDZ~]", "Stringify base85"); assert.equal(Mark.stringify(Mark("[#~\n@p\ns7\ntD.3~]")), "[#~@ps7tD.3~]", "Stringify base85"); assert.equal(Mark.stringify(Mark("[#~ @<5pm \rBfIs ~]")), "[#~@<5pmBfIs~]", "Parse base85 of 'ascii85'"); assert.end(); });
const path = require(`path`) const chunk = require(`lodash/chunk`) // This is a simple debugging tool // dd() will prettily dump to the terminal and kill the process // const { dd } = require(`dumper.js`) /** * exports.createPages is a built-in Gatsby Node API. * It's purpose is to allow you to create pages for your site! 💡 * * See https://www.gatsbyjs.com/docs/node-apis/#createPages for more info. */ exports.createPages = async gatsbyUtilities => { // Query our posts from the GraphQL server const posts = await getNodes(gatsbyUtilities) // If there are no posts in WordPress, don't do anything if (!posts.length) { return } // If there are posts and pages, create Gatsby pages for them await createSinglePages({ posts, gatsbyUtilities }) // And a paginated archive await createBlogPostArchive({ posts, gatsbyUtilities }) } /** * This function creates all the individual blog pages in this site */ const createSinglePages = async ({ posts, gatsbyUtilities }) => Promise.all( posts.map(({ previous, post, next }) => // createPage is an action passed to createPages // See https://www.gatsbyjs.com/docs/actions#createPage for more info gatsbyUtilities.actions.createPage({ // Use the WordPress uri as the Gatsby page path // This is a good idea so that internal links and menus work 👍 path: post.uri, // use the blog post template as the page component component: path.resolve( `./src/templates/${post.__typename.replace(`Wp`, ``)}.js` ), // `context` is available in the template as a prop and // as a variable in GraphQL. context: { // we need to add the post id here // so our blog post template knows which blog post // the current page is (when you open it in a browser) id: post.id, // We also use the next and previous id's to query them and add links! previousPostId: previous ? previous.id : null, nextPostId: next ? next.id : null, }, }) ) ) /** * This function creates all the individual blog pages in this site */ async function createBlogPostArchive({ posts, gatsbyUtilities }) { const graphqlResult = await gatsbyUtilities.graphql(/* GraphQL */ ` { wp { readingSettings { postsPerPage } } } `) const { postsPerPage } = graphqlResult.data.wp.readingSettings const postsChunkedIntoArchivePages = chunk(posts, postsPerPage) const totalPages = postsChunkedIntoArchivePages.length return Promise.all( postsChunkedIntoArchivePages.map(async (_posts, index) => { const pageNumber = index + 1 const getPagePath = page => { if (page > 0 && page <= totalPages) { // Since our homepage is our blog page // we want the first page to be "/" and any additional pages // to be numbered. // "/blog/2" for example return page === 1 ? `/` : `/blog/${page}` } return null } // createPage is an action passed to createPages // See https://www.gatsbyjs.com/docs/actions#createPage for more info await gatsbyUtilities.actions.createPage({ path: getPagePath(pageNumber), // use the blog post archive template as the page component component: path.resolve(`./src/templates/blog-post-archive.js`), // `context` is available in the template as a prop and // as a variable in GraphQL. context: { // the index of our loop is the offset of which posts we want to display // so for page 1, 0 * 10 = 0 offset, for page 2, 1 * 10 = 10 posts offset, // etc offset: index * postsPerPage, // We need to tell the template how many posts to display too postsPerPage, nextPagePath: getPagePath(pageNumber + 1), previousPagePath: getPagePath(pageNumber - 1), }, }) }) ) } /** * This function queries Gatsby's GraphQL server and asks for * All WordPress blog posts. If there are any GraphQL error it throws an error * Otherwise it will return the posts 🙌 * * We're passing in the utilities we got from createPages. * So see https://www.gatsbyjs.com/docs/node-apis/#createPages for more info! */ async function getNodes({ graphql, reporter }) { const graphqlResult = await graphql(/* GraphQL */ ` query WpPosts { # Query all WordPress blog posts sorted by date allWpPost(sort: { fields: [date], order: DESC }) { edges { previous { id } # note: this is a GraphQL alias. It renames "node" to "post" for this query # We're doing this because this "node" is a post! It makes our code more readable further down the line. post: node { __typename id uri } next { id } } } allWpPage(sort: { fields: [date], order: DESC }) { edges { previous { id } # note: this is a GraphQL alias. It renames "node" to "post" for this query # We're doing this because this "node" is a post! It makes our code more readable further down the line. post: node { __typename id uri } next { id } } } } `) if (graphqlResult.errors) { reporter.panicOnBuild( `There was an error loading your blog posts`, graphqlResult.errors ) return } return [ ...graphqlResult.data.allWpPost.edges, ...graphqlResult.data.allWpPage.edges, ] }
'use strict'; // Call this function when the page loads (the "ready" event) $(document).ready(function() { initializePage(); }) /* * Function that is called when the document is ready. */ function initializePage() { $('.project a').click(addProjectDetails); $('#colorBtn').click(randomizeColors); $('#apibutton').click(getExternalApi); } /* * Make an AJAX call to retrieve project details and add it in */ function addProjectDetails(e) { // Prevent following the link e.preventDefault(); // Get the div ID, e.g., "project3" var projectID = $(this).closest('.project').attr('id'); // get rid of 'project' from the front of the id 'project3' var idNumber = projectID.substr('project'.length); console.log("User clicked on project " + idNumber); $.get('/project/' + idNumber, addProject); console.log('/project/' + idNumber); } function addProject(result) { console.log(result); var projectHTML = '<a href="#" class="thumbnail">' + '<img src="' + result['image'] + '" class="detalsImage">' + '<p>' + result['title'] + '</p>' + '<p> <small>' + result['date'] + '</small></p>' + '<p>' + result['summary'] + '</p> </a>'; $("#project" + result['id'] + " .details").html(projectHTML);
 } /* * Make an AJAX call to retrieve a color palette for the site * and apply it */ function randomizeColors(e) { e.preventDefault(); $.get('/palette', addColor); } function addColor(result) { console.log(result); var colors = result['colors']['hex']; $('body').css('background-color', colors[0]); $('.thumbnail').css('background-color', colors[1]); $('h1, h2, h3, h4, h5, h5').css('color', colors[2]); $('p').css('color', colors[3]); $('.project img').css('opacity', .75); } function getExternalApi(e) { e.preventDefault(); $.get('https://api.spotify.com/v1/artists/4dpARuHxo51G3z768sgnrY', getAPI); } function getAPI(result) { console.log(result); var images = result['images']; console.log(images); var adeleHTML = '<h1>' + result['name'] + '</h1>' + '<p> popularity: ' + result['popularity'] + '</p>' + '<p> genre: ' + result['genres'][0] + '</p>' + '<img src="' + images[2]['url'] + '"> <br />' ; $("#output").html(adeleHTML);
 }
'use strict'; const path = require('path'); const srcDir = path.join(__dirname, 'src/front'), distDir = path.join(__dirname, 'front/dist'); module.exports = { envFilePath: path.join(__dirname, '.env'), src: { front: { jsEntry: path.join(srcDir, 'js/index.js'), htmlEntry: path.join(srcDir, 'index.html'), stylesEntry: path.join(srcDir, 'scss/style.scss') } }, dist: { buildDir: path.join(distDir, 'build'), releaseDir: path.join(distDir, 'release') } };
import test from 'ava'; import React from 'react'; import { shallow } from 'enzyme'; import Text from '../../../src/components/form-inputs/text'; test('Text | default props', (t) => { const textWrapper = shallow(<Text />); t.deepEqual(textWrapper.props(), { type: 'text', 'data-form-id': '', className: '', id: '', placeholder: '', required: false, value: '', min: -1, max: -1, }); }); test('Text | all props filled', (t) => { const textWrapper = shallow( <Text className="test-class" data-form-id="test-form-id" id="test-id" placeholder="test-placeholder" required value="test-value" min={8} max={30} />, ); t.deepEqual(textWrapper.props(), { type: 'text', 'data-form-id': 'test-form-id', className: 'test-class', id: 'test-id', placeholder: 'test-placeholder', required: true, value: 'test-value', min: 8, max: 30, }); });
var detailSelector = function() { return { restrict: 'E', scope : { items: '=', selectedItem: '=' }, replace: true, templateUrl: 'js/directives/detailSelector.html', link: function (scope, element, attrs) { scope.updateCurrentItem = function(value) { scope.selectedItem = value; }; } }; } module.exports = detailSelector;
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var __chunk_1 = require('./chunk-14c82365.js'); require('./helpers.js'); var __chunk_2 = require('./chunk-185921d7.js'); var __chunk_4 = require('./chunk-925c5339.js'); var __chunk_5 = require('./chunk-13e039f5.js'); var script = { name: 'BRate', components: __chunk_1._defineProperty({}, __chunk_4.Icon.name, __chunk_4.Icon), props: { value: { type: Number, default: 0 }, max: { type: Number, default: 5 }, icon: { type: String, default: 'star' }, iconPack: String, size: String, spaced: Boolean, rtl: Boolean, disabled: Boolean, showScore: Boolean, showText: Boolean, customText: String, texts: Array, locale: { type: [String, Array], default: function _default() { return __chunk_2.config.defaultLocale; } } }, data: function data() { return { newValue: this.value, hoverValue: 0 }; }, computed: { halfStyle: function halfStyle() { return "width:".concat(this.valueDecimal, "%"); }, showMe: function showMe() { var result = ''; if (this.showScore) { result = this.disabled ? this.value : this.newValue; if (result === 0) { result = ''; } else { result = new Intl.NumberFormat(this.locale).format(this.value); } } else if (this.showText) { result = this.texts[Math.ceil(this.newValue) - 1]; } return result; }, valueDecimal: function valueDecimal() { return this.value * 100 - Math.floor(this.value) * 100; } }, watch: { // When v-model is changed set the new value. value: function value(_value) { this.newValue = _value; } }, methods: { resetNewValue: function resetNewValue() { if (this.disabled) return; this.hoverValue = 0; }, previewRate: function previewRate(index, event) { if (this.disabled) return; this.hoverValue = index; event.stopPropagation(); }, confirmValue: function confirmValue(index) { if (this.disabled) return; this.newValue = index; this.$emit('change', this.newValue); this.$emit('input', this.newValue); }, checkHalf: function checkHalf(index) { var showWhenDisabled = this.disabled && this.valueDecimal > 0 && index - 1 < this.value && index > this.value; return showWhenDisabled; }, rateClass: function rateClass(index) { var output = ''; var currentValue = this.hoverValue !== 0 ? this.hoverValue : this.newValue; if (index <= currentValue) { output = 'set-on'; } else if (this.disabled && Math.ceil(this.value) === index) { output = 'set-half'; } return output; } } }; /* script */ const __vue_script__ = script; /* template */ var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"rate",class:{ 'is-disabled': _vm.disabled, 'is-spaced': _vm.spaced, 'is-rtl': _vm.rtl }},[_vm._l((_vm.max),function(item,index){return _c('div',{key:index,staticClass:"rate-item",class:_vm.rateClass(item),on:{"mousemove":function($event){return _vm.previewRate(item, $event)},"mouseleave":_vm.resetNewValue,"click":function($event){$event.preventDefault();return _vm.confirmValue(item)}}},[_c('b-icon',{attrs:{"pack":_vm.iconPack,"icon":_vm.icon,"size":_vm.size}}),(_vm.checkHalf(item))?_c('b-icon',{staticClass:"is-half",style:(_vm.halfStyle),attrs:{"pack":_vm.iconPack,"icon":_vm.icon,"size":_vm.size}}):_vm._e()],1)}),(_vm.showText || _vm.showScore || _vm.customText)?_c('div',{staticClass:"rate-text",class:_vm.size},[_c('span',[_vm._v(_vm._s(_vm.showMe))]),(_vm.customText && !_vm.showText)?_c('span',[_vm._v(_vm._s(_vm.customText))]):_vm._e()]):_vm._e()],2)}; var __vue_staticRenderFns__ = []; /* style */ const __vue_inject_styles__ = undefined; /* scoped */ const __vue_scope_id__ = undefined; /* module identifier */ const __vue_module_identifier__ = undefined; /* functional template */ const __vue_is_functional_template__ = false; /* style inject */ /* style inject SSR */ var Rate = __chunk_5.__vue_normalize__( { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ }, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, undefined, undefined ); var Plugin = { install: function install(Vue) { __chunk_5.registerComponent(Vue, Rate); } }; __chunk_5.use(Plugin); exports.BRate = Rate; exports.default = Plugin;
/*! * ui-grid - v4.8.2 - 2019-10-07 * Copyright (c) 2019 ; License: MIT */ (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('sv', { headerCell: { aria: { defaultFilterLabel: 'Kolumnfilter', removeFilter: 'Ta bort filter', columnMenuButtonLabel: 'Kolumnmeny', column: 'Kolumn' }, priority: 'Prioritet:', filterLabel: "Filter för kolumn: " }, aggregate: { label: 'Poster' }, groupPanel: { description: 'Dra en kolumnrubrik hit och släpp den för att gruppera efter den kolumnen.' }, search: { aria: { selected: 'Rad är vald', notSelected: 'Rad är inte vald' }, placeholder: 'Sök...', showingItems: 'Visar:', selectedItems: 'Valda:', totalItems: 'Antal:', size: 'Sidstorlek:', first: 'Första sidan', next: 'Nästa sida', previous: 'Föregående sida', last: 'Sista sidan' }, menu: { text: 'Välj kolumner:' }, sort: { ascending: 'Sortera stigande', descending: 'Sortera fallande', none: 'Ingen sortering', remove: 'Inaktivera sortering' }, column: { hide: 'Göm kolumn' }, aggregation: { count: 'Antal rader: ', sum: 'Summa: ', avg: 'Genomsnitt: ', min: 'Min: ', max: 'Max: ' }, pinning: { pinLeft: 'Fäst vänster', pinRight: 'Fäst höger', unpin: 'Lösgör' }, columnMenu: { close: 'Stäng' }, gridMenu: { aria: { buttonLabel: 'Meny' }, columns: 'Kolumner:', importerTitle: 'Importera fil', exporterAllAsCsv: 'Exportera all data som CSV', exporterVisibleAsCsv: 'Exportera synlig data som CSV', exporterSelectedAsCsv: 'Exportera markerad data som CSV', exporterAllAsPdf: 'Exportera all data som PDF', exporterVisibleAsPdf: 'Exportera synlig data som PDF', exporterSelectedAsPdf: 'Exportera markerad data som PDF', exporterAllAsExcel: 'Exportera all data till Excel', exporterVisibleAsExcel: 'Exportera synlig data till Excel', exporterSelectedAsExcel: 'Exportera markerad data till Excel', clearAllFilters: 'Nollställ alla filter' }, importer: { noHeaders: 'Kolumnnamn kunde inte härledas. Har filen ett sidhuvud?', noObjects: 'Objekt kunde inte härledas. Har filen data undantaget sidhuvud?', invalidCsv: 'Filen kunde inte behandlas, är den en giltig CSV?', invalidJson: 'Filen kunde inte behandlas, är den en giltig JSON?', jsonNotArray: 'Importerad JSON-fil måste innehålla ett fält. Import avbruten.' }, pagination: { aria: { pageToFirst: 'Gå till första sidan', pageBack: 'Gå en sida bakåt', pageSelected: 'Vald sida', pageForward: 'Gå en sida framåt', pageToLast: 'Gå till sista sidan' }, sizes: 'Poster per sida', totalItems: 'Poster', through: 'genom', of: 'av' }, grouping: { group: 'Gruppera', ungroup: 'Dela upp', aggregate_count: 'Agg: Antal', aggregate_sum: 'Agg: Summa', aggregate_max: 'Agg: Max', aggregate_min: 'Agg: Min', aggregate_avg: 'Agg: Genomsnitt', aggregate_remove: 'Agg: Ta bort' }, validate: { error: 'Error:', minLength: 'Värdet borde vara minst THRESHOLD tecken långt.', maxLength: 'Värdet borde vara max THRESHOLD tecken långt.', required: 'Ett värde krävs.' } }); return $delegate; }]); }]); })();
#!/usr/bin/env gjs const Gtk = imports.gi.Gtk; Gtk.init(null); function on_item_activated() { var uri = recentchoosermenu.get_current_uri(); if (uri != null) { print("Recent document selected: " + uri); } } var window = new Gtk.Window(); window.set_default_size(200, -1); window.set_title('RecentChooserMenu'); window.connect('destroy', Gtk.main_quit); var menubar = new Gtk.MenuBar(); window.add(menubar); var menuitem = new Gtk.MenuItem({label: 'Recent'}); menubar.add(menuitem); var recentchoosermenu = new Gtk.RecentChooserMenu(); recentchoosermenu.connect('item-activated', on_item_activated); menuitem.set_submenu(recentchoosermenu); window.show_all(); Gtk.main();
jsonp({"cep":"16270000","cidade":"Glic\u00e9rio","uf":"SP","estado":"S\u00e3o Paulo"});
import React from "react"; import {graphql} from "gatsby"; import "../styles/main.scss"; import BlogIndexCover from "../assets/images/blog_covers/blog_index_cover.jpeg"; import CompactHeader from "../components/compact-header"; import BlogListing from "../components/blog-post-listing"; import PageFooter from "../components/footer"; class BlogListPage extends React.Component { render() { const posts = this.props.data.allMarkdownRemark.edges; return ( <div> <CompactHeader title="Blog Articles" mood="#fdfdfd" bgUrl={BlogIndexCover}> </CompactHeader> <main> <div className="post-list-container"> <BlogListing posts={posts}> </BlogListing> </div> </main> <PageFooter> </PageFooter> </div> ); } } export default BlogListPage; export const pageQuery = graphql` query { site { siteMetadata { title } } allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }, limit: 20) { edges { node { excerpt frontmatter { date(formatString: "MMMM DD, YYYY") title basecolor author enablecomments category bgimage external_link external_site_name external_site_link page_slug } } } } } `;
import joiModule from 'joi' import { createServiceTester } from '../tester.js' const Joi = joiModule.extend(joi => ({ base: joi.array(), coerce: (value, helpers) => ({ value: value.split ? value.split(' | ') : value, }), type: 'versionArray', })) const isDottedVersionAtLeastOne = Joi.string().regex(/\d+(\.\d+)?(\.\d+)?$/) export const t = await createServiceTester() t.create('Nucleus (pluginId nucleus)') .get('/nucleus.json') .expectBadge({ label: 'sponge', message: Joi.versionArray().items(isDottedVersionAtLeastOne), }) t.create('Invalid Plugin (pluginId 1)').get('/1.json').expectBadge({ label: 'sponge', message: 'not found', })
jsonp({"cep":"36784000","cidade":"Dona Euz\u00e9bia","uf":"MG","estado":"Minas Gerais"});
#!/usr/bin/env node /* The Cedric's Swiss Knife (CSK) - CSK terminal toolbox test suite Copyright (c) 2009 - 2015 Cédric Ronvel The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ "use strict" ; /* jshint unused:false */ var fs = require( 'fs' ) ; var termkit = require( '../lib/termkit.js' ) ; termkit.getDetectedTerminal( function( error , term ) { var autoCompleter = function autoCompleter( inputString , callback ) { fs.readdir( __dirname , function( error , files ) { //console.log( files ) ; callback( undefined , termkit.autoComplete( files , inputString , true ) ) ; } ) ; } ; function question() { term( 'Choose a file: ' ) ; term.inputField( { autoComplete: autoCompleter , autoCompleteMenu: true } , function( error , input ) { if ( error ) { term.red.bold( "\nAn error occurs: " + error + "\n" ) ; question() ; } else { term.green( "\nYour file is '%s'\n" , input ) ; terminate() ; } } ) ; } function terminate() { term.grabInput( false ) ; // Add a 100ms delay, so the terminal will be ready when the process effectively exit, preventing bad escape sequences drop setTimeout( function() { process.exit() ; } , 100 ) ; } term.bold.cyan( 'Async auto-completer, type something and hit the ENTER key...\n' ) ; question() ; } ) ;
describe("twitter plugin", function () { xit("works", function () { expect(function () { var plugins = require("../index.js").convert, assert = require("assert"); var goodURLs = [ "https://twitter.com/davidmerfieId/status/500323409218117633", "http://twitter.com/davidmerfieId/status/500323409218117633", "https://twitter.com/davidmerfieId/status/500323409218117633/", "https://twitter.com/davidmerfieId/status/500323409218117633?foo=bar", "https://twitter.com/davidmerfieId/STATUS/500323409218117633?foo=bar", ]; var badURLs = [ "http://twatter.com/davidmerfieId/status/500323409218117633", "http://twitter.foo.com/davidmerfieId/status/500323409218117633", "https://twitter.com/davidmerfieId/500323409218117633", "https://twitter.com/davidmerfieId/status", "https://twitter.com/davidmerfieId/ST/500323409218117633", "", "ABC", ]; for (var i in goodURLs) goodURLs[i] = linkify(goodURLs[i]); for (var j in badURLs) badURLs[j] = linkify(badURLs[j]); goodURLs.forEach(function (html) { plugins( { plugins: { twitter: { enabled: true } } }, "/path.txt", html, function (err, newHTML) { assert(newHTML !== html); } ); }); badURLs.forEach(function (html) { plugins( { plugins: { twitter: { enabled: true } } }, "/path.txt", html, function (err, newHTML) { assert(newHTML === html); } ); }); console.log("All tests complete?"); function linkify(url) { return '<p><a href="' + url + '">' + url + "</a></p>"; } }).not.toThrow(); }); });
jsonp({"cep":"59855000","cidade":"Ita\u00fa","uf":"RN","estado":"Rio Grande do Norte"});
var library = require('./library.js'); var check_cond = function(num, div, start) { var n = ''; for(var i = start; i < start + 3; i++) { n = n + num.toString().charAt(i - 1); } if(parseInt(n) % div === 0) { return true; } return false; } var check_all = function(num) { var all = [2, 3, 5, 7, 11, 13, 17]; for(var i = 0; i < all.length; i += 1) { if(!check_cond(num, all[i], i + 2)) { return false; } } return true; } var solve = function () { var sum = 0; var start = 1234567890; var end = 9876543210; for(var i = start, count = 0; i <= end; i += 1, count += 1) { if(count % 1000000 == 0) { console.log("\$i : " + i); } if(!library.is_pandigital(i, 0)) { continue; } if(!check_all(i)) { continue; } console.log("OK : " + i); sum += i; } }; var check_all_2 = function(num) { var y = num.toString(); var n = [0]; for(var i = 0; i < y.length; i += 1) { n.push(parseInt(y[i])); } if(n[4] % 2 != 0) { return false; } var a = n[3] + n[4] + n[5]; if(a % 3 != 0) { return false; } if(n[6] % 5 != 0) { return false; } var b = n[5] * 10 + n[6] - 2 * n[7]; if(b % 7 != 0) { return false; } var c = n[6] * 10 + n[7] - n[8]; if(c % 11 != 0) { return false; } var d = n[7] * 10 + n[8] + 4 * n[9]; if(d % 13 != 0) { return false; } var e = n[8] * 10 + n[9] - 5 * n[10]; if(e % 17 != 0) { return false; } return true; } var solve_2 = function () { var sum = 0; var start = 1234567890; var end = 9876543210; for(var i = start, count = 0; i <= end; i += 1, count += 1) { if(count % 1000000 == 0) { console.log("\$i : " + i); } if(!check_all_2(i)) { continue; } if(!library.is_pandigital_v2(i, 0)) { continue; } console.log("OK : " + i); sum += i; } }; var sum = solve_2(); console.log(sum); //var num = process.argv[2]; //console.log(check_all_2(num));
var gulp = require('gulp'); var sourcemaps = require('gulp-sourcemaps'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); var browserify = require('browserify'); var watchify = require('watchify'); var babel = require('babelify'); var jade = require('gulp-jade'); var connect = require('gulp-connect'); var uglify = require('gulp-uglify'); var envify = require('envify/custom'); var file = require('gulp-file'); var buildDir = 'build'; var devBuildDir = 'dev_build'; function handleError(err) { console.error(err); // eslint-disable-line no-console this.emit('end'); } function templates(outDir) { return function() { return gulp.src('public/*.jade') .pipe(jade()) .pipe(gulp.dest(outDir)); }; } function styles(outDir) { return function() { return gulp.src('public/*.css') .pipe(gulp.dest(outDir)) .pipe(connect.reload()); }; } function vendor(outDir) { return function() { return gulp.src('public/vendor/**') .pipe(gulp.dest(outDir + '/vendor')); }; } function icons(outDir) { return function() { return gulp.src('public/icons/**') .pipe(gulp.dest(outDir + '/icons')); }; } gulp.task('templates', templates(devBuildDir)); gulp.task('styles', styles(devBuildDir)); gulp.task('vendor', vendor(devBuildDir)); gulp.task('icons', icons(devBuildDir)); function compile(opts) { var bundler = watchify( browserify('./public/main.js', { debug: true }) .transform(babel) .transform(envify({ NODE_ENV: 'development' }), {global: true}) ); function rebundle() { return bundler.bundle() .on('error', handleError) .pipe(source('main.js')) .pipe(buffer()) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(devBuildDir)) .pipe(connect.reload()); } if (opts.watch) { bundler.on('update', function() { console.log('-> bundling...'); // eslint-disable-line no-console return rebundle(); }); } return rebundle(); } gulp.task('connect', function() { return connect.server({ root: devBuildDir, livereload: true }); }); gulp.task('watch', function() { gulp.watch('public/*.css', ['styles']); return compile({watch: true}); }); gulp.task('build', function() { templates(buildDir)(); styles(buildDir)(); vendor(buildDir)(); icons(buildDir)(); file('CNAME', 'circuits.im', { src: true }) .pipe(gulp.dest(buildDir)); return browserify('./public/main.js') .transform(envify({ NODE_ENV: 'production' }), {global: true}) .transform(babel.configure({ optional: [ 'optimisation.react.constantElements', 'optimisation.react.inlineElements' ] })) .bundle().on('error', handleError) .pipe(source('main.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest(buildDir)); }); gulp.task('default', ['templates', 'vendor', 'styles', 'icons', 'connect', 'watch']);
/* Updates fields based on checkbox changes */ var PRFtoggleEnabled = function(cbox, id, type) { oldval = cbox.checked ? 0 : 1; var dataS = { "action" : "toggleEnabled", "id": id, "type": type, "oldval": oldval, }; data = $.param(dataS); $.ajax({ type: "POST", dataType: "json", url: site_admin_url + "/plugins/profile/ajax.php", data: data, success: function(result) { cbox.checked = result.newval == 1 ? true : false; try { if (result.newval == oldval) { icon = "<i class='uk-icon-exclamation-triangle'></i>&nbsp;"; } else { icon = "<i class='uk-icon-check'></i>&nbsp;"; } $.UIkit.notify(icon + result.statusMessage, {timeout: 1000,pos:'top-center'}); } catch(err) { $.UIkit.notify("<i class='uk-icon-exclamation-triangle'></i>&nbsp;" + result.statusMessage, {timeout: 1000,pos:'top-center'}); alert(result.statusMessage); } } }); return false; }; /** * Not a toggle function; this updates the 3-part date field with data * from the datepicker. * @param Date d Date object * @param string fld Field Name * @param integer tm_type 12- or 24-hour indicator, 0 = no time field */ function PRF_updateDate(d, fld, tm_type) { document.getElementById(fld + "_month").selectedIndex = d.getMonth() + 1; document.getElementById(fld + "_day").selectedIndex = d.getDate(); document.getElementById(fld + "_year").value = d.getFullYear(); // Update the time, if time fields are present. if (tm_type != 0) { var hour = d.getHours(); var ampm = 0; if (tm_type == "12") { if (hour == 0) { hour = 12; } else if (hour > 12) { hour -= 12; ampm = 1; } document.getElementById(fld + "_ampm").selectedIndex = ampm; } document.getElementById(fld + "_hour").selectedIndex = hour; document.getElementById(fld + "_minute").selectedIndex = d.getMinutes(); } }
jQuery(document).ready(function(){ jQuery("#ResponsiveContactForm").validate({ submitHandler: function(form) { jQuery.ajax({ type: "POST", dataType: "json", url:MyAjax, data:{ action: 'ai_action', fdata : jQuery(document.formValidate).serialize() }, success:function(response) { if(response == 1){ jQuery("#smsg").slideDown(function(){ jQuery('html, body').animate({scrollTop: jQuery("#smsg").offset().top},'fast'); jQuery(this).show().delay(8000).slideUp("fast")}); document.getElementById('ResponsiveContactForm').reset(); refreshCaptcha(); jQuery(".input-xlarge").removeClass("valid"); jQuery(".input-xlarge").next('label.valid').remove(); }else if(response == 2){ jQuery("#fmsg").slideDown(function(){ jQuery(this).show().delay(8000).slideUp("fast")}); jQuery("#captcha").removeClass("valid").addClass("error"); jQuery("#captcha").next('label.valid').removeClass("valid").addClass("error"); jQuery('#captcha').val(''); refreshCaptcha(); }else{ alert(response); } } }); } }); });
(function ($) { $(document).ready(function() { var highestCol = Math.max($('.first-menu .pane-content').height(),$('.middle-menu .pane-content').height(),$('.last-menu .pane-content').height()); /*.first-menu .pane-content, .middle-menu .pane-content, .last-menu .pane-content $('.elements').height(highestCol);*/ alert(highestCol); }); })(jQuery);
/* thePlatform Video Manager Wordpress Plugin Copyright (C) 2013-2014 thePlatform for Media Inc. This program 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 2 of the License, or (at your option) any later version. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Changes ======================================== qaz2wsx3@uw.edu: changed the icon on the post editor's toolbar */ tinymce.PluginManager.add( 'theplatform', function( editor, url ) { // Add a button that opens a window editor.addButton( 'theplatform', { tooltip: 'Embed MPX Media', image: url.substring( 0, url.lastIndexOf( '/js' ) ) + '/images/MediaAMP_button_icon.png', onclick: function() { // Open window var iframeUrl = ajaxurl + "?action=theplatform_media&embed=true&_wpnonce=" + editor.settings.theplatform_media_nonce; tinyMCE.activeEditor = editor; if ( window.innerHeight < 1200 ) height = window.innerHeight - 50; else height = 1024; if ( tinyMCE.majorVersion > 3 ) { editor.windowManager.open( { width: 1220, height: height, url: iframeUrl } ); } else { if ( jQuery( "#tp-embed-dialog" ).length == 0 ) { jQuery( 'body' ).append( '<div id="tp-embed-dialog"></div>' ); } jQuery( "#tp-embed-dialog" ).html( '<iframe src="' + iframeUrl + '" height="100%" width="100%">' ).dialog( { dialogClass: "wp-dialog", modal: true, resizable: true, minWidth: 1024, width: 1220, height: height } ).css( "overflow-y", "hidden" ); } } } ); } ); tinymce.init( { plugins: 'theplatform' } );
import F2 from '@antv/f2'; fetch('https://gw.alipayobjects.com/os/antfincdn/N81gEpw2Ef/income.json') .then(res => res.json()) .then(data => { const chart = new F2.Chart({ id: 'container', pixelRatio: window.devicePixelRatio }); chart.source(data, { time: { type: 'timeCat', range: [ 0, 1 ], tickCount: 3 } }); chart.axis('time', { label: function label(text, index, total) { const textCfg = {}; if (index === 0) { textCfg.textAlign = 'left'; } else if (index === total - 1) { textCfg.textAlign = 'right'; } return textCfg; } }); chart.guide().point({ position: [ '2014-01-03', 6.763 ] }); chart.guide().text({ position: [ '2014-01-03', 6.763 ], content: '受稳健货币政策影响,协定存款利\n率居高不下,收益率达6.763%', style: { textAlign: 'left', lineHeight: 16, fontSize: 10 }, offsetX: 10 }); chart.guide().point({ position: [ '2013-05-31', 2.093 ] }); chart.guide().text({ position: [ '2013-05-31', 2.093 ], content: '余额宝刚成立时,并未达到\n目标资产配置,故收益率较低', style: { textAlign: 'left', lineHeight: 16, fontSize: 10 }, offsetX: 10, offsetY: -10 }); chart.guide().point({ position: [ '2016-09-04', 2.321 ] }); chart.guide().text({ position: [ '2016-09-04', 2.321 ], content: '受积极货币政策的影响,收益率降\n到历史最低2.321%', style: { textBaseline: 'bottom', lineHeight: 16, fontSize: 10 }, offsetY: -20 }); chart.line().position('time*rate'); chart.render(); });
/** A data model representing a list of Invites @class InviteList @extends Discourse.Model @namespace Discourse @module Discourse **/ Discourse.InviteList = Discourse.Model.extend({ empty: (function() { return this.blank('pending') && this.blank('redeemed'); }).property('pending.@each', 'redeemed.@each') }); Discourse.InviteList.reopenClass({ findInvitedBy: function(user) { var promise; promise = new RSVP.Promise(); $.ajax({ url: "/users/" + (user.get('username_lower')) + "/invited.json", success: function(result) { var invitedList; invitedList = result.invited_list; if (invitedList.pending) { invitedList.pending = invitedList.pending.map(function(i) { return Discourse.Invite.create(i); }); } if (invitedList.redeemed) { invitedList.redeemed = invitedList.redeemed.map(function(i) { return Discourse.Invite.create(i); }); } invitedList.user = user; return promise.resolve(Discourse.InviteList.create(invitedList)); } }); return promise; } });
(function( window, undefined ) { kendo.cultures["ur-PK"] = { name: "ur-PK", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$n-","$n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "Rs" } }, calendars: { standard: { days: { names: ["اتوار","پير","منگل","بدھ","جمعرات","جمعه","هفته"], namesAbbr: ["اتوار","پير","منگل","بدھ","جمعرات","جمعه","هفته"], namesShort: ["ا","پ","م","ب","ج","ج","ه"] }, months: { names: ["جنوری","فروری","مارچ","اپریل","مئی","جون","جولائی","اگست","ستمبر","اکتوبر","نومبر","دسمبر"], namesAbbr: ["جنوری","فروری","مارچ","اپریل","مئی","جون","جولائی","اگست","ستمبر","اکتوبر","نومبر","دسمبر"] }, AM: ["AM","am","AM"], PM: ["PM","pm","PM"], patterns: { d: "dd/MM/yyyy", D: "dd MMMM, yyyy", F: "dd MMMM, yyyy h:mm:ss tt", g: "dd/MM/yyyy h:mm tt", G: "dd/MM/yyyy h:mm:ss tt", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "h:mm tt", T: "h:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM, yyyy", Y: "MMMM, yyyy" }, "/": "/", ":": ":", firstDay: 1 } } } })(this);
angular.module('app.controllers.ForgotPasswordCtrl', ['ngRoute']) .controller('ForgotPasswordCtrl', ['$scope', '$http', '$modalInstance', 'forgotPasswordService', function($scope, $http, $modalInstance, forgotPasswordService) { $scope.forgot_data = { email: "" }; $scope.ok = function () { forgotPasswordService.save($scope.forgot_data); $modalInstance.close($scope.forgot_data.email); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }]);
import React from 'react' import { connect } from 'react-redux' import ItemSelectInput from './ItemSelectInput' import sectionsActions from '../../../actions/SectionsActions' class SectionSelectInputComponent extends React.Component { listSections(query) { let queryObj = {} if (query) { queryObj['q'] = query } this.props.listSections(this.props.token, queryObj) } render() { return ( <ItemSelectInput many={false} value={this.props.value} inline={this.props.inline} showSortableList={this.props.showSortableList} results={this.props.sections.ids} entities={this.props.entities.sections} onChange={(value) => this.props.update(value)} fetchResults={(query) => this.listSections(query)} attribute='name' editMessage={this.props.value ? 'Edit section' : 'Add section'} /> ) } } const mapStateToProps = (state) => { return { sections: state.app.sections.list, entities: { sections: state.app.entities.sections }, token: state.app.auth.token } } const mapDispatchToProps = (dispatch) => { return { listSections: (token, query) => { dispatch(sectionsActions.list(token, query)) } } } const SectionSelectInput = connect( mapStateToProps, mapDispatchToProps )(SectionSelectInputComponent) export default SectionSelectInput
/** * Route Mappings * (sails.config.routes) * * Your routes map URLs to views and controllers. * * If Sails receives a URL that doesn't match any of the routes below, * it will check for matching files (images, scripts, stylesheets, etc.) * in your assets directory. e.g. `http://localhost:1337/images/foo.jpg` * might match an image file: `/assets/images/foo.jpg` * * Finally, if those don't match either, the default 404 handler is triggered. * See `api/responses/notFound.js` to adjust your app's 404 logic. * * Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies * flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or * CoffeeScript for the front-end. * * For more information on configuring custom routes, check out: * http://sailsjs.org/#/documentation/concepts/Routes/RouteTargetSyntax.html */ module.exports.routes = { /*************************************************************************** * * * Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, * * etc. depending on your default view engine) your home page. * * * * (Alternatively, remove this and add an `index.html` file in your * * `assets` directory) * * * ***************************************************************************/ '/': { view: 'homepage', locals: { laytout: 'layout' } }, '/admin': { view: 'admin', locals: { layout: 'cms' } }, '/admin/login': { view: 'login', locals: { layout: 'layout' } }, '/admin/week': { controller: 'week', action: 'index', locals: { layout: 'cms' } }, '/admin/week/save': { controller: 'week', action: 'save', locals: { layout: 'cms' } }, '/admin/week/add': { view: 'weeks-form', locals: { layout: 'cms' } }, /*************************************************************************** * * * Custom routes here... * * * * If a request to a URL doesn't match any of the custom routes above, it * * is matched against Sails route blueprints. See `config/blueprints.js` * * for configuration options and examples. * * * ***************************************************************************/ };
Ext.define('Planche.lib.Query', { constructor : function(query){ Ext.apply(this, query); }, getPrevRecordSetSQL : function(){ this.start -= this.end; if(this.start < 0) this.start = 0; return this.getSQL(); }, getNextRecordSetSQL : function(){ this.start += this.end; return this.getSQL(); }, getPrevRecordSQL : function(){ this.start--; if(this.start < 0) this.start = 0; return this.getSQL(); }, getNextRecordSQL : function(){ this.start++; return this.getSQL(); }, getSQL : function(){ if(this.isSelectQuery == true){ return this.sql + ' LIMIT ' + this.start + ", " + this.end; } else { return this.raw; } }, getRawSQL : function(){ return this.raw; }, getTokens : function(){ return this.tokens; }, isSelectQuery : function(){ return this.selectQuery; }, isDelimiter : function(){ return this.delimiter; }, hasNext : function(){ return this.raw.length > this.end ? true : false; }, setRecords : function(records){ Ext.apply(this, { records : records }); }, isSelectedQuery : function(line, cursor){ var linecursor = parseFloat(line + "." + cursor); if(this.sline <= linecursor && linecursor >= this.eline){ return true; } else { return false; } } });
define('util', ['jquery'], function($){ $.extend({ restGet: function(url, data, callback){ $.get(url, data, function(data){ if(data.success){ callback(data); } else { if(data.redirect){ location.href = data.redirect; } else if(data.message){ $.showError('notify', data.message); } } }); }, restPost: function(url, data, callback){ $.post(url, data, function(data){ if(data.success){ callback(data); } else { if(data.redirect){ location.href = data.redirect; } else if(data.message){ $.showError('notify', data.message); } } }); }, showError: function(id, message){ $("#" + id).append('<div class="alert alert-error fade in"><a href="#" data-dismiss="alert" class="close">×</a><strong>错误:</strong><span></span></div>') $("#" + id +" > div > span").text(message); $("#" + id +" > .alert").alert(); setTimeout(function(){ $("#" + id +" > .alert").alert('close'); }, 3000); }, showSuccess: function(id, message){ $("#" + id).append('<div class="alert alert-success fade in"><a href="#" data-dismiss="alert" class="close">×</a><span></span></div>') $("#" + id +" > div > span").text(message); $("#" + id +" > .alert").alert(); setTimeout(function(){ $("#" + id +" > .alert").alert('close'); }, 3000); }, backdrop: function(state){ if(state == 'show'){ $("body").append("<div class='modal-backdrop fade in'></div>"); } else if(state == 'hide'){ $(".modal-backdrop").remove(); }; }, }); $.fn.extend({ edata: function(id){ return this.attr("data-" + id); }, reset: function(){ var id = this.attr('id'); document.getElementById(id).reset(); }, is_disabled: function(){ return this.attr("disabled") == "disabled"; }, }); return $; });
(function(){ if ( window.xataface == undefined ) window.xataface = {}; if ( window.xataface.modules == undefined ) window.xataface.modules = {}; if ( window.xataface.modules.htmlreports == undefined ) window.xataface.modules.htmlreports = {}; })();
(function($, Translator) { Skin = function Skin(code, skinData) { this.variableRegex = /\{#([\w \|]*)\#\}/; this.translateRegex = /\{=([\w \|,]*)\=\}/; this.code = code; this.extractData(skinData); } Skin.prototype.scanChildren = function(code, skinData) { if(skinData) this.extractData(skinData); var variables = this.data.variableBlocks; var loops = this.data.loopBlocks; code = this.checkCondition(code, variables); code = this.checkLoop(code, loops, skinData); return this.executeVariableBlocks(this.executeTranslateBlocks(code, variables), variables); } /* * Gets code, parses with jQuery, checks and returns code */ Skin.prototype.checkCondition = function(code, variables) { var checkCondition = $(code); if(checkCondition.hasAttr('skif')) { var skif = checkCondition.attr('skif'); if(variables[skif]) { if($.toBoolean(variables[skif])) { checkCondition.removeAttr('skif'); return checkCondition.outerHTML(); } else return ''; } else return ''; } return code; } /* * Gets code, parses with jQuery, checks and returns code */ Skin.prototype.checkLoop = function(code, loops, skinData) { var checkLoop = $(code); var newNodeHTML = ''; var children = checkLoop.contents(); var $this = this; if(checkLoop.hasAttr('skloop')) { var skloop = checkLoop.attr('skloop'); if(loops[skloop]) { checkLoop.removeAttr('skloop'); for(var i = 0; i < loops[skloop].length; ++i) { if(typeof(loops[skloop]) === 'array' || typeof(loops[skloop]) === 'object') newNodeHTML += $this.scanChildren(checkLoop.outerHTML(), loops[skloop][i]); } } else return ''; } else { $.each(children, function(key, child) { if(child.nodeType === 1) newNodeHTML += $this.scanChildren($(child).outerHTML(), skinData); else if(child.nodeType === 3) newNodeHTML += child.textContent; }); } if(newNodeHTML !== '') code = newNodeHTML; checkLoop.html(code); return checkLoop.outerHTML(); } Skin.prototype.extractData = function(skinData) { var $this = this; this.data = { 'loopBlocks':{}, 'variableBlocks':{} }; $.each(skinData, function(key, value) { switch (typeof(value)) { case 'object': case 'array': $this.data.loopBlocks[key] = value; break; default: $this.data.variableBlocks[key] = value; break; } }); } Skin.prototype.executeVariableBlocks = function(code, variableBlocks) { if (variableBlocks) { var matchVariable = code.matchAll(this.variableRegex); if (matchVariable) { for (var variables = 0; variables < matchVariable.length; ++variables) { var explodeVar = matchVariable[variables][1].split('|'); var property = explodeVar[0].replace(' ', ''); if (variableBlocks[property]) { if(explodeVar[1]) { var explodeFunc = explodeVar[1].split(' '); for(var i = 0; i < explodeFunc.length; ++i) { var $func = this[explodeFunc[i]]; if(explodeFunc[i] && typeof $func === 'function') variableBlocks[property] = $func(variableBlocks[property]); } } return code.replace(matchVariable[variables][0], variableBlocks[property]); } else return code.replace(matchVariable[variables][0], ''); } } } return code; } Skin.prototype.executeTranslateBlocks = function(code, variableBlocks) { if(variableBlocks) { var matchTranslate = code.matchAll(this.translateRegex); if(matchTranslate) { for(var translates = 0; translates < matchTranslate.length; ++translates) { var explodeTranslate = matchTranslate[translates][1].replace(/ /g,'').split('|'); if(explodeTranslate[1]) { var arguments = explodeTranslate[1].split(','); var variables = []; for(var i = 0; i < arguments.length; ++i) variables[i] = variableBlocks[arguments[i]] ? variableBlocks[arguments[i]] : '"' + arguments[i] + '"'; return code.replace(matchTranslate[0][translates], Translator._(explodeTranslate[0], variables)); } else return code.replace(matchTranslate[0][translates], Translator._(explodeTranslate[0])); } } } return code; } Skin.prototype.render = function() { var domNode = $('<div id="skinTemporaryDiv">' + this.code + '</div>') var children = domNode.contents(); var $this = this; var outHTML = ''; $.each(children, function(key, child) { outHTML += $this.scanChildren($(child).outerHTML()); }); return outHTML; } /* * Skin functions & aliases */ Skin.prototype.e = Skin.prototype.escape = function(string) { return string.htmlentities(); } Skin.prototype.df = Skin.prototype.date = function(date) { var date = new Date(date); return date.format('dd/mm/yyyy') } Skin.prototype.l = Skin.prototype.link = function(string) { } return Skin; }($, Translator));
// Generated by CoffeeScript 1.8.0 var db, monitor; db = require('./db.js'); monitor = require('./monitor.js'); module.exports.launch = function() { require('./argv_parser.js').parse(process.argv.slice(2), function() { var m; db.createClient(); db.clearQueue(); m = monitor.createMonitor().start(); }); };
self.addEventListener("message", nextEmpty); function isAt(points, x, y) { for (var i = 0, len = points.length; i < len; i += 2) { if (points[i] == x && points[i + 1] == y) return true; } return false; } function nextEmpty(event) { var data = event.data; var x = 0; var y = 0; while (true) { x = parseInt(Math.random() * data.width); y = parseInt(Math.random() * data.height); if (!isAt(data.points, x, y)) break; } self.postMessage({x: x, y: y}); }
var Arduino = function(port) { this.portName = port; this.status = "CLOSED"; } module.exports = Arduino;
'use strict'; var config = require('../config'), gulp = require('gulp'), size = require('gulp-size'); // output size in console gulp.task('info', function() { // You can pass as many relative urls as you want return gulp.src(config.destPaths.root + '/*/**') .pipe(size()) });
'use strict'; angular.module('wordclashApp').controller('LoginCtrl', ['$scope', '$location', 'authService', 'ngAuthSettings', function ($scope, $location, authService, ngAuthSettings) { $scope.loginData = { userName: "", password: "", useRefreshTokens: false }; $scope.message = ""; $scope.clicked = false; $scope.login = function () { $scope.clicked = true; authService.login($scope.loginData).then(function (response) { $scope.clicked = false; $location.path('/arena'); }, function (err) { $scope.clicked = false; $scope.message = err.error_description; }); }; $scope.authExternalProvider = function (provider) { var redirectUri = location.protocol + '//' + location.host + '/authcomplete.html'; var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider + "&response_type=token&client_id=" + ngAuthSettings.clientId + "&redirect_uri=" + redirectUri; window.$windowScope = $scope; var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0,width=600,height=750"); }; $scope.authCompletedCB = function (fragment) { $scope.$apply(function () { if (fragment.haslocalaccount == 'False') { authService.logOut(); authService.externalAuthData = { provider: fragment.provider, userName: fragment.external_user_name, externalAccessToken: fragment.external_access_token }; $location.path('/associate'); } else { //Obtain access token and redirect to orders var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token }; authService.obtainAccessToken(externalData).then(function (response) { $location.path('/arena'); }, function (err) { $scope.message = err.error_description; }); } }); } }]);
import has from 'lodash/has'; import trim from 'lodash/trim'; import currencyFormatter from 'currency-formatter'; import { hasCurrencyCode } from '../utils/utils-settings'; import { maybeTrimHTML } from '../utils/utils-common'; import { getMoneyFormat, getShop } from '../ws/ws-shop'; import { showingLocalCurrency, getLocalCurrencyCodeCache, showingCurrencyCode } from './pricing-currency'; import { convertToLocalCurrency } from './pricing-conversion'; function priceSymbolMarkup(symbol) { return '<span class="wps-product-price-currency" itemprop="priceCurrency">' + symbol + '</span>'; } function priceAmountMarkup(amount) { return '<span itemprop="price" class="wps-product-individual-price">' + amount + '</span>'; } function priceMarkup(parts, amount) { var priceMarkup = parts.map( ({type, value}) => { switch (type) { case 'currency': return priceSymbolMarkup(value) + priceAmountMarkup(amount); default : return value; } }); return priceMarkup[0]; } /* locale currently not used Config: { locale: 'en-US', countryCode: 'US', amount: 123, } */ function formatPrice(config) { // Uses the browser locale by default if ( !has(config, 'locale') ) { config.locale = false; } var parts = new Intl.NumberFormat(config.locale, { style: 'currency', currency: config.countryCode, currencyDisplay: config.currencyDisplay }).formatToParts(config.amount); return priceMarkup(parts, config.amount); } /* "price" should always be preformatted */ function formatPriceToLocalCurrency(price) { return formatPrice({ countryCode: getLocalCurrencyCodeCache(), amount: price, currencyDisplay: showingCurrencyCode() ? 'code' : 'symbol' }); } function formatPriceFromBase(price) { return formatTotalAmount(price, maybeTrimHTML( getMoneyFormat( getShop() ) ) ); } /* Format product price into format from Shopify */ function maybeFormatPriceToLocalCurrency(price) { if ( showingLocalCurrency() ) { return formatPriceToLocalCurrency(price); } return formatPriceFromBase(price); } /* Comes from Shopify */ function maybeAddCurrencyCodeToMoney(formatWithRealAmount) { if ( hasCurrencyCode() ) { return formatWithRealAmount + ' ' + getShop().currencyCode; } return formatWithRealAmount; } /* Extract Money Format Type */ function extractMoneyFormatType(format) { if (format) { var newFormat = format; newFormat = newFormat.split('{{').pop().split('}}').shift(); return newFormat.replace(/\s+/g, " ").trim(); } else { return false; } } /* Formats the total amount */ function formatTotalAmount(amount, moneyFormat) { var extractedMoneyFormat = extractMoneyFormatType(moneyFormat); var formattedMoney = formatMoneyPerSetting(amount, extractedMoneyFormat, moneyFormat); var formatWithRealAmount = replaceMoneyFormatWithRealAmount(formattedMoney, extractedMoneyFormat, moneyFormat); formatWithRealAmount = formatWithRealAmount.replace(/ /g,''); return maybeAddCurrencyCodeToMoney(formatWithRealAmount); } /* Replace money format with real amount */ function replaceMoneyFormatWithRealAmount(formattedMoney, extractedMoneyFormat, moneyFormat = '') { if (moneyFormat) { var extractedMoneyFormat = new RegExp(extractedMoneyFormat, "g"); var finalPrice = trim(moneyFormat).replace(extractedMoneyFormat, formattedMoney); finalPrice = finalPrice.replace(/{{/g, ''); finalPrice = finalPrice.replace(/}}/g, ''); return finalPrice; } } /* Format Money per settings */ function formatMoneyPerSetting(amount, format, origFormat) { if (format === 'amount') { var string = currencyFormatter.format(amount, { symbol: '', decimal: '.', thousand: ',', precision: 2, format: '%v' }); } else if (format === 'amount_no_decimals') { amount = Number(amount); amount = Math.round(amount); var string = currencyFormatter.format(amount, { symbol: '', decimal: '.', thousand: ',', precision: 0, format: '%v' }); } else if (format === 'amount_with_comma_separator') { var string = currencyFormatter.format(amount, { symbol: '', decimal: ',', thousand: ',', precision: 2, format: '%v' }); } else if (format === 'amount_no_decimals_with_comma_separator') { amount = Number(amount); amount = Math.round(amount); var string = currencyFormatter.format(amount, { symbol: '', decimal: ',', thousand: ',', precision: 0, format: '%v' }); } else if (format === 'amount_with_space_separator') { var string = currencyFormatter.format(amount, { symbol: '', decimal: ',', thousand: ' ', precision: 2, format: '%v' }); } else if (format === 'amount_no_decimals_with_space_separator') { amount = Number(amount); amount = Math.round(amount); var string = currencyFormatter.format(amount, { symbol: '', decimal: ',', thousand: ' ', precision: 0, format: '%v' }); } else if (format === 'amount_with_apostrophe_separator') { var string = currencyFormatter.format(amount, { symbol: '', decimal: '.', thousand: '\'', precision: 2, format: '%v' }); } else { var string = currencyFormatter.format(amount, { symbol: '', decimal: '.', thousand: ',', precision: 2, format: '%v' }); } return string; } export { formatPrice, maybeFormatPriceToLocalCurrency }
/** * grunt/pipeline.js * * The order in which your css, javascript, and template files should be * compiled and linked from your views and static HTML files. * * (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions * for matching multiple files, and the ! prefix for excluding files.) */ // Path to public folder var tmpPath = '.tmp/public/'; // CSS files to inject in order // // (if you're using LESS with the built-in default config, you'll want // to change `assets/styles/importer.less` instead.) var cssFilesToInject = [ 'styles/bootstrap.min.css', 'styles/bootstrap-theme.css' ]; // Client-side javascript files to inject in order // (uses Grunt-style wildcard/glob/splat expressions) var jsFilesToInject = [ // Load sails.io before everything else 'js/dependencies/sails.io.js', 'js/dependencies/angular.js', 'js/dependencies/angular-translate.min.js', 'js/dependencies/jquery.min.js', 'js/dependencies/bootstrap.min.js', 'js/dependencies/ui-bootstrap.min.js', 'js/dependencies/ui-bootstrap-tpls.min.js', 'js/dependencies/angular-translate.min.js', 'js/dependencies/smart-table.min.js', 'js/app.js' // Dependencies like jQuery, or Angular are brought in here // All of the rest of your client-side js files // will be injected here in no particular order. // Use the "exclude" operator to ignore files // '!js/ignore/these/files/*.js' ]; // Client-side HTML templates are injected using the sources below // The ordering of these templates shouldn't matter. // (uses Grunt-style wildcard/glob/splat expressions) // // By default, Sails uses JST templates and precompiles them into // functions for you. If you want to use jade, handlebars, dust, etc., // with the linker, no problem-- you'll just want to make sure the precompiled // templates get spit out to the same file. Be sure and check out `tasks/README.md` // for information on customizing and installing new tasks. var templateFilesToInject = [ 'templates/**/*.html' ]; // Prefix relative paths to source files so they point to the proper locations // (i.e. where the other Grunt tasks spit them out, or in some cases, where // they reside in the first place) module.exports.cssFilesToInject = cssFilesToInject.map(transformPath); module.exports.jsFilesToInject = jsFilesToInject.map(transformPath); module.exports.templateFilesToInject = templateFilesToInject.map(transformPath); // Transform paths relative to the "assets" folder to be relative to the public // folder, preserving "exclude" operators. function transformPath(path) { return (path.substring(0,1) == '!') ? ('!' + tmpPath + path.substring(1)) : (tmpPath + path); }
angular.module('bhima.controllers') .controller('ConfirmDonationController', ConfirmDonationController); ConfirmDonationController.$inject = [ '$scope', '$q', '$http', 'validate', 'connect', '$location', 'uuid', 'SessionService' ]; function ConfirmDonationController($scope, $q, $http, validate, connect, $location, uuid, Session) { var vm = this, dependencies = {}, session = $scope.session = {}; dependencies.donations = { query : { identifier : 'uuid', tables : { donations : {columns : ['uuid', 'date', 'is_received', 'confirmed_by']}, donor : {columns : ['id', 'name']}, employee : {columns : ['prenom', 'name::nom_employee', 'postnom']} }, join : ['donor.id=donations.donor_id', 'donations.employee_id=employee.id'], where : ['donations.is_received=1', 'AND', 'donations.is_confirmed=0'] } }; $scope.project = Session.project; $scope.user = Session.user; function initialise(model) { angular.extend($scope, model); } function confirmDonation(donationId) { session.selected = $scope.donations.get(donationId); loadDetails(donationId); } function loadDetails(donationId) { dependencies.donationDetails = { query : { identifier : 'inventory_uuid', tables : { donations : {columns : ['uuid', 'donor_id', 'employee_id', 'date', 'is_received']}, donation_item : {columns : ['uuid::donationItemUuid']}, stock : {columns : ['inventory_uuid', 'tracking_number', 'purchase_order_uuid', 'quantity::stockQuantity', 'lot_number', 'entry_date']}, purchase : {columns : ['uuid::purchaseUuid', 'cost', 'currency_id', 'note']}, purchase_item : {columns : ['uuid::purchaseItemUuid', 'unit_price', 'quantity']} }, join : [ 'donations.uuid=donation_item.donation_uuid', 'donation_item.tracking_number=stock.tracking_number', 'stock.purchase_order_uuid=purchase.uuid', 'stock.inventory_uuid=purchase_item.inventory_uuid', 'purchase.uuid=purchase_item.purchase_uuid', ], where : ['donations.uuid=' + donationId] } }; validate.refresh(dependencies, ['donationDetails']) .then(initialise); } function confirmReception() { writeToJournal() .then(updateDonation) .then(generateDocument) .then(resetSelected) .catch(handleError); } function updatePurchase () { var purchase = { uuid : session.selected.uuid, confirmed : 1, confirmed_by : $scope.user.id, paid : 1 }; return connect.put('purchase', [purchase], ['uuid']); } function updateDonation () { var donation = { uuid : session.selected.uuid, is_confirmed : 1, confirmed_by : $scope.user.id }; return connect.put('donations', [donation], ['uuid']); } function writeToJournal() { var document_id = uuid(); var synthese = []; // Distinct inventory var unique = {}; var distinctInventory = []; $scope.donationDetails.data.forEach(function (x) { if (!unique[x.inventory_uuid]) { distinctInventory.push(x); unique[x.inventory_uuid] = true; } }); // End Distinct inventory // Grouping by lot var inventoryByLot = []; distinctInventory.forEach(function (x) { var lot = []; lot = $scope.donationDetails.data.filter(function (item) { return item.inventory_uuid === x.inventory_uuid; }); inventoryByLot.push({ inventory_uuid : x.inventory_uuid, purchase_price : x.unit_price, currency_id : x.currency_id, quantity : x.quantity, lots : lot }); }); // End Grouping by lot inventoryByLot.forEach(function (item) { var donation = { uuid : item.lots[0].uuid }, inventory_lots = []; item.lots.forEach(function (lot) { inventory_lots.push(lot.tracking_number); }); synthese.push({ movement : { document_id : document_id }, inventory_uuid : item.inventory_uuid, donation : donation, tracking_numbers : inventory_lots, quantity : item.quantity, purchase_price : item.purchase_price, currency_id : item.currency_id, project_id : $scope.project.id }); }); return $q.all(synthese.map(function (postingEntry) { // REM : Stock Account (3) in Debit and Donation Account (?) in credit // OBJECTIF : Ecrire pour chaque inventory de la donation comme une transaction dans le journal return $http.post('posting_donation/', postingEntry); })); } function paymentSuccess(result) { var purchase = { uuid : session.selected.uuid, paid : 1 }; return connect.put('purchase', [purchase], ['uuid']); } function generateDocument(res) { $location.path('/invoice/confirm_donation/' + session.selected.uuid); } function handleError(error) { console.log(error); } function resetSelected() { session.selected = null; validate.refresh(dependencies, ['donations']) .then(initialise); } $scope.confirmDonation = confirmDonation; $scope.confirmReception = confirmReception; $scope.resetSelected = resetSelected; // start the module up validate.process(dependencies) .then(initialise); }
(function () { 'use strict'; var module = angular.module('memosWebApp', []); }());
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- const Clutter = imports.gi.Clutter; const Gio = imports.gi.Gio; const GLib = imports.gi.GLib; const GObject = imports.gi.GObject; const Lang = imports.lang; const Meta = imports.gi.Meta; const Shell = imports.gi.Shell; const Dialog = imports.ui.dialog; const Main = imports.ui.main; const Tweener = imports.ui.tweener; var FROZEN_WINDOW_BRIGHTNESS = -0.3 var DIALOG_TRANSITION_TIME = 0.15 var ALIVE_TIMEOUT = 5000; var CloseDialog = new Lang.Class({ Name: 'CloseDialog', Extends: GObject.Object, Implements: [ Meta.CloseDialog ], Properties: { 'window': GObject.ParamSpec.override('window', Meta.CloseDialog) }, _init(window) { this.parent(); this._window = window; this._dialog = null; this._timeoutId = 0; }, get window() { return this._window; }, set window(window) { this._window = window; }, _createDialogContent() { let tracker = Shell.WindowTracker.get_default(); let windowApp = tracker.get_window_app(this._window); /* Translators: %s is an application name */ let title = _("“%s” is not responding.").format(windowApp.get_name()); let subtitle = _("You may choose to wait a short while for it to " + "continue or force the application to quit entirely."); let icon = new Gio.ThemedIcon({ name: 'dialog-warning-symbolic' }); return new Dialog.MessageDialogContent({ icon, title, subtitle }); }, _initDialog() { if (this._dialog) return; let windowActor = this._window.get_compositor_private(); this._dialog = new Dialog.Dialog(windowActor, 'close-dialog'); this._dialog.width = windowActor.width; this._dialog.height = windowActor.height; this._dialog.addContent(this._createDialogContent()); this._dialog.addButton({ label: _('Force Quit'), action: this._onClose.bind(this), default: true }); this._dialog.addButton({ label: _('Wait'), action: this._onWait.bind(this), key: Clutter.Escape }); global.focus_manager.add_group(this._dialog); }, _addWindowEffect() { // We set the effect on the surface actor, so the dialog itself // (which is a child of the MetaWindowActor) does not get the // effect applied itself. let windowActor = this._window.get_compositor_private(); let surfaceActor = windowActor.get_first_child(); let effect = new Clutter.BrightnessContrastEffect(); effect.set_brightness(FROZEN_WINDOW_BRIGHTNESS); surfaceActor.add_effect_with_name("gnome-shell-frozen-window", effect); }, _removeWindowEffect() { let windowActor = this._window.get_compositor_private(); let surfaceActor = windowActor.get_first_child(); surfaceActor.remove_effect_by_name("gnome-shell-frozen-window"); }, _onWait() { this.response(Meta.CloseDialogResponse.WAIT); }, _onClose() { this.response(Meta.CloseDialogResponse.FORCE_CLOSE); }, vfunc_show() { if (this._dialog != null) return; Meta.disable_unredirect_for_display(global.display); this._timeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, ALIVE_TIMEOUT, () => { this._window.check_alive(global.display.get_current_time_roundtrip()); return GLib.SOURCE_CONTINUE; }); this._addWindowEffect(); this._initDialog(); this._dialog.scale_y = 0; this._dialog.set_pivot_point(0.5, 0.5); Tweener.addTween(this._dialog, { scale_y: 1, transition: 'linear', time: DIALOG_TRANSITION_TIME, onComplete: () => { Main.layoutManager.trackChrome(this._dialog, { affectsInputRegion: true }); } }); }, vfunc_hide() { if (this._dialog == null) return; Meta.enable_unredirect_for_display(global.display); GLib.source_remove(this._timeoutId); this._timeoutId = 0; let dialog = this._dialog; this._dialog = null; this._removeWindowEffect(); Tweener.addTween(dialog, { scale_y: 0, transition: 'linear', time: DIALOG_TRANSITION_TIME, onComplete: () => { dialog.destroy(); } }); }, vfunc_focus() { if (this._dialog) this._dialog.grab_key_focus(); } });
jQuery.noConflict(); jQuery(document).ready(function(){ /** * This will remove username/password text in the login form fields **/ jQuery('.username, .password').focusout(function(){ if(jQuery(this).val() != '') { jQuery(this).css({backgroundPosition: "0 -32px"}); } else { jQuery(this).css({backgroundPosition: "0 0"}); } }); jQuery('.username, .password').focusin(function(){ if(jQuery(this).val() == '') { jQuery(this).css({backgroundPosition: "0 -32px"}); } }); /** * Message Notify Drop Down **/ jQuery('.messagenotify .wrap, .alertnotify .wrap').click(function(){ var t = jQuery(this).parent(); var url = t.attr('href'); if(t.hasClass('showmsg')) { t.removeClass('showmsg'); t.find('.thicon').removeClass('thiconhover'); t.parent().find('.dropbox').remove(); } else { jQuery('.topheader li').each(function(){ jQuery(this).find('.showmsg').removeClass('showmsg'); jQuery(this).find('.thicon').removeClass('thiconhover'); jQuery(this).find('.dropbox').remove(); }); t.addClass('showmsg'); t.find('.thicon').addClass('thiconhover'); t.parent().append('<div class="dropbox"></div>'); jQuery.post(url,function(data){ jQuery('.dropbox').append(data); }); } return false; }); jQuery(document).click(function(event) { var msglist = jQuery('.dropbox'); if(!jQuery(event.target).is('.dropbox')) { if(msglist.is(":visible")) { msglist.prev().removeClass('showmsg'); msglist.prev().find('.thicon').removeClass('thiconhover'); msglist.remove(); } } }); /** * Login form validation **/ jQuery('#loginform').submit(function(){ var username = jQuery('.username').val(); var password = jQuery('.password').val(); if(username == '' && password == '') { jQuery('.loginNotify').slideDown('fast'); return false; } else { return true; } }); /** * Sidebar accordion **/ jQuery('#accordion h3').click(function() { if(jQuery(this).hasClass('open')) { jQuery(this).removeClass('open'); jQuery(this).next().slideUp('fast'); } else { jQuery(this).addClass('open'); jQuery(this).next().slideDown('fast'); } return false; }); /** * Widget Box Toggle **/ jQuery('.widgetbox h3, .widgetbox2 h3').hover(function(){ jQuery(this).addClass('arrow'); return false; },function(){ jQuery(this).removeClass('arrow'); return false; }); jQuery('.widgetbox h3, .widgetbox2 h3').toggle(function(){ jQuery(this).next().slideUp('fast'); jQuery(this).css({MozBorderRadius: '3px', WebkitBorderRadius: '3px', borderRadius: '3px'}); return false; },function(){ jQuery(this).next().slideDown('fast'); jQuery(this).css({MozBorderRadius: '3px 3px 0 0', WebkitBorderRadius: '3px 3px 0 0', borderRadius: '3px 3px 0 0'}); return false; }); /** * Notification **/ jQuery('.notification .close').click(function(){ jQuery(this).parent().fadeOut(); }); /** Make footer always at the bottom**/ if(jQuery('body').height() > jQuery(window).height()) { jQuery('.footer').removeClass('footer_float'); } /**DROP DOWN MENU**/ jQuery(".subnav").css({display: "none"}); // Opera Fix jQuery(".tabmenu li").hover(function(){ jQuery(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400); },function(){ jQuery(this).find('ul:first').css({visibility: "hidden"}); }); });
(function ($) { Drupal.behaviors.sbac_featured_content = { attach: function (context, settings) { // If JS is working, turn cursor into a pointer and redirect on click $('.featured-content-inner').css( 'cursor', 'pointer' ); $('.featured-content-inner').click(function(){ window.location = '/' + $(this).attr('url'); }); } }; })(jQuery);
/* Publish module for wikiEditor */ ( function ( $ ) { $.wikiEditor.modules.publish = { /** * Compatability map */ browsers: { // Left-to-right languages ltr: { msie: [['>=', 7]], firefox: [['>=', 3]], opera: [['>=', 9.6]], safari: [['>=', 4]] }, // Right-to-left languages rtl: { msie: [['>=', 8]], firefox: [['>=', 3]], opera: [['>=', 9.6]], safari: [['>=', 4]] } }, /** * Internally used functions */ fn: { /** * Creates a publish module within a wikiEditor * @param context Context object of editor to create module in * @param config Configuration object to create module from */ create: function ( context, config ) { // Build the dialog behind the Publish button var dialogID = 'wikiEditor-' + context.instance + '-dialog'; $.wikiEditor.modules.dialogs.fn.create( context, { previewsave: { id: dialogID, titleMsg: 'wikieditor-publish-dialog-title', html: '\ <div class="wikiEditor-publish-dialog-copywarn"></div>\ <div class="wikiEditor-publish-dialog-editoptions">\ <form id="wikieditor-' + context.instance + '-publish-dialog-form">\ <div class="wikiEditor-publish-dialog-summary">\ <label for="wikiEditor-' + context.instance + '-dialog-summary"\ rel="wikieditor-publish-dialog-summary"></label>\ <br />\ <input type="text" id="wikiEditor-' + context.instance + '-dialog-summary"\ style="width: 100%;" />\ </div>\ <div class="wikiEditor-publish-dialog-options">\ <input type="checkbox"\ id="wikiEditor-' + context.instance + '-dialog-minor" />\ <label for="wikiEditor-' + context.instance + '-dialog-minor"\ rel="wikieditor-publish-dialog-minor"></label>\ <input type="checkbox"\ id="wikiEditor-' + context.instance + '-dialog-watch" />\ <label for="wikiEditor-' + context.instance + '-dialog-watch"\ rel="wikieditor-publish-dialog-watch"></label>\ </div>\ </form>\ </div>', init: function () { var i; $(this).find( '[rel]' ).each( function () { $(this).text( mediaWiki.msg( $(this).attr( 'rel' ) ) ); }); /* REALLY DIRTY HACK! */ // Reformat the copyright warning stuff var copyWarnHTML = $( '#editpage-copywarn p' ).html(); // TODO: internationalize by splitting on other characters that end statements var copyWarnStatements = copyWarnHTML.split( '. ' ); var newCopyWarnHTML = '<ul>'; for ( i = 0; i < copyWarnStatements.length; i++ ) { if ( copyWarnStatements[i] !== '' ) { var copyWarnStatement = $.trim( copyWarnStatements[i] ).replace( /\.*$/, '' ); newCopyWarnHTML += '<li>' + copyWarnStatement + '.</li>'; } } newCopyWarnHTML += '</ul>'; // No list if there's only one element $(this).find( '.wikiEditor-publish-dialog-copywarn' ).html( copyWarnStatements.length > 1 ? newCopyWarnHTML : copyWarnHTML ); /* END OF REALLY DIRTY HACK */ if ( $( '#wpMinoredit' ).length === 0 ) $( '#wikiEditor-' + context.instance + '-dialog-minor' ).hide(); else if ( $( '#wpMinoredit' ).is( ':checked' ) ) $( '#wikiEditor-' + context.instance + '-dialog-minor' ) .prop( 'checked', true ); if ( $( '#wpWatchthis' ).length === 0 ) $( '#wikiEditor-' + context.instance + '-dialog-watch' ).hide(); else if ( $( '#wpWatchthis' ).is( ':checked' ) ) $( '#wikiEditor-' + context.instance + '-dialog-watch' ) .prop( 'checked', true ); $(this).find( 'form' ).submit( function ( e ) { $(this).closest( '.ui-dialog' ).find( 'button:first' ).click(); e.preventDefault(); }); }, dialog: { buttons: { 'wikieditor-publish-dialog-publish': function () { var minorChecked = $( '#wikiEditor-' + context.instance + '-dialog-minor' ).is( ':checked' ) ? 'checked' : ''; var watchChecked = $( '#wikiEditor-' + context.instance + '-dialog-watch' ).is( ':checked' ) ? 'checked' : ''; $( '#wpMinoredit' ).prop( 'checked', minorChecked ); $( '#wpWatchthis' ).prop( 'checked', watchChecked ); $( '#wpSummary' ).val( $( '#wikiEditor-' + context.instance + '-dialog-summary' ).val() ); $( '#editform' ).submit(); }, 'wikieditor-publish-dialog-goback': function () { $(this).dialog( 'close' ); } }, open: function () { $( '#wikiEditor-' + context.instance + '-dialog-summary' ).focus(); }, width: 500 }, resizeme: false } } ); context.fn.addButton( { 'captionMsg': 'wikieditor-publish-button-publish', 'action': function () { $( '#' + dialogID ).dialog( 'open' ); return false; } } ); context.fn.addButton( { 'captionMsg': 'wikieditor-publish-button-cancel', 'action': function () { } } ); } } }; }( jQuery ) );
jQuery(document).ready(function ($) { const $resourcesTable = $('#resources-table'); $resourcesTable.find('tbody tr:not(.sub-table-header)').hide(); $resourcesTable.find('.sub-table-header').click(function () { $(this).nextUntil('tr.sub-table-header').toggle(); const visibleLength = $resourcesTable.find('tbody tr:has(:checkbox):visible').length, allVisibleChecked = visibleLength > 0 && visibleLength === $resourcesTable.find('tbody tr.selected:visible').length; $('#mark-all').prop('checked', allVisibleChecked); }); });
/* $Id: jquery.pngFix.js,v 1.1.1.5 2009/02/04 19:23:30 gibbozer Exp $ */ /** * -------------------------------------------------------------------- * jQuery-Plugin "pngFix" * Version: 1.1, 11.09.2007 * by Andreas Eberhard, andreas.eberhard@gmail.com * http://jquery.andreaseberhard.de/ * * Copyright (c) 2007 Andreas Eberhard * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php) * * Changelog: * 11.09.2007 Version 1.1 * - removed noConflict * - added png-support for input type=image * - 01.08.2007 CSS background-image support extension added by Scott Jehl, scott@filamentgroup.com, http://www.filamentgroup.com * 31.05.2007 initial Version 1.0 * -------------------------------------------------------------------- * @example $(function(){$(document).pngFix();}); * @desc Fixes all PNG's in the document on document.ready * * jQuery(function(){jQuery(document).pngFix();}); * @desc Fixes all PNG's in the document on document.ready when using noConflict * * @example $(function(){$('div.examples').pngFix();}); * @desc Fixes all PNG's within div with class examples * * @example $(function(){$('div.examples').pngFix( { blankgif:'ext.gif' } );}); * @desc Fixes all PNG's within div with class examples, provides blank gif for input with png * -------------------------------------------------------------------- */ (function($) { jQuery.fn.pngFix = function(settings) { // Settings settings = jQuery.extend({ blankgif: 'blank.gif' }, settings); var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1); var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1); if (jQuery.browser.msie && (ie55 || ie6)) { //fix images with png-source jQuery(this).find("img[@src$=.png]").each(function() { jQuery(this).attr('width',jQuery(this).width()); jQuery(this).attr('height',jQuery(this).height()); var prevStyle = ''; var strNewHTML = ''; var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : ''; var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : ''; var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : ''; var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : ''; var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : ''; var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : ''; if (this.style.border) { prevStyle += 'border:'+this.style.border+';'; this.style.border = ''; } if (this.style.padding) { prevStyle += 'padding:'+this.style.padding+';'; this.style.padding = ''; } if (this.style.margin) { prevStyle += 'margin:'+this.style.margin+';'; this.style.margin = ''; } var imgStyle = (this.style.cssText); strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt; strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand; strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'; strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');'; strNewHTML += imgStyle+'"></span>'; if (prevStyle != ''){ strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>'; } jQuery(this).hide(); jQuery(this).after(strNewHTML); }); // fix css background pngs jQuery(this).find("*").each(function(){ var bgIMG = jQuery(this).css('background-image'); if(bgIMG.indexOf(".png")!=-1){ var iebg = bgIMG.split('url("')[1].split('")')[0]; jQuery(this).css('background-image', 'none'); jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')"; } }); //fix input with png-source jQuery(this).find("input[@src$=.png]").each(function() { var bgIMG = jQuery(this).attr('src'); jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');'; jQuery(this).attr('src', settings.blankgif) }); } return jQuery; }; })(jQuery);
/*------------------------------------------------------------------------ # Full Name of JSN UniForm # ------------------------------------------------------------------------ # author JoomlaShine.com Team # copyright Copyright (C) 2012 JoomlaShine.com. All Rights Reserved. # Websites: http://www.joomlashine.com # Technical Support: Feedback - http://www.joomlashine.com/contact-us/get-support.html # @license - GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html # @version $Id: forms.js 19013 2012-11-28 04:48:47Z thailv $ -------------------------------------------------------------------------*/ define([ 'jquery', 'uniform/help', 'uniform/dialogedition', 'jquery.ui'], function($, JSNHelp, JSNUniformDialogEdition) { function JSNUniformForms(params) { this.params = params; this.lang = params.language; this.init(); } JSNUniformForms.prototype = { //Create modal box email list select init: function() { this.JSNHelp = new JSNHelp(); var self = this; this.JSNUniformDialogEdition = new JSNUniformDialogEdition(this.params); $(".jsn-popup-upgrade").click(function() { JSNUniformDialogEdition.createDialogLimitation($(this), self.lang["JSN_UNIFORM_YOU_HAVE_REACHED_THE_LIMITATION_OF_3_FORM_IN_FREE_EDITION_0"]); }) } } return JSNUniformForms; });
var InlineDonation = function(){ this.clientToken = document.getElementById('client_token').value; this.setupEvents(); } InlineDonation.prototype.setupEvents = function(){ jQuery(document.body).on('keyup', '#donation-form input', this.clearInvalidEntries); this.setup(); } InlineDonation.prototype.setup = function(){ braintree.setup(this.clientToken, 'dropin',{ container: 'dropin-container', form: 'donation-form', onReady: function(integration){ inlineDonation.integration = integration; }, onPaymentMethodReceived: function(response){ inlineDonation.onPaymentMethodReceived(response); } }) } InlineDonation.prototype.onPaymentMethodReceived = function(response){ inlineDonation.paymentMethodReceived = true; var element = document.getElementById('payment_method_nonce'); if(element != null){ element.value = response.nonce; } else{ element = document.createElement('input'); element.type = 'hidden'; element.name = 'payment_method_nonce'; element.id = 'payment_method_nonce'; element.value = response.nonce; jQuery('#donation-form').append(element); } inlineDonation.validateInputFields(); } InlineDonation.prototype.validateInputFields = function(){ var hasFailures = false; jQuery('#donation-form input').each(function(){ if(jQuery(this).val() === ""){ jQuery(this).parent().find('div.invalid-input-field').show().addClass('active'); hasFailures = true; } }); if(! hasFailures){ inlineDonation.submitPayment(); } } InlineDonation.prototype.submitPayment = function(){ var data = jQuery('#donation-form').serialize(); var url = jQuery('#ajax_url').val(); jQuery('.overlay-payment-processing').addClass('active'); jQuery.ajax({ type:'POST', url: url, dataType: 'json', data: data }).done(function(response){ jQuery('.overlay-payment-processing').removeClass('active'); if(response.result === 'success'){ inlineDonation.redirect(response.url); } else{ inlineDonation.showErrorMessage(response.message); } }).fail(function(response){ jQuery('.overlay-payment-processing').removeClass('active'); inlineDonation.showErrorMessage(response.message); }); } InlineDonation.prototype.redirect = function(url){ window.location.replace(url); } InlineDonation.prototype.showErrorMessage = function(message){ jQuery('#error_messages').html(message); } InlineDonation.prototype.clearInvalidEntries = function(){ jQuery(this).parent().find('div.invalid-input-field').hide().removeClass('active'); } InlineDonation.prototype.clearErrorMessages = function(){ jQuery('#error_messages').empty(); } InlineDonation.prototype.clearInvalidEntries = function(){ jQuery(this).parent().find('div.invalid-input-field').hide().removeClass('active'); } InlineDonation.prototype.displayOverlay = function(callback){ jQuery('#donation_overlay').fadeIn(400, callback); } InlineDonation.prototype.hideOverlay = function(callback){ jQuery('#donation_overlay').fadeOut(400, callback); } var inlineDonation = new InlineDonation();