text
stringlengths
2
6.14k
'use strict'; var menu = angular.module('irc.views.menu', [ 'irc.networks', 'irc.views.menu.directives', ]); menu.controller( 'MenuCtrl', [ '$scope', '$timeout', '$state', 'networks', function MenuCtrl( $scope, $timeout, $state, networks) { $scope.networks = networks; var MainCtrl = $scope.MC; var activeRoom = null; function focus() { if (activeRoom) { activeRoom.focused = false; } activeRoom = MainCtrl.room; if (MainCtrl.room) { MainCtrl.room.focused = true; } if (MainCtrl.channel) { MainCtrl.network.collapsed = false; MainCtrl.channel.unreadCount = 0; } } $scope.$on('$stateChangeSuccess', function() { focus(); }); // Networks this.onNetClick = function(network) { if (!network.online) { network.connect(); $state.go('main.conversation', { network: network.name, channel: null }); return; } if (!network.focused) { $state.go('main.conversation', { network: network.name, channel: null }); } $scope.drawer.open = false; }; this.onNetContext = function(network) { $scope.networkDialog.network = network; $timeout(function() { $scope.networkDialog.open(); }); }; this.onNetworkDialogClosed = function() { $scope.networkDialog.network = null; }; this.onDelete = function() { var network = $scope.networkDialog.network; $scope.networkDialog.close(); $scope.confirmDialog.toBeDeleted = network; $scope.confirmDialog.open(); $scope.confirmDialog.onConfirm = function() { network.delete(); }; }; // Channels this.onChanClick = function(channel) { if (!channel.focused) { $state.go('main.conversation', { network: channel.network.name, channel: channel.name }); } if (channel.network.online) { channel.join(); $scope.drawer.open = false; } else { channel.network.connect().then(function() { channel.join(); $scope.drawer.open = false; }); } }; this.onChanContext = function(channel) { $scope.channelDialog.channel = channel; $scope.channelDialog.open(); }; this.onChannelDialogClosed = function() { $scope.channelDialog.channel = null; }; this.onRemove = function(channel) { channel.delete(); // One additional digest cycle, so it will notice the height change $timeout(); }; }]);
import React from 'react'; // 参照界面,适合选中参照数据 export default class extends React.Component { }
const Clutter = imports.gi.Clutter; const Lang = imports.lang; const ModalDialog = imports.ui.modalDialog; const Signals = imports.signals; const St = imports.gi.St; const Gettext = imports.gettext; const _ = Gettext.domain('gnome-shell-extensions-scriptproxies').gettext; const EditProxyDialog = new Lang.Class({ Name: 'EditProxyDialog', Extends: ModalDialog.ModalDialog, _init: function(callback, action) { this.callback = callback; this.action = action; this.parent({ styleClass: 'prompt-dialog' }); let label, buttons; if (this.action == 'add') { buttons = [{ label: _('Cancel'), action: Lang.bind(this, this._onCancelButton), key: Clutter.Escape }, { label: _('Add proxy'), action: Lang.bind(this, this._addButton) }]; label = new St.Label({ style_class: 'edit-proxy-dialog-label', text: _('Enter the name for the new proxy') }); } else if (this.action == 'edit') { buttons = [{ label: _('Cancel'), action: Lang.bind(this, this._onCancelButton), key: Clutter.Escape }, { label: _('Modify script'), action: Lang.bind(this, this._modifyButton) }, { label: _('Rename'), action: Lang.bind(this, this._renameButton) }]; label = new St.Label({ style_class: 'edit-proxy-dialog-label', text: _('Modify the proxy script.') + '\n' + _('Or rename it (leave blank to remove the proxy).') }); } else { // this should be this.action == 'editor' buttons = [{ label: _('Cancel'), action: Lang.bind(this, this._onCancelButton), key: Clutter.Escape }, { label: _('OK'), action: Lang.bind(this, this._onSetEditorButton) }]; label = new St.Label({ style_class: 'edit-proxy-dialog-label', text: _('To edit your proxy script,') + '\n' + _('please provide the binary name of your text editor.') }); } this.contentLayout.add(label, { y_align: St.Align.START }); let entry = new St.Entry({ style_class: 'edit-proxy-dialog-entry' }); entry.label_actor = label; this._entryText = entry.clutter_text; this.contentLayout.add(entry, { y_align: St.Align.START }); this.setInitialKeyFocus(this._entryText); this.setButtons(buttons); this._entryText.connect('key-press-event', Lang.bind(this, function(o, e) { let symbol = e.get_key_symbol(); if (symbol == Clutter.Return || symbol == Clutter.KP_Enter) { if (this.action == 'add') this._addButton(); else if (this.action == 'edit') this._renameButton(); else this._onSetEditorButton(); } })); }, close: function() { this.parent(); }, _onCancelButton: function() { this.close(); }, _addButton: function() { this.callback(this._entryText.get_text(), 'new'); this.close(); }, _modifyButton: function() { this.callback(this._entryText.get_text(), 'modify'); this.close(); }, _renameButton: function() { this.callback(this._entryText.get_text(), 'rename'); this.close(); }, _onSetEditorButton: function() { this.callback(this._entryText.get_text()); this.close(); }, open: function(initialText) { if (initialText === null) { this._entryText.set_text(''); } else { this._entryText.set_text(initialText); } this.parent(); } }); Signals.addSignalMethods(EditProxyDialog.prototype);
var nodeSass = require('node-sass'), fs = require('fs'); module.exports = class Sass { constructor(config){ this.config = config; if (this.config.compileAtBootup) { this.compile(); } if (this.config.watch) { this.startWatch(); } } get timeTaken(){ return parseInt(process.hrtime(this.timeBegun)[1] / 1000000) + 'ms'; } writeOutputFile(css) { let dst = this.config.arguments.outFile; fs.writeFile(dst, css, (err)=>{ err ? console.warn(this.getFormattedTime(), 'Error writing compiled SASS to outFile:', err) : console.log(this.getFormattedTime(), 'SASS re-compiled in', this.timeTaken); }); } compile() { this.timeBegun = process.hrtime(); nodeSass.render(this.config.arguments, (err, result)=>{ err ? console.warn(this.getFormattedTime(), 'Error compiling SASS:', err) : this.writeOutputFile(result.css.toString()); }); } startWatch() { let throttleId; fs.watch(this.config.arguments.watchFolder, { recursive: true }, (eventType, filename) => { if (throttleId) { clearTimeout(throttleId); } throttleId = setTimeout(() => { throttleId = null; this.compile(); }, 50); }); } getFormattedTime(){ let d = new Date(); return d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds(); } }
import React, { Component } from "react"; import PropTypes from "prop-types"; import classnames from "classnames"; import { Components, registerComponent } from "@reactioncommerce/reaction-components"; class CardHeader extends Component { static defaultProps = { actAsExpander: false, expandable: false }; static propTypes = { actAsExpander: PropTypes.bool, children: PropTypes.node, expandOnSwitchOn: PropTypes.bool, expanded: PropTypes.bool, i18nKeyTitle: PropTypes.string, icon: PropTypes.string, imageView: PropTypes.node, onClick: PropTypes.func, onSwitchChange: PropTypes.func, showSwitch: PropTypes.bool, switchName: PropTypes.string, switchOn: PropTypes.bool, title: PropTypes.string }; handleClick = (event) => { event.preventDefault(); if (typeof this.props.onClick === "function") { this.props.onClick(event); } } handleSwitchChange = (event, isChecked, name) => { if (this.props.expandOnSwitchOn && this.props.actAsExpander && this.props.expanded === false && isChecked === true) { this.handleClick(event); } if (typeof this.props.onSwitchChange === "function") { this.props.onSwitchChange(event, isChecked, name); } } renderTitle() { if (this.props.title) { return ( <Components.CardTitle i18nKeyTitle={this.props.i18nKeyTitle} title={this.props.title} /> ); } return null; } renderImage() { if (this.props.icon) { return ( <div className="image"> <Components.Icon icon={this.props.icon} /> </div> ); } if (this.props.imageView) { return ( <div className="image"> {this.props.imageView} </div> ); } return null; } renderDisclsoureArrow() { const expanderClassName = classnames({ rui: true, expander: true, open: this.props.expanded }); return ( <div className={expanderClassName}> <Components.IconButton icon="fa fa-angle-down" bezelStyle="outline" style={{ borderColor: "#dddddd" }} onClick={this.handleClick} /> </div> ); } renderChildren() { if (this.props.showSwitch) { return ( <Components.Switch checked={this.props.switchOn} name={this.props.switchName} onChange={this.handleSwitchChange} /> ); } return this.props.children; } render() { const baseClassName = classnames({ "rui": true, "panel-heading": true, "card-header": true, "expandable": this.props.actAsExpander }); if (this.props.actAsExpander) { return ( <div className={baseClassName}> <div className="content-view" onClick={this.handleClick}> {this.renderImage()} {this.renderTitle()} </div> <div className="action-view"> {this.renderChildren()} </div> {this.renderDisclsoureArrow()} </div> ); } return ( <div className={baseClassName}> <div className="content-view"> {this.renderTitle()} </div> <div className="action-view"> {this.props.children} </div> </div> ); } } registerComponent("CardHeader", CardHeader); export default CardHeader;
/** * Created by levchenko on 5/12/14. */ function Style(styles) { this.styles = styles; this.applyStyles = function (object) { for(var key in this.styles) { if(this.getStyleProperty(key) === false) { object.setAttribute('style', object.getAttribute('style') + key + ':' + this.styles[key] + ';'); } else { object.style[this.getStyleProperty(key)] = this.styles[key]; } } }; this.getStyleProperty = function (cssProperty) { var jsProperty = ''; var partOfProperty = cssProperty.split('-'); if(cssProperty.charAt(0) == '-') { return false; } for(var key = 0; key<partOfProperty.length; key++) { if(key == 0) { jsProperty = partOfProperty[key]; continue; } jsProperty += partOfProperty[key].charAt(0).toUpperCase() + partOfProperty[key].substr(1, partOfProperty[key].length-1);; } return jsProperty; } } Element.prototype.css = function (options) { var style = (options instanceof Style) ? options : new Style(options); style.applyStyles(this); return style; }
var db = require('../db'); var User = db.model('User', { username: { type: String, required: true }, email: { type: String, required: true }, password: { type: String, required: true, select: false }, created: { type: Date, default: Date.now }, color: { type: String }, active: { type: Boolean, default: true, select: false }, scores: [], resetToken: { type: String }, resetTokenValid: { type: Date } }); module.exports = User;
(function (angular) { angular.module("rmApp", ["ui.router", "rmApp.templates", "rmApp.controllers"]) .config(["$stateProvider", "$urlRouterProvider", "$locationProvider", function ($stateProvider, $urlRouterProvider, $locationProvider) { $urlRouterProvider.otherwise("/"); $locationProvider.html5Mode(false); // $stateProvider .state("index", { url: "/", templateUrl: "index.tpl.html", controller: "rmCtrl" }) .state("home", { url: "/home", templateUrl: "home.tpl.html", controller: "rmCtrl" }).state("about", { url: "/about", templateUrl: "about.tpl.html", controller: "rmCtrl" }).state("contact", { url: "/contact", templateUrl: "contact.tpl.html", controller: "rmCtrl" }).state("spinner1", { url: "/spinner1", templateUrl: "spinner1.tpl.html", controller: "rmCtrl" }).state("spinner2", { url: "/spinner2", templateUrl: "spinner2.tpl.html", controller: "rmCtrl" }); }]); })(angular);
/** * */ var $info = false; function LoadServerStats() { $.getJSON("phpsysinfo/xml.php?plugin=complete&json", function (data) { $info = data; updateCPU($info.Vitals["@attributes"].LoadAvg, $info.Vitals["@attributes"].Processes); updateRAM($info.Memory["@attributes"].Percent); updateHDD($info.FileSystem.Mount[0]["@attributes"].Percent); /** OTHER INFO **/ updateIP($info.Network.NetDevice); updateUptime($info.Vitals["@attributes"].Uptime); updateUSB($info.Hardware.USB.Device); }); setTimeout(LoadServerStats, 10000); } function updateUSB(devices) { var $html = ""; $.each(devices, function (i, val) { $html += '<div class="row"><span class="value">' + val['@attributes'].Name + '</span></div>'; }); $('.other-info-stats .usb-devices .usb-list').html($html); } function updateUptime(value) { var d = new Date(0, 0, 0, 0, 0, value); var s = d.getSeconds(); var m = d.getMinutes(); var h = d.getHours(); var D = d.getDate(); var M = d.getMonth(); var Y = d.getYear(); var formated = ''; if (Y > 0) formated += ' ' + Y + 'Y' if (M > 0) formated += ' ' + M + 'M' if (D > 0) formated += ' ' + D + 'D' if (h > 0) formated += ' ' + h + 'h' if (m > 0) formated += ' ' + m + 'm' if (s > 0) formated += ' ' + s + 's' $('.other-info-stats .uptime span.value').html(formated); } function updateIP(value) { var ipadd = "" if ($.isArray(value)) { $.each(value, function (i, val) { var list = val['@attributes'].Info; var arr = list.split(';'); ipadd += ' ' + arr[1]; }); } else { var list = value['@attributes'].Info; var arr = list.split(';'); ipadd += ' ' + arr[1]; } $('.other-info-stats .ip-address span.value').html(ipadd); } function updateHDD(value) { $('.usage .disk .progress-bar').css('width', value + '%'); $('.usage .disk .progress-bar span.value').html(value + '%'); } function updateRAM(value) { $('.ram.chart').data('easyPieChart').update(Math.round(value)); } function updateCPU(loadavg, processesCount) { var data = loadavg; var arr = data.split(' '); var $value = (arr[0] / processesCount) * 100; $('.cpu.chart').data('easyPieChart').update(Math.round($value)); }
import React from "react"; import PropTypes from "prop-types"; import styled from "@emotion/styled"; import { insertEmbeddedImages } from "../../../utils/embedded-images"; const RichTextareaFieldResponseWrapper = styled("div")(props => ({ // TODO: fluid video lineHeight: "1.3rem", "& img": { maxWidth: "100%", margin: "16px 0 0 0", }, "& ul": { marginTop: 0, marginBottom: "16px", fontWeight: "normal", }, "& p": { fontFamily: props.theme.text.bodyFontFamily, marginTop: 0, marginBottom: "16px", fontWeight: "normal", }, "& li": { fontFamily: props.theme.text.bodyFontFamily, fontWeight: "normal", }, "& a": { textDectoration: "none", fontWeight: "normal", }, "& h1,h2,h3,h4,h5,h6": { fontFamily: props.theme.text.titleFontFamily, margin: "16px 0 8px 0", }, })); const RichTextareaFieldResponse = props => { return ( <RichTextareaFieldResponseWrapper> <div className="rich-textarea-field-response" dangerouslySetInnerHTML={{ __html: insertEmbeddedImages(props.value, props.attachments), }} /> </RichTextareaFieldResponseWrapper> ); }; RichTextareaFieldResponse.propTypes = { attachments: PropTypes.array, value: PropTypes.string.isRequired, }; export default RichTextareaFieldResponse;
/** * A script for handling the bootstrap switch on the resume page. */ // Import css. require("bootstrap-switch/dist/css/bootstrap3/bootstrap-switch.min.css"); require('bootstrap-switch'); $("[name='my-checkbox']").bootstrapSwitch(); // http://www.bootstrap-switch.org/events.html $('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch', function(event, state) { var img = document.getElementById("resume-image"); var pdf_link = document.getElementById('pdf_link'); if (state) { img.src = "/Content/Resume/resume.png"; // Changes the download link. pdf_link.href = "/Content/Resume/resume.pdf"; pdf_link.download = 'MattGaikemaResume'; } else { img.src = "/Content/Resume/cv.png"; pdf_link.href = "/Content/Resume/cv.pdf"; pdf_link.download = 'MattGaikemaCV'; } });
/* * Copyright (C) 2016-2021 phantombot.github.io/PhantomBot * * 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 3 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, see <http://www.gnu.org/licenses/>. */ /** * lang.js * * Provide a language API * Use the $.lang API * * NOTE: Reading from/writing to the lang data directly is not possbile anymore! * Use the register(), exists() and get() functions! */ (function() { var data = [], curLang = ($.inidb.exists('settings', 'lang') ? $.inidb.get('settings', 'lang') : 'english'); /** * @function load */ function load(force) { $.bot.loadScriptRecursive('./lang/english', true, (force ? force : false)); if (curLang != 'english') { $.bot.loadScriptRecursive('./lang/' + curLang, true, (force ? force : false)); } if ($.isDirectory('./scripts/lang/custom')) { $.bot.loadScriptRecursive('./lang/custom', true, (force ? force : false)); } // Set "response_@chat" to true if it hasn't been set yet, so the bot isn't muted when using a fresh install if (!$.inidb.exists('settings', 'response_@chat')) { $.setIniDbBoolean('settings', 'response_@chat', true); } } /** * @function register * @export $.lang * @param {string} key * @param {string} string */ function register(key, string) { if (key && string) { data[key.toLowerCase()] = string; } if (key && string.length === 0) { data[key.toLowerCase()] = '<<EMPTY_PLACEHOLDER>>'; } } /** * @function get * @export $.lang * @param {string} key * @returns {string} */ function get(key) { var string = data[key.toLowerCase()], i; if (string === undefined) { $.log.warn('Lang string for key "' + key + '" was not found.'); return ''; } if (string == '<<EMPTY_PLACEHOLDER>>') { return ''; } for (i = 1; i < arguments.length; i++) { while (string.indexOf("$" + i) >= 0) { string = string.replace("$" + i, arguments[i]); } } return string; } /** * @function paramCount * @export $.lang * @param {string} key * @returns {Number} */ function paramCount(key) { var string = data[key.toLowerCase()], i, ctr = 0; if (!string) { return 0; } for (i = 1; i < 99; i++) { if (string.indexOf("$" + i) >= 0) { ctr++; } else { break; } } return ctr; } /** * @function exists * @export $.lang * @param {string} key * @returns {boolean} */ function exists(key) { return (data[key.toLowerCase()]); } /** * @event command */ $.bind('command', function(event) { var sender = event.getSender().toLowerCase(), command = event.getCommand(), args = event.getArgs(), action = args[0], inversedState; /** * @commandpath lang [language name] - Get or optionally set the current language (use folder name from "./lang" directory); */ if (command.equalsIgnoreCase('lang')) { if (!action) { $.say($.whisperPrefix(sender) + get('lang.curlang', curLang)); } else { action = action.toLowerCase(); if (!$.fileExists('./scripts/lang/' + action + '/main.js')) { $.say($.whisperPrefix(sender) + get('lang.lang.404')); } else { $.inidb.set('settings', 'lang', action); curLang = action; load(true); $.say($.whisperPrefix(sender) + get('lang.lang.changed', action)); } } } /** * @commandpath mute - Toggle muting the bot in the chat */ if (command.equalsIgnoreCase('mute')) { inversedState = !$.getIniDbBoolean('settings', 'response_@chat'); $.setIniDbBoolean('settings', 'response_@chat', inversedState); $.reloadMisc(); $.say($.whisperPrefix(sender) + (inversedState ? get('lang.response.enabled') : get('lang.response.disabled'))); } /** * @commandpath toggleme - Toggle prepending chat output with "/me". */ if (command.equalsIgnoreCase('toggleme')) { inversedState = !$.getIniDbBoolean('settings', 'response_action'); $.setIniDbBoolean('settings', 'response_action', inversedState); $.reloadMisc(); $.say($.whisperPrefix(sender) + (inversedState ? get('lang.response.action.enabled') : get('lang.response.action.disabled'))); } }); /** * @event initReady */ $.bind('initReady', function() { $.registerChatCommand('./core/lang.js', 'lang', 1); $.registerChatCommand('./core/lang.js', 'mute', 1); $.registerChatCommand('./core/lang.js', 'toggleme', 1); }); /** Export functions to API */ $.lang = { exists: exists, get: get, register: register, paramCount: paramCount }; // Run the load function to enable modules, loaded after lang.js, to access the language strings immediatly load(); })();
(function (root, factory) { if (typeof module === 'object' && module.exports) { module.exports = factory(require('jquery'), require('../common/utility')); } else { root.api = factory(root.jQuery, root.utility); } }(this, function ($, util) { // API var self = {}; // Object -> Promise[[Entity]] self.searchEntity = function(query){ return get('/search/entity', { num: 10, q: query }) .then(format) .catch(handleError); // [Entity] -> [Entity] function format(results){ // stringify id & rename keys (`primary_type` -> `primary_ext`; `description` -> `blurb`) return results.map(function(result) { var _result = Object.assign({}, result, { primary_ext: result.primary_ext || result.primary_type, blurb: result.blurb || result.description, id: String(result.id) }); delete _result.primary_type; delete _result.description; return _result; }); } // Error -> [] function handleError(err){ console.error('API request error: ', err); return []; } }; // [EntityWithoutId] -> Promise[[Entity]] self.createEntities = function(entities){ return post('/entities/bulk', formatReq(entities)) .then(formatResp); // [Entity] -> [Entity] function formatReq(entities){ return { data: entities.map(function(entity){ return { type: "entities", attributes: entity }; }) }; }; // [Entity] -> [Entity] function formatResp(resp){ // copy, but stringify id return resp.data.map(function(datum){ return Object.assign( datum.attributes, { id: String(datum.attributes.id)} ); }); } }; // Integer, [Integer] -> Promise[[ListEntity]] self.addEntitiesToList = function(listId, entityIds, reference){ return post('/lists/'+listId+'/entities/bulk', formatReq(entityIds)) .then(formatResp); function formatReq(entityIds){ return { data: entityIds.map(function(id){ return { type: 'entities', id: id }; }).concat({ type: 'references', attributes: reference }) }; }; function formatResp(resp){ return resp.data.map(function(datum){ return util.stringifyValues(datum.attributes); }); } }; // String, Integer -> Promise // helpers function get(url, queryParams){ return fetch(url + qs(queryParams), { headers: headers(), method: 'get', credentials: 'include' // use auth tokens stored in session cookies }).then(jsonify); } function post(url, payload){ return fetch(url, { headers: headers(), method: 'post', credentials: 'include', // use auth tokens stored in session cookies body: JSON.stringify(payload) }).then(jsonify); }; function patch(url, payload){ return fetch(url, { headers: headers(), method: 'PATCH', credentials: 'include', // use auth tokens stored in session cookies body: JSON.stringify(payload) }).then(function(response) { if (response.body) { return jsonify(response); } else { return response; } }); }; function headers(){ return { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'Littlesis-Request-Type': 'API', // TODO: retrieve this w/o JQuery 'X-CSRF-Token': $("meta[name='csrf-token']").attr("content") || "" }; } function qs(queryParams){ return '?' + $.param(queryParams); } // Response -> Promise[Error|JSON] function jsonify(response){ return response .json() .then(function(json){ return json.errors ? Promise.reject(json.errors[0].title) : Promise.resolve(json); }); } return self; }));
import VK from 'VK'; import { VK_API_VERSION } from '../constants'; /** * Fetch friends. * @param {Object} options * @return {Promise<Object>} */ export function fetchFriends(options = {}) { const mergedOptions = { ...options, order: 'hints', fields: 'photo_100', v: VK_API_VERSION, }; return new Promise((resolve, reject) => { VK.api('friends.get', mergedOptions, response => { if (response.response) resolve(response.response); else reject(response.error); }); }); }
var repl = repl || {}; repl.prompt = "> "; repl.cont = "+\t"; repl.command = {}; load(":/resources/core.js"); soft_version = "SOFT v" + version() + " "; soft_license = "GNU LESSER GENERAL PUBLIC LICENSE (v 2.1, February 1999)"; function showHelp() { var message = soft_version + "(" + soft_license + ")\n\n" + "Welcome to Soft Shell\n" + "Shell commands:\n" + ":h This message\n"+ ":ld <file> Load and evaluate file <file>\n" + ":chk <file> Checks the syntax of the program <file>\n" + ":q Quit the shell\n\n"; print (message); } function quit() { repl.exit = true; print ("Bye"); } repl.command['q'] = quit; repl.command['quit'] = quit; repl.command['ld'] = load; repl.command['chk'] = checkSyntax; repl.command['h'] = showHelp; repl.command['help'] = showHelp; function parseCommand(cmd) { if( cmd != undefined ) { var command = cmd[1]; if( command !== undefined && repl.command[command] !== undefined) { repl.command[command](cmd[2]); return true; } else { print("Unknown command " + command); } } return undefined; } function mainrepl() { var s = ""; while(repl.exit === undefined) { try { if( s.length == 0 ) writeline(repl.prompt); s += readline(); cmd = s.match(/^[\:]([a-zA-Z]*)\s?(\S*)/); if( cmd != undefined ) { s = ""; parseCommand(cmd); } else { if( s.trim().length == 0 ) continue; if( isIncompleteSyntax(s) || s[s.length-1] == '\\' ) { if(s[s.length-1] == '\\') { s = s.substring(0,s.length-1); } writeline(repl.cont); } else { ret = eval(s); s = ""; if(!isQObject(ret) && isObject(ret)) { print(JSON.stringify(ret, null, 2)); } else if( ret != undefined) print(ret); else print('undefined'); } } } catch (err) { if (isIncompleteSyntax(s)) continue; print (err); s = ""; } } } function __main__() { var message = soft_version + "(" + soft_license + ")\n\n" + "For help, type :help\n"; print(message); mainrepl(); return 0; }
import { Meteor } from 'meteor/meteor'; import '../images.js'; import { Devs } from '../../devs/devs.js'; import { Teams } from '../../teams/teams.js'; import { Visitors } from '../../visitors/visitors.js'; import { Sponsors } from '../../sponsors/sponsors.js'; Meteor.publish('profile.image', function(id){ let d = Devs.findOne({"user":id}); //console.log(Images.findOne({"_id":d.picture})); return Images.find({"_id":d.picture}).cursor; }); Meteor.publish('profile.image.user', function(username){ let u = Meteor.users.findOne({"username":username}); let d = Devs.findOne({"user":u._id}); return Images.find({"_id":d.picture}).cursor; }); Meteor.publish('profile.image.team', function(id){ let t = Teams.findOne({'_id':id}); if ( t !== undefined ) { let list = []; let c = Devs.findOne({"user":t.captain}); list.push(c.picture); t.members.forEach(function(m){ let d = Devs.findOne({"user":m}); if ( d.picture != undefined ) list.push(d.picture); }); return Images.find({'_id':{ $in : list }}).cursor; } }); Meteor.publish('visitor.image', function(){ let d = Visitors.findOne({"user":this.userId}); if ( d !== undefined ) return Images.find({"_id":d.picture}).cursor; }); Meteor.publish('sponsors.members.image', function(name){ let s = Sponsors.findOne({'short':name}); if ( s !== undefined ) { let list = []; s.members.forEach(function(m){ let v = Visitors.findOne({"user":m}); if ( v.picture !== undefined ) list.push(v.picture); }); return Images.find({'_id':{ $in : list }}).cursor; } }); Meteor.publish('sponsors.single.image', function(name){ let s = Sponsors.findOne({"short":name}); if ( s !== undefined ) return Images.find({"_id":s.picture}).cursor; }); Meteor.publish('sponsor.image', function(){ let v = Visitors.findOne({"user":this.userId}); if ( v !== undefined ) { let s = Sponsors.findOne({"short":v.company}); if ( s !== undefined ) return Images.find({"_id":s.picture}).cursor; } }); Meteor.publish('alldevs.image', function(){ let d = Devs.find({"picture":{"$exists":true}}); if ( d !== undefined ) { //console.log(d); let list = []; d.forEach(function(m){ list.push(m.picture); }); return Images.find({'_id':{ $in : list }}).cursor; //return Images.find({}).cursor; } }); //Admin Use Meteor.publish('files.images.all', function () { return Images.find().cursor; });
import React from 'react'; import { shallow, mount } from 'enzyme'; import Tabs from '../components/layout/Tabs'; describe('Tabs render with different props', () => { const tabs = [ { label: 'Přihlášení', render: () => {} }, { label: 'Registrace', render: () => {} } ]; it('renders without crashing', () => { expect( shallow(<Tabs tabs={tabs} />).length ).toEqual(1); }); it('contains exactly two tabs', () => { const wrapper = mount(<Tabs tabs={tabs} />); expect(wrapper.render().find('li').length).toEqual(2); }); it('contains correct labels in tabs', () => { const wrapper = mount(<Tabs tabs={tabs} />); expect(wrapper.find('li').at(0).text()).toEqual(tabs[0].label); expect(wrapper.find('li').at(1).text()).toEqual(tabs[1].label); }); });
var fs = require('fs'); const readline = require('readline'); Lexer = require("./Lexer.js") const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('File name please. ', (answer) => { var data = fs.readFileSync(answer, 'utf8'); console.log("Got", answer, "->", data) var test = new Lexer(data) console.log(test) test.lex() console.log("Lexed!") console.log(test.tokens) rl.close(); });
/* jshint -W117 */ /* Copyright 2016 Herko ter Horst __________________________________________________________________________ Filename: _videoplayerApp.js __________________________________________________________________________ */ log.addSrcFile("_videoplayerApp.js", "_videoplayer"); function _videoplayerApp(uiaId) { log.debug("Constructor called."); // Base application functionality is provided in a common location via this call to baseApp.init(). // See framework/js/BaseApp.js for details. baseApp.init(this, uiaId); } // load jQuery Globally (if needed) if (!window.jQuery) { utility.loadScript("addon-common/jquery.min.js"); } /********************************* * App Init is standard function * * called by framework * *********************************/ /* * Called just after the app is instantiated by framework. * All variables local to this app should be declared in this function */ _videoplayerApp.prototype.appInit = function() { log.debug("_videoplayerApp appInit called..."); // These values need to persist through videoplayer instances this.hold = false; this.resumePlay = 0; this.musicIsPaused = false; this.savedVideoList = null; this.resumeVideo = JSON.parse(localStorage.getItem('videoplayer.resumevideo')) || true; // resume is now checked by default this.currentVideoTrack = JSON.parse(localStorage.getItem('videoplayer.currentvideo')) || null; //this.resumePlay = JSON.parse(localStorage.getItem('videoplayer.resume')) || 0; //Context table //@formatter:off this._contextTable = { "Start": { // initial context must be called "Start" "sbName": "Video Player", "template": "VideoPlayerTmplt", "templatePath": "apps/_videoplayer/templates/VideoPlayer", //only needed for app-specific templates "readyFunction": this._StartContextReady.bind(this), "contextOutFunction": this._StartContextOut.bind(this), "noLongerDisplayedFunction": this._noLongerDisplayed.bind(this) } // end of "VideoPlayer" }; // end of this.contextTable object //@formatter:on //@formatter:off this._messageTable = { // haven't yet been able to receive messages from MMUI }; //@formatter:on framework.transitionsObj._genObj._TEMPLATE_CATEGORIES_TABLE.VideoPlayerTmplt = "Detail with UMP"; }; /** * ========================= * CONTEXT CALLBACKS * ========================= */ _videoplayerApp.prototype._StartContextReady = function() { framework.common.setSbDomainIcon("apps/_videoplayer/templates/VideoPlayer/images/icon.png"); }; _videoplayerApp.prototype._StartContextOut = function() { CloseVideoFrame(); framework.common.setSbName(''); }; _videoplayerApp.prototype._noLongerDisplayed = function() { // Stop and close video frame CloseVideoFrame(); // If we are in reverse then save CurrentVideoPlayTime to resume the video where we left of if (framework.getCurrentApp() === 'backupparking'|| framework.getCurrentApp() === 'phone' || (ResumePlay && CurrentVideoPlayTime !== null)) { this.resumePlay = this.resumePlay || CurrentVideoPlayTime; CurrentVideoPlayTime = 0; //localStorage.setItem('videoplayer.resume', JSON.stringify(CurrentVideoPlayTime)); } // If we press the 'Entertainment' button we will be running this in the 'usbaudio' context if (!this.musicIsPaused) { setTimeout(function() { if (framework.getCurrentApp() === 'usbaudio') { framework.sendEventToMmui('Common', 'Global.Pause'); framework.sendEventToMmui('Common', 'Global.GoBack'); this.musicIsPaused = true; // Only run this once } }, 100); } }; /** * ========================= * Framework register * Tell framework this .js file has finished loading * ========================= */ framework.registerAppLoaded("_videoplayer", null, false);
import { Link, LocationProvider } from '@reach/router'; import router from '@elementor/router'; import { arrayToClassName } from 'elementor-app/utils/utils.js'; import './inline-link.scss'; export default function InlineLink( props ) { const baseClassName = 'eps-inline-link', colorClassName = `${ baseClassName }--color-${ props.color }`, underlineClassName = 'none' !== props.underline ? `${ baseClassName }--underline-${ props.underline }` : '', italicClassName = props.italic ? `${ baseClassName }--italic` : '', classes = [ baseClassName, colorClassName, underlineClassName, italicClassName, props.className, ], className = arrayToClassName( classes ), getRouterLink = () => ( <LocationProvider history={ router.appHistory }> <Link to={ props.url } className={ className } > { props.children } </Link> </LocationProvider> ), getExternalLink = () => ( <a href={ props.url } target={ props.target } rel={ props.rel } className={ className } > { props.children } </a> ); return props.url.includes( 'http' ) ? getExternalLink() : getRouterLink(); } InlineLink.propTypes = { className: PropTypes.string, children: PropTypes.string, url: PropTypes.string, target: PropTypes.string, rel: PropTypes.string, text: PropTypes.string, color: PropTypes.oneOf( [ 'primary', 'secondary', 'cta', 'link', 'disabled' ] ), underline: PropTypes.oneOf( [ 'none', 'hover', 'always' ] ), italic: PropTypes.bool, }; InlineLink.defaultProps = { className: '', color: 'link', underline: 'always', target: '_blank', rel: 'noopener noreferrer', };
/// <reference path="windowbutton/battlelog.windowbutton.js" /> /// <reference path="playbar/battlelog.bf3.playbar.js" /> /// <reference path="dialog/battlelog.bf3.dialog.js" /> /// <reference path="stats/battlelog.bf3.stats.js" /> var baseurl = 'http://battlelogium.github.io/Battlelogium/Battlelogium.Core/Javascript'; function injectOnce() { if (document.getElementById('_windowbutton') == null) { injectScript('_windowbutton', baseurl+'/windowbutton/battlelog.windowbutton.min.js'); } if (document.getElementById('css_windowbutton') == null) { injectCSS('css_windowbutton', baseurl + '/windowbutton/battlelog.windowbutton.min.css'); } if (document.getElementById('css_misc') == null) { injectCSS('css_misc', baseurl + '/misc/battlelog.misc.min.css'); } if (document.getElementById('_battlelogplaybar') == null) { injectScript('_battlelogplaybar', baseurl + '/playbar/battlelog.mohw.playbar.min.js'); } if (document.getElementById('_battlelogstats') == null) { injectScript('_battlelogstats', baseurl + '/stats/battlelog.mohw.stats.min.js'); } if (document.getElementById('_battlelogsettings') == null) { injectScript('_battlelogsettings', baseurl + '/settings/battlelog.mohw.settings.min.js'); } } function runCustomJS() { try { battlelogplaybar.fixQuickMatchButtons(); windowbutton.addWindowButtons(); windowbutton.updateMaximizeButton(); battlelogplaybar.fixEAPlaybarButtons(); battlelogplaybar.addPlaybarButton(battlelogplaybar.createPlaybarButton('btnServers', 'SERVERS', 'location.href = "http://battlelog.battlefield.com/mohw/servers/"')); $("#base-header-secondary-nav>ul>li>a:contains('Buy Battlefield 4')").remove(); } catch (error) { } if (window.location.href.match(/\/soldier\//) != null) { battlelogstats.overview(); } if (window.location.href == 'http://battlelog.battlefield.com/mohw/profile/edit/') { battlelogsettings.addSettingsSection(); } } function injectScript(id, url) { var script = document.createElement('script'); script.setAttribute('src', url); script.setAttribute('id', id); document.getElementsByTagName('head')[0].appendChild(script); } function injectCSS(id, url) { var script = document.createElement('link'); script.setAttribute('rel', 'stylesheet'); script.setAttribute('type', 'text/css'); script.setAttribute('href', url); script.setAttribute('id', id); document.getElementsByTagName('head')[0].appendChild(script); } injectOnce();
/** * Created by gjrwcs on 10/25/2016. */ 'use strict'; /** * Game Behavior and Logic for Warp * @module pulsar.warp */ var warp = require('angular').module('pulsar.warp', []); const ADT = require('../app.dependency-tree.js').ADT; ADT.warp = { Level: 'warp.Level', WarpField: 'warp.WarpField', Bar: 'warp.Bar', State: 'warp.State', }; require('./bar.factory'); require('./game.controller'); require('./hud.directive'); require('./level-loader.svc'); require('./level.svc'); require('./scoring.svc'); require('./ship.svc'); require('./ship-effects.svc'); require('./warp-field.factory'); require('./warp-field-cache.svc'); require('./warp-field-draw.svc'); require('./state.svc'); module.exports = warp;
/* Copyright (c) 2012 Richard Klancer <rpk@pobox.com> 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. */ /*global $ console */ var x = 0, y = 0, intervalID, INTERVAL_LENGTH = 200; // ms // define console as a noop if not defined if (typeof console === 'undefined') console = { log: function() {} }; function postJoystickPosition() { $.post('/joystick', { x: x, y: y }); } function startSending() { intervalID = setInterval(postJoystickPosition, INTERVAL_LENGTH); } function stopSending() { // one last time postJoystickPosition(); clearInterval(intervalID); } // draws "joystick", updates x and y function joystickGo() { // Just do the dead simplest thing right now -- we have one draggable element, and no encapsulation var dragInfo = {}, centerX, centerY, radialLimit, radialLimitSquared; function updatePosition(_x, _y) { x = _x / radialLimit; y = - _y / radialLimit; console.log(x,y); } function centerKnob() { var $el = $(dragInfo.element), width = $('#background').width(); $el.animate({ left: width/2, top: width/2 }, 200); updatePosition(0, 0); } function dragStart(evt) { dragInfo.dragging = true; evt.preventDefault(); var $el = $(dragInfo.element), offset = $el.offset(), width = $el.width(), cx = offset.left + width/2 - centerX, cy = offset.top + width/2 - centerY; dragInfo.dx = evt.pageX - cx; dragInfo.dy = evt.pageY - cy; startSending(); } function drag(evt) { if ( ! dragInfo.dragging ) return; evt.preventDefault(); var $el = $(dragInfo.element), offset = $el.offset(), width = $el.width(), // find the current center of the element cx = offset.left + width/2 - centerX, cy = offset.top + width/2 - centerY, newcx = evt.pageX - dragInfo.dx, newcy = evt.pageY - dragInfo.dy, newRadiusSquared = newcx*newcx + newcy*newcy, scale; if (newRadiusSquared > radialLimitSquared) { scale = Math.sqrt( radialLimitSquared / newRadiusSquared ); newcx *= scale; newcy *= scale; } updatePosition(newcx, newcy); offset.left += (newcx - cx); offset.top += (newcy - cy); $(dragInfo.element).offset(offset); } function dragEnd() { dragInfo.dragging = false; centerKnob(); stopSending(); } function adjustDimensions() { var $background = $('#background'), $knob = $('#knob'), offset = $background.offset(), width = $background.width(); makeCircular($background); makeCircular($knob); centerX = width/2 + offset.left; centerY = width/2 + offset.top; radialLimit = (width - $knob.width()) / 2; radialLimitSquared = radialLimit * radialLimit; } function makeCircular($el) { var width = $el.width(); // Android 2 browser doesn't seem to understand percentage border-radius, so we need to set it // via an inline style once we know the width $el.css({ height: width, borderRadius: width/2 }); } function wrapForTouch(f) { return function(evt) { if (evt.originalEvent && evt.originalEvent.touches && evt.originalEvent.touches.length === 1) { evt.pageX = evt.originalEvent.touches[0].pageX; evt.pageY = evt.originalEvent.touches[0].pageY; } return f(evt); }; } $(function() { var $background = $('#background'), $knob = $('#knob'); adjustDimensions(); dragInfo.element = $knob[0]; $knob.bind('touchstart mousedown', wrapForTouch(dragStart)); $(document).bind('touchmove mousemove', wrapForTouch(drag)); $(document).bind('touchend mouseup', wrapForTouch(dragEnd)); $background.bind('mousedown', function() { return false; }); $(window).bind('resize', adjustDimensions); }); } // and...go: joystickGo();
/** * This file is part of "PCPIN Chat 6". * * "PCPIN Chat 6" is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * "PCPIN Chat 6" 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, see <http://www.gnu.org/licenses/>. */ /** * Callback function to execute after confirm box receives "OK". */ var confirmboxCallback=''; /** * Display confirm box * @param string $text Text to display * @param int top_offset Optional. How many pixels to add to the top position. Can be negative or positive. * @param int left_offset Optional. How many pixels to add to the left position. Can be negative or positive. * @param string callback Optional. Callback function to execute after confirm box receives "OK". */ function confirm(text, top_offset, left_offset, callback) { if (typeof(text)!='undefined' && typeof(text)!='string') { try { text=text.toString(); } catch (e) {} } if (typeof(text)=='string') { document.onkeyup_confirmbox=document.onkeyup; document.onkeyup=function(e) { switch (getKC(e)) { case 27: hideConfirmBox(false); break; } }; if (typeof(top_offset)!='number') top_offset=0; if (typeof(left_offset)!='number') left_offset=0; $('confirmbox_text').innerHTML=nl2br(htmlspecialchars(text)); $('confirmbox').style.display=''; $('confirmbox_btn_ok').focus(); setTimeout("moveToCenter($('confirmbox'), "+top_offset+", "+left_offset+"); $('confirmbox_btn_ok').focus();", 25); if (typeof(callback)=='string') { confirmboxCallback=callback; } else { confirmboxCallback=''; } setTimeout("$('confirmbox').style.display='none'; $('confirmbox').style.display='';", 200); } } /** * Hide confirm box @param boolean ok TRUE, if "OK" button was clicked */ function hideConfirmBox(ok) { document.onkeyup=document.onkeyup_confirmbox; $('confirmbox').style.display='none'; if (typeof(ok)=='boolean' && ok && confirmboxCallback!='') { eval('try { '+confirmboxCallback+' } catch(e) {}'); } }
function processData(allText) { var allTextLines = allText.split(/\r\n|\n/); var headers = allTextLines[0].split(','); var lines = []; for (var i=1; i<allTextLines.length; i++) { var data = allTextLines[i].split(','); if (data.length == headers.length) { var tarr = []; for (var j=0; j<headers.length; j++) { tarr.push(headers[j]+":"+data[j]); } lines.push(tarr); } } console.log(lines); } csv = "heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2" $(document).ready(function() { $.ajax({ type: "POST", url: "/echo/html/", dataType: "text", data: { html: csv }, success: function(data) { processData(data); } }); });
define(["exports"], function (_exports) { "use strict"; Object.defineProperty(_exports, "__esModule", { value: true }); _exports.phpLang = phpLang; function phpLang(hljs) { var VARIABLE = { begin: "\\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*" }; var PREPROCESSOR = { className: "meta", begin: /<\?(php)?|\?>/ }; var STRING = { className: "string", contains: [hljs.BACKSLASH_ESCAPE, PREPROCESSOR], variants: [{ begin: 'b"', end: '"' }, { begin: "b'", end: "'" }, hljs.inherit(hljs.APOS_STRING_MODE, { illegal: null }), hljs.inherit(hljs.QUOTE_STRING_MODE, { illegal: null })] }; var NUMBER = { variants: [hljs.BINARY_NUMBER_MODE, hljs.C_NUMBER_MODE] }; return { aliases: ["php", "php3", "php4", "php5", "php6", "php7"], case_insensitive: true, keywords: "and include_once list abstract global private echo interface as static endswitch " + "array null if endwhile or const for endforeach self var while isset public " + "protected exit foreach throw elseif include __FILE__ empty require_once do xor " + "return parent clone use __CLASS__ __LINE__ else break print eval new " + "catch __METHOD__ case exception default die require __FUNCTION__ " + "enddeclare final try switch continue endfor endif declare unset true false " + "trait goto instanceof insteadof __DIR__ __NAMESPACE__ " + "yield finally", contains: [hljs.HASH_COMMENT_MODE, hljs.COMMENT("//", "$", { contains: [PREPROCESSOR] }), hljs.COMMENT("/\\*", "\\*/", { contains: [{ className: "doctag", begin: "@[A-Za-z]+" }] }), hljs.COMMENT("__halt_compiler.+?;", false, { endsWithParent: true, keywords: "__halt_compiler", lexemes: hljs.UNDERSCORE_IDENT_RE }), { className: "string", begin: /<<<['"]?\w+['"]?$/, end: /^\w+;?$/, contains: [hljs.BACKSLASH_ESCAPE, { className: "subst", variants: [{ begin: /\$\w+/ }, { begin: /\{\$/, end: /\}/ }] }] }, PREPROCESSOR, { className: "keyword", begin: /\$this\b/ }, VARIABLE, { // swallow composed identifiers to avoid parsing them as keywords begin: /(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/ }, { className: "function", beginKeywords: "function", end: /[;{]/, excludeEnd: true, illegal: "\\$|\\[|%", contains: [hljs.UNDERSCORE_TITLE_MODE, { className: "params", begin: "\\(", end: "\\)", contains: ["self", VARIABLE, hljs.C_BLOCK_COMMENT_MODE, STRING, NUMBER] }] }, { className: "class", beginKeywords: "class interface", end: "{", excludeEnd: true, illegal: /[:\(\$"]/, contains: [{ beginKeywords: "extends implements" }, hljs.UNDERSCORE_TITLE_MODE] }, { beginKeywords: "namespace", end: ";", illegal: /[\.']/, contains: [hljs.UNDERSCORE_TITLE_MODE] }, { beginKeywords: "use", end: ";", contains: [hljs.UNDERSCORE_TITLE_MODE] }, { begin: "=>" // No markup, just a relevance booster }, STRING, NUMBER] }; } });
/** * Policy mappings (ACL) * * Policies are simply Express middleware functions which run **before** your controllers. * You can apply one or more policies to a given controller, or protect just one of its actions. * * Any policy file (e.g. `authenticated.js`) can be dropped into the `/policies` folder, * at which point it can be accessed below by its filename, minus the extension, (e.g. `authenticated`) * * For more information on policies, check out: * http://sailsjs.org/#documentation */ // var serviceStack = ADCore.policy.serviceStack([ 'policy1', 'policy2']); module.exports = { // 'opstool-process-reports/YourController': { // method: ['isAuthenticatedService'], // auth: [], // sync: serviceStack, // logout:true // } };
/* * Copyright (c) 2011-2013 Lp digital system * * This file is part of BackBuilder5. * * BackBuilder5 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BackBuilder5 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 BackBuilder5. If not, see <http://www.gnu.org/licenses/>. */ define(['tb.core'], function (Core) { 'use strict'; /** * Register every routes of bundle application into Core.routeManager */ Core.RouteManager.registerRoute('user', { prefix: 'user', routes: { index: { url: '/index', action: 'MainController:index' } } }); });
const products = [{id : 'classic', name : 'Classic Ad', price : 269.99}, {id : 'standout', name : 'Standout Ad', price : 322.99}, {id : 'premium', name : 'Premium Ad', price : 394.99}] class ProductDao { constructor() { console.log('Instantiating ProductDao') } listAll(){ return products } findById(id){ } } module.exports = new ProductDao
import Ember from 'ember'; const { Route, RSVP } = Ember; export default Route.extend({ model() { const job = this.modelFor('jobs.job'); return RSVP.all([job.get('deployments'), job.get('versions')]).then(() => job); }, });
import animate; import event.Emitter as Emitter; import device; import ui.View; import ui.ImageView; import ui.TextView; import src.Match3Core as Core; import src.Utils as Utils; //var Chance = require('chance'); //Some constants var CoreGame = new Core(); var level = new Core(); //var chance = new Chance(); /* The Game Screen code. * The child of the main application in * the game. Everything else is a child * of game so it is all visible. */ exports = Class(ui.View, function(supr) { this.init = function(opts) { opts = merge(opts, { x: 0, y: 0, width: 576, height: 1024, backgroundColor: '#37b34a' }); supr(this, 'init', [opts]); this.build(); }; this.build = function() { this.on('app:start', start_game_flow.bind(this)); }; // Main Menu Functions this.SetMenu = function(menu) { this._menu = menu; }; this.GetMenu = function() { return this._menu; }; this.OnLaunchMainMenu = function(){ this.emit('MainMenu'); }; }); /* function ReadyGame() { CoreGame.InitializeBoard(); CoreGame.CreateLevel(); //Find Initial Moves and Clusters CoreGame.FindMoves(); CoreGame.FindClusters(); } */ // Starts the game function start_game_flow() { CoreGame.ReadyGame(); play_game(this); } // Game play function play_game() { if(CoreGame.moves.length === 0) { end_game_flow.call(this); } } // function tick() {} // function update_countdown() {} // Game End function end_game_flow() { //slight delay before allowing a tap reset setTimeout(emit_endgame_event.bind(this), 2000); } function emit_endgame_event() { this.once('InputSelect', function() { this.emit('gamescreen:end'); reset_game.call(this); }); } function reset_game() {}
var fs = require("fs"); var path = require("path"); var _ = require("underscore"); var chai = require("chai"); var expect = chai.expect; var profile = require("../../lib/profile"); var PREFS = require("../../data/preferences"); var simpleXpiPath = path.join(__dirname, '..', 'xpis', 'simple-addon.xpi'); describe("lib/profile", function () { it("creates a profile and returns the path", function (done) { profile().then(function (profilePath) { var contents = fs.readFileSync(path.join(profilePath, "user.js"), "utf8"); expect(contents).to.be.ok; }) .then(done, done); }); it("creates a profile with proper default preferences (Firefox)", function (done) { profile().then(function (profilePath) { var contents = fs.readFileSync(path.join(profilePath, "user.js"), "utf8"); var defaults = _.extend({}, PREFS.DEFAULT_COMMON_PREFS, PREFS.DEFAULT_FIREFOX_PREFS); comparePrefs(defaults, contents); }) .then(done, done); }); it("creates a profile with an addon installed when given a XPI", function (done) { profile({ xpi: simpleXpiPath }).then(function (profilePath) { var addonPath = path.join(profilePath, "extensions", "simple-addon"); var files = fs.readdirSync(addonPath, "utf8"); var index = fs.readFileSync(path.join(addonPath, "index.js")); var manifest = fs.readFileSync(path.join(addonPath, "package.json")); expect(index).to.be.ok; expect(manifest).to.be.ok; }) .then(done, done); }); }); function comparePrefs (defaults, prefs) { var count = Object.keys(defaults).length; prefs.split("\n").forEach(function (pref) { var parsed = pref.match(/user_pref\("(.*)", "?([^"]*)"?\)\;$/); if (!parsed || parsed.length < 2) return; var key = parsed[1]; var value = parsed[2]; // Cast booleans and numbers in string formative to primitives if (value === 'true') value = true; else if (value === 'false') value = false; else if (!isNaN(parseFloat(value)) && isFinite(value)) value = +value; // TODO need to override firefox-profile setting default prefs // but we still override them if we explicitly set them if (key in defaults) { expect(defaults[key]).to.be.equal(value); --count; } }); expect(count).to.be.equal(0); }
/* @flow */ import * as React from 'react'; import Link from 'amo/components/Link'; import { addParamsToHeroURL, checkInternalURL } from 'amo/utils'; import tracking from 'core/tracking'; import LoadingText from 'ui/components/LoadingText'; import type { HeroCallToActionType, SecondaryHeroShelfType, } from 'amo/reducers/home'; import './styles.scss'; export const SECONDARY_HERO_CLICK_CATEGORY = 'AMO Secondary Hero Clicks'; export const SECONDARY_HERO_SRC = 'homepage-secondary-hero'; type Props = {| shelfData?: SecondaryHeroShelfType |}; type InternalProps = {| ...Props, _checkInternalURL: typeof checkInternalURL, _tracking: typeof tracking, |}; const makeCallToActionURL = (urlString: string) => { return addParamsToHeroURL({ heroSrcCode: SECONDARY_HERO_SRC, urlString }); }; export const SecondaryHeroBase = ({ _checkInternalURL = checkInternalURL, _tracking = tracking, shelfData, }: InternalProps) => { const { headline, description, cta } = shelfData || {}; const modules = (shelfData && shelfData.modules) || Array(3).fill({}); const onHeroClick = (event: SyntheticEvent<HTMLAnchorElement>) => { _tracking.sendEvent({ action: event.currentTarget.href, category: SECONDARY_HERO_CLICK_CATEGORY, }); }; const getLinkProps = (link: HeroCallToActionType | null) => { const props = { onClick: onHeroClick }; if (link) { const urlInfo = _checkInternalURL({ urlString: link.url }); if (urlInfo.isInternal) { return { ...props, to: makeCallToActionURL(urlInfo.relativeURL) }; } return { ...props, href: makeCallToActionURL(link.url), prependClientApp: false, prependLang: false, target: '_blank', }; } return {}; }; const renderedModules = []; modules.forEach((module) => { renderedModules.push( <div className="SecondaryHero-module" key={module.description}> {module.icon ? ( <img alt={module.description} className="SecondaryHero-module-icon" src={module.icon} /> ) : ( <div className="SecondaryHero-module-icon" /> )} <div className="SecondaryHero-module-description"> {module.description || <LoadingText width={60} />} </div> {module.cta && ( <Link className="SecondaryHero-module-link" {...getLinkProps(module.cta)} > <span className="SecondaryHero-module-linkText"> {module.cta.text} </span> </Link> )} {!module.description && ( <div className="SecondaryHero-module-link"> <LoadingText width={50} /> </div> )} </div>, ); }); return ( <section className="SecondaryHero"> <div className="SecondaryHero-message"> <h2 className="SecondaryHero-message-headline"> {headline || ( <> <LoadingText width={70} /> <br /> <LoadingText width={50} /> </> )} </h2> <div className="SecondaryHero-message-description"> {description || ( <> <LoadingText width={80} /> <br /> <LoadingText width={60} /> </> )} </div> {cta && ( <Link className="SecondaryHero-message-link" {...getLinkProps(cta)}> <span className="SecondaryHero-message-linkText">{cta.text}</span> </Link> )} {!headline && ( <div className="SecondaryHero-message-link"> <LoadingText width={50} /> </div> )} </div> {renderedModules} </section> ); }; export default SecondaryHeroBase;
#!/usr/bin/env node const fs = require('fs'); const Gcp = require('../static/app/js/classes/Gcp'); const argv = process.argv.slice(2); function die(s){ console.log(s); process.exit(1); } if (argv.length != 2){ die(`Usage: ./resize_gcp.js <path/to/gcp_file.txt> <JSON encoded image-->ratio map>`); } const [inputFile, jsonMap] = argv; if (!fs.existsSync(inputFile)){ die('File does not exist: ' + inputFile); } const originalGcp = new Gcp(fs.readFileSync(inputFile, 'utf8')); try{ const map = JSON.parse(jsonMap); const newGcp = originalGcp.resize(map, true); console.log(newGcp.toString()); }catch(e){ die("Not a valid JSON string: " + jsonMap); }
// listen and handle messages from the content script // via the background script import { addStackingContext } from "./actions/stacking-context"; function connectToInspectedWindow({ dispatch }) { browser.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.tabId !== browser.devtools.inspectedWindow.tabId) { return; } switch (request.action) { case "SET_STACKING_CONTEXT_TREE": const { tree, selector } = request.data; dispatch(addStackingContext(tree, selector)); } }); } export { connectToInspectedWindow };
/** * Image Processing * * In imaging science, image processing is any form of signal processing for * which the input is an image, such as a photograph or video frame; the output * of image processing may be either an image or a set of characteristics or * parameters related to the image. Most image-processing techniques involve * treating the image as a two-dimensional signal and applying standard * signal-processing techniques to it. * * -->Image Processing (image in -> image out) * Image Analysis (image in -> measurements out) * Image Understanding (image in -> high-level description out) * * - http://en.wikipedia.org/wiki/Image_processing */ var util = require('util'); var stream = require('stream'); var Transform = stream.Transform; var cv = require('opencv'); function Processing(settings, options) { if (!(this instanceof Processing)) return new Processing(options); if (options === undefined) options = {}; options.objectMode = true; Transform.call(this, options); this.settings = settings; this.decodeSettings(); } util.inherits(Processing, Transform); Processing.prototype.decodeSettings = function() { var profile = this.settings.profile; this.profile = this.settings[profile]; this.lowerbound = this.profile.lowerb.reverse(); this.upperbound = this.profile.upperb.reverse(); }; /** * Expects a full image */ Processing.prototype._transform = function(chunk, encoding, callback) { var self = this; cv.readImage(chunk, function(err, image) { // Color filter image.inRange(self.lowerbound, self.upperbound); // Do canny operations on a copy var im_canny = image.copy(); // Feature detection with canny algorithm im_canny.canny(self.settings.lowThresh, self.settings.highThresh); im_canny.dilate(self.settings.nIters); // All done self.push({ 'original': chunk, 'image': image }); callback(); }); }; module.exports = Processing;
import basicAuth from 'express-basic-auth' import { Ability } from '@casl/ability' const userAccountAuthorizer = (app) => async (email, password, cb) => { try { const auth = await app .service('authentication') .create({ email, password, strategy: 'local' }, { provider: 'rest' }) const ability = new Ability(auth.abilities) return cb(null, ability.can('read', 'arena')) } catch (e) { app.info('basic auth failed', e) return cb(null, false) } } export default (app) => basicAuth({ authorizer: userAccountAuthorizer(app), challenge: true, authorizeAsync: true, })
function Component(type,id,uri,name,query,inputList,x,y) { // this.code = code; // this.type = type; this.componentId = id; this.uri = uri; this.name = name; this.query = query; this.inputList = inputList; this.x = x; this.y = y; }; Component.prototype = { constructor: Component, // getCode: function() { return this.code; }, getType: function() { return this.type; }, getId: function() { return this.componentId; }, getURI: function() { return this.uri; }, getName: function() { return this.name; }, getQuery: function() { return this.query; }, getInputList: function() { return this.inputList; }, getPositionX: function() { return this.x; }, getPositionY: function() { return this.y; } }; /*Scrive il nome del componente nel div*/ Component.scriviNome = function(div,code,cnt){ var name = Component.getName(code); var label = document.createElement("label"); label.setAttribute("class","activeimg"); var br = document.createElement("br"); if(code == 0 || code == 1){ name = div.title; var text = document.createTextNode(name); label.appendChild(text); label.appendChild(br); label.appendChild(br); return label; } if(name == null){ name = div.title + " " + cnt; var text = document.createTextNode(name); label.appendChild(text); label.appendChild(br); return label; } else{ var text = document.createTextNode(name); label.appendChild(text); label.appendChild(br); return label; } }; /*Ricarica la pipeline creata*/ Component.loadPipeline = function(editor,code,component,id,uri,name,query,inputlist,x,y){ //alert(code + component + id + uri + name + query + inputlist + x + y); var div = document.createElement("div"); div.setAttribute("class","activegraph"); div.setAttribute("id","comp-" + code); div.title = code; var img = document.createElement("img"); img.setAttribute("id","activeimg"); if(component == "inputdefault" || component == "input"){img.src = "IMG/Input.gif";} if(component == "outputdefault" || component == "output"){img.src = "IMG/Output.gif";} if(component == "union"){img.src = "IMG/Union.gif";} if(component == "construct"){img.src = "IMG/Construct.gif";} if(component == "updatable"){img.src = "IMG/Updatable.gif";} if(component == "dataset"){img.src = "IMG/Dataset.gif";} div.appendChild(img); var label = document.createElement("label"); label.setAttribute("class","activeimg"); var br = document.createElement("br"); var text = document.createTextNode(name); label.appendChild(text); label.appendChild(br); label.appendChild(br); div.appendChild(label); if(component == "input" || component == "output" || component == "union" || component == "construct" || component == "updatable" || component == "dataset"){ var proprieta = document.createElement("img"); proprieta.setAttribute("class","bottongraph"); proprieta.src = "IMG/pulsanteproprieta.gif"; proprieta.title = "property"; div.appendChild(proprieta); Core.addEventListener(proprieta,"click",function(){ var body = document.createElement("div"); body.setAttribute("class","body"); formIN = Form.createForm(div,code); document.getElementsByTagName("body")[0].appendChild(formIN); document.getElementsByTagName("body")[0].appendChild(body); }); var elimina = document.createElement("img"); elimina.setAttribute("class","bottongraph"); elimina.src = "IMG/iconaX.gif"; elimina.title = "delete"; div.appendChild(elimina); Core.addEventListener(elimina,"click",function(){ temp = elimina.parentNode.parentNode; jsPlumb.removeAllEndpoints(elimina.parentNode); jsPlumb.detachAllConnections(elimina.parentNode); temp.removeChild(elimina.parentNode); Component.elimina(componentVett,code); Code.cancellaCodice(code); }); } var x = div.style.left = x; var y = div.style.top = y; editor.appendChild(div); Endpoint.createEndpoint(div,code,null); if((component == "construct" || component == "updatable") && inputlist.length != 0){Endpoint.createEndpoint(div,code,2);} Code.modificaCodice(code); };
// EXIF Orientation test // iOS looks at the EXIF Orientation flag in jpgs and rotates the image // accordingly. Looks like most desktop browsers just ignore this data. // description: www.impulseadventure.com/photo/exif-orientation.html // Bug trackers: // bugzil.la/298619 (unimplemented) // crbug.com/56845 (looks incomplete) // webk.it/19688 (available upstream but its up all ports to turn on individually) // // detect by Paul Sayre (function(){ var img = new Image(); img.onerror = function() { Modernizr.addTest('exif-orientation', function () { return false; }); }; img.onload = function() { Modernizr.addTest('exif-orientation', function () { return img.width !== 2; }); }; // There may be a way to shrink this more, it's a 1x2 white jpg with the orientation flag set to 6 img.src = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAASUkqAAgAAAABABIBAwABAAAABgASAAAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAABAAIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEIIKxwRVSfAkM2JyggkKFhcYGRolJicoKSoNTY3ODk6QRFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP9fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanNdXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrOtba3uLm6wsPExcbHyMnKtPU1dbX2Nna4uPk5ebn6Onq8vP9fb3+Pn6/9oADAMBAAIRAxEAPwD+/iiiigD/2Q=="; })();
/* This file is a part of libertysoil.org website Copyright (C) 2016 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import i from 'immutable'; import { getTypeError, createRequirableTypeChecker, createSimplifiedRequirableTypeChecker, checkValues, checkKeys } from './utils'; export const mapOfKeys = (keyCheckType) => ( createSimplifiedRequirableTypeChecker( (propValue, propFullName, componentName, location, ...rest) => { const expectedType = 'object'; if (typeof propValue !== expectedType) { return getTypeError(propValue, expectedType, propFullName, componentName, location); } return checkKeys( keyCheckType, propValue, propFullName, componentName, location, ...rest ); } ) ); export const mapOfValues = (valueCheckType) => ( createSimplifiedRequirableTypeChecker( (propValue, propFullName, componentName, location, ...rest) => { const expectedType = 'object'; if (typeof propValue !== expectedType) { return getTypeError(propValue, expectedType, propFullName, componentName, location); } return checkValues( valueCheckType, propValue, propFullName, componentName, location, ...rest ); } ) ); export const mapOf = (keyCheckType, valueCheckType) => ( createSimplifiedRequirableTypeChecker( (propValue, propFullName, componentName, location, ...rest) => { const expectedType = 'object'; if (typeof propValue !== expectedType) { return getTypeError(propValue, expectedType, propFullName, componentName, location); } const error = checkKeys( keyCheckType, propValue, propFullName, componentName, location, ...rest ); if (error instanceof Error) { return error; } return checkValues( valueCheckType, propValue, propFullName, componentName, location, ...rest ); } ) ); export const Immutable = (checkType) => ( createRequirableTypeChecker( (props, propName, componentName, location, propFullName, ...rest) => { const propValue = props[propName]; // all Immutable date types are subclasses of Immutable.Iterable if (i.Iterable.isIterable(propValue)) { const preparedPropValue = propValue.toJS(); const preraredProps = { ...props, [propName]: preparedPropValue }; // vanilla instance of PropTypes' checkType() // or result of createRequirableTypeChecker() if (!checkType.isSimplified) { return checkType( preraredProps, propName, componentName, location, propFullName, ...rest ); } // result of createSimplifiedRequirableTypeChecker() let fullName = propName; if (propFullName) { fullName = propFullName; } return checkType( preparedPropValue, fullName, componentName, location, ...rest ); } return new Error( `Invalid prop \`${propFullName}\` of type \`${typeof propValue}\` ` + `supplied to \`${componentName}\` isn't an instance of any Immutable data type.` ); } ) ); export const uuid4 = createSimplifiedRequirableTypeChecker( (propValue, propFullName, componentName, location) => { const expectedType = 'string'; if (typeof propValue !== expectedType) { return getTypeError(propValue, expectedType, propFullName, componentName, location); } const test = RegExp(/^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}$/i); if (!propValue.match(test)) { return new Error( `Invalid prop \`${propFullName}\` of type \`${expectedType}\` ` + `supplied to \`${componentName}\` doesn't match the UUID pattern.` ); } return null; } ); export const date = createSimplifiedRequirableTypeChecker( (propValue, propFullName, componentName, location) => { if (propValue instanceof Date) { return null; } const expectedType = 'string'; if (typeof propValue !== expectedType) { return getTypeError(propValue, expectedType, propFullName, componentName, location); } const date = new Date(propValue); const dateString = date.toString(); if (dateString === 'Invalid date') { return new Error( `Invalid prop \`${propFullName}\` of type \`${expectedType}\` ` + `supplied to \`${componentName}\` is invalid date string representation.` ); } return null; } ); export const url = createSimplifiedRequirableTypeChecker( (propValue, propFullName, componentName, location) => { const expectedType = 'string'; if (typeof propValue !== expectedType) { return getTypeError(propValue, expectedType, propFullName, componentName, location); } const test = RegExp(/^[a-z0-9_.'-]+$/i); if (!propValue.match(test)) { return new Error( `Invalid prop \`${propFullName}\` of type \`${expectedType}\` ` + `supplied to \`${componentName}\` is invalid URL representation.` ); } return null; } );
engine.eval("load('nashorn:mozilla_compat.js');"); /* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** -- Odin JavaScript -------------------------------------------------------------------------------- Harry - Before Takeoff <To Orbis>(240000111) -- By --------------------------------------------------------------------------------------------- Information -- Version Info ----------------------------------------------------------------------------------- 1.3 - Add missing return statement [Thanks sadiq for the bug, fix by Information] 1.2 - Replace function to support latest [Information] 1.1 - Fix wrong placed statement [Information] 1.0 - First Version by Information --------------------------------------------------------------------------------------------------- **/ importPackage(Packages.net.sf.odinms.client); function start() { status = -1; cb = cm.getEventManager("Cabin"); action(1, 0, 0); } function action(mode, type, selection) { if(mode == -1) { cm.dispose(); return; } else { status++; if(mode == 0) { cm.sendOk("You'll get to your destination in moment. Go ahead and talk to other people, and before you know it, you'll be there already."); cm.dispose(); return; } if(status == 0) { cm.sendYesNo("Do you want to leave the waiting room? You can, but the ticket is NOT refundable. Are you sure you still want to leave this room?"); } else if(status == 1) { cm.warp(240000110); cm.dispose(); } } }
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'sourcearea', 'ko', { toolbar: '소스' } );
// i18n.js App.i18n = { strings: {}, loaded: false, setLanguage: function(languageCode, callback) { this.languageCode = languageCode; App.localStorage.set('selected_interface_locale', languageCode); this.loadStrings(callback); }, getLanguage: function(languageCode) { return this.languageCode; }, translate: function(string, stringId) { if (typeof(stringId) == 'undefined') stringId = string; if (typeof(this.strings[stringId]) === 'undefined' || this.strings[stringId] === false || this.strings[stringId] === '') return string; else return this.strings[stringId]; }, translateDOM: function() { var that = this; $("[data-i18n]").each(function() { var string = $(this).data('i18n'); string = that.translate(string); $(this).text(string); }); $("[data-i18nvalue]").each(function() { var string = $(this).data('i18nvalue'); string = that.translate(string); $(this).val(string); }); $("[data-i18nplaceholder]").each(function() { var string = $(this).data('i18nplaceholder'); string = that.translate(string); $(this).attr('placeholder', string); }); }, loadStrings: function(callback) { var that = this; var process = function(data) { that.strings = data; that.loaded = true; that.translateDOM(); if (typeof(callback) == 'function') callback(); }; this.loaded = false; if (this.languageCode == 'default') process({}); else $.ajax({ url: App.settings.apiEntryPoint + 'i18n/bycode/' + this.languageCode.split('-').join(''), data: {}, success: process, dataType: 'json', mimeType: 'application/json', cache: true }); } };
{ "metadata" : { "formatVersion" : 3.1, "sourceFile" : "Buffalo.obj", "generatedBy" : "OBJConverter", "vertices" : 2202, "faces" : 4134, "normals" : 2113, "uvs" : 0, "materials" : 4 }, "materials": [ { "DbgColor" : 15658734, "DbgIndex" : 0, "DbgName" : "Material.006", "colorDiffuse" : [0.287072, 0.214367, 0.076018], "colorSpecular" : [0.5, 0.5, 0.5], "illumination" : 2, "opacity" : 1.0, "opticalDensity" : 1.0, "specularCoef" : 96.078431 }, { "DbgColor" : 15597568, "DbgIndex" : 1, "DbgName" : "hoof", "colorDiffuse" : [0.017583, 0.008414, 0.0], "colorSpecular" : [0.0, 0.0, 0.0], "illumination" : 2, "opacity" : 1.0, "opticalDensity" : 1.0, "specularCoef" : 96.078431 }, { "DbgColor" : 60928, "DbgIndex" : 2, "DbgName" : "horse_body", "colorDiffuse" : [0.098968, 0.055305, 0.002045], "colorSpecular" : [0.0, 0.0, 0.0], "illumination" : 2, "opacity" : 1.0, "opticalDensity" : 1.0, "specularCoef" : 96.078431 }, { "DbgColor" : 238, "DbgIndex" : 3, "DbgName" : "tail", "colorDiffuse" : [0.0, 0.0, 0.0], "colorSpecular" : [0.0, 0.0, 0.0], "illumination" : 2, "opacity" : 1.0, "opticalDensity" : 1.0, "specularCoef" : 96.078431 }], "buffers": "Buffalo.bin" }
/* * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting. * * Copyright (C) 2015 John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4. * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ function BaseDemographicEstimateController($scope, rights, categories, programs , years, $filter) { //TODO: read this configuration from backend. $scope.enableAutoCalculate = false; $scope.showFacilityAggregatesOption = false; $scope.currentPage = 1; $scope.pageSize = 50; $scope.categories = categories; $scope.rights = rights; $scope.years = years; $scope.programs = programs; $scope.$watch('currentPage', function () { if ($scope.isDirty()) { $scope.save(); } if (angular.isDefined($scope.lineItems)) { $scope.pageLineItems(); } }); $scope.isDirty = function () { return $scope.$dirty; }; $scope.hasPermission = function (permission) { return ($scope.rights.indexOf(permission) >= 0); }; $scope.showParent = function (index) { if (index > 0) { return ($scope.form.estimateLineItems[index].parentName !== $scope.form.estimateLineItems[index - 1].parentName); } return true; }; $scope.pageLineItems = function () { $scope.pageCount = Math.ceil($scope.lineItems.length / $scope.pageSize); if ($scope.lineItems.length > $scope.pageSize) { $scope.form.estimateLineItems = $scope.lineItems.slice($scope.pageSize * ($scope.currentPage - 1), $scope.pageSize * Number($scope.currentPage)); } else { $scope.form.estimateLineItems = $scope.lineItems; } }; $scope.clearMessages = function(){ $scope.message = ''; $scope.error = ''; }; $scope.init = function(){ // default to the current year $scope.year = Number( $filter('date')(new Date(), 'yyyy') ); // when the available program is only 1, default to this program. if(programs.length === 1){ $scope.program = programs[0].id; } $scope.onParamChanged(); }; } BaseDemographicEstimateController.resolve = { categories: function ($q, $timeout, DemographicEstimateCategories) { var deferred = $q.defer(); $timeout(function () { DemographicEstimateCategories.get({}, function (data) { deferred.resolve(data.estimate_categories); }, {}); }, 100); return deferred.promise; }, years: function ($q, $timeout, OperationYears) { var deferred = $q.defer(); $timeout(function () { OperationYears.get({}, function (data) { deferred.resolve(data.years); }); }, 100); return deferred.promise; }, programs: function($q, $timeout, DemographicEstimatePrograms){ var deferred = $q.defer(); $timeout(function(){ DemographicEstimatePrograms.get({}, function(data){ deferred.resolve(data.programs); }); },100); return deferred.promise; }, rights: function ($q, $timeout, UserSupervisoryRights) { var deferred = $q.defer(); $timeout(function () { UserSupervisoryRights.get({}, function (data) { deferred.resolve(data.rights); }, {}); }, 100); return deferred.promise; } };
function recaptcha_verified () { document.querySelector('.recaptcha_submit').removeAttribute('disabled') } function recaptcha_expired () { document.querySelector('.recaptcha_submit').setAttribute('disabled', 'disabled') }
/* * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later. * * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla 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 Mozilla Public License for more details. * * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/ */ function DistrictDemographicEstimateController($scope, categories, years, DistrictDemographicEstimates, SaveDistrictDemographicEstimates) { $scope.categories = categories; $scope.years = years; $scope.year = years[0]; $scope.OnPopulationChanged = function(population, district, category){ var pop = $scope.toNumber(population.value); if(category.isPrimaryEstimate){ angular.forEach(district.districtEstimates, function(estimate){ if(population.demographicEstimateId !== estimate.demographicEstimateId){ estimate.value = $scope.round(estimate.conversionFactor * pop / 100) ; } }); } }; $scope.onParamChanged = function(){ DistrictDemographicEstimates.get({year: $scope.year}, function(data){ $scope.form = data.estimates; angular.forEach($scope.form.estimateLineItems, function(fe){ fe.indexedEstimates = _.indexBy( fe.districtEstimates , 'demographicEstimateId' ); }); }); }; $scope.toNumber = function (val) { if (angular.isDefined(val) && val !== null) { return parseInt(val, 10); } return 0; }; $scope.round = function(val){ return Math.ceil(val); }; $scope.save = function(){ SaveDistrictDemographicEstimates.update($scope.form, function(data){ // show the saved message //TODO: move this string to the messages property file. $scope.message = "District demographic estimates successfully saved."; }); }; $scope.onParamChanged(); } DistrictDemographicEstimateController.resolve = { categories: function ($q, $timeout, DemographicEstimateCategories) { var deferred = $q.defer(); $timeout(function () { DemographicEstimateCategories.get({}, function (data) { deferred.resolve(data.estimate_categories); }, {}); }, 100); return deferred.promise; }, years: function ($q, $timeout, OperationYears) { var deferred = $q.defer(); $timeout(function () { OperationYears.get({}, function (data) { deferred.resolve(data.years); }); }, 100); return deferred.promise; } };
module.exports = { error: require('./error'), store: require('./store'), task: require('./task') };
/*Copyright (c) Shelloid Systems LLP. All rights reserved. The use and distribution terms for this software are covered by the GNU Affero General Public License 3.0 (http://www.gnu.org/licenses/agpl-3.0.html) which can be found in the file LICENSE at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. */ /** * Created by Harikrishnan on 21/5/14. */ exports.index = function (req, res) { easydb(dbPool) .query(function () { return { query: "SELECT email, name, gen_code FROM pending_registrations WHERE email = ? and gen_code = ? and name = ?", params: [decodeURIComponent(req.body.email), decodeURIComponent(req.body.id), decodeURIComponent(req.body.name)] }; }) .success(function (rows) { if (rows.length > 0) { res.send({status: 200, name: rows[0].name}); } else { throw new Error("Validation failed."); } }). query(function () { return { query: "INSERT INTO users (`email`, `md5_password`, `salt`, `name`, `last_login_time`) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)", params: [req.body.email, req.body.md5_secret, req.body.salt, req.body.name] }; }). query(function () { return { query: "DELETE FROM pending_registrations WHERE email = ?", params: [decodeURIComponent(req.body.email)] }; }). success(function (rows) { res.send({status: 200}); }). error(function (err) { console.log(err); res.send({msg: err, status: 500}); }).execute({transaction: true}); };
// document.getElementsByTagName('body')[0].style.visibility = 'hidden'; // //console.log("first" + "/\\b" + "Hello" + "\\b/gi"); var fn2 = function() { //console.log('running'); document.getElementsByTagName('body')[0].style.visibility = 'hidden'; //console.log('hidden'); }; fn2();
describe('Introduction', function () { beforeEach(function () { cy.login(); cy.createContact('John', 'Doe', 'Man'); cy.createContact('Jane', 'Doe', 'Woman'); cy.createContact('Joe', 'Shmoe', 'Man'); }); it('lets you fill first met without an introducer', function () { cy.url().should('include', '/people/h:'); cy.get('.introductions a[href$="introductions/edit"]').click(); cy.url().should('include', '/introductions/edit'); cy.get('textarea[name=first_met_additional_info]').type('Lorem ipsum'); cy.get('button.btn-primary[type=submit]').click(); cy.url().should('include', '/people/h:'); cy.get('.alert-success'); cy.get('.introductions').contains('Lorem ipsum'); }); it('lets you save first met', function () { cy.url().should('include', '/people/h:'); cy.get('.introductions a[href$="introductions/edit"]').click(); cy.url().should('include', '/introductions/edit'); cy.get('textarea[name=first_met_additional_info]').type('Lorem ipsum'); cy.get('#metThrough > .v-select input').click(); cy.get('#metThrough ul[role="listbox"]').contains('John Doe'); cy.get('#metThrough ul[role="listbox"]').contains('Jane Doe'); cy.get('#metThrough ul[role="listbox"]').contains('Joe Shmoe'); cy.get('#metThrough ul[role="listbox"]').contains('John Doe').click(); cy.get('button.btn-primary[type=submit]').click(); cy.url().should('include', '/people/h:'); cy.get('.alert-success'); cy.get('.introductions').contains('Lorem ipsum'); cy.get('.introductions').contains('John Doe'); }); it('lets you search first met', function () { cy.url().should('include', '/people/h:'); cy.get('.introductions a[href$="introductions/edit"]').click(); cy.url().should('include', '/introductions/edit'); cy.get('textarea[name=first_met_additional_info]').type('Lorem ipsum'); cy.get('#metThrough input[type=search]').type('John'); cy.get('#metThrough ul[role="listbox"]').contains('John Doe'); cy.get('#metThrough ul[role="listbox"]').should('not.contain', 'Joe Shmoe'); cy.get('#metThrough ul[role="listbox"]').should('not.contain', 'Jane Doe'); cy.get('#metThrough ul[role="listbox"]').contains('John Doe').click(); cy.get('button.btn-primary[type=submit]').click(); cy.url().should('include', '/people/h:'); cy.get('.introductions').contains('Lorem ipsum'); cy.get('.introductions').contains('John Doe'); }); });
var C = crel2; var ventana = API.widget.create(); var textarea; C(ventana, C('button', ['onclick', local_set_test], 'LOCAL SET test'), C('button', ['onclick', local_get_test], 'LOCAL GET test'), C('button', ['onclick', local_delete_test], 'LOCAL DELETE test'), C('button', ['onclick', local_delete_all_test], 'LOCAL DELETE ALL test'), C('button', ['onclick', local_exists], 'LOCAL EXISTS test'), C('br'), C('button', ['onclick', remote_set_test], 'REMOTE SET test'), C('button', ['onclick', remote_get_test], 'REMOTE GET test'), C('button', ['onclick', remote_delete_test], 'REMOTE DELETE test'), C('button', ['onclick', remote_delete_all_test], 'REMOTE DELETE ALL test'), C('button', ['onclick', remote_exists], 'REMOTE EXISTS test'), C('br'), C('button', ['onclick', global_set_test], 'GLOBAL SET test'), C('button', ['onclick', global_get_test], 'GLOBAL GET test'), C('button', ['onclick', global_delete_test], 'GLOBAL DELETE test'), C('button', ['onclick', global_exists], 'GLOBAL EXISTS test'), C('br'), textarea = C('textarea') ); function log(what){ textarea.value += what+"\n"; } //log(API.url(widgetID,'main.js')); // Variables are saved as text ///////////////////////////// // LOCAL ///////////////////////////// function local_set_test(){ var text_rnd = Math.random(); log('LOCAL SET Test Saving the text: '+text_rnd); API.storage.localStorage.set('test', text_rnd, function(entrada){ if(entrada){ log('LOCAL SET Test Text Saved.'); } else{ log('LOCAL SET Test Text NOT saved.'); } }); } function local_get_test(){ log('LOCAL GET Test'); API.storage.localStorage.get('test', function(entrada){ if(entrada){ log('LOCAL GET Test Got the text: '+entrada); } else{ log('LOCAL GET Test There is not a saved variable with that name.'); } }); } function local_delete_test(){ log('LOCAL DELETE Test'); API.storage.localStorage.delete('test', function(entrada){ if(entrada){ log('LOCAL DELETE Test deleted OK.'); } else{ log('LOCAL DELETE Test deleted FAIL.'); } }); API.storage.localStorage.get('test', function(entrada){ if(entrada){ log('LOCAL DELETE Test confirmed FAIL.'); } else{ log('LOCAL DELETE Test confirmed OK.'); } }); } function local_delete_all_test(){ log('LOCAL DELETE ALL Test'); API.storage.localStorage.deleteAll(function(entrada){ if(entrada){ log('LOCAL DELETE ALL Test deleted OK.'); } else{ log('LOCAL DELETE ALL Test deleted FAIL.'); } }); API.storage.localStorage.get('test', function(entrada){ if(entrada){ log('LOCAL DELETE ALL Test confirmed FAIL.'); } else{ log('LOCAL DELETE ALL Test confirmed OK.'); } }); } function local_exists(){ log('LOCAL EXISTS Test'); API.storage.localStorage.exists('test', function(entrada){ if(entrada){ log('LOCAL EXISTS Test variable exists = YES.'); } else{ log('LOCAL EXISTS Test variable exists = NO.'); } }); } ///////////////////////////// // REMOTE ///////////////////////////// function remote_set_test(){ var text_rnd = Math.random(); log('REMOTE SET Test Saving the text: '+text_rnd); API.storage.remoteStorage.set('test', text_rnd, function(entrada){ if(entrada){ log('REMOTE SET Test Text Saved.'); } else{ log('REMOTE SET Test Text NOT saved.'); } }); } function remote_get_test(){ log('REMOTE GET Test'); API.storage.remoteStorage.get('test', function(entrada){ if(entrada){ log('REMOTE GET Test Got the text: '+entrada); } else{ log('REMOTE GET Test There is not a saved variable with that name.'); } }); } function remote_delete_test(){ log('REMOTE DELETE Test'); API.storage.remoteStorage.delete('test', function(entrada){ if(entrada){ log('REMOTE DELETE Test deleted OK.'); } else{ log('REMOTE DELETE Test deleted FAIL.'); } }); API.storage.remoteStorage.get('test', function(entrada){ if(entrada){ log('REMOTE DELETE Test confirmed FAIL.'); } else{ log('REMOTE DELETE Test confirmed OK.'); } }); } function remote_delete_all_test(){ log('REMOTE DELETE ALL Test'); API.storage.remoteStorage.deleteAll(function(entrada){ if(entrada){ log('REMOTE DELETE ALL Test deleted OK.'); } else{ log('REMOTE DELETE ALL Test deleted FAIL.'); } }); API.storage.remoteStorage.get('test', function(entrada){ if(entrada){ log('REMOTE DELETE ALL Test confirmed FAIL.'); } else{ log('REMOTE DELETE ALL Test confirmed OK.'); } }); } function remote_exists(){ log('REMOTE EXISTS Test'); API.storage.remoteStorage.exists('test', function(entrada){ if(entrada){ log('REMOTE EXISTS Test variable exists = YES.'); } else{ log('REMOTE EXISTS Test variable exists = NO.'); } }); } ///////////////////////////// // GLOBAL ///////////////////////////// function global_set_test(){ var text_rnd = Math.random(); log('GLOBAL SET Test Saving the text: '+text_rnd); API.storage.sharedStorage.set('test', text_rnd, function(entrada){ if(entrada){ log('GLOBAL SET Test Text Saved.'); } else{ log('GLOBAL SET Test Text NOT saved.'); } }); } function global_get_test(){ log('GLOBAL GET Test'); API.storage.sharedStorage.get('test', function(entrada){ if(entrada){ log('GLOBAL GET Test Got the text: '+entrada); } else{ log('GLOBAL GET Test There is not a saved variable with that name.'); } }); } function global_delete_test(){ log('GLOBAL DELETE Test'); API.storage.sharedStorage.delete('test', function(entrada){ if(entrada){ log('GLOBAL DELETE Test deleted OK.'); } else{ log('GLOBAL DELETE Test deleted FAIL.'); } }); API.storage.sharedStorage.get('test', function(entrada){ if(entrada){ log('GLOBAL DELETE Test confirmed FAIL.'); } else{ log('GLOBAL DELETE Test confirmed OK.'); } }); } function global_exists(){ log('GLOBAL EXISTS Test'); API.storage.sharedStorage.exists('test', function(entrada){ if(entrada){ log('GLOBAL EXISTS Test variable exists = YES.'); } else{ log('GLOBAL EXISTS Test variable exists = NO.'); } }); }
var ERR = require('async-stacktrace'); var assert = require('assert'); var fs = require('fs'); var courseDB = require('../lib/course-db'); var logger = require('./dummyLogger'); describe('courseDB.loadFullCourse() on exampleCourse', function() { this.timeout(20000); var courseDir = 'exampleCourse'; var course; before('load course from disk', function(callback) { courseDB.loadFullCourse(courseDir, logger, function(err, c) { if (ERR(err, callback)) return; course = c; callback(null); }); }); describe('the in-memory "course" object', function() { it('should contain "courseInfo"', function() { assert.ok(course.courseInfo); }); it('should contain "questionDB"', function() { assert.ok(course.questionDB); }); it('should contain "courseInstanceDB"', function() { assert.ok(course.courseInstanceDB); }); }); }); describe('courseDB.loadFullCourse() on brokenCourse', function() { var courseDir = 'tests/testLoadCourse/brokenCourse'; var assessmentFilename = `${courseDir}/courseInstances/Fa18/assessments/quiz1/infoAssessment.json`; var questionFilename = `${courseDir}/questions/basicV3/info.json`; beforeEach('write correct infoAssessment and question', function(callback) { var assessmentJson = { 'uuid': 'bee70f4d-4220-47f1-b4ed-59c88ce08657', 'type': 'Exam', 'number': '1', 'title': 'Test quiz 1', 'set': 'Quiz', 'allowAccess': [ { 'startDate': '2018-01-01T00:00:00', 'endDate': '2019-01-01T00:00:00'}, ], }; var questionJson = { 'uuid': 'ba0b8e5b-6348-43f8-b483-083e0bea6332', 'title': 'Basic V3 question', 'topic': 'basic', 'type': 'v3', }; fs.writeFile(assessmentFilename, JSON.stringify(assessmentJson), function(err) { if (ERR(err, callback)) return; fs.writeFile(questionFilename, JSON.stringify(questionJson), function(err) { if (ERR(err, callback)) return; callback(null); }); }); }); after('removing test files', function(callback) { fs.unlink(assessmentFilename, function(err) { if (ERR(err, callback)) return; fs.unlink(questionFilename, function(err) { if (ERR(err, callback)) return; callback(null); }); }); }); describe('trying to load broken course pieces', function() { it('assessment: invalid set should fail', function(callback) { var assessmentJson = { 'uuid': 'bee70f4d-4220-47f1-b4ed-59c88ce08657', 'type': 'Exam', 'number': '1', 'title': 'Test quiz 1', 'set': 'NotARealSet', 'allowAccess': [ { 'startDate': '2018-01-01T00:00:00', 'endDate': '2019-01-01T00:00:00'}, ], }; var filename = 'courseInstances/Fa18/assessments/quiz1/infoAssessment.json'; loadHelper(courseDir, filename, assessmentJson, /invalid "set":/, callback); }); it('assessment: access rule: invalid startDate should fail', function(callback) { var assessmentJson = { 'uuid': 'bee70f4d-4220-47f1-b4ed-59c88ce08657', 'type': 'Exam', 'number': '1', 'title': 'Test quiz 1', 'set': 'Quiz', 'allowAccess': [ { 'startDate': 'NotADate', 'endDate': '2019-01-01T00:00:00'}, ], }; var filename = 'courseInstances/Fa18/assessments/quiz1/infoAssessment.json'; loadHelper(courseDir, filename, assessmentJson, /invalid allowAccess startDate/, callback); }); it('assessment: access rule: invalid endDate should fail', function(callback) { var assessmentJson = { 'uuid': 'bee70f4d-4220-47f1-b4ed-59c88ce08657', 'type': 'Exam', 'number': '1', 'title': 'Test quiz 1', 'set': 'Quiz', 'allowAccess': [ { 'startDate': '2019-01-01T22:22:22', 'endDate': 'AlsoReallyNotADate'}, ], }; var filename = 'courseInstances/Fa18/assessments/quiz1/infoAssessment.json'; loadHelper(courseDir, filename, assessmentJson, /invalid allowAccess endDate/, callback); }); it('assessment: access rule: startDate after endDate should fail', function(callback) { var assessmentJson = { 'uuid': 'bee70f4d-4220-47f1-b4ed-59c88ce08657', 'type': 'Exam', 'number': '1', 'title': 'Test quiz 1', 'set': 'Quiz', 'allowAccess': [ { 'startDate': '2020-01-01T11:11:11', 'endDate': '2019-01-01T00:00:00'}, ], }; var filename = 'courseInstances/Fa18/assessments/quiz1/infoAssessment.json'; loadHelper(courseDir, filename, assessmentJson, /must not be after/, callback); }); }); }); var loadHelper = function(courseDir, filename, contents, expectedErrorRE, callback) { fs.writeFile(courseDir + '/' + filename, JSON.stringify(contents), function(err) { if (err) { return callback(err); } courseDB.loadFullCourse(courseDir, logger, function(err, _c) { if (err) { if (expectedErrorRE.test(err)) { callback(null); } else { callback(new Error('unexpected error ' + err)); } } else { callback(new Error('returned successfully, which should not happen')); } }); }); };
(function() { "use strict"; angular.module("blocktrail.setup") .factory("newAccountFormService", function($log, $http, $q, _, cryptoJS, device, CONFIG, launchService, settingsService, trackingService) { return new NewAccountFormService($log, $http, $q, _, cryptoJS, device, CONFIG, launchService, settingsService, trackingService); } ); function NewAccountFormService($log, $http, $q, _, cryptoJS, device, CONFIG, launchService, settingsService, trackingService) { var self = this; self._$log = $log; self._$http = $http; self._$q = $q; self._lodash = _; self._cryptoJS = cryptoJS; self._device = device || {}; self._CONFIG = CONFIG; self._launchService = launchService; self._settingsService = settingsService; self._trackingService = trackingService; } /** * Register * @param data * @return { promise } */ NewAccountFormService.prototype.register = function(data) { var self = this; var postData = { username: null, email: data.email, password: self._cryptoJS.SHA512(data.password).toString(), password_score: data.passwordCheck && data.passwordCheck.score || 0, platform: ionic.Platform.isIOS() ? "iOS" : "Android", version: self._CONFIG.VERSION || self._CONFIG.VERSION_REV, device_uuid: self._device.uuid, device_name: (self._device.platform || self._device.model) ? ([self._device.platform, self._device.model].clean().join(" / ")) : "Unknown Device", super_secret: null, powtcha: null, browser_fingerprint: null, skip_two_factor: true, // will make the resulting API key not require 2FA in the future captcha : window.captchaToken }; var url = self._CONFIG.API_URL + "/v1/" + data.networkType + "/mywallet/register"; self._$log.debug("M:SETUP:newAccountFormService: register", postData.email, postData.platform, postData.device_name); return self._$http.post(url, postData) .then(self._trackEvent.bind(self)) .then(self._setAccountInfo.bind(self)) .catch(self._errorHandler.bind(self)); }; /** * @param response * @return response * @private */ NewAccountFormService.prototype._trackEvent = function(response) { var self = this; self._trackingService.trackEvent(self._trackingService.EVENTS.SIGN_UP); return response; }; /** * Set the account info * @param response * @return { promise } * @private */ NewAccountFormService.prototype._setAccountInfo = function(response) { var self = this; var accountInfo = { username: response.data.username, email: response.data.email, apiKey: response.data.api_key, apiSecret: response.data.api_secret }; self._$log.debug("M:SETUP:newAccountFormService:_setAccountInfo", accountInfo); return self._launchService.setAccountInfo(accountInfo) .then(function() { return self._launchService.getAccountInfo(); }); }; /** * Error handler * @param error * @return { promise<string> } * @private */ NewAccountFormService.prototype._errorHandler = function(error) { var self = this; var response; var ifr = document.querySelector('#ifr'); ifr.contentWindow.postMessage({a: 1}, '*'); // window.fetchCaptchaToken(); self._$log.debug("M:SETUP:newAccountFormService:_errorHandler", error); if (error && error.data && error.data.msg.toLowerCase().match(/username exists/)) { response = "MSG_USERNAME_TAKEN"; } else if (error && error.data && error.data.msg.toLowerCase().match(/already in use/)) { response = "MSG_EMAIL_TAKEN"; } else if (!!error) { response = "" + (error.message || error.msg || error.data && error.data.msg || error); } return this._$q.reject(response); }; })();
import { setAttrs } from '../actions/object' /*MATERIALDB_GROUP*/ export const addGroup = () => ({ type: "MATERIALDB_GROUP_ADD" }); export const deleteGroup = (groupId) => ({ type: "MATERIALDB_GROUP_DELETE", payload: groupId }); export const setGroupAttrs = (groupId, attrs) => ({ type: "MATERIALDB_GROUP_SET_ATTRS", payload: { groupId, attrs } }); export const toggleGroupView = (groupId) => ({ type: "MATERIALDB_GROUP_TOGGLE_VIEW", payload: groupId }); export const toggleGroupEdit = (groupId) => ({ type: "MATERIALDB_GROUP_TOGGLE_EDIT", payload: groupId }); /*MATERIALDB_PRESET (operations)*/ export const addPreset = (groupId, attrs = {}) => ({ type: "MATERIALDB_PRESET_ADD", payload: { groupId, attrs } }) export const deletePreset = (presetId) => ({ type: "MATERIALDB_PRESET_DELETE", payload: presetId }); export const setPresetAttrs = (presetId, attrs) => ({ type: "MATERIALDB_PRESET_SET_ATTRS", payload: { presetId, attrs } }); export const togglePresetEdit = (presetId) => ({ type: "MATERIALDB_PRESET_TOGGLE_EDIT", payload: presetId }); /*MATERIALDB PICKER*/ export const applyPreset = (presetId) => ({ type: "MATERIALDB_PRESET_APPLY", payload: presetId }); export const newPreset = (preset, grouping, name) => ({ type: "MATERIALDB_PRESET_NEW", payload: { preset, grouping, name } }) /*MATERIALDB*/ export const uploadMaterialDatabase = (file, content) => ({ type: "MATERIALDB_UPLOAD", payload: { file, database: JSON.parse(content) } }); export const importMaterialDatabase = (file, content) => ({ type: "MATERIALDB_IMPORT", payload: { file, database: content } }); export const downloadMaterialDatabase = (database) => ({ type: "MATERIALDB_DOWNLOAD", payload: { database } });
/* Copyright 2018 Onestein * License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). */ odoo.define('website_lazy_load_image.lazy_image_loader', function (require) { 'use strict'; var Class = require('web.Class'); var mixins = require('web.mixins'); /** * Handles lazy loading of images. */ var LazyImageLoader = Class.extend(mixins.EventDispatcherMixin, { /** * The instance of the jQuery lazy loading plugin. * * @type {jQuery.lazy} */ plugin: null, /** * Use this to hook on the onFinishedAll of the lazy loading plugin * of a specific instance of LazyImageLoader. * * @type {jQuery.Deferred} */ all_finished: null, /** * @class * @param {String} selector The selector for the elements to lazy load. */ init: function (selector) { mixins.EventDispatcherMixin.init.call(this); this.all_finished = $.Deferred(); this.plugin = $(selector).data('loaded', false).lazy( this._getPluginConfiguration() ); }, /** * Get the settings for the initialization of the lazy loading plugin. * * @private * @returns {Object} Lazy loading plugin settings */ _getPluginConfiguration: function () { return { afterLoad: this._afterLoad.bind(this), beforeLoad: this._beforeLoad.bind(this), onError: this._onError.bind(this), onFinishedAll: this._onFinishedAll.bind(this), chainable: false, }; }, /** * Triggered by the beforeLoad event of the lazy loading plugin. * * @param {DOMElement} el * @private */ _beforeLoad: function (el) { this.trigger('beforeLoad', el); }, /** * Triggered by the afterLoad event of the lazy loading plugin. * * @param {DOMElement} el * @private */ _afterLoad: function (el) { this.trigger('afterLoad', el); }, /** * Triggered by the onError event of the lazy loading plugin. * * @param {DOMElement} el * @private */ _onError: function (el) { this.trigger('onError', el); }, /** * Triggered by the onFinished event of the lazy loading plugin. * * @private */ _onFinishedAll: function () { this.all_finished.resolve(); this.trigger('onFinishedAll'); }, }); require('web.dom_ready'); var lazy_image_loader = new LazyImageLoader( '#wrapwrap > main img:not(.lazyload-disable), ' + '#wrapwrap > footer img:not(.lazyload-disable)' ); return { LazyImageLoader: LazyImageLoader, lazy_image_loader: lazy_image_loader, }; });
/* @flow */ import React, { Component, PropTypes } from 'react'; import ReactNative from 'react-native'; import shallowEqual from 'shallowequal'; import Colors from '../../../Colors'; import AppText from '../AppText'; import ListItem from '../ListItem'; import Icon from '../Icon'; import Time from '../Time'; import ActionSheet from '../ActionSheet'; import ActionSheetItem from '../ActionSheetItem'; import Share from '../../../modules/Share'; import { convertRouteToURL } from '../../../../lib/Route'; import { config } from '../../../../core-client'; const { StyleSheet, TouchableOpacity, View, } = ReactNative; const styles = StyleSheet.create({ item: { flex: 1, justifyContent: 'center', paddingHorizontal: 16, }, title: { color: Colors.darkGrey, fontWeight: 'bold', }, subtitle: { flexDirection: 'row', alignItems: 'center', }, label: { color: Colors.grey, fontSize: 10, lineHeight: 15, }, dot: { fontSize: 2, lineHeight: 3, marginHorizontal: 4, }, badge: { backgroundColor: Colors.accent, height: 6, width: 6, marginRight: 8, borderRadius: 3, elevation: 1, }, expand: { margin: 20, color: Colors.fadedBlack, }, }); type Props = { room: { id: string; name: string; updateTime?: number; }; unread?: boolean; onSelect: Function; } type State = { actionSheetVisible: boolean; } export default class RoomItem extends Component<void, Props, State> { static propTypes = { room: PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string, }), unread: PropTypes.bool, onSelect: PropTypes.func, }; state: State = { actionSheetVisible: false, }; shouldComponentUpdate(nextProps: Props, nextState: State): boolean { return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState); } _getRoomLink: Function = () => { const { room } = this.props; return config.server.protocol + '//' + config.server.host + convertRouteToURL({ name: 'room', props: { room: room.id, }, }); }; _getShareText: Function = () => { const { room } = this.props; return `Hey! Join me in the ${room.name} group on ${config.app_name}.\n${this._getRoomLink()}`; }; _handleInvite: Function = () => { Share.shareItem('Share group', this._getShareText()); }; _handleShowMenu: Function = () => { this.setState({ actionSheetVisible: true, }); }; _handleRequestClose: Function = () => { this.setState({ actionSheetVisible: false, }); }; _handlePress: Function = () => { if (this.props.onSelect) { this.props.onSelect(this.props.room); } }; render() { const { room, unread, } = this.props; const followers = room.counts && room.counts.follower ? room.counts.follower : 0; let followersLabel; switch (followers) { case 1: followersLabel = '1 person'; break; default: followersLabel = `${followers > 1000 ? Math.round(followers / 100) / 10 + 'k' : followers} people`; } return ( <ListItem {...this.props} onPress={this._handlePress}> <View style={styles.item}> <AppText numberOfLines={1} style={styles.title}>{room.name || 'Loading…'}</AppText> {room.updateTime ? <View style={styles.subtitle}> {unread ? <View style={styles.badge} /> : null } <Time style={styles.label} time={room.updateTime} type='long' /> <AppText style={styles.dot}>●</AppText> <AppText style={styles.label}>{followersLabel}</AppText> </View> : null } </View> <TouchableOpacity onPress={this._handleShowMenu}> <Icon name='expand-more' style={styles.expand} size={20} /> </TouchableOpacity> <ActionSheet visible={this.state.actionSheetVisible} onRequestClose={this._handleRequestClose}> <ActionSheetItem onPress={this._handleInvite}> Invite friends to group </ActionSheetItem> </ActionSheet> </ListItem> ); } }
/** * @class NetProfile.tickets.controller.TicketGrid * @extends Ext.app.Controller */ Ext.define('NetProfile.tickets.controller.TicketGrid', { extend: 'Ext.app.Controller', requires: [ 'Ext.menu.Menu' ], fromTemplateText: 'From Template', fromTemplateTipText: 'Add ticket from template', scheduleText: 'Schedule', init: function() { this.control({ 'grid_tickets_Ticket' : { beforerender: function(grid) { var tb; tb = grid.getDockedItems('toolbar[dock=top]'); if(!tb || !tb.length) return; tb = tb[0]; tb.add({ text: this.fromTemplateText, tooltip: { text: this.fromTemplateTipText, title: this.fromTemplateText }, iconCls: 'ico-add', handler: function() { grid.spawnWizard('tpl'); } }); } }, 'npwizard button#btn_sched' : { click: { scope: this, fn: function(btn, ev) { var wiz = btn.up('npwizard'), date_field = wiz.down('datetimefield[name=assigned_time]'), cfg = { dateField: date_field }, win, sched, values; values = wiz.getValues(); if(values['assigned_uid']) cfg.userId = parseInt(values['assigned_uid']); if(values['assigned_gid']) cfg.groupId = parseInt(values['assigned_gid']); if(values['ticketid']) cfg.ticketId = parseInt(values['ticketid']); if(values['tstid']) cfg.ticketStateId = parseInt(values['tstid']); if(values['tschedid']) cfg.schedulerId = parseInt(values['tschedid']); if(values['ttplid']) cfg.templateId = parseInt(values['ttplid']); win = Ext.create('Ext.ux.window.CenterWindow', { title: this.scheduleText, modal: true }); sched = Ext.create('NetProfile.tickets.view.Scheduler', cfg); win.add(sched); win.show(); return true; }} } }); } });
/** * Copyright (C) 2017 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ "use strict"; (() => { // calulate how many weeks an issue has been created. // 0 - <=1 = week 0 // >1 - <=2 = week 1 // ... module.exports = { "$ceil": { "$divide": [ {"$subtract": [new Date().valueOf(), "$$CURRENT.created"]}, // one week in milliseconds 604800000 ] } }; })();
export default (original) => { const url = getHashUrl(original); let [path, params] = url.split('?'); if (path.length >= 2) { path = path.replace(/\/$/, ''); } if (params) { params = parseSearchParams(params); } else { params = {} } const actual = path + joinSearchParams(params); return { path, params, original, actual }; } const getHashUrl = (original) => { let url = original.split('#'); if (url.length >= 2) { url = url[1]; } else { url = '/'; } if (url === '') { url = '/'; } if (url[0] !== '/') { url = '/' + url; } return url; } const parseSearchParams = (searchString) => { let pairSplit; return (searchString || '').replace(/^\?/, '').split('&').reduce((p, pair) => { pairSplit = pair.split('='); if (pairSplit.length >= 1 && pairSplit[0].length >= 1) { p[decodeURIComponent(pairSplit[0])] = decodeURIComponent(pairSplit[1]) || ''; } return p; }, {}); } const joinSearchParams = (searchParams) => { const searchString = Object .keys(searchParams) .reduce((p, paramKey) => p += `&${paramKey}=${searchParams[paramKey]}`, '?'); if (searchString.length <= 1) { return ''; } return searchString.replace('?&', '?'); }
/* * decaffeinate suggestions: * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ //############################################################################## // // CoCalc: Collaborative web-based calculation // Copyright (C) 2017, Sagemath Inc. // AGPLv3 // //############################################################################## /* Custom Prop Validation for immutable.js types, so they work just like other React prop-types. FUTURE: Put prop validation code in a debug area so that it doesn't get loaded for production In addition to React Prop checks, we implement the following type checkers: immutable, immutable.List, immutable.Map, immutable.Set, immutable.Stack, which may be chained with .isRequired just like normal React prop checks Additional validations may be added with the following signature rtypes.custom_checker_name<function ( props, propName, componentName, location, propFullName, secret ) => <Error-Like-Object or null> > Check React lib to see if this has changed. */ const check_is_immutable = function( props, propName, componentName, location, propFullName ) { if (componentName == null) { componentName = "ANONYMOUS"; } if (props[propName] == null || props[propName].toJS != null) { return null; } else { const type = typeof props[propName]; return new Error( `Invalid prop \`${propName}\` of` + ` type ${type} supplied to` + ` \`${componentName}\`, expected an immutable collection or frozen object.` ); } }; const allow_isRequired = function(validate) { const check_type = function( isRequired, props, propName, componentName, location ) { if (componentName == null) { componentName = "ANONYMOUS"; } if (props[propName] == null && isRequired) { return new Error( `Required prop \`${propName}\` was not specified in \`${componentName}\`` ); } return validate(props, propName, componentName, location); }; const chainedCheckType = check_type.bind(null, false); chainedCheckType.isRequired = check_type.bind(null, true); chainedCheckType.isRequired.category = "IMMUTABLE"; chainedCheckType.category = "IMMUTABLE"; return chainedCheckType; }; const create_immutable_type_required_chain = function(validate) { const check_type = function( immutable_type_name, props, propName, componentName ) { if (componentName == null) { componentName = "ANONYMOUS"; } if (immutable_type_name && props[propName] != null) { const T = immutable_type_name; if (props[propName].toJS == null) { return new Error( `NOT EVEN IMMUTABLE, wanted immutable.${T} ${props}, ${propName}` ); } if (require("immutable")[`${T}`][`is${T}`](props[propName])) { return null; } else { return new Error( `Component \`${componentName}\`` + ` expected ${propName} to be an immutable.${T}` + ` but was supplied ${props[propName]}` ); } } else { return validate(props, propName, componentName, location); } }; // To add more immutable.js types, mimic code below. const check_immutable_chain = allow_isRequired( check_type.bind(null, undefined) ); check_immutable_chain.Map = allow_isRequired(check_type.bind(null, "Map")); check_immutable_chain.List = allow_isRequired(check_type.bind(null, "List")); check_immutable_chain.Set = allow_isRequired(check_type.bind(null, "Set")); check_immutable_chain.Stack = allow_isRequired( check_type.bind(null, "Stack") ); check_immutable_chain.category = "IMMUTABLE"; return check_immutable_chain; }; exports.immutable = create_immutable_type_required_chain(check_is_immutable);
'use strict'; var openUrl = require('./utils').open; module.exports = new PublishQueue(); function PublishQueue() { this.openPublishQueue = function() { openUrl('/#/publish_queue'); }; this.getRow = function(rowNo) { return element.all(by.css('[ng-click="preview(queue_item);"]')).get(rowNo); }; this.getHeadline = function(rowNo) { var row = this.getRow(rowNo); return row.all(by.className('ng-binding')).get(2); }; this.getUniqueName = function(rowNo) { var row = this.getRow(rowNo); return row.all(by.className('ng-binding')).get(1); }; this.getDestination = function(rowNo) { var row = this.getRow(rowNo); return row.all(by.className('ng-binding')).get(6); }; this.previewAction = function(rowNo) { var row = this.getRow(rowNo); row.click(); }; this.openCompositeItem = function(group) { var _list = element(by.css('[data-title="' + group.toLowerCase() + '"]')) .all(by.repeater('child in item.childData')); _list.all(by.css('[ng-click="open(data)"]')).get(0).click(); }; this.getCompositeItemHeadline = function(index) { return element.all(by.className('package-item__item-headline')).get(index).getText(); }; this.getOpenedItemHeadline = function() { return element.all(by.className('headline')).get(0).getText(); }; this.getPreviewTitle = function() { return element(by.css('.content-container')) .element(by.binding('selected.preview.headline')) .getText(); }; this.searchAction = function(search) { element(by.css('.flat-searchbar')).click(); browser.sleep(100); element(by.model('query')).clear(); element(by.model('query')).sendKeys(search); }; var list = element(by.className('list-pane')); this.getItemCount = function () { browser.sleep(500); // wait for a while to get list populated. return list.all(by.repeater('queue_item in publish_queue track by queue_item._id')).count(); }; }
var PlayerWrapper = function() { this.underlyingPlayer = 'aurora'; this.aurora = {}; this.sm2 = {}; this.duration = 0; this.volume = 100; return this; }; PlayerWrapper.prototype = _.extend({}, OC.Backbone.Events); PlayerWrapper.prototype.play = function() { switch(this.underlyingPlayer) { case 'sm2': this.sm2.play('ownCloudSound'); break; case 'aurora': this.aurora.play(); break; } }; PlayerWrapper.prototype.stop = function() { switch(this.underlyingPlayer) { case 'sm2': this.sm2.stop('ownCloudSound'); this.sm2.destroySound('ownCloudSound'); break; case 'aurora': if(this.aurora.asset !== undefined) { // check if player's constructor has been called, // if so, stop() will be available this.aurora.stop(); } break; } }; PlayerWrapper.prototype.togglePlayback = function() { switch(this.underlyingPlayer) { case 'sm2': this.sm2.togglePause('ownCloudSound'); break; case 'aurora': this.aurora.togglePlayback(); break; } }; PlayerWrapper.prototype.seekingSupported = function() { // Seeking is not implemented in aurora/flac.js and does not work on all // files with aurora/mp3.js. Hence, we disable seeking with aurora. return this.underlyingPlayer == 'sm2'; }; PlayerWrapper.prototype.pause = function() { switch(this.underlyingPlayer) { case 'sm2': this.sm2.pause('ownCloudSound'); break; case 'aurora': this.aurora.pause(); break; } }; PlayerWrapper.prototype.seek = function(percentage) { if (this.seekingSupported()) { console.log('seek to '+percentage); switch(this.underlyingPlayer) { case 'sm2': this.sm2.setPosition('ownCloudSound', percentage * this.duration); break; case 'aurora': this.aurora.seek(percentage * this.duration); break; } } else { console.log('seeking is not supported for this file'); } }; PlayerWrapper.prototype.setVolume = function(percentage) { this.volume = percentage; switch(this.underlyingPlayer) { case 'sm2': this.sm2.setVolume('ownCloudSound', this.volume); break; case 'aurora': this.aurora.volume = this.volume; break; } }; PlayerWrapper.prototype.fromURL = function(typeAndURL) { var self = this; var url = typeAndURL['url']; var type = typeAndURL['type']; if (soundManager.canPlayURL(url)) { this.underlyingPlayer = 'sm2'; } else { this.underlyingPlayer = 'aurora'; } console.log('Using ' + this.underlyingPlayer + ' for type ' + type + ' URL ' + url); switch(this.underlyingPlayer) { case 'sm2': this.sm2 = soundManager.setup({ html5PollingInterval: 200 }); this.sm2.html5Only = true; this.sm2.createSound({ id: 'ownCloudSound', url: url, whileplaying: function() { self.trigger('progress', this.position); }, whileloading: function() { self.duration = this.durationEstimate; self.trigger('duration', this.durationEstimate); // The buffer may contain holes after seeking but just ignore those. // Show the buffering status according the last buffered position. var bufCount = this.buffered.length; var bufEnd = (bufCount > 0) ? this.buffered[bufCount-1].end : 0; self.trigger('buffer', bufEnd / this.durationEstimate * 100); }, onfinish: function() { self.trigger('end'); }, onload: function(success) { if (success) { self.trigger('ready'); } else { console.log('SM2: sound load error'); } } }); break; case 'aurora': this.aurora = AV.Player.fromURL(url); this.aurora.asset.source.chunkSize=524288; this.aurora.on('buffer', function(percent) { self.trigger('buffer', percent); }); this.aurora.on('progress', function(currentTime) {//currentTime is in msec self.trigger('progress', currentTime); }); this.aurora.on('ready', function() { self.trigger('ready'); }); this.aurora.on('end', function() { self.trigger('end'); }); this.aurora.on('duration', function(msecs) { self.duration = msecs; self.trigger('duration', msecs); }); break; } // Set the current volume to the newly created player instance this.setVolume(this.volume); }; PlayerWrapper.prototype.setVolume = function(vol) { console.log("setVolume not implemented");// TODO };
OC.L10N.register( "passman", { "General" : "ទូទៅ", "Done" : "Done", "Sharing" : "ការ​ចែក​រំលែក", "Share link" : "Share link", "Username" : "ឈ្មោះ​អ្នកប្រើ", "File" : "File", "Add" : "បញ្ចូល", "Type" : "Type", "Size" : "ទំហំ", "Expiration date" : "ពេល​ផុត​កំណត់", "Disabled" : "បាន​បិទ", "Export" : "នាំចេញ", "Version" : "កំណែ", "Import" : "នាំយកចូល", "Uploading" : "Uploading", "User" : "User", "Files" : "ឯកសារ", "Pending" : "កំពុង​រង់ចាំ", "Details" : "ព័ត៌មាន​លម្អិត", "by" : "ដោយ", "Save" : "រក្សាទុក", "Cancel" : "បោះបង់", "Settings" : "ការកំណត់", "Unshare" : "លែង​ចែក​រំលែក", "Password" : "ពាក្យសម្ងាត់", "URL" : "URL", "Notes" : "កំណត់​ចំណាំ", "Edit" : "កែប្រែ", "Delete" : "លុប", "Share" : "ចែក​រំលែក", "Date" : "Date", "Tags" : "ស្លាក", "Description" : "ការ​អធិប្បាយ", "You created %1$s" : "អ្នក​បាន​បង្កើត %1$s", "You deleted %1$s" : "អ្នក​បាន​លុប %1$s", "seconds ago" : "វិនាទី​មុន" }, "nplurals=1; plural=0;");
export class Toolbar { }
OC.L10N.register( "weather", { "Monday" : "Måndag", "Tuesday" : "Tysdag", "Wednesday" : "Onsdag", "Thursday" : "Torsdag", "Friday" : "Fredag", "Saturday" : "Laurdag", "Sunday" : "Søndag", "Weather" : "Vær", "Save" : "Lagre", "Add a city" : "Legg til ein by", "Add city" : "Legg til by", "City name" : "Bynamn", "Add" : "Legg til", "Cancel" : "Avbryt", "Settings" : "Instillingar", "Pressure" : "Trykk", "Humidity" : "Luftfuktigheit", "Wind" : "Vind", "Sunrise" : "Soloppgang", "Sunset" : "Solnedgang", "Date" : "Date" }, "nplurals=2; plural=(n != 1);");
import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; module('Unit | Adapter | organization cleanup', function(hooks) { setupTest(hooks); // Replace this with your real tests. test('it exists', function(assert) { let adapter = this.owner.lookup('adapter:organization-cleanup'); assert.ok(adapter); }); });
import React from 'react' import { connect } from 'react-redux' import { VelocityComponent } from 'velocity-react' import TopNav from '../components/TopNav' import NetworkNav from '../components/NetworkNav' import LeftNav, { leftNavWidth, leftNavEasing } from '../components/LeftNav' import { toggleLeftNav, updateCurrentUser } from '../actions' import { getCurrentCommunity } from '../models/community' import { getCurrentNetwork } from '../models/network' import { aggregatedTags } from '../models/hashtag' import { canInvite, canModerate } from '../models/currentUser' import { filter, get } from 'lodash/fp' const { array, bool, func, object, oneOfType, string } = React.PropTypes const makeNavLinks = (currentUser, community) => { const { slug, network } = community || {} const url = slug ? suffix => `/c/${slug}/${suffix}` : suffix => '/' + suffix const rootUrl = slug ? `/c/${slug}` : '/app' return filter('url', [ {url: rootUrl, icon: 'Comment-Alt', label: 'Conversations', index: true}, get('settings.events.enabled', community) && {url: url('events'), icon: 'Calendar', label: 'Events'}, get('settings.projects.enabled', community) && {url: url('projects'), icon: 'ProjectorScreen', label: 'Projects'}, {url: url('people'), icon: 'Users', label: 'Members'}, canInvite(currentUser, community) && {url: url('invite'), icon: 'Mail', label: 'Invite'}, {url: network && `/n/${network.slug}`, icon: 'merkaba', label: 'Network'}, canModerate(currentUser, community) && {url: url('settings'), icon: 'Settings', label: 'Settings'}, {url: slug && url('about'), icon: 'Help', label: 'About'} ]) } const PageWithNav = (props, context) => { const { leftNavIsOpen, community, networkCommunities, network, tags, path, children } = props const { dispatch, currentUser, isMobile } = context const moveWithMenu = {marginLeft: leftNavIsOpen ? leftNavWidth : 0} const toggleLeftNavAndSave = open => { if (leftNavIsOpen !== open) dispatch(toggleLeftNav()) if (!isMobile) { setTimeout(() => { const settings = {leftNavIsOpen: open} dispatch(updateCurrentUser({settings})) }, 5000) } } const openLeftNav = () => toggleLeftNavAndSave(true) const closeLeftNav = () => toggleLeftNavAndSave(false) const links = makeNavLinks(currentUser, community) const showNetworkNav = currentUser && !isMobile && networkCommunities && networkCommunities.length > 1 && !path.startsWith('/t/') const tagNotificationCount = filter(tag => tag.new_post_count > 0, tags).length return <div> {currentUser && <LeftNav opened={leftNavIsOpen} links={links} community={community} network={network} tags={tags} close={closeLeftNav} />} <TopNav currentUser={currentUser} links={links} community={community} network={network} openLeftNav={openLeftNav} leftNavIsOpen={leftNavIsOpen} path={path} opened={leftNavIsOpen} tagNotificationCount={tagNotificationCount} /> <VelocityComponent animation={moveWithMenu} easing={leftNavEasing}> <div id='main'> {showNetworkNav && <NetworkNav communities={networkCommunities} network={network || community.network} />} {children} </div> </VelocityComponent> </div> } PageWithNav.propTypes = { leftNavIsOpen: bool, community: object, network: object, networkCommunities: array, tags: object, path: string, children: oneOfType([array, object]), history: object } PageWithNav.contextTypes = {isMobile: bool, dispatch: func, currentUser: object} export default connect((state, props) => { const { leftNavIsOpen, tagsByCommunity, communitiesForNetworkNav } = state const community = getCurrentCommunity(state) const network = getCurrentNetwork(state) const networkCommunities = communitiesForNetworkNav[network ? network.id : get('network.id', community)] return { leftNavIsOpen, community, networkCommunities, network, tags: get(get('slug', community), tagsByCommunity) || aggregatedTags(state), path: state.routing.locationBeforeTransitions.pathname } })(PageWithNav)
/* * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting. * * Copyright (C) 2015 John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4. * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ function CustomReportDesignerController($scope, reports, SaveCustomReport, CustomReportFullList){ $scope.r = reports; $scope.reports = _.groupBy( $scope.r, 'category'); $scope.init = function(){ if($scope.sqleditor === undefined){ $scope.sqleditor = ace.edit("sqleditor"); $scope.sqleditor.setTheme("ace/theme/chrome"); $scope.sqleditor.getSession().setMode("ace/mode/pgsql"); $scope.filter = ace.edit("filtereditor"); $scope.filter.setTheme("ace/theme/chrome"); $scope.filter.getSession().setMode("ace/mode/json"); $scope.column = ace.edit("columneditor"); $scope.column.setTheme("ace/theme/chrome"); $scope.column.getSession().setMode("ace/mode/json"); $scope.meta = ace.edit("metaeditor"); $scope.meta.setTheme("ace/theme/chrome"); $scope.meta.getSession().setMode("ace/mode/html"); } $scope.sqleditor.setValue($scope.current.query); $scope.filter.setValue($scope.current.filters); $scope.column.setValue($scope.current.columnoptions); $scope.meta.setValue($scope.current.meta); }; $scope.select = function(report){ // clear previous values and message on screen $scope.columns = $scope.data = []; $scope.message = undefined; $scope.current = report; $scope.init(); }; $scope.New = function(){ $scope.current = {quer:'', filters:'[]',columnoptions:'[]'}; $scope.init(); }; $scope.Save = function(){ $scope.current.query = $scope.sqleditor.getValue(); $scope.current.filters = $scope.filter.getValue(); $scope.current.columnoptions = $scope.column.getValue(); $scope.current.meta = $scope.meta.getValue(); var save = SaveCustomReport.save($scope.current); save.$promise.then(function(){ $scope.message = $scope.current.name + ' saved successfully!'; $scope.current = undefined; $scope.r = CustomReportFullList.get(); $scope.r.$promise.then(function(){ $scope.reports = _.groupBy( $scope.r.reports, 'category'); }); }); }; } CustomReportDesignerController.resolve = { reports: function ($q, $timeout, CustomReportFullList) { var deferred = $q.defer(); $timeout(function () { CustomReportFullList.get(function (data) { deferred.resolve(data.reports); }); }, 100); return deferred.promise; } };
(function(global){ var PollXBlockI18N = { init: function() { (function(globals) { var django = globals.django || (globals.django = {}); django.pluralidx = function(count) { return (count == 1) ? 0 : 1; }; /* gettext library */ django.catalog = django.catalog || {}; if (!django.jsi18n_initialized) { django.gettext = function(msgid) { var value = django.catalog[msgid]; if (typeof(value) == 'undefined') { return msgid; } else { return (typeof(value) == 'string') ? value : value[0]; } }; django.ngettext = function(singular, plural, count) { var value = django.catalog[singular]; if (typeof(value) == 'undefined') { return (count == 1) ? singular : plural; } else { return value.constructor === Array ? value[django.pluralidx(count)] : value; } }; django.gettext_noop = function(msgid) { return msgid; }; django.pgettext = function(context, msgid) { var value = django.gettext(context + '\x04' + msgid); if (value.indexOf('\x04') != -1) { value = msgid; } return value; }; django.npgettext = function(context, singular, plural, count) { var value = django.ngettext(context + '\x04' + singular, context + '\x04' + plural, count); if (value.indexOf('\x04') != -1) { value = django.ngettext(singular, plural, count); } return value; }; django.interpolate = function(fmt, obj, named) { if (named) { return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])}); } else { return fmt.replace(/%s/g, function(match){return String(obj.shift())}); } }; /* formatting library */ django.formats = { "DATETIME_FORMAT": "j E Y H:i", "DATETIME_INPUT_FORMATS": [ "%d.%m.%Y %H:%M:%S", "%d.%m.%Y %H:%M:%S.%f", "%d.%m.%Y %H:%M", "%d.%m.%Y", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M", "%Y-%m-%d" ], "DATE_FORMAT": "j E Y", "DATE_INPUT_FORMATS": [ "%d.%m.%Y", "%d.%m.%y", "%y-%m-%d", "%Y-%m-%d" ], "DECIMAL_SEPARATOR": ",", "FIRST_DAY_OF_WEEK": 1, "MONTH_DAY_FORMAT": "j E", "NUMBER_GROUPING": 3, "SHORT_DATETIME_FORMAT": "d-m-Y H:i", "SHORT_DATE_FORMAT": "d-m-Y", "THOUSAND_SEPARATOR": "\u00a0", "TIME_FORMAT": "H:i", "TIME_INPUT_FORMATS": [ "%H:%M:%S", "%H:%M:%S.%f", "%H:%M" ], "YEAR_MONTH_FORMAT": "F Y" }; django.get_format = function(format_type) { var value = django.formats[format_type]; if (typeof(value) == 'undefined') { return format_type; } else { return value; } }; /* add to global namespace */ globals.pluralidx = django.pluralidx; globals.gettext = django.gettext; globals.ngettext = django.ngettext; globals.gettext_noop = django.gettext_noop; globals.pgettext = django.pgettext; globals.npgettext = django.npgettext; globals.interpolate = django.interpolate; globals.get_format = django.get_format; django.jsi18n_initialized = true; } }(this)); } }; PollXBlockI18N.init(); global.PollXBlockI18N = PollXBlockI18N; }(this));
import reducer, { addFlag, fetchAll } from '../reducer' import fetchAllSuccess from './__fixtures__/fetch_all_success' const INITIAL_STATE = reducer(undefined, {}) test('has correct defaults', () => { snapshot(INITIAL_STATE) }) test('fetch all', () => { snapshotReducer(reducer, INITIAL_STATE, fetchAll(fetchAllSuccess)) }) test('add flag', () => { snapshotReducer(reducer, INITIAL_STATE, addFlag(42), addFlag(43), addFlag(44)) })
define([ 'collections/credit_provider_collection', 'ecommerce', 'models/course_seats/credit_seat' ], function (CreditProviderCollection, ecommerce, CreditSeat) { 'use strict'; var model, data = { id: 9, url: 'http://ecommerce.local:8002/api/v2/products/9/', structure: 'child', product_class: 'Seat', title: 'Seat in edX Demonstration Course with honor certificate', price: '0.00', expires: null, attribute_values: [ { name: 'certificate_type', value: 'credit' }, { name: 'course_key', value: 'edX/DemoX/Demo_Course' }, { name: 'id_verification_required', value: false } ], is_available_to_buy: true }; beforeEach(function () { model = CreditSeat.findOrCreate(data, {parse: true}); ecommerce.credit.providers = new CreditProviderCollection([{id: 'harvard', display_name: 'Harvard'}]); }); describe('Credit course seat model', function () { describe('credit provider validation', function () { function assertCreditProviderInvalid(credit_provider, expected_msg) { model.set('credit_provider', credit_provider); expect(model.validate().credit_provider).toEqual(expected_msg); expect(model.isValid(true)).toBeFalsy(); } it('should do nothing if the credit provider is valid', function () { model.set('credit_provider', ecommerce.credit.providers.at(0).get('id')); expect(model.validate().credit_provider).toBeUndefined(); }); it('should return a message if the credit provider is not set', function () { var msg = 'All credit seats must have a credit provider.', values = [null, undefined, '']; values.forEach(function (value) { assertCreditProviderInvalid(value, msg); }); }); it('should return a message if the credit provider is not a valid credit provider', function () { var msg = 'Please select a valid credit provider.'; assertCreditProviderInvalid('acme', msg); }); }); }); } );
(function($) { $(document).ready(function() { $('.nsfw').on('click', function() { if($(this).hasClass('show')) { $(this).removeClass('show'); } else { $(this).addClass('show'); } }); $('.snip').on('click', function() { if($(this).hasClass('show')) { $(this).removeClass('show'); $(this).find('.message a').text('Read More'); } else { $(this).addClass('show'); $(this).find('.message a').text('Show Less'); } }); }); })(basic);
const t = require('tcomb') const Message = require('./message') const Messages = t.list(Message, 'Messages') module.exports = Messages
/* Copyright (c) 2016 eyeOS This file is part of Open365. Open365 is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ window.platformSettings = { lang: 'en', theme:'open365', cleanUrlParameters: false, customTitle: false, disableAnalytics: false, forceDomain: true, defaultDomain: "open365.io", publicTenant: "cloud", domainFromUrl: false, domainFromUrlExceptions: "", suggestDomain: true, enableUserRegistration: true, minBrowsersVersion: { "Chrome":30, "Firefox": 30 }, lastSettingsInFile: null // This line is to make sure that all the settings have a trailing coma };
/** * Crypto module for Geierlein. * * @author Stefan Siegl * * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ (function() { var geierlein = {}; var gzipjs = {}; var forge = {}; if(typeof(window) !== 'undefined') { geierlein = window.geierlein = window.geierlein || {}; gzipjs = window.gzipjs; forge = window.forge; } // define node.js module else if(typeof(module) !== 'undefined' && module.exports) { geierlein = { }; module.exports = geierlein.crypto = {}; gzipjs = require('../gzip-js/lib/gzip.js'); forge = require('../forge/js/forge.js'); } var crypto = geierlein.crypto = geierlein.crypto || {}; /** * The X.509 certificate with the Elster project's public key. * * The public key is used to encrypt the tax case. */ var elsterPem = '-----BEGIN CERTIFICATE-----\n' + 'MIIDKjCCAhICAQAwDQYJKoZIhvcNAQEEBQAwWTELMAkGA1UEBhMCREUxDzANBgNV\n' + 'BAoTBkVMU1RFUjEMMAoGA1UECxMDRUJBMQ8wDQYDVQQDEwZDb2RpbmcxGjAYBgNV\n' + 'BAUTETIwMDMwOTMwMTQzMzIzeDAwMCIYDzIwMDMwMTAxMDAwMDAwWhgPMjAwOTEy\n' + 'MzEyMzU5NTlaMFkxCzAJBgNVBAYTAkRFMQ8wDQYDVQQKEwZFTFNURVIxDDAKBgNV\n' + 'BAsTA0VCQTEPMA0GA1UEAxMGQ29kaW5nMRowGAYDVQQFExEyMDAzMDkzMDE0MzMy\n' + 'M3gwMDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAIKjQAK3+1WlW6Az\n' + 'bp5C0UISN7+H7KFydsH3xvmvtVHV2XpAlQJxpMt3APH1NzSAmsz7FQlsVPYcTqgd\n' + 'tzwd6s/2bINLm/owNXTjCNRjmf2NLI2cTe9Gq+ovcujFVxVLO1IYjEpj6K09KJc4\n' + 'e9F+LTyJujaRg/W/cSY7aBwPhv/+1o49IoG7nXSwmpMp6CyRZwCVT26RbVAuTJ2R\n' + 'fmDgSmcc5Tostd/gQGSwVcreElrrN2LJM2MP5xDzP5tTQGmB8tMFwEYa7otPuhjF\n' + 'eV5ry3GSlgrFqUdt8JaZ03WQD2dbPZYbNGUvuzb4GebuEdnKCwRrOiGG6bUCx8Qk\n' + 'xXy6sMsCAwEAATANBgkqhkiG9w0BAQQFAAOCAQEABu72l9QUIng2n08p5uzffJA2\n' + 'Zx04ZfKWC+dBJB6an03ax8YqxUPm+e83D341NQtLlgJ4qKn9ShNZW85YoL/I02mU\n' + '/sj50O4NAX72RwzHe/rPi+sS5BU5p4fi8YL+xN00r8R+Mbqctg8QJXleMmvuS/JF\n' + 'qB8F9m72Ud9kmZsV1Letl/qog0El4QHNnU9rSoI+MpchfDaoGvdqoVa+729SEBlc\n' + 'agWaHE8RNF43+aaVZQScvuwQZBrTJq2kqKmPm4Kg7GYuIGMqrm2/g0ldRrm8KfI2\n' + 'vxZIknBdmDknjnQHGMuLXmV3HKZTeN1F6I9BgmBXXqzTJu4gEDpY5n/h7mM+bA==\n' + '-----END CERTIFICATE-----'; /** * The Elster project's X.509 certificate as a Forge PKI instance. */ var elsterCert = forge.pki.certificateFromPem(elsterPem); /** * Perform whole encoding process of one XML piece as required by Elster specs. * * This is, take the provided data, GZIP it, encrypt it with DES3-EDE & RSA, * encode the DER encoding of the resulting PKCS#7 enveloped document with * Base64 and return it. * * @param {string} data The data block to encode. * @param {object} key The key to use to encrypt the data (as a Forge buffer) * @return {string} Base64-encoded result. */ crypto.encryptBlock = function(data, key) { // gzip data var out = gzipjs.zip(data, { level: 9 }); out = gzipjs.charArrayToString(out); out = forge.util.createBuffer(out); // encrypt data var p7 = forge.pkcs7.createEnvelopedData(); p7.addRecipient(elsterCert); p7.content = out; p7.encrypt(key.copy(), forge.pki.oids['des-EDE3-CBC']); // convert to base64 out = forge.asn1.toDer(p7.toAsn1()); return forge.util.encode64(out.getBytes(), 0); }; /** * Decrypt all the encoded parts of a response document from Elster the servers. * * This function performs the full decoding process, i.e. it decrypts the * PKCS#7 encrypted data blocks and unzips them. * * @param {string} data The XML document. * @param {object} key A Forge buffer containing the decryption key. */ crypto.decryptDocument = function(data, key) { function decryptBlock(regex) { var pieces = data.split(regex); if(pieces.length !== 5) { return; } var encBlock = pieces[2].replace(/[\r\n]*/g, ''); if(encBlock === '') { /* On error <DatenTeil> is in some cases returned empty. */ return; } /* Base64-decode block, result is DER-encoded PKCS#7 encrypted data. */ encBlock = forge.util.decode64(encBlock); /* Convert to Forge ASN.1 object. */ encBlock = forge.asn1.fromDer(encBlock); /* Convert to Forge PKCS#7 object. */ var p7 = forge.pkcs7.messageFromAsn1(encBlock); p7.decrypt(key.copy()); /* Covert Forge buffer to gzipJS buffer (array of bytes). */ var gzippedData = []; while(!p7.content.isEmpty()) { gzippedData.push(p7.content.getByte()); } /* Gunzip and replace back into pieces. */ pieces[2] = gzipjs.charArrayToString(gzipjs.unzip(gzippedData)); /* Join pieces together again. */ data = pieces.join(''); } decryptBlock(/(<\/?DatenLieferant>)/); decryptBlock(/(<\/?DatenTeil>)/); return data; }; /** * Generate a key suitable for encryptBlock function. * * @return {object} A new random DES3 key as a Forge buffer. */ crypto.generateKey = function() { return forge.util.createBuffer(forge.random.getBytes(24)); }; })();
/** * @file tools.js * @brief Used by cutes agent to invoke async actions * @copyright (C) 2014 Jolla Ltd. * @par License: LGPL 2.1 http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html */ var make_system_action = function(name) { return function() { var subprocess = require("subprocess"); subprocess.check_call("sailfish_tools_system_action", [name]); }; }; exports.removeBackups = function(msg, ctx) { var os = require("os"); var home = os.home(); if (!os.path.isDir(home)) error.raise({message: "No home directory " + home}); os.rmtree(os.path(home, ".vault")); }; exports.cleanRpmDb = make_system_action("repair_rpm_db"); exports.cleanTrackerDb = function(msg, ctx) { var os = require("os"); os.system("tracker-control", ["-krs"]); }; exports.restartKeyboard = function(msg, ctx) { var os = require("os"); os.system("systemctl", ["--user", "restart", "maliit-server.service"]); }; exports.isAndroidControlNeeded = function(msg, ctx) { var os = require("os"); var rc = os.system("rpm", ["-q", "aliendalvik"]); return (rc === 0 && os.system("rpm", ["-q", "apkd-android-settings"]) !== 0); }; exports.restartAlien = make_system_action("restart_dalvik"); exports.stopAlien = make_system_action("stop_dalvik"); exports.restartNetwork = make_system_action("restart_network"); exports.restartLipstick = make_system_action("restart_lipstick"); exports.restartDevice = make_system_action("restart_device"); exports.toggleSensors = make_system_action("toggle_sensors");
var path = require('path') var utils = require('./utils') var config = require('../config') var vueLoaderConfig = require('./vue-loader.conf') function resolve (dir) { return path.join(__dirname, '..', dir) } module.exports = { entry: { app: './src/main.js' }, output: { path: config.build.assetsRoot, filename: '[name].js', publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath }, resolve: { extensions: ['.js', '.vue', '.json'], alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src') } }, module: { rules: [ { test: /\.(js|vue)$/, loader: 'eslint-loader', enforce: 'pre', include: [resolve('src'), resolve('test')], options: { formatter: require('eslint-friendly-formatter') } }, { test: /\.vue$/, loader: 'vue-loader', options: vueLoaderConfig }, { test: /\.js$/, loader: 'babel-loader', include: [resolve('src'), resolve('test')] }, { test: /\.scss$/, loaders: ["style-loader", "css-loader", "sass-loader"] }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, // name: utils.assetsPath('img/[name].[hash:7].[ext]') name: utils.assetsPath('img/[name].[ext]') } }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]') } } ] } }
var slidedelay = $('#bannerslider').attr('data-delay'); var pauseonhover = $('#bannerslider').attr('data-pause'); var fadedelay = 2000; $(document).ready(function() { if ($('#bannerslider').hasClass("slide") && $('#bannerslider').hasClass("carousel")) { $('#bannerslider').carousel({ interval: slidedelay, pause: '"' + pauseonhover + '"' }); } else if ($('#bannerslider').hasClass("slide") && $('#imageContainer').children().length>1) { $('#imageContainer').children(':first-child').addClass("showbanner"); setTimeout(nextSlide, slidedelay); } }); function nextSlide() { var images = $('#imageContainer').children(); $(images).each( function(i) { if ($(this).hasClass("showbanner")) { $(this).fadeOut(fadedelay).removeClass("showbanner"); var nextIndex = (i == (images.length - 1)) ? 0 : i+1; $(images[nextIndex]).fadeIn(fadedelay).addClass("showbanner"); setTimeout(nextSlide, slidedelay); return false } }); }
var dir_d5c97c2750cda5d5e748b76e78cc7d4b = [ [ "Masking.cu", "_masking_8cu.html", "_masking_8cu" ] ];
'use strict'; /** * @ngdoc service * @name ortolangMarketApp.STATIC_WEBSITE_FR * @description * # STATIC_WEBSITE_FR * Constant in the ortolangMarketApp. */ angular.module('ortolangMarketApp') .constant('STATIC_WEBSITE_FR', { STATIC_WEBSITE: { PATH: { LEGAL_NOTICES: 'common/static-website/fr/legal-notices.html' }, ALL_THE_NEWS: 'Toutes les actualités...', USERS: '{{::stat}} utilisateurs', WORKSPACES: '{{::stat}} ressources', DATA: '{{::stat | bytes}} de données', FILES: '{{::stat | numbers:"fr"}} fichiers', LEGAL_NOTICES: { TITLE: 'Mentions Légales', INFO_PUBLICATION: 'Informations de publication', PUBLICATION_DIRECTOR: 'Directeur de la publication', SECONDARY_DIRECTOR: 'Directeurs adjoints', IT_MANAGER: 'Responsable informatique', IT_DEVELOPMENT: 'Développement informatique', PERSONNAL_DATA: 'Données personnelles', PERSONNAL_DATA_CONTENT_1 : 'Conformément à la Loi Informatique et Libertés, nous vous informons que la collecte de données personnelles associée à ce site est en cours de déclaration auprès de la CNIL. A aucun moment ces informations ne sont transmises à un tiers.', PERSONNAL_DATA_CONTENT_2 : 'Vous bénéficiez d\'un droit d\'accès et de rectification aux informations qui vous concernent. Si vous souhaitez exercer ce droit et obtenir communication des informations vous concernant, veuillez adresser un courrier à ATILF, 44, avenue de la libération, 54063 Nancy Cedex - France, en joignant une photocopie de votre carte d\'identité. Afin de répondre à votre demande, merci de nous fournir quelques indications (identifiant ORTOLANG) et d\'indiquer un numéro de téléphone pour vous joindre.', TERMS_OF_USE: 'Conditions générales d’utilisation', USAGE_RULES: 'Règles de bonne conduite', LIABILITY_DISCLAIMER: 'Clause de non-responsabilité', LIABILITY_DISCLAIMER_CONTENT: 'La responsabilité du CNRS et des partenaires ORTOLANG ne peut, en aucune manière, être engagée quant au contenu des informations figurant sur ce site ou aux conséquences pouvant résulter de leur utilisation ou interprétation.', INTELLECTUAL_PROPERTY: 'Propriété intellectuelle', INTELLECTUAL_PROPERTY_CONTENT: 'Le site de ORTOLANG est une oeuvre de création, propriété exclusive du CNRS, protégé par la législation française et internationale sur le droit de la propriété intellectuelle. Aucune reproduction ou représentation ne peut être réalisée en contravention avec les droits du CNRS issus de la législation susvisée.', HYPERLINKS: 'Liens hypertextes', HYPERLINKS_CONTENT: 'La mise en place de liens hypertextes par des tiers vers des pages ou des documents diffusés sur le site de ORTOLANG, est autorisée sous réserve que les liens ne contreviennent pas aux intérêts des partenaires du projet ORTOLANG, et, qu’ils garantissent la possibilité pour l’utilisateur d’identifier l’origine et l’auteur du document.', CONFIDENTIALITY: 'Politique de confidentialité', COOKIES_USE: 'Utilisation des cookies', COOKIES_USE_CONTENT: 'Le site de ORTOLANG utilise des cookies afin de réaliser des statistiques d\'audiences anonymes uniquement destinées à un usage interne. Ces statistiques sont réalisées grâce au logiciel libre et open source de mesure de statistiques web <a href="https://fr.piwik.org/" target="_blank">Piwik</a> hébergé sur nos propres serveur.', DO_NOT_TRACK: 'Ne pas autoriser à suivre mes visites', DO_NOT_TRACK_CONTENT: '<ul><li>Si la fonction "Ne pas me pister" ("Do No Track" en anglais) de votre navigateur est activée, notre outil d\'analyse web n\'enregistrera pas votre activité sur notre site.</li><li>Vous avez également la possibilité de demander à ne pas être suivi ci-dessous :</li></ul>', DO_NOT_TRACK_ACTUAL_CONFIG: 'Configuration actuelle :' } } });
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ import React from 'react'; import { translate } from '../../../helpers/l10n'; const EmptyOverview = ({ component }) => { return ( <div className="page page-limited"> <div className="alert alert-warning"> {translate('provisioning.no_analysis')} </div> <div className="big-spacer-top"> <h4>{translate('key')}</h4> <code>{component.key}</code> </div> </div> ); }; export default EmptyOverview;
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ import _ from 'underscore'; import Backbone from 'backbone'; export default Backbone.Model.extend({ idAttribute: 'key', defaults: { _hidden: false, _system: false }, _matchAttribute: function (attr, query) { var value = this.get(attr) || ''; return value.search(new RegExp(query, 'i')) !== -1; }, match: function (query) { return this._matchAttribute('name', query) || this._matchAttribute('category', query) || this._matchAttribute('description', query); }, _action: function (options) { var that = this; var opts = _.extend({}, options, { type: 'POST', data: { key: this.id }, beforeSend: function () { // disable global ajax notifications }, success: function () { options.success(that); }, error: function (jqXHR) { that.set({ _status: 'failed', _errors: jqXHR.responseJSON.errors }); } }); var xhr = Backbone.ajax(opts); this.trigger('request', this, xhr); return xhr; }, install: function () { return this._action({ url: baseUrl + '/api/plugins/install', success: function (model) { model.set({ _status: 'installing' }); } }); }, update: function () { return this._action({ url: baseUrl + '/api/plugins/update', success: function (model) { model.set({ _status: 'installing' }); } }); }, uninstall: function () { return this._action({ url: baseUrl + '/api/plugins/uninstall', success: function (model) { model.set({ _status: 'uninstalling' }); } }); } });
const keystone = require('keystone'); const Types = keystone.Field.Types; const Gallery = new keystone.List('Gallery', { autokey: { path: 'slug', from: 'title', unique: true }, map: { name: 'title' }, defaultSort: 'order' }); Gallery.add({ title: { type: String, required: true }, state: { type: Types.Select, options: 'draft, published', default: 'draft' }, order: { type: Types.Number, format: false }, items: { type: Types.Relationship, ref: 'Gallery item', many: true }, appearance: { type: Types.Select, options: 'grid, carousel, block', default: 'grid'}, description: { type: Types.Textarea } }); Gallery.defaultColumns = 'title, state|20%, order|20%' module.exports = Gallery;
isc.VStack.create({ membersMargin: 30, members: [ isc.VStack.create({ membersMargin: 30, members: [ isc.DynamicForm.create({ ID: "filterForm", width: 300, operator: "and", saveOnEnter: true, dataSource: worldDS, submit: function () { filterGrid.filterData(filterForm.getValuesAsCriteria()); }, fields: [ {name: "countryName", title: "Country Name contains", wrapTitle: false, type: "text" }, {type: "blurb", defaultValue: "<b>AND</b>" }, {name: "population", title: "Population smaller than", wrapTitle: false, type: "number", operator: "lessThan" }, {type: "blurb", defaultValue: "<b>AND</b>" }, {name: "independence", title: "Nationhood later than", wrapTitle: false, type: "date", useTextField: true, operator: "greaterThan" } ] }), isc.IButton.create({ title: "Filter", click: function () { filterForm.submit(); } }) ] }), isc.ListGrid.create({ ID: "filterGrid", width:850, height:300, alternateRecordStyles:true, dataSource: worldDS, autoFetchData: true, useAllDataSourceFields: true, fields: [ {name:"countryCode", width: 50}, {name:"government", title:"Government", width: 95}, {name:"independence", title:"Nationhood", width: 100}, {name:"population", title:"Population", width: 100}, {name:"gdp", title:"GDP ($M)", width: 85} ] }) ] });
var vueBody = new coreBody({ el: 'body', data : { user : "leasunhy", selectedTab : 'All Questions', currentOrder : 'vote', orders : ['vote', 'view', 'time'], page : 1, tasks : [], searchTerm : '', ckeInit : false, }, ready: function() { $('#taskhall-index-sticky').sticky({ offset: 60 }); $('#taskhall-index-order-dropdown').dropdown(); this.updateTasks(this, false); this.$watch('page', function() { this.updateTasks(this, false); }); this.$watch('selectedTab', function() { this.updateTasks(this, true); }); this.$watch('currentOrder', function() { this.updateTasks(this, true); }); this.$watch('searchTerm', function() { this.updateTasks(this, true); }); this.$watch('tasks', function() { $('.question.author').popup({ inline: true, position: 'right center', width: '300px', }); }); }, computed : { unansweredOnly : function() { return this.selectedTab === 'Unanswered'; } }, methods: { showAskModal : function() { $('#taskhall-index-ask-modal').modal('show'); if (!this.ckeInit) { this.ckeInit = true; CKEDITOR.replace('askcontent'); } }, updateTasks : function(store, resetPage) { if (resetPage) store.page = 1; var url = '/co-dev/list?page=' + store.page + '&order=' + store.currentOrder + '&keyword=' + store.searchTerm + (store.unansweredOnly ? '&unanswered=True' : ''); $.get(url, function(data) { store.tasks = data.tasks; console.log(data); }); $('.taskhall-index.question.item > .question.main > .detail').ellipsis(); $("html, body").animate({ scrollTop: 0 }, "slow"); }, }, });
var User = require('../config/Sequelize.js').import('../models/User.js'); module.exports = function(app) { function indexController(request, response) { User.findOne({ where: { 'username': 'admin' } }).then(function(userObj) { if(userObj === null) { var salt = User.generateSalt(); User.create({ name: "Administrator", username: "admin", password: User.generateHash("admin", salt), salt: salt, cellphone: '99999999999999', email: 'admin@admin', administrator: true }).then(function() { if(request.isAuthenticated() && request.user.dataValues.administrator) { return response.redirect("/configuration/projects"); } else if(request.isAuthenticated()) { return response.redirect("/configuration/projects"); } else { app.locals.activeProject = {}; return response.redirect("/login"); } }).catch(function(err) { console.log(err); }); } else { if(request.isAuthenticated() && request.user.dataValues.administrator) { return response.redirect("/configuration/projects"); } else if(request.isAuthenticated()) { return response.redirect("/configuration/projects"); } else { app.locals.activeProject = {}; return response.redirect("/login"); } } }); } return indexController; };
if(typeof define !== 'function') var define = require('amdefine')(module); define(["require","deep/deep", "./ajax"],function (require, deep, Ajax) { deep.store.jqueryajax = deep.store.jqueryajax || {}; deep.store.jqueryajax.HTML = deep.compose.Classes(Ajax, { headers:{ "Accept" : "text/html; charset=utf-8" }, dataType:"html", bodyParser : function(data){ if(typeof data === 'string') return data; if(data.toString()) return data.toString(); return String(data); }, responseParser : function(data, msg, jqXHR){ return data.toString(); } }); //__________________________________________________ deep.extensions.push({ extensions:[ /(\.(html|htm|xhtm|xhtml)(\?.*)?)$/gi ], store:deep.store.jqueryajax.HTML }); deep.store.jqueryajax.HTML.createDefault = function(){ new deep.store.jqueryajax.HTML("html"); }; return deep.store.jqueryajax.HTML; });
import {ModelAttributeMetaData} from 'administration/model-management/meta/model-attribute-meta'; /** * Represents a specific field meta data extending from {@link ModelAttributeMetaData} * * @author Svetlozar Iliev */ export class ModelFieldMetaData extends ModelAttributeMetaData { constructor(id) { super(id); } }
var yhr = require('./main.js'); module.exports = function(uri,opt){ return yhr('DELETE',uri,null,opt); };
import _cloneRegExp from './internal/_cloneRegExp'; import _curry2 from './internal/_curry2'; import _isRegExp from './internal/_isRegExp'; import toString from './toString'; /** * Determines whether a given string matches a given regular expression. * * @func * @memberOf R * @since v0.12.0 * @category String * @sig RegExp -> String -> Boolean * @param {RegExp} pattern * @param {String} str * @return {Boolean} * @see R.match * @example * * R.test(/^x/, 'xyz'); //=> true * R.test(/^y/, 'xyz'); //=> false */ var test = /*#__PURE__*/_curry2(function test(pattern, str) { if (!_isRegExp(pattern)) { throw new TypeError('‘test’ requires a value of type RegExp as its first argument; received ' + toString(pattern)); } return _cloneRegExp(pattern).test(str); }); export default test;
module.exports = { 'Auth': { 'Token': process.env['NODE_AUTH'] || '' } }
import firebase from 'firebase' export default function ({ isServer, store, req, redirect }) { // Don't run this middleware on the server if (isServer) { // TODO: check cookie return } else { console.log('firebase.auth().currentUser =', firebase.auth().currentUser) if (firebase.auth().currentUser === null) return redirect('/login') } }
(function() { var app = angular.module('hebergement', []); app.controller('TabController', function(){ this.tab = 1; this.setTab = function(newValue){ this.tab = newValue; }; this.isSet = function(tabName){ return this.tab === tabName; }; }); app.controller('HostingController', function(){ var host = {}; this.addHost = function(){ // Ajout d'un hébergement } }); app.directive('formLogin', function(){ return { restrict: 'E', templateUrl : 'snips/form-login.html' }; }); app.directive('formCreateAccount', function(){ return { restrict: 'E', templateUrl : 'snips/form-create-account.html' }; }); })();
const { environment } = require('@rails/webpacker') const webpack = require('webpack'); environment.toWebpackConfig().merge({ resolve: { alias: { 'jquery': 'jquery/src/jquery' } } }); module.exports = environment
JabberApp.module('DashboardApp.Show', function(Show, App, Backbone, Marionette, $, _) { Show.Layout = App.Views.Layout.extend({ template: require('./tpl/layout.hbs') , regions: { upcomingRegion: '#upcoming-region' , theatreRegion: '#theatre-region' } }); });
({ // for an explanation of these fields, you should go through // https://github.com/jrburke/r.js/blob/master/build/example.build.js baseUrl: '${basedir}/src/main/webapp/js', inlineText: true, useStrict: false, name: '../../scripts/almond', include: ['main'], insertRequire: ['main'], out: '${project.build.directory}/${project.build.finalName}/build/app.js', wrap: false, mainConfigFile: '${basedir}/src/main/webapp/js/main.js', preserveLicenseComments: true, logLevel: 0, stubModules: ['text', 'hgn', 'hb'], optimize: 'closure', pragmasOnSave: { // exclude compiler logic from Hogan.js and customHandlebars.js excludeHogan: true, excludeHandlebars: true } })
import inspectISOBMFF from "isobmff-inspector"; import render from "./renderer.js"; // -- Feature switching based on the various API support -- if (window.File && window.FileReader && window.Uint8Array) { /** * @param {Event} evt * @returns {Boolean} */ function onFileSelection(evt) { const files = evt.target.files; // FileList object if (!files.length) { return; } const file = files[0]; const reader = new FileReader(); // TODO read progressively to skip mdat and whatnot reader.onload = (evt) => { const arr = new Uint8Array(evt.target.result); const res = inspectISOBMFF(arr); render(res); }; reader.readAsArrayBuffer(file); return false; } document.getElementById("file-input") .addEventListener("change", onFileSelection, false); } else { const localSegmentInput = document.getElementById("choices-local-segment"); localSegmentInput.style.display = "none"; const choiceSeparator = document.getElementById("choices-separator"); choiceSeparator.style.display = "none"; } if (window.fetch && window.Uint8Array) { /** * @param {Event} evt */ function onUrlValidation(url) { fetch(url) .then(response => response.arrayBuffer()) .then((arrayBuffer) => { const parsed = inspectISOBMFF(new Uint8Array(arrayBuffer)); render(parsed); }); } /** * @returns {Boolean} */ function onButtonClicking() { const url = document.getElementById("url-input").value; if (url) { onUrlValidation(url); return false; } } /** * @param {Event} evt * @returns {Boolean} */ function onInputKeyPress(evt) { const keyCode = evt.keyCode || evt.which; if (keyCode == 13) { const url = evt.target.value; if (url) { onUrlValidation(url); } return false; } } document.getElementById("url-input") .addEventListener("keypress", onInputKeyPress, false); document.getElementById("url-button") .addEventListener("click", onButtonClicking, false); } else { const choiceSeparator = document.getElementById("choices-separator"); choiceSeparator.style.display = "none"; const urlSegmentInput = document.getElementById("choices-url-segment"); urlSegmentInput.style.display = "none"; }
// Particle var position = new Vector(0, 0); var velocity = new Vector(0, 0); var size = 42; var mass = 42; var color = [0, 0, 0]; var particle = new Particle(position, velocity, size, mass, color); console.log('p', particle);
var baseURL = window.location.pathname; var webRoot = "/"+baseURL.split("/")[1]; $(function(){ $('#logo_top').click(function() { window.location = webRoot; }); $('.link_formate').click(function() { $('.selected_menu').removeClass('selected_menu'); $(this).addClass('selected_menu'); window.location = webRoot+"/Formate"; }); $('.link_iniciativas').click(function() { $('.selected_menu').removeClass('selected_menu'); $(this).addClass('selected_menu'); window.location = webRoot+"/Iniciativas"; }); $('.link_perfil').click(function() { $('.selected_menu').removeClass('selected_menu'); $(this).addClass('selected_menu'); window.location = webRoot+"/usuarios/perfil"; }); $('.btn_usuario').click(function() { let id = $(this).attr('id').split('_')[2]; window.location = webRoot+"/usuarios/perfil/"+id; }); $('#btn_abrirSideMenu').click(function() { $('#sideMenu').show(); $(this).hide(); $('#btn_cerrarSideMenu').show(); }); $('#btn_cerrarSideMenu').click(function() { $('#sideMenu').hide(); $(this).hide(); $('#btn_abrirSideMenu').show(); }); }); function mainMenu() { console.log('click'); if($('#mainMenu').is(':visible')){ $('#mainMenu').hide(); } else $('#mainMenu').show(); } //Funcion CSS function ajustarMarginTop(elementoId,newMarginTop){ var elemento = document.getElementById(elementoId); var cssMarginTop = $('#'+elementoId).css("margin-top"); //var cssMargin = $('#'+elementoId).css("margin").split(" "); //elemento.style.margin = newMarginTop+"px "+cssMargin[1]+" "+cssMargin[2]+" "+cssMargin[3] ; //elemento.style.margin = $('#'+elementoId).css("margin").replace(cssMarginTop,newMarginTop+"px");; }