code
stringlengths 2
1.05M
|
---|
'use strict';
/*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
const
{validators} = require('@pzlr/build-core');
/**
* RegExp to match a tag declaration body
*
* @type {!RegExp}
* @example
* ```
* <div class="foo">
* ```
*/
exports.tagRgxp = /<[^>]+>/;
/**
* RegExp to match a component element class
*
* @type {!RegExp}
* @example
* ```
* b-foo__bla-bar
* ```
*/
exports.componentElRgxp = new RegExp(`\\b${validators.baseBlockName}__[a-z0-9][a-z0-9-_]*\\b`);
/**
* RegExp to match declaration of an object literal
*
* @type {!RegExp}
* @example
* ```
* [1, 2]
* {a: 1}
* ```
*/
exports.isObjLiteral = /^\s*[[{]/;
/**
* RegExp to match requiring of svg images
*
* @type {!RegExp}
* @example
* ```
* require('foo.svg')
* ```
*/
exports.isSvgRequire = /require\(.*?\.svg[\\"']+\)/;
/**
* RegExp to detect V4Fire specific attributes
* @type {!RegExp}
*/
exports.isV4Prop = /^(:|@|v-)/;
/**
* RegExp to detect V4Fire specific static attributes
* @type {!RegExp}
*/
exports.isStaticV4Prop = /^[^[]+$/;
/**
* RegExp to detect commas
* @type {!RegExp}
*/
exports.commaRgxp = /\s*,\s*/;
/**
* RegExp to detect Snakeskin file extensions
* @type {!RegExp}
*/
exports.ssExtRgxp = /\.e?ss$/;
|
'use strict';
var mysql = require('mysql'); // https://www.npmjs.com/package/mysql
/*
MySQL washer
input: TODO
output: Writes an array of Items to a MySQL table
*/
ns('Washers', global);
Washers.MySQL = function(config, job) {
Washer.call(this, config, job);
this.name = 'MySQL';
this.className = Helpers.buildClassName(__filename);
this.output = _.merge({
description: 'Writes an array of Items to a MySQL table',
prompts: [{
name: 'hostname',
message: 'What\'s the hostname of the MySQL server?',
default: 'localhost'
}, {
name: 'port',
message: 'What port is the MySQL server listening on?',
default: 3306,
validate: function(value, answers) {
return value && validator.isInt(value.toString());
}
}, {
name: 'username',
message: 'What username should we log in with?'
}, {
name: 'password',
message: 'What password should we use?',
validate: function(value, answers) {
return true;
}
}, {
name: 'database',
message: 'What\'s the name of the database to use?'
}]
}, this.output);
};
Washers.MySQL.prototype = Object.create(Washer.prototype);
Washers.MySQL.className = Helpers.buildClassName(__filename);
Washers.MySQL.prototype.doOutput = function(items, callback) {
// The schema is a mapping of object properties to JavaScript types.
var schema = new allItems[items[0].className]();
var primaryKey = schema._primaryKey;
schema = Helpers.typeMap(schema);
var table = mysql.escapeId(this.job.name);
// A mapping of JavaScript types to MySQL types.
var typeMap = {
string: 'MEDIUMTEXT',
date: 'DATETIME',
array: 'MEDIUMTEXT', // Someday JSON? http://dev.mysql.com/doc/refman/5.7/en/json.html
object: 'MEDIUMTEXT', // Someday JSON? http://dev.mysql.com/doc/refman/5.7/en/json.html
number: 'NUMERIC',
boolean: 'BOOL'
};
var connection = mysql.createConnection({
host: this.hostname,
port: this.port,
user: this.username,
password: this.password,
database: this.database,
// debug: commander.verbose
});
var that = this;
async.waterfall([
function(callback) {
// Connect to the database.
connection.connect(function(err) {
callback(err);
});
},
function(callback) {
// Create the table.
var query = 'CREATE TABLE IF NOT EXISTS ' + table + ' (\n';
Object.keys(schema).forEach(function(column, i) {
if (i > 0) {
query += ',\n';
}
query += mysql.escapeId(column);
query += ' ' + typeMap[schema[column]];
});
// Define the primary key to prevent duplicates.
if (primaryKey) {
if (schema[primaryKey] !== 'number' && schema[primaryKey] !== 'date') {
query += ', PRIMARY KEY (' + mysql.escapeId(primaryKey) + ' (100))';
} else {
query += ', PRIMARY KEY (' + mysql.escapeId(primaryKey) + ')';
}
}
query += ')';
that.job.log.debug(query);
connection.query(query, function(err, results) {
callback(err);
});
},
function(callback) {
// Insert items.
async.eachSeries(items, function(item, callback) {
var query = 'INSERT INTO ' + table + '(' + Object.keys(schema).join(', ') + ') VALUES (';
query += Object.keys(schema).map(function(key) {
var val = item[key];
if (key.indexOf('_') !== -1) {
val = Object.byString(item, key.replace('_', '.'));
}
if (schema[key] === 'date') {
val = val.format();
} else if (schema[key] === 'array' || schema[key] === 'object') {
val = JSON.stringify(val);
}
return connection.escape(val);
}).join(', ');
query += ')';
that.job.log.debug(query);
// Handle errors, if it's a duplicate that's fine, continue on.
connection.query(query, function(err, result) {
if (err && err.code === 'ER_DUP_ENTRY') {
err = null;
}
callback(err);
});
}, callback);
}
], function(err) {
// Disconnect and exit.
connection.destroy();
callback(err);
});
};
module.exports = Washers.MySQL;
|
export const ic_print_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M19 8h-1V3H6v5H5c-1.66 0-3 1.34-3 3v6h4v4h12v-4h4v-6c0-1.66-1.34-3-3-3zM8 5h8v3H8V5zm8 12v2H8v-4h8v2zm2-2v-2H6v2H4v-4c0-.55.45-1 1-1h14c.55 0 1 .45 1 1v4h-2z"},"children":[]},{"name":"circle","attribs":{"cx":"18","cy":"11.5","r":"1"},"children":[]}]};
|
// Call this somethings that is triggered when upload page is loaded
function init() {
// Globals
var user = window.globaData.user;
var focusEntity = window.globaData.focusEntity;
var path = location.pathname;
var columnTypes = [];
var file = null;
var title = null;
// calculate once
var timezoneOffset = 0;// new Date().getTimezoneOffset() / 60 * (-1) ;
var dateFormatOptions = {
weekday: "long",
year: "numeric", month: "short",
day: "numeric", hour: "2-digit", minute: "2-digit"
};
var data = {
parentID: user._id,
parentCollectionName: user.__t // will never change unless model name changes
}
function buildNotification(notification){
var noteTime = new Date( notification.dateAdded );
noteTime.setHours( noteTime.getHours() - timezoneOffset );
var containerSettings = {
id: 'notification-'+ notification._id,
class: 'pure-g notification'
};
var isNewSettings = {
id: 'notification-'+ notification._id +'-is-new',
class: 'pure-u-1-8 notification-content',
href: '/notifications/'+ notification._id,
html: !notification.read ? '<span class="pure-badge-success">New</span>' : ''
};
var dateSettings = {
id: 'notification-'+ notification._id +'-date',
class: 'pure-u-5-24 notification-content',
href: '/notifications/'+ notification._id,
html: '<p>'+ noteTime.toLocaleTimeString("en-us", dateFormatOptions) +'</p>'
};
var bodySettings = {
id: 'notification-'+ notification._id +'-body',
class: 'pure-u-10-24 notification-content',
href: '/notifications/'+ notification._id,
html: '<p>'+ notification.title +'</p>'
};
var deleteContainerSettings = {
id: 'notification-'+ notification._id +'-delete-container',
class: 'pure-u-5-24 notification-content'
}
var deleteButtonSettings = {
id: 'notification-'+ notification._id +'-delete',
class: 'pure-button pure-button-error',
html: 'Delete'
}
var container = $('<div/>', containerSettings);
var isNew = $("<a/>", isNewSettings);
var date = $("<a/>", dateSettings);
var body = $("<a/>", bodySettings);
var deleteContainer = $("<div/>", deleteContainerSettings);
var deleteButton = $('<button/>', deleteButtonSettings)
deleteContainer.append( deleteButton );
container.append( isNew );
container.append( date );
container.append( body );
container.append( deleteContainer );
deleteButton.click(function(){
$.ajax({
url: '/api/notifications' ,
type: 'DELETE',
cache: false,
data: {notificationID: notification._id}
}).success(function(data){
container.remove();
}).error(function(err){
displayError();
});
});
return container;
}
function constructDisplay(notifications){
var container = $('#notifications-container');
notifications.forEach( function(note){
container.append( buildNotification( note ) );
});
}
function displayError(){
console.log('bad error')
}
$.ajax({
url: '/api/notifications',
type: 'GET',
dataType: 'json',
cache: false,
data: data
}).success(function(data){
constructDisplay( data );
}).error(function(err){
displayError();
});
}
document.addEventListener("DOMContentLoaded", init);
|
var foo = [1, 2];
foo.push(3, 4), foo.push(5);
foo.push(6);
|
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {List, Button} from 'react-onsenui';
import Medicine from './Medicine';
import * as Actions from '../actions';
const MedicineList = ({medicines, navigator, actions}) => {
const changeVisibility = (isVisible) => {
Object.keys(medicines).map((key) => {
const medicine = medicines[key];
medicine.isVisible = isVisible;
actions.addMedicine(medicine);
});
};
return (
<div>
<Button onClick={() => changeVisibility(true)}>表示</Button>
<Button onClick={() => changeVisibility(false)}>非表示</Button>
<List
dataSource={Object.keys(medicines).map((key) => medicines[key]).filter(medicine => medicine.isVisible)}
renderRow={(medicine) =>
<Medicine
key={medicine.id}
navigator={navigator}
{...medicine}
/>
}
/>
</div>
);
};
const mapStateToProps = (state) => ({
medicines: state.medicines
});
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators(Actions, dispatch)
};
};
export default connect(mapStateToProps, mapDispatchToProps)(MedicineList);
|
// BASE SETUP
// ======================================
// CALL THE PACKAGES --------------------
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser'); // get body-parser
var morgan = require('morgan'); // used to see requests
var mongoose = require('mongoose');
var config = require('./config');
var path = require('path');
// log all requests to the console
app.use(morgan('dev'));
// set static files location
// used for requests that our frontend will make
app.use(express.static(__dirname + '/public'));
// MAIN CATCHALL ROUTE ---------------
// SEND USERS TO FRONTEND ------------
// has to be registered after API ROUTES
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/index.html'));
});
// START THE SERVER
// ====================================
app.listen(config.port);
console.log('Magic happens on port ' + config.port);
|
import React, {Component} from 'react'
import './myCreateTeam.scss'
import { connect } from 'react-redux'
import {Link} from 'react-router'
import { tipShow } from '../../../../components/Tips/modules/tips'
import Select from '../../../../components/Select'
import Confirm,{confirmShow} from '../../../../components/Confirm'
import Modal,{modalShow,modalHide,modalUpdate} from '../../../../components/Modal'
import {addOrganization,getCatelogy,getOrganizationByMe,modifyOrganization,deleteOrganization,getMyOrganization} from './modules'
// import {fetchCatelogue} from '../../../../reducers/category'
import {asyncConnect} from 'redux-async-connect'
@asyncConnect([{
promise: ({store: {dispatch, getState}}) => {
// const promises = [];
// if (!getState().catelogues.isloaded) {
// promises.push(dispatch(fetchCatelogue()));
// }
// return Promise.all(promises);
}
}])
@connect(
state => ({
auth:state.auth,
// catelogues:state.catelogues
}),
{modalShow,modalHide,modalUpdate,tipShow,confirmShow}
)
export default class myCreateTeam extends Component {
state = {
hasImg:false,
items:[],
OrganizationByMe:[]
}
static contextTypes = {
router: React.PropTypes.object.isRequired
};
componentWillMount =()=>{
getCatelogy().then(({data})=>{
this.setState({
items:data.data
})
})
this.updateDate()
}
updateDate = ()=>{
getOrganizationByMe().then(({data})=>{
if (data.status == 200) {
this.setState({
OrganizationByMe:data.data
})
}else if (data.status==600) {
this.props.dispatch({type:"AUTHOUT"})
this.context.router.push('/login')
}{
this.props.tipShow({type:'error',msg:data.msg})
}
})
}
modifyHead =(e)=>{
//判断文件类型
var value = e.target.value
var filextension=value.substring(value.lastIndexOf("."),value.length);
filextension = filextension.toLowerCase();
if ((filextension!='.jpg')&&(filextension!='.gif')&&(filextension!='.jpeg')&&(filextension!='.png')&&(filextension!='.bmp'))
{
this.props.tipShow({type:'error',msg:'文件类型不正确'})
return;
}
if (document.getElementById('editCanvas')) { //清空画布
document.getElementById('editCanvas').getContext("2d").clearRect(0,0,300,150);
}
var imageUrl = window.URL.createObjectURL(e.target.files[0])
var content = <div id="headerEdit" onWheel={this.imgZoom} style={{width:"400px",height:'250px',position:'relative',margin:'0 auto',backgroundImage:`url(${imageUrl})`,backgroundPosition:'center',backgroundRepeat:'no-repeat',backgroundSize:'100%'}}>
<div style={{width:'400px',height:'75px',float:'left',margin:'0',background:'rgba(0,0,0,0.4)'}}></div>
<div style={{width:'150px',height:'100px',float:'left',margin:'0',background:'rgba(0,0,0,0.4)'}}></div>
<canvas id="editCanvas" width="100" height="100" style={{width:'100px',height:'100px',float:'left',margin:'0',cursor:'move',border:'1px solid white'}} onMouseDown={this.start} onMouseUp={this.end} onMouseOut={this.end} ></canvas>
<div style={{width:'150px',height:'100px',float:'left',margin:'0',background:'rgba(0,0,0,0.4)'}}></div>
<div style={{width:'400px',height:'75px',float:'left',margin:'0',background:'rgba(0,0,0,0.4)'}}></div>
<img id="editImg" src={imageUrl} alt="" style={{display:'none'}}/>
</div>
this.props.modalShow({header:"修改头像",content:content,submit:this.modifyHeadSubmit})
this.setState({
canvas:e.target.parentNode.parentNode.parentNode.getElementsByTagName('canvas')[0]
})
}
imgZoom =(e)=>{ //放大缩小图片
var element = document.getElementById('headerEdit')
if(parseFloat(element.style.backgroundSize.slice(0,-1))>400){
element.style.backgroundSize = "400%"
return
}
if(parseFloat(element.style.backgroundSize.slice(0,-1))<25){
element.style.backgroundSize = "25%"
return
}
if(e.deltaY > 0){
element.style.backgroundSize = parseFloat(element.style.backgroundSize.slice(0,-1))/1.1+'%'
}else{
element.style.backgroundSize = parseFloat(element.style.backgroundSize.slice(0,-1))*1.1+'%'
}
}
modifyHeadSubmit =()=>{ //提交
this.editInit()
var element = document.getElementById('headerEdit')
var image = document.getElementById('editImg')
var ratio = image.width*100/(400*parseFloat(element.style.backgroundSize.slice(0,-1)))
var ctx= this.state.canvas.getContext("2d");
var X = (this.divcenter.offsetLeft - (400-image.width/ratio)/2) * ratio;
var Y = (this.divcenter.offsetTop - (250-image.height/ratio)/2) * ratio;
ctx.drawImage(image,X,Y,100*ratio,100*ratio,0,0,100,100)
this.setState({
hasImg:true
})
this.props.modalHide()
}
editInit=(e)=>{
var headerEdit = document.getElementById('headerEdit')
if(!this.divtop)this.divtop = headerEdit.getElementsByTagName('div')[0]
if(!this.divcenterLeft)this.divcenterLeft = headerEdit.getElementsByTagName('div')[1]
if(!this.divcenter)this.divcenter = headerEdit.getElementsByTagName('canvas')[0]
if(!this.divcenterRight)this.divcenterRight = headerEdit.getElementsByTagName('div')[2]
if(!this.divottom)this.divottom = headerEdit.getElementsByTagName('div')[3]
}
start =(e)=>{ //可移动选区
this.editInit()
var startX = e.clientX;
var startY = e.clientY;
document.onmousemove = (e)=>{
var diffX = e.clientX - startX
var diffY = e.clientY - startY
var divtopH = Math.min(150,parseFloat(this.divtop.style.height.slice(0,-2))+ diffY)
var divleftW = Math.min(300,parseFloat(this.divcenterLeft.style.width.slice(0,-2))+ diffX)
divleftW = Math.max(0,divleftW)
if (divleftW == 0) {
this.divcenterLeft.style.height = 0;
}else{
this.divcenterLeft.style.height = '100px';
}
this.divtop.style.height = divtopH + 'px';
this.divcenterLeft.style.width = divleftW + 'px'
this.divcenterRight.style.width = 300 - divleftW + 'px'
this.divottom.style.height = (150-divtopH) + 'px';
startX = e.clientX;
startY = e.clientY;
}
}
end =(e)=>{
document.onmousemove = null;
}
modifyOrganization =(e,id,oname)=>{
var name = this.refs['organizationName'+id].value;
var brief = this.refs['organizationBrief'+id].value;
if (!name || name.length > 38) {
this.props.tipShow({type:"error",msg:"名称不为空或者大于30位字符"})
return
}
if (!brief || brief.length > 995) {
this.props.tipShow({type:"error",msg:"简介不为空或者大于1000位字符"})
return
}
var img = this.state.canvas
var fd=new FormData();
if (this.state.hasImg) {
var data=img.toDataURL();
data=data.split(',')[1];
data=window.atob(data);
var ia = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
ia[i] = data.charCodeAt(i);
};
var blob=new Blob([ia], {type:"image/png"});
fd.append('file',blob);
}
fd.append('name',name)
fd.append('brief',brief)
fd.append('id',id)
modifyOrganization(fd).then(({data})=>{
if (data.status == 200) {
this.state[oname] = false
this.setState({})
this.updateDate()
}else{
this.props.tipShow({type:"error",msg:data.msg})
return
}
})
}
verfied =(name,brief,speciality)=>{
if (!name || name.length > 38) {
this.props.tipShow({type:"error",msg:"名称不为空或者大于30位字符"})
return
}
if (!brief || brief.length > 295) {
this.props.tipShow({type:"error",msg:"简介不为空或者大于300位字符"})
return
}
if (!speciality) {
this.props.tipShow({type:"error",msg:"选择一个类目"})
return
}
var img = this.state.canvas
if (!this.state.hasImg) {
this.props.tipShow({type:"error",msg:"选择一张头像"})
return
}
var data=img.toDataURL();
data=data.split(',')[1];
data=window.atob(data);
var ia = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
ia[i] = data.charCodeAt(i);
};
var blob=new Blob([ia], {type:"image/png"});
var fd=new FormData();
fd.append('file',blob);
fd.append('name',name)
fd.append('brief',brief)
fd.append('categoryId',speciality)
return fd
}
addOrganization =(e)=>{
var name = this.refs.organizationName.value;
var brief = this.refs.organizationBrief.value;
var speciality = this.refs.speciality.getValue();
var fd = this.verfied(name,brief,speciality)
addOrganization(fd).then(({data})=>{
if (data.status == 200) {
this.setState({
isShowAdd:false
})
this.updateDate()
}else{
this.props.tipShow({type:"error",msg:data.msg})
return
}
})
}
createNew =()=>{
if (this.state.OrganizationByMe.length > 4) {
this.props.tipShow({type:"error",msg:"最多可创建5个社团"})
return
}
this.setState({isShowAdd:true})
}
confirmDelete =()=>{
if (!this.state.deleteId) {
this.props.tipShow({type:"error",msg:"未选中条目"})
return
}
deleteOrganization(this.state.deleteId).then(({data})=>{
// console.log(data)
if (data.status == 200) {
for (var i = this.state.OrganizationByMe.length - 1; i >= 0; i--) {
if(this.state.OrganizationByMe[i].id == this.state.deleteId){
this.state.OrganizationByMe.splice(i,1)
this.setState({})
break;
}
};
}else if (data.status==600) {
this.props.dispatch({type:"AUTHOUT"})
this.context.router.push('/login')
}{
this.props.tipShow({type:'error',msg:data.msg})
}
})
}
deleteOrganization =(e,id)=>{
this.setState({
deleteId:id
})
this.props.confirmShow({submit:this.confirmDelete})
}
render () {
return (
<div className="team">
<div className="createTeam">
{this.state.OrganizationByMe.length == 0 && <div className="text-center">您还没有创建社团耶~</div>}
{this.state.OrganizationByMe.map((item,index)=>{
var headImg = `/originImg?name=${item.head}&from=organizations`
var date = new Date(item.time)
var time = `${date.getFullYear()}-${(date.getMonth()+1)< 10 ? '0'+(date.getMonth()+1) :(date.getMonth()+1) }-${date.getDate()} ${date.getHours()}:${date.getMinutes() < 10 ? '0'+date.getMinutes():date.getMinutes()}`
var organizationName = `organizationName${item.id}`
var organizationBrief = `organizationBrief${item.id}`
var link = `/organizationsHome/${item.id}`
var linkApproval = `/memberCenter/requestApproval/${item.id}`
return <div className="items" key = {index}>
{!this.state[item.name] && <div>{item.name}<span><Link to={link} >去社团主页</Link><Link to={linkApproval} >{item.requests > 0 && <span className="noRead">{item.requests}</span>} 入社申请</Link><a onClick={(e)=>{this.state[item.name] = true;this.setState({})}}><i className="fa fa-edit"></i>修改</a><a onClick={(e)=>this.deleteOrganization(e,item.id)}><i className="fa fa-trash"></i>解散</a></span></div>}
{!this.state[item.name] && <img src={headImg} />}
<ul>
{!this.state[item.name] && <li><span>所属类别:</span>{item.categoryName}</li>}
{!this.state[item.name] && <li><span>创建时间:</span>{time}</li>}
{!this.state[item.name] && <li><span>社团简介:</span>{item.brief}</li>}
{this.state[item.name] && <li className="editLi">
<canvas style={{background:`url(${headImg})`}} width="100" height="100" ></canvas>
<div>
<button className="btn-default modifyHead">修改社团头像<input onChange={this.modifyHead} type="file" /></button>
</div>
<p>修改名称</p>
<div>
<input defaultValue={item.name} ref={organizationName} type="text"/>
</div>
<p>填写简介</p>
<div>
<textarea defaultValue={item.brief} ref={organizationBrief} cols="30" rows="10" ></textarea>
</div>
<div>
<button onClick={(e)=>{this.state[item.name] = false;this.setState({})}} className="btn-default">取消</button>
<button onClick={(e)=>this.modifyOrganization(e,item.id,item.name)} className="submit btn-success">提交</button>
</div>
</li>}
</ul>
</div>
})}
<div className="addBtn">
<button className="btn-success" onClick={this.createNew}>创建新社团</button>
</div>
{this.state.isShowAdd && <ul className="addNew">
<li>
<p><1.选择社团头像</p>
<div>
<button className="btn-default modifyHead">选择图片<input onChange={this.modifyHead} type="file" /></button>
</div>
<canvas id="showEdit" width="100" height="100" ></canvas>
</li>
<li>
<p><2.选择类目</p>
<div>
<Select header="选择类目" optionsItems={this.state.items} ref="speciality" />
</div>
</li>
<li>
<p><3.名称</p>
<div>
<input ref="organizationName" type="text"/>
</div>
</li>
<li>
<p><4.填写简介</p>
<div>
<textarea ref="organizationBrief" cols="30" rows="10" defaultValue="不超过300个字符"></textarea>
</div>
</li>
<li>
<p><5.提交</p>
<div>
<button onClick={()=>{this.setState({isShowAdd:false})}} className="btn-default">取消</button>
<button onClick={this.addOrganization} className="submit btn-success">提交</button>
</div>
</li>
</ul>}
</div>
<Modal />
<Confirm />
</div>
)
}
}
myCreateTeam.propTypes = {
auth: React.PropTypes.object
}
|
'use strict';
var bcrypt = require('bcrypt');
var expect = require('chai').expect;
var uuid = require('node-uuid');
var chance = new require('chance')();
var PostgreStore = require('../');
var TokenStore = require('passwordless-tokenstore');
var pg = require('pg');
var standardTests = require('passwordless-tokenstore-test');
function TokenStoreFactory(options) {
return new PostgreStore(conString, options);
}
var conString = 'postgres://localhost';
var pgClient = new pg.Pool(conString);
pgClient.connect(function (err) {
if (err) {
done(err);
throw new Error('Could not connect to Postgres database, with error : ' + err);
}
});
var beforeEachTest = function(done) {
done();
};
var afterEachTest = function(done) {
done();
};
// Call all standard tests
standardTests(TokenStoreFactory, beforeEachTest, afterEachTest, 1000);
describe('Specific tests', function() {
beforeEach(function(done) {
beforeEachTest(done);
});
afterEach(function(done) {
afterEachTest(done);
});
it('should allow the instantiation with an empty constructor', function () {
expect(function() { new PostgreStore() }).to.not.throw;
});
it('should allow the instantiation with host and port but no options', function () {
expect(function() { new PostgreStore(conString) }).to.not.throw;
});
it('should allow proper instantiation', function () {
expect(function () { TokenStoreFactory() }).to.not.throw;
});
it('should disconnect without errors', function () {
var store = TokenStoreFactory();
expect(function () { store.disconnect() }).to.not.throw;
});
it('should store tokens only in their hashed form', function(done) {
var store = TokenStoreFactory();
var user = chance.email();
var token = uuid.v4();
store.storeOrUpdate(token, user,
1000*60, 'http://' + chance.domain() + '/page.html',
function() {
pgClient.query('SELECT * FROM passwordless WHERE uid=$1',[user], function(err, obj) {
expect(err).to.not.exist;
expect(obj).to.exist;
expect(obj.rows[0].token).to.exist;
expect(obj.rows[0].token).to.not.equal(token);
done();
})
});
});
it('should respect the bcrypt difficulty option', function (done) {
var store = TokenStoreFactory({ pgstore: { difficulty: 5 }});
var user = chance.email();
var token = uuid.v4();
store.storeOrUpdate(token, user,
1000 * 60, 'http://' + chance.domain() + '/page.html',
function () {
pgClient.query('SELECT token FROM passwordless WHERE uid=$1', [user], function (err, obj) {
expect(err).to.not.exist;
expect(obj).to.exist;
expect(obj.rows[0].token).to.exist;
expect(bcrypt.getRounds(obj.rows[0].token)).to.equal(5);
done();
})
});
});
it('should store tokens not only hashed but also salted', function(done) {
var store = TokenStoreFactory();
var user = chance.email();
var token = uuid.v4();
var hashedToken1;
store.storeOrUpdate(token, user,
1000*60, 'http://' + chance.domain() + '/page.html',
function() {
pgClient.query('SELECT * FROM passwordless WHERE uid=$1',[user], function(err, obj) {
expect(err).to.not.exist;
expect(obj).to.exist;
expect(obj.rows[0].token).to.exist;
hashedToken1 = obj.rows[0].token;
store.storeOrUpdate(token, user,
1000*60, 'http://' + chance.domain() + '/page.html',
function() {
pgClient.query('SELECT * FROM passwordless WHERE uid=$1',[user], function(err, obj) {
expect(err).to.not.exist;
expect(obj).to.exist;
expect(obj.rows[0].token).to.exist;
expect(obj.rows[0].token).to.not.equal(hashedToken1);
done();
});
});
})
});
});
});
|
'use strict';
const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
describe('generator-rtjs:app', () => {
it('creates webapp base setup', () => {
return helpers.run(path.join(__dirname, '../generators/app'))
.withPrompts({
name: 'my-test-app',
appType: 'webapp',
cssFramework: 'none',
cssDevStyle: 'none',
optionalPkg: {},
description: 'my test app',
homepage: 'test.com',
authorName: 'tester',
authorEmail: 'tester@test.com',
authorUrl: 'tester.test.com',
keywords: 'node, javascript',
includeCoverall: false,
githubAccount: 'tester',
license: 'Apache-2.0',
installer: 'npm'
}).then(() => {
// @TODO add the full list of expected create files here
assert.file([
'package.json',
'README.md',
'gulpfile.js'
]);
// this should not exsited
assert.noFile('modules/index.js');
});
});
});
|
import { isLeapYear as _isLeapYear, validateDate } from '../lib/utils';
export function isLeapYear(date) {
date = date ?? new Date();
validateDate(date);
return _isLeapYear(date);
}
export function isLeapYearUTC(date) {
date = date ?? new Date();
validateDate(date);
return _isLeapYear(date, 'UTC');
}
|
'use strict';
var React = require('react-native');
var {
PropTypes,
StyleSheet,
PanResponder,
View,
Platform
} = React;
var TRACK_SIZE = 4;
var THUMB_SIZE = 20;
function Rect(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
Rect.prototype.containsPoint = function(x, y) {
return (x >= this.x
&& y >= this.y
&& x <= this.x + this.width
&& y <= this.y + this.height);
};
var Slider = React.createClass({
propTypes: {
/**
* Initial value of the slider. The value should be between minimumValue
* and maximumValue, which default to 0 and 1 respectively.
* Default value is 0.
*
* *This is not a controlled component*, e.g. if you don't update
* the value, the component won't be reset to its inital value.
*/
value: PropTypes.number,
/**
* Initial minimum value of the slider. Default value is 0.
*/
minimumValue: PropTypes.number,
/**
* Initial maximum value of the slider. Default value is 1.
*/
maximumValue: PropTypes.number,
/**
* The color used for the track to the left of the button. Overrides the
* default blue gradient image.
*/
minimumTrackTintColor: PropTypes.string,
/**
* The color used for the track to the right of the button. Overrides the
* default blue gradient image.
*/
maximumTrackTintColor: PropTypes.string,
/**
* The color used for the thumb.
*/
thumbTintColor: PropTypes.string,
/**
* The size of the touch area that allows moving the thumb.
* The touch area has the same center has the visible thumb.
* This allows to have a visually small thumb while still allowing the user
* to move it easily.
* The default is {width: 40, height: 40}.
*/
thumbTouchSize: PropTypes.shape(
{width: PropTypes.number, height: PropTypes.number}
),
/**
* Callback continuously called while the user is dragging the slider.
*/
onValueChange: PropTypes.func,
/**
* Callback called when the user starts changing the value (e.g. when
* the slider is pressed).
*/
onSlidingStart: PropTypes.func,
/**
* Callback called when the user finishes changing the value (e.g. when
* the slider is released).
*/
onSlidingComplete: PropTypes.func,
/**
* The style applied to the slider container.
*/
style: View.propTypes.style,
/**
* The style applied to the track.
*/
trackStyle: View.propTypes.style,
/**
* The style applied to the thumb.
*/
thumbStyle: View.propTypes.style,
/**
* Set this to true to visually see the thumb touch rect in green.
*/
debugTouchArea: PropTypes.bool,
},
getInitialState() {
return {
containerSize: {},
trackSize: {},
thumbSize: {},
previousLeft: 0,
value: this.props.value,
};
},
getDefaultProps() {
return {
value: 0,
minimumValue: 0,
maximumValue: 1,
minimumTrackTintColor: '#3f3f3f',
maximumTrackTintColor: '#b3b3b3',
thumbTintColor: '#343434',
thumbTouchSize: {width: 40, height: 40},
debugTouchArea: false,
};
},
componentWillMount() {
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder,
onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
onPanResponderGrant: this._handlePanResponderGrant,
onPanResponderMove: this._handlePanResponderMove,
onPanResponderRelease: this._handlePanResponderEnd,
onPanResponderTerminate: this._handlePanResponderEnd,
});
},
componentWillReceiveProps: function(nextProps) {
this.setState({value: nextProps.value});
},
render() {
var {
minimumTrackTintColor,
maximumTrackTintColor,
thumbTintColor,
styles,
style,
trackStyle,
thumbStyle,
debugTouchArea,
...other
} = this.props;
var {value, containerSize, trackSize, thumbSize} = this.state;
var mainStyles = styles || defaultStyles;
var thumbLeft = this._getThumbLeft(value);
var valueVisibleStyle = {};
if (containerSize.width === undefined
|| trackSize.width === undefined
|| thumbSize.width === undefined) {
valueVisibleStyle.opacity = 0;
}
var minimumTrackStyle = {
position: 'absolute',
width: 300, // needed to workaround a bug for borderRadius
marginTop: -trackSize.height,
backgroundColor: minimumTrackTintColor,
...valueVisibleStyle
};
if (thumbLeft >= 0 && thumbSize.width >= 0) {
minimumTrackStyle.width = thumbLeft + thumbSize.width / 2;
}
var touchOverflowStyle = this._getTouchOverflowStyle();
return (
<View {...other} style={[mainStyles.container, style]} onLayout={this._measureContainer}>
<View
style={[{backgroundColor: maximumTrackTintColor}, mainStyles.track, trackStyle]}
onLayout={this._measureTrack} />
<View style={[mainStyles.track, trackStyle, minimumTrackStyle]} />
<View
ref={(thumb) => this.thumb = thumb}
onLayout={this._measureThumb}
style={[
{backgroundColor: thumbTintColor, marginTop: -(trackSize.height + thumbSize.height) / 2},
mainStyles.thumb, thumbStyle, {left: thumbLeft, ...valueVisibleStyle}
]}
/>
<View
style={[defaultStyles.touchArea, touchOverflowStyle]}
{...this._panResponder.panHandlers}>
{debugTouchArea === true && this._renderDebugThumbTouchRect()}
</View>
</View>
);
},
_handleStartShouldSetPanResponder: function(e: Object, /*gestureState: Object*/): boolean {
// Until the PR https://github.com/facebook/react-native/pull/3426 is merged, we need to always return "true" for android
if (Platform.OS === 'android') {
return true;
}
// Should we become active when the user presses down on the thumb?
return this._thumbHitTest(e);
},
_handleMoveShouldSetPanResponder: function(/*e: Object, gestureState: Object*/): boolean {
// Should we become active when the user moves a touch over the thumb?
return false;
},
_handlePanResponderGrant: function(/*e: Object, gestureState: Object*/) {
this.setState({ previousLeft: this._getThumbLeft(this.state.value) },
this._fireChangeEvent.bind(this, 'onSlidingStart'));
},
_handlePanResponderMove: function(e: Object, gestureState: Object) {
this.setState({ value: this._getValue(gestureState) },
this._fireChangeEvent.bind(this, 'onValueChange'));
},
_handlePanResponderEnd: function(e: Object, gestureState: Object) {
this.setState({ value: this._getValue(gestureState) },
this._fireChangeEvent.bind(this, 'onSlidingComplete'));
},
_measureContainer(x: Object) {
var {width, height} = x.nativeEvent.layout;
var containerSize = {width: width, height: height};
this.setState({ containerSize: containerSize });
},
_measureTrack(x: Object) {
var {width, height} = x.nativeEvent.layout;
var trackSize = {width: width, height: height};
this.setState({ trackSize: trackSize });
},
_measureThumb(x: Object) {
var {width, height} = x.nativeEvent.layout;
var thumbSize = {width: width, height: height};
this.setState({ thumbSize: thumbSize });
},
_getRatio(value: number) {
return (value - this.props.minimumValue) / (this.props.maximumValue - this.props.minimumValue);
},
_getThumbLeft(value: number) {
var ratio = this._getRatio(value);
return ratio * (this.state.containerSize.width - this.state.thumbSize.width);
},
_getValue(gestureState: Object) {
var length = this.state.containerSize.width - this.state.thumbSize.width;
var thumbLeft = Math.min(length,
Math.max(0, this.state.previousLeft + gestureState.dx));
var ratio = thumbLeft / length;
return ratio * (this.props.maximumValue - this.props.minimumValue) + this.props.minimumValue;
},
_fireChangeEvent(event) {
if (this.props[event]) {
this.props[event](this.state.value);
}
},
_getTouchOverflowSize() {
var state = this.state;
var props = this.props;
var size = {};
if (state.containerSize.width !== undefined
&& state.thumbSize.width !== undefined) {
size.width = Math.max(0, props.thumbTouchSize.width - state.thumbSize.width);
size.height = Math.max(0, props.thumbTouchSize.height - state.containerSize.height);
}
return size;
},
_getTouchOverflowStyle() {
var {width, height} = this._getTouchOverflowSize();
var touchOverflowStyle = {};
if (width !== undefined && height !== undefined) {
var verticalMargin = -height / 2;
touchOverflowStyle.marginTop = verticalMargin;
touchOverflowStyle.marginBottom = verticalMargin;
var horizontalMargin = -width / 2;
touchOverflowStyle.marginLeft = horizontalMargin;
touchOverflowStyle.marginRight = horizontalMargin;
}
if (this.props.debugTouchArea === true) {
touchOverflowStyle.backgroundColor = 'orange';
touchOverflowStyle.opacity = 0.5;
}
return touchOverflowStyle;
},
_thumbHitTest(e: Object) {
var nativeEvent = e.nativeEvent;
var thumbTouchRect = this._getThumbTouchRect();
return thumbTouchRect.containsPoint(nativeEvent.locationX, nativeEvent.locationY);
},
_getThumbTouchRect() {
var state = this.state;
var props = this.props;
var touchOverflowSize = this._getTouchOverflowSize();
return new Rect(
touchOverflowSize.width / 2 + this._getThumbLeft(state.value) + (state.thumbSize.width - props.thumbTouchSize.width) / 2,
touchOverflowSize.height / 2 + (state.containerSize.height - props.thumbTouchSize.height) / 2,
props.thumbTouchSize.width,
props.thumbTouchSize.height
);
},
_renderDebugThumbTouchRect() {
var thumbTouchRect = this._getThumbTouchRect();
var positionStyle = {
left: thumbTouchRect.x,
top: thumbTouchRect.y,
width: thumbTouchRect.width,
height: thumbTouchRect.height,
};
return (
<View
style={[defaultStyles.debugThumbTouchArea, positionStyle]}
pointerEvents='none'
/>
);
}
});
var defaultStyles = StyleSheet.create({
container: {
height: 40,
justifyContent: 'center',
},
track: {
height: TRACK_SIZE,
borderRadius: TRACK_SIZE / 2,
},
thumb: {
position: 'absolute',
width: THUMB_SIZE,
height: THUMB_SIZE,
borderRadius: THUMB_SIZE / 2,
},
touchArea: {
position: 'absolute',
backgroundColor: 'transparent',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
debugThumbTouchArea: {
position: 'absolute',
backgroundColor: 'green',
opacity: 0.5,
}
});
module.exports = Slider;
|
'use strict';
var angular = require('angular');
var translate = require('../node_modules/angular-translate/dist/angular-translate.min');
var angularLocalStorage = require('../node_modules/angular-local-storage/dist/angular-local-storage.min');
var uiBootstrap = require('../node_modules/angular-bootstrap/dist/ui-bootstrap.min');
var uiBootstrapTpls = require('../node_modules/angular-bootstrap/dist/ui-bootstrap-tpls.min');
/**
* Global Dependencies
* @type {module}
*/
var app = angular.module('Studymode', [
require('ui-router'),
require('angular-messages'),
require('angular-toastr'),
'LocalStorageModule',
'pascalprecht.translate',
'ui.bootstrap'
]);
/**
* Wrap external libs in Angular DI
*/
app.value('_', require('lodash'));
app.value('CLIENT_ID', $.stmode.tplVars.client_id);
/**
* Root
*/
app.controller('NavController', require('./NavController'));
app.factory('smAuth', require('./smAuth'));
app.factory('smUser', require('./smUser'));
app.factory('httpRequestInterceptor', require('./httpRequestInterceptor'));
app.config(require('./Config'));
app.config(require('./Translations'));
app.config(require('./Interceptors'));
app.run(require('./Run'));
/**
* Require other modules
*/
require('./directives');
require('./dashboard');
require('./services');
/**
* Manually bootstrap the app
*/
angular.element(document).ready(function() {
angular.bootstrap(document, ['Studymode']);
});
|
/**
* Created by ZK on 16/12/1.
*/
//接口IP地址和端口
var baseUrl = 'http://wx.hoootao.com/api/';
// var domainConfig = {};
// if (!$.cookie('downloadDomain')) {
// $.ajax({
// url: baseUrl + 'data/getDomainInfo',
// type: 'POST',
// data: {
// platform: '2',
// },
// success: function (data) {
// var download = data.p.domain.downloadDomain + '/';
// domainConfig.downloadDomain = download;
// $.cookie('downloadDomain', download, {
// expires: -1,
// });
// },
// error: function () {
//
// }
// });
// }
// else {
// domainConfig.downloadDomain = $.cookie('downloadDomain');
// }
//建立一個可存取到該file的url
function getObjectURL(file) {
var url = null ;
if (window.createObjectURL!=undefined) { // basic
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
function getQueryStringArgs() {
var qs = (location.search.length > 0 ? location.search.substring(1) : ''),
args = {},
items = qs.length ? qs.split('&') : [],
item = null,
name = null,
value = null,
i = 0,
len = items.length;
for (i = 0; i < len; i ++) {
item = items[i].split('=');
name = decodeURIComponent(item[0]);
value = decodeURIComponent(item[1]);
if (name.length) {
args[name] = value;
}
}
return args;
}
// loading图
var loading = {
$loadingContainer: $('<div style="background: rgba(255, 255, 255, .95); position: fixed; width: 100%; height: 100%; top: 0; left: 0;"></div>'),
$loadImg: $('<img src="imgs/loding.gif" alt="" style="position: absolute; width: 90px; height: 90px; top: 50%; left: 50%; margin-left: -45px; margin-top: -55px">'),
show: function () {
this.$loadingContainer.append(this.$loadImg);
$('body').append(this.$loadingContainer);
},
hide: function () {
this.$loadingContainer.remove();
}
};
//注意: 依赖base.css样式 和 jQuery框架
var zkUploadHint = {
$container: $('<div class="upload-container"></div>').css('opacity', 0),
$clock: $('<div class="clock"></div>'),
$progressBar: $('<div class="progress-bar"></div>'),
$hintTop: $('<p class="hint-top">资料提交中...</p>'),
$hintBottom: $('<p class="hint-bottom">公共WIFi网络速度可能较慢<br />建议您使用4G网络上传</p>'),
show: function () {
var $contentView = $('<div class="content-view"></div>'),
$progressContainer = $('<div class="progress-container"></div>');
$progressContainer.append(this.$progressBar);
$contentView.append(this.$clock).append(this.$hintTop).append($progressContainer).append(this.$hintBottom);
this.$container.append($contentView);
$('body').append(this.$container);
this.$container.animate({
'opacity': 1,
}, 200);
},
error: function () {
this.$clock.css({
'background': 'url("../imgs/upload-error.png") no-repeat top center / 35px 35px'
});
this.$progressBar.css('background', 'red');
},
hide: function () {
var $this = this;
this.$container.animate({
'opacity': 0
}, 250, function () {
$this.$container.remove();
})
}
};
// <div class="upload-container">
// <div class="content-view">
// <div class="clock"></div>
// <p class="hint-top">资料提交中...</p>
// <div class="progress-container">
// <div class="progress-bar"></div>
// </div>
// <p class="hint-bottom">公共WIFi网络速度可能较慢<br />建议您使用4G网络上传</p>
// </div>
// </div>
|
/* eslint no-else-return: 0 */
const router = require('express').Router();
const Auth = require('./helper/api/auth');
const Actions = require('./helper/api/actions');
// Handing `action` & `provider` & `id` Params
router.param('action', (req, res, next, action) => {
req.olAction = action;
next();
});
router.param('provider', (req, res, next, provider) => {
req.olProvider = provider;
next();
});
router.param('id', (req, res, next, id) => {
req.olId = id;
next();
});
router.all('/:action/:provider/:id', (req, res, next) => {
const provider = req.olProvider;
const id = provider + req.olPassports[provider];
const actionOpts = {
id : req.olId,
params: req.body.params,
method: req.method.toLowerCase(),
query : req.query,
};
promiseUserFindOne({ id })
.then(found => {
const { token, tokenSecret, refreshToken } = found;
Object.assign(actionOpts, { token, tokenSecret, refreshToken });
return Actions[provider](req.olAction, actionOpts);
})
.fail(err => {
const isTokenExpired = /expired?/i.test(err.msg);
if (isTokenExpired) {
// Try to refresh token and re-request
return (
Auth[provider].refreshToken(actionOpts.refreshToken)
.then(updateToken)
.then(reRequest)
);
} else {
throw err;
}
})
.then(data => res.json(data))
.fail(err => next(err));
function updateToken(data) {
const update = {
token : data.access_token,
refreshToken: data.refresh_token,
};
Object.assign(actionOpts, update);
return promiseUserFindOneAndUpdate({ id }, update);
}
function reRequest() {
return Actions[provider](req.olAction, actionOpts);
}
});
module.exports = router;
|
define(["app/app"], function(App) {
"use strict";
App.Router.map(function() {
this.route('home', { path: '/about'})
this.resource('session', function() {
this.route('new', { path: '/signin' })
this.route('destroy', { path: '/logout' })
})
this.resource('users', function() {
this.route('new', { path: '/signup' })
})
this.resource('timeline', { path: '/' }, function() {
this.route('home', { path: '/' })
this.route('directs', { path: '/filter/direct' })
this.route('discussions', { path: '/filter/discussions' })
this.route('index', { path: '/:username' })
this.route('comments', { path: '/:username/comments' })
this.route('likes', { path: '/:username/likes' })
this.route('subscribers', { path: '/:username/subscribers' })
this.route('subscriptions', { path: '/:username/subscriptions' })
})
this.resource('settings', { path: '/settings' }, function() {
this.route('index', { path: '/' })
this.route('feed', { path: '/:username' })
})
this.resource('requests', { path: '/requests' }, function() {
this.route('index', { path: '/' })
})
this.route('bookmarklet', { path: '/bookmarklet' })
this.route('forgot-password', { path: '/account/password' })
this.route('reset-password', { path: '/account/reset' })
this.route('post', { path: '/:username/:postId' })
this.resource('groups', { path: '/groups' }, function() {
this.route('home', { path: '/' })
this.route('new', { path: '/new' })
})
this.route('not-found', { path: '/404'})
})
App.Router.reopen({
location: 'history'
})
App.Router.reopen({
notifyGoogleAnalytics: function() {
return ga('send', 'pageview', {
'page': this.get('url'),
'title': this.get('url')
});
}.on('didTransition')
});
})
|
module.exports = window.React.addons.TestUtils;
|
'use strict'
// refer to https://github.com/zloirock/core-js
import 'core-js/es6' // pulls in all ES6 polyfills (adds about 15KB to our bundle [minified/gzipped])
// example of individual includes ...
// import 'core-js/modules/es6.object.assign'
// import 'core-js/es6/symbol'
// import 'core-js/es6/array'
|
// Generated on 2015-05-08 using generator-angular 0.11.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Configurable paths for the application
var appConfig = {
app: require('./bower.json').appPath || 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: appConfig,
// Watches files for changes and runs tasks based on the changed files
watch: {
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
styles: {
files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer'],
options: {
livereload: true
}
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>',
spawn: false
},
files: [
'<%= yeoman.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9009,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
//hostname: '0.0.0.0',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect().use(
'/app/styles',
connect.static('./app/styles')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: 9001,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
dist: {
options: {
open: true,
base: '<%= yeoman.dist %>'
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git{,*/}*'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
server: {
options: {
map: true
},
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: /\.\.\//
},
test: {
devDependencies: true,
src: '<%= karma.unit.configFile %>',
ignorePath: /\.\.\//,
fileTypes:{
js: {
block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
detect: {
js: /'(.*\.js)'/gi
},
replace: {
js: '\'{{filePath}}\','
}
}
}
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat','uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on filerev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
options: {
assetsDirs: [
'<%= yeoman.dist %>',
'<%= yeoman.dist %>/images',
'<%= yeoman.dist %>/styles'
]
}
},
// The following *-min tasks will produce minified files in the dist folder
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
conservativeCollapse: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true,
removeOptionalTags: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html', 'views/{,*/}*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
// ng-annotate tries to make the code safe for minification automatically
// by using the Angular long form for dependency injection.
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'*.html',
'views/{,*/}*.html',
'images/{,*/}*.{webp}',
'styles/fonts/{,*/}*.*'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
cwd: 'bower_components/bootstrap/dist',
src: 'fonts/*',
dest: '<%= yeoman.dist %>'
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'test/karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer:server',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve:' + target]);
});
grunt.registerTask('test', [
'clean:server',
'wiredep',
'concurrent:test',
'autoprefixer',
'connect:test',
'karma'
]);
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'ngAnnotate',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
]);
};
|
import test from 'ava';
import textExtensions from '.';
test('main', t => {
t.true(Array.isArray(textExtensions));
t.true(textExtensions.length > 0);
});
|
pref('extensions.skts.prevTabKey', '1');
pref('extensions.skts.nextTabKey', '2');
|
/*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict'
var fs = require('fs')
var path = require('path')
var _ = require('lodash')
var EOL = require('os').EOL
module.exports = function () {
function loadEnvFile (root, envFile) {
var ef
var env = {}
var lines
var expr
var p = path.resolve(path.join(root, envFile))
if (fs.existsSync(p)) {
ef = fs.readFileSync(p, 'utf8')
lines = ef.split(EOL)
_.each(lines, function (line) {
if (!/^#.*/g.test(line)) {
if ((expr = /(^[A-Za-z0-9_]+)=(.+$)/g.exec(line)) !== null) {
env[expr[1]] = expr[2]
}
}
})
}
return env
}
function loadEnvFiles (yamlPath, obj) {
var env = {}
var block
if (obj.env_file) {
if (_.isArray(obj.env_file)) {
_.each(obj.env_file, function (envFile) {
if (obj.path) {
block = loadEnvFile(obj.path, envFile)
} else {
block = loadEnvFile(path.dirname(yamlPath), envFile)
}
env = _.merge(env, block)
})
} else {
if (obj.path) {
block = loadEnvFile(obj.path, obj.env_file)
} else {
block = loadEnvFile(path.dirname(yamlPath), obj.env_file)
}
env = _.merge(env, block)
}
}
return env
}
function buildEnvironmentBlock (envIn) {
var env = {}
if (_.isArray(envIn)) {
if (envIn.length > 0) {
_.each(envIn, function (ev) {
var k = ev.substring(0, ev.indexOf('='))
var v = ev.substring(ev.indexOf('=') + 1)
env[k] = v
})
}
} else if (_.isObject(envIn)) {
env = envIn
}
return env
}
function findEnvVar (system, varName) {
var result = null
_.each(_.keys(system.topology.containers), function (key) {
if (system.topology.containers[key].environment[varName]) {
result = system.topology.containers[key].environment[varName]
}
})
if (!result) {
if (process.env[varName]) {
result = process.env[varName]
}
}
return result
}
function interpolate (system) {
if (system.topology.containers && _.keys(system.topology.containers).length > 0) {
_.each(_.keys(system.topology.containers), function (key) {
var container = system.topology.containers[key]
var cstr = JSON.stringify(container, null, 2)
var envVar
var value
if (/\$\{([a-zA-Z0-9-_]+)\}/g.test(cstr)) {
while ((envVar = /\$\{([a-zA-Z0-9-_]+)\}/g.exec(cstr)) !== null) {
if (container.environment[envVar[1]]) {
if (/\$\{([a-zA-Z0-9-_]+)\}/g.test(container.environment[envVar[1]])) {
value = ''
} else {
value = container.environment[envVar[1]]
}
cstr = cstr.replace(new RegExp('\\$\\{' + envVar[1] + '\\}', 'g'), value)
} else {
if ((value = findEnvVar(system, envVar[1])) !== null) {
if (/\$\{([a-zA-Z0-9-_]+)\}/g.test(value)) {
value = ''
}
cstr = cstr.replace(new RegExp('\\$\\{' + envVar[1] + '\\}', 'g'), value)
} else {
cstr = cstr.replace(new RegExp('\\$\\{' + envVar[1] + '\\}', 'g'), '')
}
}
}
system.topology.containers[key] = JSON.parse(cstr)
}
})
}
}
return {
loadEnvFile,
loadEnvFiles,
buildEnvironmentBlock,
interpolate
}
}
|
/* global it, describe */
import { expect } from 'chai';
import FlowTemplate from '../src/template/flow-template';
import card from './cards/card.json';
describe('Flow Template', () => {
describe('Constructor', () => {
it('Should construct an instance', () => {
let instance = new FlowTemplate({ localesPath: __dirname+'/locales' });
expect(instance).to.exist;
});
});
describe('Translate a phrase', () => {
it('Should translate using variables', () => {
let instance = new FlowTemplate({ localesPath: __dirname+'/locales' });
let view = {
user: {
name: 'Jesús'
}
};
let translated = instance.translatePhrase('Hello {{ user.name }}, how are you today?', 'es', view);
let expected = 'Hola Jesús, ¿cómo andas?';
expect(translated).to.equal(expected);
});
});
describe('Translate an object', () => {
it('Should translate an object using variables', () => {
let instance = new FlowTemplate({ localesPath: __dirname+'/locales' });
let view = {
user: {
name: 'Jesús'
}
};
let translated = instance.translate(card, 'es', view);
let expected = {
greet: 'Hola',
greetUser: 'Hola Jesús, ¿cómo andas?'
};
expect(translated).to.deep.equal(expected);
});
});
});
|
// In this file you can configure migrate-mongo
const config = {
mongodb: {
// TODO Change (or review) the url to your MongoDB:
url: "mongodb://localhost:27017",
// TODO Change this to your database name:
databaseName: "YOURDATABASENAME",
options: {
useNewUrlParser: true, // removes a deprecation warning when connecting
useUnifiedTopology: true, // removes a deprecating warning when connecting
// connectTimeoutMS: 3600000, // increase connection timeout to 1 hour
// socketTimeoutMS: 3600000, // increase socket timeout to 1 hour
}
},
// The migrations dir, can be an relative or absolute path. Only edit this when really necessary.
migrationsDir: "migrations",
// The mongodb collection where the applied changes are stored. Only edit this when really necessary.
changelogCollectionName: "changelog",
// The file extension to create migrations and search for in migration dir
migrationFileExtension: ".js",
// Enable the algorithm to create a checksum of the file contents and use that in the comparison to determin
// if the file should be run. Requires that scripts are coded to be run multiple times.
useFileHash: false
};
// Return the config as a promise
module.exports = config;
|
class DashboardCtrl {
constructor(Wallet, Alert, $location, DataBridge, $scope, $filter, Transactions, NetworkRequests) {
'ngInject';
// Alert service
this._Alert = Alert;
// Filters
this._$filter = $filter;
// $location to redirect
this._location = $location;
// Wallet service
this._Wallet = Wallet;
// Transaction service
this._Transactions = Transactions;
// DataBridge service
this._DataBridge = DataBridge;
this._NetworkRequests = NetworkRequests;
// If no wallet show alert and redirect to home
if (!this._Wallet.current) {
this._Alert.noWalletLoaded();
this._location.path('/');
}
/**
* Default Dashboard properties
*/
// Harvesting chart data
this.labels = [];
this.valuesInFee = [];
// Helper to know if no data for chart
this.chartEmpty = true;
// Default tab on confirmed transactions
this.tabConfirmed = true;
/**
* Watch harvested blocks in Databridge service for the chart
*/
$scope.$watch(() => this._DataBridge.harvestedBlocks, (val) => {
this.labels = [];
this.valuesInFee = [];
if (!val) {
return;
}
for (let i = 0; i < val.length; ++i) {
// If fee > 0 we push the block as label and the fee as data for the chart
if (val[i].totalFee / 1000000 > 0) {
this.labels.push(val[i].height)
this.valuesInFee.push(val[i].totalFee / 1000000);
}
}
// If nothing above 0 XEM show message
if (!this.valuesInFee.length) {
this.chartEmpty = true;
} else {
this.chartEmpty = false;
}
});
//Confirmed txes pagination properties
this.currentPage = 0;
this.pageSize = 5;
this.numberOfPages = function() {
return Math.ceil(this._DataBridge.transactions.length / this.pageSize);
}
//Unconfirmed txes pagination properties
this.currentPageUnc = 0;
this.pageSizeUnc = 5;
this.numberOfPagesUnc = function() {
return Math.ceil(this._DataBridge.unconfirmed.length / this.pageSizeUnc);
}
// Harvested blocks pagination properties
this.currentPageHb = 0;
this.pageSizeHb = 5;
this.numberOfPagesHb = function() {
return Math.ceil(this._DataBridge.harvestedBlocks.length / this.pageSizeHb);
}
}
/**
* refreshMarketInfo() Fetch data from CoinMarketCap api to refresh market information
*/
refreshMarketInfo() {
// Get market info
this._NetworkRequests.getMarketInfo().then((data) => {
this._DataBridge.marketInfo = data;
},
(err) => {
// Alert error
this._Alert.errorGetMarketInfo();
});
// Gets btc price
this._NetworkRequests.getBtcPrice().then((data) => {
this._DataBridge.btcPrice = data;
},
(err) => {
this._Alert.errorGetBtcPrice();
});
}
/**
* Fix a value to 4 decimals
*/
toFixed4(value) {
return value.toFixed(4);
}
}
export default DashboardCtrl;
|
var should = require('should');
var assert = require('assert');
var request = require('supertest');
var mongoose = require('mongoose');
var _ = require('underscore');
var cfg = require('../../../config.js');
var bunyan = require('bunyan');
var log = bunyan.createLogger(_.extend(cfg.test_log, {name: 'test_message'}));
describe('Messages', function() {
var url = cfg.test.url;
var test_message_id;
/**
* insert a special message
*/
before(function(done){
log.debug('setup test in before()');
//mongoose.connect(cfg.test_db.name);
//message_id_list = [];
var message = {
title: 'once we have specified the info we',
content: 'we need to actually perform the action on the resource, in this case we want to'
};
request(url)
.post(cfg.app.api_url + '/messages')
.send(message)
.expect('Content-Type', /json/)
//.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
.expect(200)
.end(function(err, res) {
if (err) {
return done(err);
//throw err;
}
test_message_id = res.body._id;
//message_id_list.push(res.body._id);
done();
//res.body.should.have.property('title', 'once we have specified the info we');
});
});
// list push()
describe('read and update', function() {
it('should support find message by id', function(done) {
request(url)
.get(cfg.app.api_url + '/messages/' + test_message_id)
.expect('Content-Type', /json/)
//.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
.expect(200)
.end(function(err, res) {
if (err) {
return done(err);
//throw err;
}
log.debug('GET message by id %s', res.body._id);
//message_id_list.push(res.body._id)
res.body.should.have.property('title', 'once we have specified the info we');
done();
});
});
it('should support update message', function(done) {
var message = {
title: 'once we have specified the info we updated',
content: 'we need to actually perform the action on the resource, in this case we want to update'
};
log.debug('PUT message by id %s', test_message_id);
request(url)
.put(cfg.app.api_url + '/messages/' + test_message_id)
.send(message)
.expect('Content-Type', /json/)
//.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
//.expect(200)
.end(function(err, res) {
if (err) {
log.error('find all messages err= %j', err);
return done(err);
//throw err;
}
log.debug('return PUT message by id %s', res.body._id);
//message_id_list.push(res.body._id)
res.body.should.have.property('n',1);
res.body.should.have.property('ok', 1);
//res.body.should.have.property('nModified', 1);
done();
});
});
});
after(function (done){
log.debug('clean up DB in after()');
request(url)
.delete(cfg.app.api_url + '/messages/' + test_message_id)
.expect('Content-Type', /json/)
//.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
.expect(200)
.end(function(err, res) {
if (err) {
return done(err);
//throw err;
}
log.debug('deleted message by id %s', res.body._id);
//message_id_list.push(res.body._id)
//res.body.should.have.property('title', 'once we have specified the info we');
done();
});
// console.log('clean up in after(), size = ' + message_id_list.length);
// //value, key, list
// _.each(message_id_list, function(value){
//
// });
// message_id_list = [];
});
});
|
/**
* Created by amos on 14-8-18.
*/
LBF.define('util.Event', function(require, exports){
var toArray = require('lang.toArray'),
Callbacks = require('util.Callbacks');
var ATTR = '_EVENTS';
/**
* [mixable] Common event handler. Can be extended to any object that wants event handler.
* @class Event
* @namespace util
* @example
* // mix in instance example
* // assume classInstance is instance of lang.Class or its sub class
*
* // use class's mix method
* classInstance.mix(Attribute);
*
* // set your attributes
* classInstance.set('a', 1);
* classInstance.get('a') // returns 1
*
* @example
* // extend a sub class example
*
* // use class's extend method
* var SubClass = Class.extend(Attribute, {
* // some other methods
* method1: function(){
* },
*
* method2: function(){
* }
* });
*
* // initialize an instance
* classInstance = new SubClass;
*
* // set your attributes
* classInstance.set('a', 1);
* classInstance.get('a') // returns 1
*/
/**
* Bind events
* @method on
* @param {String} eventNames Event names that to be subscribed and can be separated by a blank space
* @param {Function} callback Callback to be invoked when the subscribed events are published
* @chainable
*/
exports.on = function(type, handler, one){
var events = this[ATTR];
if(!events){
events = this[ATTR] = {};
}
var callbacks = events[type] || (events[type] = Callbacks('stopOnFalse'));
if(one === 1){
var origFn = handler,
self = this;
handler = function() {
// Can use an empty set, since event contains the info
self.off(type, handler);
return origFn.apply(this, arguments);
};
}
callbacks.add(handler);
return this;
}
/**
* Unbind events
* @method off
* @param {String} eventNames Event names that to be subscribed and can be separated by a blank space
* @param {Function} [callback] Callback to be invoked when the subscribed events are published. Leave blank will unbind all callbacks on this event
* @chainable
*/
exports.off = function(type, handler){
if(!type){
this[ATTR] = {};
return this;
}
var events = this[ATTR];
if(!events || !events[type]){
return this;
}
if(!handler){
events[type].empty();
return this;
}
events[type].remove(handler);
return this;
}
/**
* Publish an event
* @method trigger
* @param {String} eventName
* @param arg* Arguments to be passed to callback function. No limit of arguments' length
* @chainable
*/
exports.trigger = function(){
var args = toArray(arguments),
type = args.shift(),
events = this[ATTR];
if(!events || !events[type]){
return this;
}
events[type].fireWith(this, args);
return this;
}
/**
* Bind event callback to be triggered only once
* @method one
* @param {String} eventNames Event names that to be subscribed and can be separated by a blank space
* @param {Function} callback Callback to be invoked when the subscribed events are published. Leave blank will unbind all callbacks on this event
* @chainable
*/
exports.once = function(type, handler){
return this.on(type, handler, 1);
}
});
|
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
const vscode_languageserver_1 = require("vscode-languageserver");
const vscode_uri_1 = require("vscode-uri");
const nodes_1 = require("../types/nodes");
const parser_1 = require("../services/parser");
const symbols_1 = require("../utils/symbols");
const document_1 = require("../utils/document");
function samePosition(a, b) {
return a.line === b.line && a.character === b.character;
}
/**
* Returns the Symbol, if it present in the documents.
*/
function getSymbols(symbolList, identifier, currentPath) {
const list = [];
symbolList.forEach((symbols) => {
const fsPath = document_1.getDocumentPath(currentPath, symbols.document);
symbols[identifier.type].forEach((item) => {
if (item.name === identifier.name && !samePosition(item.position, identifier.position)) {
list.push({
document: symbols.document,
path: fsPath,
info: item
});
}
});
});
return list;
}
/**
* Do Go Definition :)
*/
function goDefinition(document, offset, cache, settings) {
const documentPath = vscode_languageserver_1.Files.uriToFilePath(document.uri) || document.uri;
if (!documentPath) {
return Promise.resolve(null);
}
const resource = parser_1.parseDocument(document, offset, settings);
const hoverNode = resource.node;
if (!hoverNode || !hoverNode.type) {
return Promise.resolve(null);
}
let identifier = null;
if (hoverNode.type === nodes_1.NodeType.VariableName) {
const parent = hoverNode.getParent();
if (parent.type !== nodes_1.NodeType.FunctionParameter && parent.type !== nodes_1.NodeType.VariableDeclaration) {
identifier = {
name: hoverNode.getName(),
position: document.positionAt(hoverNode.offset),
type: 'variables'
};
}
}
else if (hoverNode.type === nodes_1.NodeType.Identifier) {
let i = 0;
let node = hoverNode;
while (node.type !== nodes_1.NodeType.MixinReference && node.type !== nodes_1.NodeType.Function && i !== 2) {
node = node.getParent();
i++;
}
if (node && (node.type === nodes_1.NodeType.MixinReference || node.type === nodes_1.NodeType.Function)) {
let type = 'mixins';
if (node.type === nodes_1.NodeType.Function) {
type = 'functions';
}
identifier = {
name: node.getName(),
position: document.positionAt(node.offset),
type
};
}
}
if (!identifier) {
return Promise.resolve(null);
}
// Symbols from Cache
resource.symbols.ctime = new Date();
cache.set(resource.symbols.document, resource.symbols);
const symbolsList = symbols_1.getSymbolsCollection(cache);
// Symbols
const candidates = getSymbols(symbolsList, identifier, documentPath);
if (candidates.length === 0) {
return Promise.resolve(null);
}
const definition = candidates[0];
const symbol = vscode_languageserver_1.Location.create(vscode_uri_1.default.file(definition.document).toString(), {
start: definition.info.position,
end: {
line: definition.info.position.line,
character: definition.info.position.character + definition.info.name.length
}
});
return Promise.resolve(symbol);
}
exports.goDefinition = goDefinition;
|
'use strict';
var express = require('express'),
mongoose = require('mongoose'),
async = require('async'),
mock = require('./mock'),
User = require('./models/User'),
Post = require('./models/Post'),
admin = require('../../');
var dbURL = 'mongodb://localhost/siracha-simple-example';
mongoose.connect(dbURL);
var app = express();
app.use('/admin', admin());
app.get('/', function(req, res) {
res.send('This is the index route. You are probably looking for the <a href="/admin">admin</a> route!');
})
var server = app.listen(3000, function() {
mock.init();
console.log('Simple example app listening at port %s', 3000);
})
server.on('close', function(done) {
console.log('Closing simple example app port %s', 3000);
});
process.on('SIGINT', function() {
server.close();
mock.destroy(function() {
process.kill(0);
});
});
module.exports = server;
|
(function () {
'use strict';
/** Defines the Category module, which handles all interaction with the
* server for Category objects.
* - ngResource is required in order to interact with the server's REST API,
* by sending HTTP requests.
*/
angular.module('core.category', [ 'ngResource' ]);
})();
|
module.exports = {
simpleNameSchema: {
first_name: [
['minLength', 8, 'minLength.fail'],
],
email: [
['isEmail', 'isEmail.fail'],
],
custom_validator: [
[v => !!v, 'customValidator.fail'],
],
custom_validator_with_args: [
[
(value, attribute, model, v1, v2) => v1 + value === v2,
1,
2,
'customValidatorWithArgs.fail'
],
],
required_min_length_combined: [
['isRequired', 'isRequired.fail'],
['minLength', 5, 'minLength.fail'],
]
},
simpleNameFailingModel: {
first_name: 'Kasper', // Failing because of minLength 8
email: 'woof@me',
custom_validator: false,
custom_validator_with_args: 2,
required_min_length_combined: undefined,
},
simpleNamePassingModel: {
first_name: 'Kasper Janebrink',
email: 'woofatme@example.org',
custom_validator: true,
custom_validator_with_args: 1,
required_min_length_combined: "blabla",
},
};
|
var Demo = {};
Demo.Helpers = (function (undefined) {
function getPage(array, page, pageSize) {
var result = [];
for (var i = (page - 1) * pageSize; i < page * pageSize; i++) {
if (array[i] === undefined)
return result;
result.push(array[i]);
}
return result;
}
function addRange(array, items) {
for (var i = 0; i < items.length; i++) {
array.push(items[i]);
}
}
return { getPage: getPage, addRange: addRange };
})();
Demo.Api = (function () {
var call = function (url, success) {
$.ajax({
url: url,
dataType: "jsonp",
success: success
});
};
return { getStatuses: call };
})();
Demo.SearchStore = (function () {
var getUrlFromCriteria = function (data) {
var base = "http://search.twitter.com/search.json";
var queryStr = '?q=';
if (data.searchType === 'text') {
queryStr += '"' + data.query + '"';
} else {
queryStr += encodeURIComponent(data.searchType + data.query);
}
queryStr += "&page=" + data.page;
queryStr += "&result_type=" + data.resultType;
queryStr += "&rpp=100";
return base + queryStr;
};
var getKeyFromCriteria = function(data) {
return data.query + data.searchType + data.resultType;
};
var cacheItem = function (key, data) {
var that = this;
that.results = [];
that.add = function (newData) {
Demo.Helpers.addRange(that.results, newData.results);
if (newData.next_page !== undefined)
that.nextUrl = 'http://search.twitter.com/search.json' + newData.next_page;
};
that.add(data);
};
var searchStore = function() {
var that = this;
that.cache = {};
};
searchStore.prototype.getStatusesForCriteria = function (criteria, callback) {
var that = this;
var key = getKeyFromCriteria(criteria);
var initialLoad = function () {
var url = getUrlFromCriteria(criteria);
Demo.Api.getStatuses(url, function (data) {
that.cache[key] = new cacheItem(key, data);
callback(Demo.Helpers.getPage(that.cache[key].results, criteria.page, 10));
});
};
var loadFromNextUrl = function () {
var url = that.cache[key].nextUrl;
Demo.Api.getStatuses(url, function (data) {
that.cache[key].add(data);
callback(Demo.Helpers.getPage(that.cache[key].results, criteria.page, 10));
});
};
var populateCache = function () {
if (that.cache[key] === undefined) {
initialLoad(key, criteria, callback);
} else if (that.cache[key].nextUrl !== undefined) {
loadFromNextUrl(key, criteria, callback);
} else {
callback([]);
}
};
if (this.cache[key] === undefined || this.cache[key].results.length < criteria.page * 10) {
populateCache();
} else {
callback(Demo.Helpers.getPage(this.cache[key].results, criteria.page, 10));
}
};
return searchStore;
})();
Demo.ViewModels = (function () {
var mainViewModel = function () {
var searchStore = new Demo.SearchStore();
var that = this;
that.criteria = ko.observable(new search());
that.results = ko.observableArray([]);
that.page = ko.observable(1);
that.loading = ko.observable(false);
var refresh = function () {
that.loading(true);
that.results.removeAll();
searchStore.getStatusesForCriteria({
searchType: that.criteria().searchType(),
resultType: that.criteria().resultType(),
query: that.criteria().query(),
page: that.page()
}, function (data) {
Demo.Helpers.addRange(that.results, $.map(data, function (elem) { return new result(elem); }));
that.loading(false);
});
};
that.changePage = function (newPage) {
that.page(newPage);
refresh();
};
};
var result = function (data) {
this.name = data.from_user_name;
this.userUrl = "http://twitter.com/" + encodeURIComponent(data.from_user);
this.profileUrl = data.profile_image_url;
this.text = data.text;
this.created = new Date(data.created_at).toLocaleString();
this.retweets = (data.metadata.recent_retweets !== undefined) ? data.metadata.recent_retweets : 0;
};
var search = function () {
var that = this;
that.searchType = ko.observable('#');
that.resultType = ko.observable('both');
that.query = ko.observable('');
};
return { MainViewModel: mainViewModel };
})();
|
var fs = require('fs');
var events = require('events');
var util = require('util');
// id is the file system index of the joystick (e.g. /dev/input/js0 has id '0')
// deadzone is the amount of sensitivity at the center of the axis to ignore.
// Axis reads from -32k to +32k and empirical testing on an XBox360 controller
// shows that a good 'dead stick' value is 3500
// Note that this deadzone algorithm assumes that 'center is zero' which is not generally
// the case so you may want to set deadzone === 0 and instead perform some form of
// calibration.
// sensitivity is the amount of change in an axis reading before an event will be emitted.
// Empirical testing on an XBox360 controller shows that sensitivity is around 350 to remove
// noise in the data
function Joystick(id, deadzone, sensitivity) {
var self = this;
this.id = id;
var buffer = new Buffer(8);
var fd = undefined;
// Last reading from this axis, used for debouncing events using sensitivty setting
var lastAxisValue = [];
var lastAxisEmittedValue = [];
events.EventEmitter.call(this);
function parse(buffer) {
var event = {
time : buffer.readUInt32LE(0),
value: buffer.readInt16LE(4),
number: buffer[7]
}
var type = buffer[6];
if (type & 0x80) event.init = true;
if (type & 0x01) event.type = 'button';
if (type & 0x02) event.type = 'axis';
event.id = self.id;
return event;
}
function startRead() {
fs.read(fd, buffer, 0, 8, null, onRead);
};
function onOpen(err, fdOpened) {
if (err) return self.emit("error", err);
fd = fdOpened;
startRead();
};
function onRead(err, bytesRead) {
if (err) return self.emit("error", err);
var event = parse(buffer);
if (event.type === 'axis') {
if (sensitivity) {
if (lastAxisValue[event.number] && Math.abs(lastAxisValue[event.number] - event.value) < sensitivity) {
// data squelched due to sensitivity, no self.emit
var squelch = true;
} else {
lastAxisValue[event.number] = event.value;
}
}
if (deadzone && Math.abs(event.value) < deadzone) {
event.value = 0;
}
if (lastAxisEmittedValue[event.number] === event.value) {
var squelch = true;
} else {
lastAxisEmittedValue[event.number] = event.value;
}
}
if (!squelch) {
self.emit(event.type, event);
}
if (fd) startRead();
};
this.close = function (callback) {
fs.close(fd, callback);
fd = undefined;
};
fs.open("/dev/input/js" + id, "r", onOpen);
}
util.inherits(Joystick, events.EventEmitter);
module.exports = Joystick;
|
/**
* @param {number} n
* @return {number}
*/
var numSquares = function(n) {
var nums = [0];
for (var i = 1; i <= n; i++) {
var least = i;
for (var x = 1; x * x <= i; x++) {
var num = 1 + nums[i - x * x];
if (least > num) {
least = num;
}
}
nums.push(least);
}
return nums[n];
};
|
import { Environment } from '../environment';
@Environment
export class EntryBuilder {
constructor(name) {
this._name = name;
this._files = [];
}
get name() { return this._name; }
get and() { return this; }
from(...files) {
this._files = [...this._files, ...files];
return this;
}
build() {
return {
[this._name]: this._files
};
}
}
|
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
Q = require('q'),
errorHandler = require('./errors.server.controller'),
storeService = require('../services/store.service'),
commonService = require('../services/common.service.js');
//新建商铺
exports.create = function (req, res) {
var storeInfo = req.body;
storeService.create(storeInfo)
.then(function (result) {
if (result.code !== 0) {
res.status(200).send(result);
return;
}
res.send(result.store);
})
.catch(function (err) {
res.status(500).send(err.message);
})
.done();
};
//获取商铺列表
exports.list = function (req, res) {
storeService.list()
.then(function (result) {
if (result.code !== 0) {
throw new Error(result.message);
}
var storesPromise = [];
result.stores.forEach(function(item) {
storesPromise.push(resolveStore(item));
});
Q.all(storesPromise)
.then(function (resolvedStores) {
return res.send(resolvedStores);
})
})
.catch(function (err) {
res.status(500).send(err.message);
})
.done();
};
//根据ID获取商铺
exports.findById = function (req, res) {
storeService.findById(req.params.storeId)
.then(function (result) {
if (result.code !== 0) {
throw new Error(result.message);
}
res.send(result.store);
})
.catch(function (err) {
res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
})
.done();
};
//编辑商铺
exports.update = function (req, res) {
storeService.edit(req.params.storeId, req.body)
.then(function (result) {
if (result.code !== 0) {
throw new Error(result.message);
}
res.send(result.message);
})
.catch(function (err) {
res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
})
.done();
};
//删除商铺
exports.delete = function (req, res) {
storeService.del(req.params.storeId)
.then(function (result) {
if (result.code !== 0) {
throw new Error(result.message);
}
res.send(result.message);
})
.catch(function (err) {
res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
})
.done();
};
var resolveStore = function (stores) {
var deferrd = Q.defer();
Q.all([
stores,
commonService.getProvince(stores.province_id),
commonService.getCity(stores.city_id),
commonService.getDist(stores.area_id),
commonService.getChannel(stores.store_channel_id)
]).spread(function (stores, provinceResult, cityResult, distResult, channelResult) {
if (provinceResult.code !== 0
|| cityResult.code !== 0
|| distResult.code !== 0
|| channelResult.code !== 0 ) {
throw new Error(result.message);
}
stores.province = provinceResult.province.name;
stores.city = cityResult.city.name;
stores.dist = distResult.area.name;
stores.channel = channelResult.channel.name;
deferrd.resolve(stores);
}).catch(function (err) {
deferrd.reject(err);
}).done();
return deferrd.promise;
};
|
/* globals XMLHttpRequest */
exports.create = function () {
return this;
};
/**
* Browser based GET request
* @param options {Object}
* options.request {Object} - Request data including host and path
* options.https {Boolean} - Whether to utilize HTTPS library for requests or HTTP. Defaults to HTTP.
* options.timeout {Number} - Request timeout before returning an error. Defaults to 30000 milliseconds
* options.fmt {String} - Return results in html or json format (useful for viewing responses as GIFs to debug/test)
*/
exports.get = function (options, resolve, reject) {
var request = options.request;
var timeout = options.timeout;
var fmt = options.fmt;
var timerId = setTimeout(function () {
reject(new Error('Timeout while fetching asset'));
}, timeout);
var xhr = new XMLHttpRequest();
xhr.withCredentials = false;
var onFail = function (err) {
clearTimeout(timerId);
err = err || new Error('Giphy API request failed!');
reject(err);
};
xhr.addEventListener('error', onFail);
xhr.addEventListener('abort', onFail);
xhr.addEventListener('load', function () {
clearTimeout(timerId);
var body = xhr.response;
if (fmt !== 'html') {
body = JSON.parse(body);
}
resolve(body);
});
var protocol = options.https ? 'https' : 'http';
var host = request.host;
var path = request.path;
var url = protocol + '://' + host + path;
xhr.open('GET', url, true);
xhr.send();
};
|
module.exports = function() {
this.loadNpmTasks("grunt-karma-coveralls");
return this.config("coveralls", {
options: {
coverage_dir: "test/coverage"
}
});
};
|
var util = require("../lib/6to5/util");
var path = require("path");
var fs = require("fs");
var _ = require("lodash");
var humanise = function (val, noext) {
if (noext) val = path.basename(val, path.extname(val));
return val.replace(/-/g, " ");
};
var readFile = exports.readFile = function (filename) {
if (fs.existsSync(filename)) {
var file = fs.readFileSync(filename, "utf8").trim();
file = file.replace(/\r\n/g, "\n");
return file;
} else {
return "";
}
};
exports.get = function (entryName, entryLoc) {
if (exports.cache[entryName]) return exports.cache[entryName];
var suites = [];
var entryLoc = entryLoc || __dirname + "/fixtures/" + entryName;
_.each(fs.readdirSync(entryLoc), function (suiteName) {
if (suiteName[0] === ".") return;
var suite = {
options: {},
tests: [],
title: humanise(suiteName),
filename: entryLoc + "/" + suiteName
};
suites.push(suite);
var suiteOptsLoc = util.resolve(suite.filename + "/options");
if (suiteOptsLoc) suite.options = require(suiteOptsLoc);
if (fs.statSync(suite.filename).isFile()) {
push(suiteName, suite.filename);
} else {
_.each(fs.readdirSync(suite.filename), function (taskName) {
var taskDir = suite.filename + "/" + taskName;
push(taskName, taskDir);
});
}
function push(taskName, taskDir) {
// tracuer error tests
if (taskName.indexOf("Error_") >= 0) return;
var actualLocAlias = suiteName + "/" + taskName + "/actual.js";
var expectLocAlias = suiteName + "/" + taskName + "/expected.js";
var execLocAlias = suiteName + "/" + taskName + "/exec.js";
var actualLoc = taskDir + "/actual.js";
var expectLoc = taskDir + "/expected.js";
var execLoc = taskDir + "/exec.js";
if (fs.statSync(taskDir).isFile()) {
var ext = path.extname(taskDir);
if (ext !== ".js" && ext !== ".module.js") return;
execLoc = taskDir;
}
var taskOpts = _.merge({
filenameRelative: expectLocAlias,
sourceFileName: actualLocAlias,
sourceMapName: expectLocAlias
}, _.cloneDeep(suite.options));
var taskOptsLoc = util.resolve(taskDir + "/options");
if (taskOptsLoc) _.merge(taskOpts, require(taskOptsLoc));
var test = {
title: humanise(taskName, true),
disabled: taskName[0] === ".",
options: taskOpts,
exec: {
loc: execLoc,
code: readFile(execLoc),
filename: execLocAlias,
},
actual: {
loc: actualLoc,
code: readFile(actualLoc),
filename: actualLocAlias,
},
expect: {
loc: expectLoc,
code: readFile(expectLoc),
filename: expectLocAlias
}
};
// traceur checks
var shouldSkip = function (code) {
return code.indexOf("// Error:") >= 0 || code.indexOf("// Skip.") >= 0;
};
if (shouldSkip(test.actual.code) || shouldSkip(test.exec.code)) {
return;
} else if (test.exec.code.indexOf("// Async.") >= 0) {
//test.options.asyncExec = true;
}
suite.tests.push(test);
var sourceMappingsLoc = taskDir + "/source-mappings.json";
if (fs.existsSync(sourceMappingsLoc)) {
test.options.sourceMap = true;
test.sourceMappings = require(sourceMappingsLoc);
}
var sourceMap = taskDir + "/source-map.json";
if (fs.existsSync(sourceMap)) {
test.options.sourceMap = true;
test.sourceMap = require(sourceMap);
}
}
});
return exports.cache[entryName] = suites;
};
try {
exports.cache = require("../tests.json");
} catch (err) {
if (err.code !== "MODULE_NOT_FOUND") throw err;
var cache = exports.cache = {};
cache.transformation = exports.get("transformation");
cache.generation = exports.get("generation");
cache.esnext = exports.get("esnext");
}
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'format', 'bg', {
label: 'Формат',
panelTitle: 'Формат на параграф',
tag_address: 'Адрес',
tag_div: 'Нормален (DIV)',
tag_h1: 'Заглавие 1',
tag_h2: 'Заглавие 2',
tag_h3: 'Заглавие 3',
tag_h4: 'Заглавие 4',
tag_h5: 'Заглавие 5',
tag_h6: 'Заглавие 6',
tag_p: 'Нормален',
tag_pre: 'Форматиран'
} );
|
###Client###
function(cabrillo, $timeout) {
/* widget controller */
var c = this;
c.isNative = cabrillo.isNative();
function setScanButton() {
cabrillo.viewLayout.setBottomButtons([{
title: 'Scan Code',
enabled: true,
backgroundColor: '#2d86d5',
textColor: '#FFFFFF'
}], function(e) {
c.getBarcode();
});
}
setScanButton();
c.getBarcode = function() {
cabrillo.camera.getBarcode().then(function(value) {
cabrillo.viewLayout.showSpinner();
c.barcode = value;
c.server.get({
action: "get_asset",
barcode: c.barcode
}).then(openAssetPageModal);
}, function(err) {
cabrillo.log('Whoops.');
c.barcode = "COFFEE_MACHINE_1011";
c.server.get({
action: "get_asset",
barcode: c.barcode
}).then(openAssetPageModal);
});
}
c.viewIncidents = function() {
cabrillo.navigation.goto("", {
table: 'incident',
query: 'active=true^caller_id=javascript:gs.user_id()'
});
}
function openAssetPageModal(response) {
removeButtons();
cabrillo.viewLayout.hideSpinner();
cabrillo.modal.presentModal("Confirm Incident", "/$sp.do?id=k17_asset_incident_confirmation&asset=" + response.data.assetID, cabrillo.modal.CLOSE_BUTTON_STYLE_CANCEL, cabrillo.modal.MODAL_PRESENTATION_STYLE_FORM_SHEET).then(function(response) {
if (!response) {
c.barcode = null;
setScanButton();
}
if (response.results.success === true) {
c.done = true;
c.success = true;
} else {
c.barcode = null;
setScanButton();
}
});
}
function removeButtons() {
cabrillo.viewLayout.setBottomButtons([], function(){});
}
}
#### SERVER ####
(function() {
/* populate the 'data' object */
/* e.g., data.table = $sp.getValue('table'); */
if (input && input.action == "get_asset") {
data.assetID = input.barcode;
return;
}
})();
|
export const inverted = {"viewBox":"0 0 20 20","children":[{"name":"path","attribs":{"d":"M18,3H2C1.447,3,1,3.447,1,4v12c0,0.552,0.447,1,1,1h16c0.553,0,1-0.448,1-1V4C19,3.448,18.553,3,18,3z M13.25,6.5\r\n\tc0.69,0,1.25,0.56,1.25,1.25S13.94,9,13.25,9S12,8.44,12,7.75S12.56,6.5,13.25,6.5z M4,14l3.314-7.619l3.769,6.102l3.231-1.605\r\n\tL16,14H4z"}}]};
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
var ImprovedNoise = __webpack_require__(1);
/**
* Mountain component.
*/
AFRAME.registerComponent('mountain', {
schema: {
color: {default: 'rgb(92, 32, 0)'},
shadowColor: {default: 'rgb(128, 96, 96)'},
sunposition: {type: 'vec3', default: {x: 1, y: 1, z: 1}},
worldDepth: {default: 256},
worldWidth: {default: 256}
},
update: function () {
var data = this.data;
var worldDepth = data.worldDepth;
var worldWidth = data.worldWidth;
// Generate heightmap.
var terrainData = generateHeight(worldWidth, worldDepth);
// Texture.
var canvas = generateTexture(
terrainData, worldWidth, worldDepth, new THREE.Color(data.color),
new THREE.Color(data.shadowColor), data.sunposition);
var texture = new THREE.CanvasTexture(canvas);
texture.wrapS = THREE.ClampToEdgeWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping;
// Create geometry.
var geometry = new THREE.PlaneBufferGeometry(7500, 7500, worldWidth - 1, worldDepth - 1);
geometry.rotateX(- Math.PI / 2);
var vertices = geometry.attributes.position.array;
for (var i = 0, j = 0, l = vertices.length; i < l; i ++, j += 3) {
vertices[j + 1] = terrainData[i] * 10;
}
// Lower geometry.
geometry.translate(
0, -1 * (terrainData[worldWidth / 2 + worldDepth / 2* worldWidth] * 10 + 500), 0
);
// Create material.
var material = new THREE.MeshBasicMaterial({map: texture});
// Create mesh.
var mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({map: texture}));
this.el.setObject3D('mesh', mesh);
}
});
function generateHeight (width, height) {
var size = width * height;
var data = new Uint8Array(size);
var perlin = new ImprovedNoise();
var quality = 1;
var z = Math.random() * 100;
for (var j = 0; j < 4; j ++) {
for (var i = 0; i < size; i ++) {
var x = i % width, y = ~~ (i / width);
data[i] += Math.abs(perlin.noise(x / quality, y / quality, z) * quality * 1.75);
}
quality *= 5;
}
return data;
}
function generateTexture (terrainData, width, height, color, colorShadow, sunPos) {
var sun = new THREE.Vector3(sunPos.x, sunPos.y, sunPos.z);
sun.normalize();
// Create canvas and context.
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
context.fillStyle = '#000';
context.fillRect(0, 0, width, height);
var image = context.getImageData(0, 0, canvas.width, canvas.height);
var imageData = image.data;
// Convert three.js rgb to 256.
var red = color.r * 256;
var green = color.g * 256;
var blue = color.b * 256;
var redShadow = colorShadow.r * 256;
var greenShadow = colorShadow.g * 256;
var blueShadow = colorShadow.b * 256;
var shade;
var vector3 = new THREE.Vector3(0, 0, 0);
for (var i = 0, j = 0, l = imageData.length; i < l; i += 4, j ++) {
vector3.x = terrainData[j - 2] - terrainData[j + 2];
vector3.y = 2;
vector3.z = terrainData[j - width * 2] - terrainData[j + width * 2];
vector3.normalize();
shade = vector3.dot(sun);
imageData[i] = (red + shade * redShadow) * (0.5 + terrainData[j] * 0.007);
imageData[i + 1] = (green + shade * blueShadow) * (0.5 + terrainData[j] * 0.007);
imageData[i + 2] = (blue + shade * greenShadow) * (0.5 + terrainData[j] * 0.007);
}
context.putImageData(image, 0, 0);
// Scaled 4x.
var canvasScaled = document.createElement('canvas');
canvasScaled.width = width * 4;
canvasScaled.height = height * 4;
context = canvasScaled.getContext('2d');
context.scale(4, 4);
context.drawImage(canvas, 0, 0);
image = context.getImageData(0, 0, canvasScaled.width, canvasScaled.height);
imageData = image.data;
for (var i = 0, l = imageData.length; i < l; i += 4) {
var v = ~~ (Math.random() * 5);
imageData[i] += v;
imageData[i + 1] += v;
imageData[i + 2] += v;
}
context.putImageData(image, 0, 0);
return canvasScaled;
}
/**
* <a-mountain>
*/
AFRAME.registerPrimitive('a-mountain', {
defaultComponents: {
mountain: {}
},
mappings: {
color: 'mountain.color',
'shadow-color': 'mountain.shadowColor',
'sun-position': 'mountain.sunposition',
'world-depth' :'mountain.worldDepth',
'world-width' :'mountain.worldWidth'
}
});
/***/ },
/* 1 */
/***/ function(module, exports) {
// http://mrl.nyu.edu/~perlin/noise/
var ImprovedNoise = function () {
var p = [ 151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,
23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,
174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,
133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,
89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,
202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,
248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,
178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,
14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,
93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 ];
for (var i = 0; i < 256 ; i ++) {
p[256 + i] = p[i];
}
function fade(t) {
return t * t * t * (t * (t * 6 - 15) + 10);
}
function lerp(t, a, b) {
return a + t * (b - a);
}
function grad(hash, x, y, z) {
var h = hash & 15;
var u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
}
return {
noise: function (x, y, z) {
var floorX = ~~x, floorY = ~~y, floorZ = ~~z;
var X = floorX & 255, Y = floorY & 255, Z = floorZ & 255;
x -= floorX;
y -= floorY;
z -= floorZ;
var xMinus1 = x - 1, yMinus1 = y - 1, zMinus1 = z - 1;
var u = fade(x), v = fade(y), w = fade(z);
var A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z, B = p[X + 1] + Y, BA = p[B] + Z, BB = p[B + 1] + Z;
return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z),
grad(p[BA], xMinus1, y, z)),
lerp(u, grad(p[AB], x, yMinus1, z),
grad(p[BB], xMinus1, yMinus1, z))),
lerp(v, lerp(u, grad(p[AA + 1], x, y, zMinus1),
grad(p[BA + 1], xMinus1, y, z - 1)),
lerp(u, grad(p[AB + 1], x, yMinus1, zMinus1),
grad(p[BB + 1], xMinus1, yMinus1, zMinus1))));
}
}
};
module.exports = ImprovedNoise;
/***/ }
/******/ ]);
|
import React, { Component, PropTypes } from 'react';
import SolutionBase from '../Shared/Solution';
import { Pairs } from './Algorithm';
import MultTargetStepItem from './MultTargetStepItem';
import MultTargetClock from './MultTargetClock';
import StepList from './StepList';
export default class Solution extends React.Component {
constructor(props) {
super(props);
}
render () {
const target = this.props.inputValues.target;
const modulus = this.props.inputValues.modulus;
console.log(target, modulus);
const pairs = Pairs(target, modulus);
console.log(pairs);
return <SolutionBase inputValues={this.props.inputValues}
steps={pairs}
stepItem={MultTargetStepItem}
stepList={StepList}
graph={MultTargetClock}
unconfigureFunc={this.props.unconfigureFunc} />;
}
}
|
/// <reference name="MicrosoftAjax.js" />
/// <reference name="MicrosoftAjaxTimer.debug.js" />
/// <reference name="MicrosoftAjaxWebForms.debug.js" />
/// <reference name="AjaxControlToolkit.ExtenderBase.BaseScripts.js" assembly="AjaxControlToolkit" />
//TODO: Need to control if setting activeIndex or selectedIndex, should select or toggle the appropriate
//checkmark; need to figure out if selectedIndex should be lower index or how that should be handled.
Type.registerNamespace("Nucleo.Web.ListControls");
Nucleo.Web.ListControls.ListControl = function(associatedElement) {
Nucleo.Web.ListControls.ListControl.initializeBase(this, [associatedElement]);
this._activeIndex = null;
this._alternatingItemStyle = null;
this._dataTextField = null;
this._dataTextFormatString = null;
this._dataValueField = null;
this._interfaceBuilder = null;
this._interfaceType = null;
this._items = null;
this._itemSelectedStyle = null;
this._itemStyle = null;
this._itemToggledStyle = null;
this._renderOnLoad = null;
this._repeatColumnCount = null;
this._repeatingDirection = null;
this._repeatingLayout = null;
this._selectedIndex = null;
this._currentCheckIndex = 1;
this._clickedHandler = null;
this._listItemAddedHandler = null;
this._listItemRemovedHandler = null;
this._listClearedHandler = null;
this._listSelectionClearedHandler = null;
}
Nucleo.Web.ListControls.ListControl.prototype = {
//******************************************************
// Properties
//******************************************************
get_activeIndex: function() {
if (this._activeIndex >= 0)
return this._activeIndex;
else {
if (this._selectedIndex >= 0)
this._activeIndex = this._selectedIndex;
return this._activeIndex;
}
},
get_alternatingItemStyle: function() {
return this._alternatingItemStyle;
},
set_alternatingItemStyle: function(value) {
if (this._alternatingItemStyle != value) {
this._alternatingItemStyle = value;
this.raisePropertyChanged("alternatingItemStyle");
}
},
get_dataTextField: function() {
return this._dataTextField;
},
set_dataTextField: function() {
if (this._dataTextField != value) {
this._dataTextField = value;
this.raisePropertyChanged("dataTextField");
}
},
get_dataTextFormatString: function() {
return this._dataTextFormatString;
},
set_dataTextFormatString: function() {
if (this._dataTextFormatString != value) {
this._dataTextFormatString = value;
this.raisePropertyChanged("dataTextFormatString");
}
},
get_dataValueField: function() {
return this._dataValueField;
},
set_dataValueField: function() {
if (this._dataValueField != value) {
this._dataValueField = value;
this.raisePropertyChanged("dataValueField");
}
},
get_interfaceBuilder: function() {
if (this._interfaceBuilder == null)
this._createBuilder();
return this._interfaceBuilder;
},
get_interfaceType: function() {
return this._interfaceType;
},
set_interfaceType: function(value) {
if (this.get_isInitialized())
throw Error.notImplemented("The interface type cannot be changed after initialization");
if (value == Nucleo.Web.ListControls.ListInterfaceType.Custom)
throw new Error.notImplemented("The custom interface type will be implemented in a later release. This is currently not supported.");
if (this._interfaceType != value) {
this._interfaceType = value;
this.raisePropertyChanged("interfaceType");
}
},
get_items: function() {
if (this._items == null)
this._items = [];
return this._items;
},
set_items: function(value) {
if (this.get_isInitialized())
throw Error.notImplemented("The items cannot be set after initialization");
if (this._items != value) {
if (typeof (value) == 'string')
this._items = this._convertToListItemCollection(Sys.Serialization.JavaScriptSerializer.deserialize(value).ItemsList);
else
this._items = value;
this.raisePropertyChanged("items");
}
},
get_itemSelectedStyle: function() {
return this._itemSelectedStyle;
},
set_itemSelectedStyle: function(value) {
if (this._itemSelectedStyle != value) {
this._itemSelectedStyle = value;
this.raisePropertyChanged("itemSelectedStyle");
}
},
get_itemStyle: function() {
return this._itemStyle;
},
set_itemStyle: function(value) {
if (this._itemStyle != value) {
this._itemStyle = value;
this.raisePropertyChanged("itemStyle");
}
},
get_itemToggledStyle: function() {
return this._itemToggledStyle;
},
set_itemToggledStyle: function(value) {
if (this._itemToggledStyle != value) {
this._itemToggledStyle = value;
this.raisePropertyChanged("itemToggledStyle");
}
},
get_renderOnLoad: function() {
return this._renderOnLoad;
},
set_renderOnLoad: function(value) {
if (this._renderOnLoad != value) {
this._renderOnLoad = value;
this.raisePropertyChanged("renderOnLoad");
}
},
get_repeatColumnCount: function() {
return this._repeatColumnCount;
},
set_repeatColumnCount: function(value) {
if (this._repeatColumnCount != value) {
this._repeatColumnCount = value;
this.raisePropertyChanged("repeatColumnCount");
}
},
get_repeatingDirection: function() {
return this._repeatingDirection;
},
set_repeatingDirection: function(value) {
if (this._repeatingDirection != value) {
this._repeatingDirection = value;
this.raisePropertyChanged("repeatingDirection");
}
},
get_repeatingLayout: function() {
return this._repeatingLayout;
},
set_repeatingLayout: function(value) {
if (this._repeatingLayout != value) {
this._repeatingLayout = value;
this.raisePropertyChanged("repeatingLayout");
}
},
get_selectedItem: function() {
var index = this.get_selectedIndex();
if (index < 0 || index >= this.get_items().get_count())
return null;
return this.get_items().get_item(index);
},
get_selectedIndex: function() {
return this._selectedIndex;
},
set_selectedIndex: function(value) {
if (this._selectedIndex != value) {
this._selectedIndex = value;
this.raisePropertyChanged("selectedIndex");
}
},
get_showFooter: function() {
return false;
},
get_showHeader: function() {
return false;
},
get_totalCount: function() {
return this.get_items().get_count();
},
//******************************************************
// Event Methods
//******************************************************
add_allItemsSelected: function(handler) {
this.get_events().addHandler("allItemsSelected", handler);
},
remove_allItemsSelected: function(handler) {
this.get_events().removeHandler("allItemsSelected", handler);
},
raise_allItemsSelected: function() {
var handler = this.get_events().getHandler("allItemsSelected");
if (handler != null)
handler(this, Sys.EventArgs.Empty);
},
add_noItemsSelected: function(handler) {
this.get_events().addHandler("noItemsSelected", handler);
},
remove_noItemsSelected: function(handler) {
this.get_events().removeHandler("noItemsSelected", handler);
},
raise_noItemsSelected: function() {
var handler = this.get_events().getHandler("noItemsSelected");
if (handler != null)
handler(this, Sys.EventArgs.Empty);
},
add_itemSelected: function(handler) {
this.get_events().addHandler("itemSelected", handler);
},
remove_itemSelected: function(handler) {
this.get_events().removeHandler("itemSelected", handler);
},
raise_itemSelected: function() {
var handler = this.get_events().getHandler("itemSelected");
if (handler != null)
handler(this, Sys.EventArgs.Empty);
},
add_itemToggled: function(handler) {
this.get_events().addHandler("itemToggled", handler);
},
remove_itemToggled: function(handler) {
this.get_events().removeHandler("itemToggled", handler);
},
raise_onItemToggled: function() {
var handler = this.get_events().getHandler("itemToggled");
if (handler != null)
handler(this, Sys.EventArgs.Empty);
},
//******************************************************
// Methods
//******************************************************
_convertToListItemCollection: function(items) {
if (items.length == 0)
return [];
var listItems = new Nucleo.Web.ListControls.ListItemCollection();
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item.get_text == undefined) {
var listItem = new Nucleo.Web.ListControls.ListItem(item.Text, item.Value, item.Selected, item.Enabled);
listItems.add(listItem);
}
}
this._listItemAddedHandler = Function.createDelegate(this, this._listItemAddedCallback);
this._listItemRemovedHandler = Function.createDelegate(this, this._listItemRemovedCallback);
this._listClearedHandler = Function.createDelegate(this, this._listClearedCallback);
this._listSelectionClearedHandler = Function.createDelegate(this, this._listSelectionClearedCallback);
listItems.add_itemAdded(this._listItemAddedHandler);
listItems.add_itemRemoved(this._listItemRemovedHandler);
listItems.add_cleared(this._listClearedHandler);
listItems.add_selectionCleared(this._listSelectionClearedHandler);
return listItems;
},
_createBuilder: function() {
if (this._interfaceBuilder != null)
return;
this._interfaceBuilder = Nucleo.Web.ListControls.Builders.ListInterfaceBuilder.buildInterface(this);
if (this.get_renderOnLoad() == true)
this._interfaceBuilder._render();
return this._interfaceBuilder;
},
findIndex: function(listItem) {
return Array.indexOf(listItem);
},
findSelectedIndex: function() {
for (var i = 0; i < this.get_items().length; i++) {
if (this.get_items()[i].get_selected())
return i;
}
return -1;
},
// _processCheckboxes : function()
// {
// this._checkboxClickHandler = Function.createDelegate(this, this.checkboxClickCallback);
// this._checkboxes = this.get_element().getElementsByTagName("input");
// for (var i = 0; i < this.get_checkboxes().length; i++)
// $addHandler(this.get_checkboxes()[i], "click", this._checkboxClickHandler);
// },
_listClearedCallback: function(sender, e) {
this.get_interfaceBuilder().clearItems();
},
_listItemAddedCallback: function(sender, e) {
this._setupItem(e.get_data());
this.get_interfaceBuilder().addItem(e.get_data());
},
_listItemClickedCallback: function(sender, e) {
var index = this.findIndex(sender);
this.set_activeIndex(index);
if (sender.get_selected())
this.set_selectedIndex(index);
else
this.findSelectedIndex();
},
_listItemRemovedCallback: function(sender, e) {
this._teardownItem(e.get_data());
this.get_interfaceBuilder().removeItem(e.get_data());
},
_listItemSelectedCallback: function(sender, e) {
if (this.get_itemSelectedStyle() != null)
sender.style = this.get_itemSelectedStyle();
},
_listSelectionClearedCallback: function(sender, e) {
this.set_selectedIndex(-1);
},
_listItemToggledCallback: function(sender, e) {
if (this.get_itemToggledStyle() != null)
sender.style = this.get_itemToggledStyle();
},
_renderItem: function(index, parentElement) {
var listItem = this.get_items().get_item(index);
this.get_interfaceBuilder().createItem(listItem, parentElement);
},
selectAllItems: function() {
for (var i = 0; i < this.get_items().length; i++)
this.get_items()[i].set_selected(true);
},
_setupItem: function(listItem) {
listItem.add_clicked(this._listItemClickedCallback);
listItem.add_selected(this._listItemSelectedCallback);
listItem.add_toggled(this._listItemToggledCallback);
},
_teardownItem: function(listItem) {
listItem.remove_clicked(this._listItemClickedCallback);
listItem.remove_selected(this._listItemSelectedCallback);
listItem.remove_toggled(this._listItemToggledCallback);
},
//******************************************************
// Callback Methods
//******************************************************
// checkboxClickCallback : function(domEvent)
// {
// var checkbox = domEvent.target;
// if (checkbox == null) return;
// if (checkbox.checked)
// this.raise_itemSelected();
//
// var total = this.get_checkboxes().length;
// var count = 0;
//
// for (var i = 0; i < this.get_checkboxes().length; i++)
// {
// var checkboxToCompare = this.get_checkboxes()[i];
// if (checkbox == checkboxToCompare)
// this.set_activeIndex(i);
//
// if (checkboxToCompare.checked)
// {
// this.set_selectedIndex(i);
// count++;
// }
// }
//
// if (count == 0)
// this.raise_noItemsSelected();
// else if (count == total)
// this.raise_allItemsSelected();
// this.raise_onItemToggled();
// },
//******************************************************
// Lifecycle Methods
//******************************************************
initialize: function() {
Nucleo.Web.ListControls.ListControl.callBaseMethod(this, "initialize");
if (this.get_bind
this._createBuilder();
},
dispose: function() {
Nucleo.Web.ListControls.ListControl.callBaseMethod(this, "dispose");
}
}
Nucleo.Web.ListControls.ListControl.descriptor = {
properties:
[
{ name: 'activeIndex', type: Number },
{ name: 'dataTextField', type: String },
{ name: 'dataTextFormatString', type: String },
{ name: 'dataValueField', type: String },
{ name: 'items', type: Array, readOnly: true },
{ name: 'repeatColumnCount', type: Number },
{ name: 'repeatingDirection', type: Nucleo.Web.RepeatDirection },
{ name: 'repeatingLayout', type: Nucleo.Web.RepeatLayout },
{ name: 'selectedIndex', type: Number }
],
methods:
[
{ name: 'clearAll' },
{ name: 'selectAll' }
],
events:
[
{ name: 'allItemsSelected' },
{ name: 'noItemsSelected' },
{ name: 'itemToggled' },
{ name: 'itemSelected' }
]
}
Nucleo.Web.ListControls.ListControl.registerClass('Nucleo.Web.ListControls.ListControl', Nucleo.Web.DataboundControls.AjaxDataboundControl, Nucleo.Web.Repeating.IRepeatingList);
if (typeof (Sys) !== 'undefined')
Sys.Application.notifyScriptLoaded();
|
'use strict';
var child = require('./child.js');
var defaults = {
viewportSize: {
// this should be equal to paper size
width: 1050,
height: 1485
},
paperSize: {
/**
* A4 ratio in millimeters: 210 x 297
* DPI is hardcoded 72 in phantomJS.
* A resolution of 1050px will give 1050 / 72 * 25.4 ~ 370 mm width,
* which is way much larger than A4. Most printers will handle this,
* and scale correctly to given paper source.
*/
width: 1050,
height: 1485,
orientation: 'portrait',
margin: '1cm'
},
args: '',
captureDelay: 100
};
/**
* Render pages til PDFs.
*
* @param {array of strings} pages
* @param {object} options
* @param {function} called when done
*/
module.exports = function (pages, options, callback) {
if (typeof options === 'function') {
callback = options;
options = defaults;
};
options = Object.assign(defaults, options);
child.supports(function (support){
if (!support) {
callback(new Error('PhantomJS not installed'));
}
child.exec(pages, options, callback);
});
};
|
import { assert } from '@ember/debug';
import { computed, get } from '@ember/object';
export default function createTranslatedComputedProperty(key, interpolations = {}) {
const values = Object.keys(interpolations).map(key => interpolations[key]);
const dependencies = [ 'i18n.locale' ].concat(values);
return computed(...dependencies, function() {
const i18n = get(this, 'i18n');
assert(`Cannot translate ${key}. ${this} does not have an i18n.`, i18n);
return i18n.t(key, mapPropertiesByHash(this, interpolations));
});
}
function mapPropertiesByHash(object, hash) {
const result = {};
Object.keys(hash).forEach(function(key) {
result[key] = get(object, hash[key]);
});
return result;
}
|
jui.define("chart.brush.area", [], function() {
/**
* @class chart.brush.area
*
* @extends chart.brush.line
*/
var AreaBrush = function() {
this.drawArea = function(path) {
var g = this.chart.svg.group(),
y = this.axis.y(this.brush.startZero ? 0 : this.axis.y.min());
for(var k = 0; k < path.length; k++) {
var p = this.createLine(path[k], k),
xList = path[k].x;
if(path[k].length > 0) {
p.LineTo(xList[xList.length - 1], y);
p.LineTo(xList[0], y);
p.ClosePath();
}
p.attr({
fill: this.color(k),
"fill-opacity": this.chart.theme("areaBackgroundOpacity"),
"stroke-width": 0
});
this.addEvent(p, null, k);
g.prepend(p);
// Add line
if(this.brush.line) {
g.prepend(this.createLine(path[k], k));
}
}
return g;
}
this.draw = function() {
return this.drawArea(this.getXY());
}
this.drawAnimate = function(root) {
root.append(
this.chart.svg.animate({
attributeName: "opacity",
from: "0",
to: "1",
begin: "0s" ,
dur: "1.5s",
repeatCount: "1",
fill: "freeze"
})
);
}
}
AreaBrush.setup = function() {
return {
/** @cfg {"normal"/"curve"/"step"} [symbol="normal"] Sets the shape of a line (normal, curve, step). */
symbol: "normal", // normal, curve, step
/** @cfg {Number} [active=null] Activates the bar of an applicable index. */
active: null,
/** @cfg {String} [activeEvent=null] Activates the bar in question when a configured event occurs (click, mouseover, etc). */
activeEvent: null,
/** @cfg {"max"/"min"} [display=null] Shows a tool tip on the bar for the minimum/maximum value. */
display: null,
/** @cfg {Boolean} [startZero=false] The end of the area is zero point. */
startZero: false,
/** @cfg {Boolean} [line=true] Visible line */
line: true
};
}
return AreaBrush;
}, "chart.brush.line");
|
/**
* Unit test for the PropTypes.any validator
*/
import Ember from 'ember'
const {Logger} = Ember
import {afterEach, beforeEach, describe} from 'mocha'
import sinon from 'sinon'
import {itValidatesTheProperty, spyOnValidateMethods} from 'dummy/tests/helpers/validator'
import PropTypesMixin, {PropTypes} from 'ember-prop-types/mixins/prop-types'
const requiredDef = {
required: true,
type: 'any'
}
const notRequiredDef = {
isRequired: requiredDef,
required: false,
type: 'any'
}
describe('Unit / validator / PropTypes.any', function () {
const ctx = {propertyName: 'bar'}
let sandbox, Foo
beforeEach(function () {
sandbox = sinon.sandbox.create()
spyOnValidateMethods(sandbox)
})
afterEach(function () {
sandbox.restore()
})
describe('when required', function () {
beforeEach(function () {
ctx.def = requiredDef
Foo = Ember.Object.extend(PropTypesMixin, {
propTypes: {
bar: PropTypes.any.isRequired
}
})
})
describe('when initialized with array value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar: []})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized with boolean value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar: true})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized with function value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar () {}})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized with null value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar: null})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized with number value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar: 1})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized with object value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar: {}})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized with string value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar: 'test'})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized without value', function () {
beforeEach(function () {
ctx.instance = Foo.create()
})
itValidatesTheProperty(ctx, false, 'Missing required property bar')
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
})
describe('when not required', function () {
beforeEach(function () {
ctx.def = notRequiredDef
Foo = Ember.Object.extend(PropTypesMixin, {
propTypes: {
bar: PropTypes.any
}
})
})
describe('when initialized with array value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar: []})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized with boolean value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar: true})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized with function value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar () {}})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized with null value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar: null})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized with number value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar: 1})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized with object value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar: {}})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized with string value', function () {
beforeEach(function () {
ctx.instance = Foo.create({bar: 'test'})
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
describe('when initialized without value', function () {
beforeEach(function () {
ctx.instance = Foo.create()
})
itValidatesTheProperty(ctx, false)
describe('when updated with array value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', [])
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with boolean value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', false)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with null value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', null)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with number value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 2)
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with object value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', {})
})
itValidatesTheProperty(ctx, false)
})
describe('when updated with string value', function () {
beforeEach(function () {
Logger.warn.reset()
ctx.instance.set('bar', 'baz')
})
itValidatesTheProperty(ctx, false)
})
})
})
})
|
smalltalk.addPackage('Helios-Inspector');
smalltalk.addClass('HLInspectorDisplayWidget', smalltalk.HLNavigationListWidget, ['model'], 'Helios-Inspector');
smalltalk.addMethod(
smalltalk.method({
selector: "model",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@model"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"model",{},smalltalk.HLInspectorDisplayWidget)})},
args: [],
source: "model\x0a\x0a\x09^ model",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorDisplayWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "model:",
category: 'accessing',
fn: function (aModel){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@model"]=aModel;
return self}, function($ctx1) {$ctx1.fill(self,"model:",{aModel:aModel},smalltalk.HLInspectorDisplayWidget)})},
args: ["aModel"],
source: "model: aModel\x0a\x0a\x09model := aModel",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorDisplayWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "renderContentOn:",
category: 'rendering',
fn: function (html){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(_st(html)._div())._with_(self._selectionDisplayString());
return self}, function($ctx1) {$ctx1.fill(self,"renderContentOn:",{html:html},smalltalk.HLInspectorDisplayWidget)})},
args: ["html"],
source: "renderContentOn: html\x0a\x09\x0a html div with: self selectionDisplayString\x0a ",
messageSends: ["with:", "selectionDisplayString", "div"],
referencedClasses: []
}),
smalltalk.HLInspectorDisplayWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "selectionDisplayString",
category: 'rendering',
fn: function (){
var self=this;
var selection;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
selection=_st(self["@model"])._selection();
$2=_st(_st(_st(self["@model"])._variables())._keys())._includes_(selection);
if(smalltalk.assert($2)){
$1=_st(_st(self["@model"])._instVarObjectAt_(selection))._printString();
} else {
$1="";
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"selectionDisplayString",{selection:selection},smalltalk.HLInspectorDisplayWidget)})},
args: [],
source: "selectionDisplayString\x0a\x09|selection|\x0a\x09selection := model selection.\x0a ^ (model variables keys includes: selection)\x0a \x09ifTrue:[(model instVarObjectAt: selection) printString]\x0a \x09ifFalse:['']",
messageSends: ["selection", "ifTrue:ifFalse:", "printString", "instVarObjectAt:", "includes:", "keys", "variables"],
referencedClasses: []
}),
smalltalk.HLInspectorDisplayWidget);
smalltalk.addClass('HLInspectorModel', smalltalk.Object, ['announcer', 'environment', 'inspectee', 'code', 'variables', 'label', 'selection'], 'Helios-Inspector');
smalltalk.addMethod(
smalltalk.method({
selector: "announcer",
category: 'accessing',
fn: function (){
var self=this;
function $Announcer(){return smalltalk.Announcer||(typeof Announcer=="undefined"?nil:Announcer)}
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@announcer"];
if(($receiver = $2) == nil || $receiver == undefined){
self["@announcer"]=_st($Announcer())._new();
$1=self["@announcer"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"announcer",{},smalltalk.HLInspectorModel)})},
args: [],
source: "announcer\x0a\x09^ announcer ifNil: [announcer := Announcer new ]",
messageSends: ["ifNil:", "new"],
referencedClasses: ["Announcer"]
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "code",
category: 'accessing',
fn: function (){
var self=this;
function $HLCodeModel(){return smalltalk.HLCodeModel||(typeof HLCodeModel=="undefined"?nil:HLCodeModel)}
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@code"];
if(($receiver = $2) == nil || $receiver == undefined){
self["@code"]=_st($HLCodeModel())._on_(self._environment());
$1=self["@code"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"code",{},smalltalk.HLInspectorModel)})},
args: [],
source: "code\x0a\x09\x22Answers the code model working for this workspace model\x22\x0a\x09^ code ifNil:[ code := HLCodeModel on: self environment ]",
messageSends: ["ifNil:", "on:", "environment"],
referencedClasses: ["HLCodeModel"]
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "environment",
category: 'accessing',
fn: function (){
var self=this;
function $HLManager(){return smalltalk.HLManager||(typeof HLManager=="undefined"?nil:HLManager)}
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@environment"];
if(($receiver = $2) == nil || $receiver == undefined){
$1=_st(_st($HLManager())._current())._environment();
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"environment",{},smalltalk.HLInspectorModel)})},
args: [],
source: "environment\x0a\x09^ environment ifNil: [ HLManager current environment ]",
messageSends: ["ifNil:", "environment", "current"],
referencedClasses: ["HLManager"]
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "environment:",
category: 'accessing',
fn: function (anEnvironment){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@environment"]=anEnvironment;
return self}, function($ctx1) {$ctx1.fill(self,"environment:",{anEnvironment:anEnvironment},smalltalk.HLInspectorModel)})},
args: ["anEnvironment"],
source: "environment: anEnvironment\x0a\x09environment := anEnvironment",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "inspect:on:",
category: 'actions',
fn: function (anObject,anInspector){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@inspectee"]=anObject;
self["@variables"]=[];
_st(self["@inspectee"])._inspectOn_(anInspector);
return self}, function($ctx1) {$ctx1.fill(self,"inspect:on:",{anObject:anObject,anInspector:anInspector},smalltalk.HLInspectorModel)})},
args: ["anObject", "anInspector"],
source: "inspect: anObject on: anInspector\x0a\x09inspectee := anObject.\x0a\x09variables := #().\x0a\x09inspectee inspectOn: anInspector ",
messageSends: ["inspectOn:"],
referencedClasses: []
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "inspectee",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@inspectee"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"inspectee",{},smalltalk.HLInspectorModel)})},
args: [],
source: "inspectee \x0a\x09^ inspectee ",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "inspectee:",
category: 'accessing',
fn: function (anObject){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@inspectee"]=anObject;
return self}, function($ctx1) {$ctx1.fill(self,"inspectee:",{anObject:anObject},smalltalk.HLInspectorModel)})},
args: ["anObject"],
source: "inspectee: anObject \x0a\x09inspectee := anObject\x0a ",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "instVarObjectAt:",
category: 'actions',
fn: function (anInstVarName){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._variables())._at_(anInstVarName);
return $1;
}, function($ctx1) {$ctx1.fill(self,"instVarObjectAt:",{anInstVarName:anInstVarName},smalltalk.HLInspectorModel)})},
args: ["anInstVarName"],
source: "instVarObjectAt: anInstVarName\x0a\x09^ self variables at: anInstVarName",
messageSends: ["at:", "variables"],
referencedClasses: []
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "label",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@label"];
if(($receiver = $2) == nil || $receiver == undefined){
$1=_st(self._inspectee())._printString();
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"label",{},smalltalk.HLInspectorModel)})},
args: [],
source: "label\x0a ^ label ifNil: [ self inspectee printString ]",
messageSends: ["ifNil:", "printString", "inspectee"],
referencedClasses: []
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "label:",
category: 'accessing',
fn: function (aString){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@label"]=aString;
return self}, function($ctx1) {$ctx1.fill(self,"label:",{aString:aString},smalltalk.HLInspectorModel)})},
args: ["aString"],
source: "label: aString\x0a label := aString",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "onKeyDown:",
category: 'reactions',
fn: function (anEvent){
var self=this;
return smalltalk.withContext(function($ctx1) {
if(anEvent.ctrlKey) {
if(anEvent.keyCode === 80) { //ctrl+p
self._printIt();
anEvent.preventDefault();
return false;
}
if(anEvent.keyCode === 68) { //ctrl+d
self._doIt();
anEvent.preventDefault();
return false;
}
if(anEvent.keyCode === 73) { //ctrl+i
self._inspectIt();
anEvent.preventDefault();
return false;
}
};
return self}, function($ctx1) {$ctx1.fill(self,"onKeyDown:",{anEvent:anEvent},smalltalk.HLInspectorModel)})},
args: ["anEvent"],
source: "onKeyDown: anEvent\x0a\x0a\x09<if(anEvent.ctrlKey) {\x0a\x09\x09if(anEvent.keyCode === 80) { //ctrl+p\x0a\x09\x09\x09self._printIt();\x0a\x09\x09\x09anEvent.preventDefault();\x0a\x09\x09\x09return false;\x0a\x09\x09}\x0a\x09\x09if(anEvent.keyCode === 68) { //ctrl+d\x0a\x09\x09\x09self._doIt();\x0a\x09\x09\x09anEvent.preventDefault();\x0a\x09\x09\x09return false;\x0a\x09\x09}\x0a\x09\x09if(anEvent.keyCode === 73) { //ctrl+i\x0a\x09\x09\x09self._inspectIt();\x0a\x09\x09\x09anEvent.preventDefault();\x0a\x09\x09\x09return false;\x0a\x09\x09}\x0a\x09}>",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "selectedInstVar:",
category: 'actions',
fn: function (anInstVarName){
var self=this;
return smalltalk.withContext(function($ctx1) {
self._selection_(anInstVarName);
return self}, function($ctx1) {$ctx1.fill(self,"selectedInstVar:",{anInstVarName:anInstVarName},smalltalk.HLInspectorModel)})},
args: ["anInstVarName"],
source: "selectedInstVar: anInstVarName\x0a self selection: anInstVarName",
messageSends: ["selection:"],
referencedClasses: []
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "selectedInstVarObject",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self._instVarObjectAt_(self._selection());
return $1;
}, function($ctx1) {$ctx1.fill(self,"selectedInstVarObject",{},smalltalk.HLInspectorModel)})},
args: [],
source: "selectedInstVarObject\x0a\x09^ self instVarObjectAt: self selection\x0a ",
messageSends: ["instVarObjectAt:", "selection"],
referencedClasses: []
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "selection",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@selection"];
if(($receiver = $2) == nil || $receiver == undefined){
$1="";
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"selection",{},smalltalk.HLInspectorModel)})},
args: [],
source: "selection\x0a\x09^ selection ifNil:[ '' ] ",
messageSends: ["ifNil:"],
referencedClasses: []
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "selection:",
category: 'accessing',
fn: function (anObject){
var self=this;
function $HLInstanceVariableSelected(){return smalltalk.HLInstanceVariableSelected||(typeof HLInstanceVariableSelected=="undefined"?nil:HLInstanceVariableSelected)}
return smalltalk.withContext(function($ctx1) {
self["@selection"]=anObject;
_st(self._announcer())._announce_(_st($HLInstanceVariableSelected())._on_(self["@selection"]));
return self}, function($ctx1) {$ctx1.fill(self,"selection:",{anObject:anObject},smalltalk.HLInspectorModel)})},
args: ["anObject"],
source: "selection: anObject\x0a\x09selection := anObject.\x0a\x0a\x09self announcer announce: (HLInstanceVariableSelected on: selection)\x0a ",
messageSends: ["announce:", "on:", "announcer"],
referencedClasses: ["HLInstanceVariableSelected"]
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "subscribe:",
category: 'actions',
fn: function (aWidget){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(aWidget)._subscribeTo_(self._announcer());
return self}, function($ctx1) {$ctx1.fill(self,"subscribe:",{aWidget:aWidget},smalltalk.HLInspectorModel)})},
args: ["aWidget"],
source: "subscribe: aWidget\x0a\x09aWidget subscribeTo: self announcer",
messageSends: ["subscribeTo:", "announcer"],
referencedClasses: []
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "variables",
category: 'accessing',
fn: function (){
var self=this;
function $Dictionary(){return smalltalk.Dictionary||(typeof Dictionary=="undefined"?nil:Dictionary)}
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@variables"];
if(($receiver = $2) == nil || $receiver == undefined){
$1=_st($Dictionary())._new();
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"variables",{},smalltalk.HLInspectorModel)})},
args: [],
source: "variables\x0a\x09^ variables ifNil: [ Dictionary new ]",
messageSends: ["ifNil:", "new"],
referencedClasses: ["Dictionary"]
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "variables:",
category: 'accessing',
fn: function (aCollection){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@variables"]=aCollection;
return self}, function($ctx1) {$ctx1.fill(self,"variables:",{aCollection:aCollection},smalltalk.HLInspectorModel)})},
args: ["aCollection"],
source: "variables: aCollection\x0a\x09variables := aCollection\x0a ",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorModel);
smalltalk.addMethod(
smalltalk.method({
selector: "on:",
category: 'actions',
fn: function (anEnvironment){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$3,$1;
$2=self._new();
_st($2)._environment_(anEnvironment);
$3=_st($2)._yourself();
$1=$3;
return $1;
}, function($ctx1) {$ctx1.fill(self,"on:",{anEnvironment:anEnvironment},smalltalk.HLInspectorModel.klass)})},
args: ["anEnvironment"],
source: "on: anEnvironment\x0a\x0a\x09^ self new\x0a \x09environment: anEnvironment;\x0a yourself",
messageSends: ["environment:", "new", "yourself"],
referencedClasses: []
}),
smalltalk.HLInspectorModel.klass);
smalltalk.addClass('HLInspectorVariablesWidget', smalltalk.HLNavigationListWidget, ['announcer', 'model', 'list', 'diveButton'], 'Helios-Inspector');
smalltalk.addMethod(
smalltalk.method({
selector: "announcer",
category: 'accessing',
fn: function (){
var self=this;
function $Announcer(){return smalltalk.Announcer||(typeof Announcer=="undefined"?nil:Announcer)}
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@announcer"];
if(($receiver = $2) == nil || $receiver == undefined){
self["@announcer"]=_st($Announcer())._new();
$1=self["@announcer"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"announcer",{},smalltalk.HLInspectorVariablesWidget)})},
args: [],
source: "announcer\x0a\x09^ announcer ifNil:[ announcer := Announcer new ]",
messageSends: ["ifNil:", "new"],
referencedClasses: ["Announcer"]
}),
smalltalk.HLInspectorVariablesWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "defaultItems",
category: 'defaults',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self._variables();
return $1;
}, function($ctx1) {$ctx1.fill(self,"defaultItems",{},smalltalk.HLInspectorVariablesWidget)})},
args: [],
source: "defaultItems\x0a\x09^ self variables",
messageSends: ["variables"],
referencedClasses: []
}),
smalltalk.HLInspectorVariablesWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "label",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._model())._label();
return $1;
}, function($ctx1) {$ctx1.fill(self,"label",{},smalltalk.HLInspectorVariablesWidget)})},
args: [],
source: "label\x0a\x09^ self model label",
messageSends: ["label", "model"],
referencedClasses: []
}),
smalltalk.HLInspectorVariablesWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "model",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@model"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"model",{},smalltalk.HLInspectorVariablesWidget)})},
args: [],
source: "model\x0a ^ model\x0a ",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorVariablesWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "model:",
category: 'accessing',
fn: function (aModel){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@model"]=aModel;
return self}, function($ctx1) {$ctx1.fill(self,"model:",{aModel:aModel},smalltalk.HLInspectorVariablesWidget)})},
args: ["aModel"],
source: "model: aModel\x0a model := aModel\x0a ",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorVariablesWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "refresh",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._variables()).__eq(self._items());
if(! smalltalk.assert($1)){
self._resetItems();
smalltalk.HLInspectorVariablesWidget.superclass.fn.prototype._refresh.apply(_st(self), []);
};
return self}, function($ctx1) {$ctx1.fill(self,"refresh",{},smalltalk.HLInspectorVariablesWidget)})},
args: [],
source: "refresh\x0a\x09self variables = self items ifFalse: [\x0a\x09\x09self resetItems.\x0a \x09super refresh ]",
messageSends: ["ifFalse:", "resetItems", "refresh", "=", "items", "variables"],
referencedClasses: []
}),
smalltalk.HLInspectorVariablesWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "renderButtonsOn:",
category: 'rendering',
fn: function (html){
var self=this;
function $HLDiveRequested(){return smalltalk.HLDiveRequested||(typeof HLDiveRequested=="undefined"?nil:HLDiveRequested)}
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=_st(html)._button();
_st($1)._class_("btn");
_st($1)._with_("Dive");
$2=_st($1)._onClick_((function(){
return smalltalk.withContext(function($ctx2) {
return _st(self._announcer())._announce_(_st($HLDiveRequested())._new());
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
self["@diveButton"]=$2;
return self}, function($ctx1) {$ctx1.fill(self,"renderButtonsOn:",{html:html},smalltalk.HLInspectorVariablesWidget)})},
args: ["html"],
source: "renderButtonsOn: html\x0a\x09diveButton := html button \x0a\x09\x09class: 'btn';\x0a\x09\x09with: 'Dive'; \x0a\x09\x09onClick: [ self announcer announce: HLDiveRequested new ]",
messageSends: ["class:", "button", "with:", "onClick:", "announce:", "new", "announcer"],
referencedClasses: ["HLDiveRequested"]
}),
smalltalk.HLInspectorVariablesWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "renderContentOn:",
category: 'rendering',
fn: function (html){
var self=this;
return smalltalk.withContext(function($ctx1) {
self._renderHeadOn_(html);
smalltalk.HLInspectorVariablesWidget.superclass.fn.prototype._renderContentOn_.apply(_st(self), [html]);
return self}, function($ctx1) {$ctx1.fill(self,"renderContentOn:",{html:html},smalltalk.HLInspectorVariablesWidget)})},
args: ["html"],
source: "renderContentOn: html\x0a\x09self renderHeadOn: html.\x0a\x09super renderContentOn: html",
messageSends: ["renderHeadOn:", "renderContentOn:"],
referencedClasses: []
}),
smalltalk.HLInspectorVariablesWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "renderHeadOn:",
category: 'rendering',
fn: function (html){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=_st(html)._div();
_st($1)._class_("list-label");
$2=_st($1)._with_(self._label());
return self}, function($ctx1) {$ctx1.fill(self,"renderHeadOn:",{html:html},smalltalk.HLInspectorVariablesWidget)})},
args: ["html"],
source: "renderHeadOn: html\x0a\x09html div \x0a\x09\x09class: 'list-label';\x0a\x09\x09with: self label",
messageSends: ["class:", "div", "with:", "label"],
referencedClasses: []
}),
smalltalk.HLInspectorVariablesWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "resetItems",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@items"]=nil;
return self}, function($ctx1) {$ctx1.fill(self,"resetItems",{},smalltalk.HLInspectorVariablesWidget)})},
args: [],
source: "resetItems\x0a\x09items := nil",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorVariablesWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "selectItem:",
category: 'reactions',
fn: function (anObject){
var self=this;
return smalltalk.withContext(function($ctx1) {
smalltalk.HLInspectorVariablesWidget.superclass.fn.prototype._selectItem_.apply(_st(self), [anObject]);
_st(self._model())._selectedInstVar_(anObject);
return self}, function($ctx1) {$ctx1.fill(self,"selectItem:",{anObject:anObject},smalltalk.HLInspectorVariablesWidget)})},
args: ["anObject"],
source: "selectItem: anObject\x0a\x09super selectItem: anObject.\x0a self model selectedInstVar: anObject",
messageSends: ["selectItem:", "selectedInstVar:", "model"],
referencedClasses: []
}),
smalltalk.HLInspectorVariablesWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "selection",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self["@model"])._selection();
return $1;
}, function($ctx1) {$ctx1.fill(self,"selection",{},smalltalk.HLInspectorVariablesWidget)})},
args: [],
source: "selection\x0a\x09^ model selection",
messageSends: ["selection"],
referencedClasses: []
}),
smalltalk.HLInspectorVariablesWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "variables",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(_st(self._model())._variables())._keys();
return $1;
}, function($ctx1) {$ctx1.fill(self,"variables",{},smalltalk.HLInspectorVariablesWidget)})},
args: [],
source: "variables\x0a\x09^ self model variables keys",
messageSends: ["keys", "variables", "model"],
referencedClasses: []
}),
smalltalk.HLInspectorVariablesWidget);
smalltalk.addClass('HLInspectorWidget', smalltalk.HLWidget, ['model', 'variablesWidget', 'displayWidget', 'codeWidget'], 'Helios-Inspector');
smalltalk.addMethod(
smalltalk.method({
selector: "codeWidget",
category: 'accessing',
fn: function (){
var self=this;
function $HLCodeWidget(){return smalltalk.HLCodeWidget||(typeof HLCodeWidget=="undefined"?nil:HLCodeWidget)}
return smalltalk.withContext(function($ctx1) {
var $2,$3,$4,$1;
$2=self["@codeWidget"];
if(($receiver = $2) == nil || $receiver == undefined){
$3=_st($HLCodeWidget())._new();
_st($3)._model_(_st(self["@model"])._code());
_st($3)._receiver_(_st(self["@model"])._inspectee());
$4=_st($3)._yourself();
self["@codeWidget"]=$4;
$1=self["@codeWidget"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"codeWidget",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "codeWidget\x0a\x09^ codeWidget ifNil: [\x0a\x09\x09codeWidget := HLCodeWidget new\x0a \x09\x09model: model code;\x0a \x09receiver: model inspectee;\x0a \x09yourself ]",
messageSends: ["ifNil:", "model:", "code", "new", "receiver:", "inspectee", "yourself"],
referencedClasses: ["HLCodeWidget"]
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "displayWidget",
category: 'accessing',
fn: function (){
var self=this;
function $HLInspectorDisplayWidget(){return smalltalk.HLInspectorDisplayWidget||(typeof HLInspectorDisplayWidget=="undefined"?nil:HLInspectorDisplayWidget)}
return smalltalk.withContext(function($ctx1) {
var $2,$3,$4,$1;
$2=self["@displayWidget"];
if(($receiver = $2) == nil || $receiver == undefined){
$3=_st($HLInspectorDisplayWidget())._new();
_st($3)._model_(self._model());
$4=_st($3)._yourself();
self["@displayWidget"]=$4;
$1=self["@displayWidget"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"displayWidget",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "displayWidget\x0a\x09^ displayWidget ifNil: [\x0a\x09\x09displayWidget := HLInspectorDisplayWidget new\x0a \x09\x09model: self model;\x0a \x09yourself ]",
messageSends: ["ifNil:", "model:", "model", "new", "yourself"],
referencedClasses: ["HLInspectorDisplayWidget"]
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "initialize",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
smalltalk.HLInspectorWidget.superclass.fn.prototype._initialize.apply(_st(self), []);
self._register();
return self}, function($ctx1) {$ctx1.fill(self,"initialize",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "initialize\x0a\x09super initialize.\x0a\x09self register",
messageSends: ["initialize", "register"],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "inspect:",
category: 'actions',
fn: function (anObject){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2;
_st(self._model())._inspect_on_(anObject,self);
$1=self;
_st($1)._refreshVariablesWidget();
$2=_st($1)._refreshDisplayWidget();
return self}, function($ctx1) {$ctx1.fill(self,"inspect:",{anObject:anObject},smalltalk.HLInspectorWidget)})},
args: ["anObject"],
source: "inspect: anObject\x0a\x09self model inspect: anObject on: self.\x0a \x0a\x09self \x0a \x09refreshVariablesWidget;\x0a\x09\x09refreshDisplayWidget",
messageSends: ["inspect:on:", "model", "refreshVariablesWidget", "refreshDisplayWidget"],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "inspectee",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._model())._inspectee();
return $1;
}, function($ctx1) {$ctx1.fill(self,"inspectee",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "inspectee\x0a\x09^ self model inspectee",
messageSends: ["inspectee", "model"],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "inspectee:",
category: 'accessing',
fn: function (anObject){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._model())._inspectee_(anObject);
return self}, function($ctx1) {$ctx1.fill(self,"inspectee:",{anObject:anObject},smalltalk.HLInspectorWidget)})},
args: ["anObject"],
source: "inspectee: anObject\x0a\x09self model inspectee: anObject",
messageSends: ["inspectee:", "model"],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "label",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._model())._label();
return $1;
}, function($ctx1) {$ctx1.fill(self,"label",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "label\x0a ^ self model label",
messageSends: ["label", "model"],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "model",
category: 'accessing',
fn: function (){
var self=this;
function $HLInspectorModel(){return smalltalk.HLInspectorModel||(typeof HLInspectorModel=="undefined"?nil:HLInspectorModel)}
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@model"];
if(($receiver = $2) == nil || $receiver == undefined){
self._model_(_st($HLInspectorModel())._new());
$1=self["@model"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"model",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "model\x0a\x09^ model ifNil: [ \x0a \x09self model: HLInspectorModel new.\x0a\x09\x09model ]",
messageSends: ["ifNil:", "model:", "new"],
referencedClasses: ["HLInspectorModel"]
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "model:",
category: 'accessing',
fn: function (aModel){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2;
self["@model"]=aModel;
_st(self._codeWidget())._model_(_st(aModel)._code());
$1=self;
_st($1)._observeCodeWidget();
_st($1)._observeVariablesWidget();
$2=_st($1)._observeModel();
return self}, function($ctx1) {$ctx1.fill(self,"model:",{aModel:aModel},smalltalk.HLInspectorWidget)})},
args: ["aModel"],
source: "model: aModel\x0a\x09model := aModel. \x0a self codeWidget model: aModel code.\x0a \x0a self \x0a observeCodeWidget;\x0a \x09observeVariablesWidget;\x0a observeModel",
messageSends: ["model:", "code", "codeWidget", "observeCodeWidget", "observeVariablesWidget", "observeModel"],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "observeCodeWidget",
category: 'actions',
fn: function (){
var self=this;
function $HLDoItExecuted(){return smalltalk.HLDoItExecuted||(typeof HLDoItExecuted=="undefined"?nil:HLDoItExecuted)}
return smalltalk.withContext(function($ctx1) {
_st(_st(self._codeWidget())._announcer())._on_do_($HLDoItExecuted(),(function(){
return smalltalk.withContext(function($ctx2) {
return self._onDoneIt();
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
return self}, function($ctx1) {$ctx1.fill(self,"observeCodeWidget",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "observeCodeWidget\x0a\x09self codeWidget announcer \x0a \x09on: HLDoItExecuted \x0a do: [ self onDoneIt ]",
messageSends: ["on:do:", "onDoneIt", "announcer", "codeWidget"],
referencedClasses: ["HLDoItExecuted"]
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "observeModel",
category: 'actions',
fn: function (){
var self=this;
function $HLInstanceVariableSelected(){return smalltalk.HLInstanceVariableSelected||(typeof HLInstanceVariableSelected=="undefined"?nil:HLInstanceVariableSelected)}
return smalltalk.withContext(function($ctx1) {
_st(_st(self._model())._announcer())._on_send_to_($HLInstanceVariableSelected(),"onInstanceVariableSelected",self);
return self}, function($ctx1) {$ctx1.fill(self,"observeModel",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "observeModel\x0a\x09self model announcer\x0a on: HLInstanceVariableSelected\x0a\x09\x09send: #onInstanceVariableSelected\x0a\x09\x09to: self",
messageSends: ["on:send:to:", "announcer", "model"],
referencedClasses: ["HLInstanceVariableSelected"]
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "observeVariablesWidget",
category: 'actions',
fn: function (){
var self=this;
function $HLDiveRequested(){return smalltalk.HLDiveRequested||(typeof HLDiveRequested=="undefined"?nil:HLDiveRequested)}
return smalltalk.withContext(function($ctx1) {
_st(_st(self._variablesWidget())._announcer())._on_do_($HLDiveRequested(),(function(){
return smalltalk.withContext(function($ctx2) {
return self._onDive();
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
return self}, function($ctx1) {$ctx1.fill(self,"observeVariablesWidget",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "observeVariablesWidget\x0a\x09self variablesWidget announcer \x0a on: HLDiveRequested do:[ self onDive ]\x0a ",
messageSends: ["on:do:", "onDive", "announcer", "variablesWidget"],
referencedClasses: ["HLDiveRequested"]
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "onDive",
category: 'reactions',
fn: function (){
var self=this;
function $HLInspector(){return smalltalk.HLInspector||(typeof HLInspector=="undefined"?nil:HLInspector)}
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=_st($HLInspector())._new();
_st($1)._inspect_(_st(self._model())._selectedInstVarObject());
$2=_st($1)._openAsTab();
return self}, function($ctx1) {$ctx1.fill(self,"onDive",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "onDive\x0a\x0a\x09HLInspector new \x0a\x09\x09inspect: self model selectedInstVarObject;\x0a\x09\x09openAsTab",
messageSends: ["inspect:", "selectedInstVarObject", "model", "new", "openAsTab"],
referencedClasses: ["HLInspector"]
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "onDoneIt",
category: 'reactions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
self._refresh();
return self}, function($ctx1) {$ctx1.fill(self,"onDoneIt",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "onDoneIt\x0a\x0a\x09self refresh",
messageSends: ["refresh"],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "onInspectIt",
category: 'reactions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return self}, function($ctx1) {$ctx1.fill(self,"onInspectIt",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "onInspectIt",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "onInstanceVariableSelected",
category: 'reactions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._codeWidget())._receiver_(_st(self._model())._selectedInstVarObject());
self._refreshDisplayWidget();
return self}, function($ctx1) {$ctx1.fill(self,"onInstanceVariableSelected",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "onInstanceVariableSelected\x0a\x09self codeWidget receiver: self model selectedInstVarObject.\x0a\x09self refreshDisplayWidget",
messageSends: ["receiver:", "selectedInstVarObject", "model", "codeWidget", "refreshDisplayWidget"],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "onPrintIt",
category: 'reactions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return self}, function($ctx1) {$ctx1.fill(self,"onPrintIt",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "onPrintIt",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "refresh",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
self._inspect_(self._inspectee());
return self}, function($ctx1) {$ctx1.fill(self,"refresh",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "refresh\x0a\x09self inspect: self inspectee",
messageSends: ["inspect:", "inspectee"],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "refreshDisplayWidget",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._displayWidget())._refresh();
return self}, function($ctx1) {$ctx1.fill(self,"refreshDisplayWidget",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "refreshDisplayWidget\x0a\x09self displayWidget refresh",
messageSends: ["refresh", "displayWidget"],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "refreshVariablesWidget",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._variablesWidget())._refresh();
return self}, function($ctx1) {$ctx1.fill(self,"refreshVariablesWidget",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "refreshVariablesWidget\x0a\x09self variablesWidget refresh",
messageSends: ["refresh", "variablesWidget"],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "register",
category: 'registration',
fn: function (){
var self=this;
function $HLInspector(){return smalltalk.HLInspector||(typeof HLInspector=="undefined"?nil:HLInspector)}
return smalltalk.withContext(function($ctx1) {
_st($HLInspector())._register_(self);
return self}, function($ctx1) {$ctx1.fill(self,"register",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "register\x0a\x09HLInspector register: self",
messageSends: ["register:"],
referencedClasses: ["HLInspector"]
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "renderContentOn:",
category: 'rendering',
fn: function (html){
var self=this;
function $HLVerticalSplitter(){return smalltalk.HLVerticalSplitter||(typeof HLVerticalSplitter=="undefined"?nil:HLVerticalSplitter)}
function $HLHorizontalSplitter(){return smalltalk.HLHorizontalSplitter||(typeof HLHorizontalSplitter=="undefined"?nil:HLHorizontalSplitter)}
return smalltalk.withContext(function($ctx1) {
_st(html)._with_(_st($HLHorizontalSplitter())._with_with_(_st($HLVerticalSplitter())._with_with_(self._variablesWidget(),self._displayWidget()),self._codeWidget()));
return self}, function($ctx1) {$ctx1.fill(self,"renderContentOn:",{html:html},smalltalk.HLInspectorWidget)})},
args: ["html"],
source: "renderContentOn: html\x0a \x09html with: (HLHorizontalSplitter\x0a \x09with: (HLVerticalSplitter \x0a with: self variablesWidget\x0a with: self displayWidget)\x0a with: self codeWidget)\x0a ",
messageSends: ["with:", "with:with:", "variablesWidget", "displayWidget", "codeWidget"],
referencedClasses: ["HLVerticalSplitter", "HLHorizontalSplitter"]
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "setLabel:",
category: 'actions',
fn: function (aString){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._model())._label_(aString);
return self}, function($ctx1) {$ctx1.fill(self,"setLabel:",{aString:aString},smalltalk.HLInspectorWidget)})},
args: ["aString"],
source: "setLabel: aString\x0a\x09self model label: aString",
messageSends: ["label:", "model"],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "setVariables:",
category: 'actions',
fn: function (aDictionary){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._model())._variables_(aDictionary);
return self}, function($ctx1) {$ctx1.fill(self,"setVariables:",{aDictionary:aDictionary},smalltalk.HLInspectorWidget)})},
args: ["aDictionary"],
source: "setVariables: aDictionary\x0a\x09self model variables: aDictionary",
messageSends: ["variables:", "model"],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "tabLabel",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return "Inspector";
}, function($ctx1) {$ctx1.fill(self,"tabLabel",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "tabLabel\x0a ^ 'Inspector'",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "unregister",
category: 'registration',
fn: function (){
var self=this;
function $HLInspector(){return smalltalk.HLInspector||(typeof HLInspector=="undefined"?nil:HLInspector)}
return smalltalk.withContext(function($ctx1) {
smalltalk.HLInspectorWidget.superclass.fn.prototype._unregister.apply(_st(self), []);
_st($HLInspector())._unregister_(self);
return self}, function($ctx1) {$ctx1.fill(self,"unregister",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "unregister\x0a\x09super unregister.\x0a\x09HLInspector unregister: self",
messageSends: ["unregister", "unregister:"],
referencedClasses: ["HLInspector"]
}),
smalltalk.HLInspectorWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "variablesWidget",
category: 'accessing',
fn: function (){
var self=this;
function $HLInspectorVariablesWidget(){return smalltalk.HLInspectorVariablesWidget||(typeof HLInspectorVariablesWidget=="undefined"?nil:HLInspectorVariablesWidget)}
return smalltalk.withContext(function($ctx1) {
var $2,$3,$4,$1;
$2=self["@variablesWidget"];
if(($receiver = $2) == nil || $receiver == undefined){
$3=_st($HLInspectorVariablesWidget())._new();
_st($3)._model_(self._model());
$4=_st($3)._yourself();
self["@variablesWidget"]=$4;
$1=self["@variablesWidget"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"variablesWidget",{},smalltalk.HLInspectorWidget)})},
args: [],
source: "variablesWidget\x0a\x09^ variablesWidget ifNil: [\x0a\x09\x09variablesWidget := HLInspectorVariablesWidget new\x0a \x09\x09model: self model;\x0a \x09yourself ]",
messageSends: ["ifNil:", "model:", "model", "new", "yourself"],
referencedClasses: ["HLInspectorVariablesWidget"]
}),
smalltalk.HLInspectorWidget);
smalltalk.addClass('HLInspector', smalltalk.HLInspectorWidget, [], 'Helios-Inspector');
smalltalk.addMethod(
smalltalk.method({
selector: "renderContentOn:",
category: 'rendering',
fn: function (html){
var self=this;
function $HLVerticalSplitter(){return smalltalk.HLVerticalSplitter||(typeof HLVerticalSplitter=="undefined"?nil:HLVerticalSplitter)}
function $HLHorizontalSplitter(){return smalltalk.HLHorizontalSplitter||(typeof HLHorizontalSplitter=="undefined"?nil:HLHorizontalSplitter)}
function $HLContainer(){return smalltalk.HLContainer||(typeof HLContainer=="undefined"?nil:HLContainer)}
return smalltalk.withContext(function($ctx1) {
_st(html)._with_(_st($HLContainer())._with_(_st($HLHorizontalSplitter())._with_with_(_st($HLVerticalSplitter())._with_with_(self._variablesWidget(),self._displayWidget()),self._codeWidget())));
_st(self._variablesWidget())._focus();
return self}, function($ctx1) {$ctx1.fill(self,"renderContentOn:",{html:html},smalltalk.HLInspector)})},
args: ["html"],
source: "renderContentOn: html\x0a \x09html with: (HLContainer with: (HLHorizontalSplitter\x0a \x09with: (HLVerticalSplitter \x0a with: self variablesWidget\x0a with: self displayWidget)\x0a with: self codeWidget)).\x0a\x09\x0a\x09self variablesWidget focus",
messageSends: ["with:", "with:with:", "variablesWidget", "displayWidget", "codeWidget", "focus"],
referencedClasses: ["HLVerticalSplitter", "HLHorizontalSplitter", "HLContainer"]
}),
smalltalk.HLInspector);
smalltalk.HLInspector.klass.iVarNames = ['inspectors'];
smalltalk.addMethod(
smalltalk.method({
selector: "canBeOpenAsTab",
category: 'testing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return false;
}, function($ctx1) {$ctx1.fill(self,"canBeOpenAsTab",{},smalltalk.HLInspector.klass)})},
args: [],
source: "canBeOpenAsTab\x0a\x09^ false",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspector.klass);
smalltalk.addMethod(
smalltalk.method({
selector: "initialize",
category: 'initialization',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
smalltalk.HLInspector.klass.superclass.fn.prototype._initialize.apply(_st(self), []);
self._watchChanges();
return self}, function($ctx1) {$ctx1.fill(self,"initialize",{},smalltalk.HLInspector.klass)})},
args: [],
source: "initialize\x0a\x09super initialize.\x0a\x09self watchChanges",
messageSends: ["initialize", "watchChanges"],
referencedClasses: []
}),
smalltalk.HLInspector.klass);
smalltalk.addMethod(
smalltalk.method({
selector: "inspect:",
category: 'actions',
fn: function (anObject){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=self._new();
_st($1)._inspect_(anObject);
$2=_st($1)._openAsTab();
return self}, function($ctx1) {$ctx1.fill(self,"inspect:",{anObject:anObject},smalltalk.HLInspector.klass)})},
args: ["anObject"],
source: "inspect: anObject\x0a\x09self new\x0a\x09\x09inspect: anObject;\x0a\x09\x09openAsTab",
messageSends: ["inspect:", "new", "openAsTab"],
referencedClasses: []
}),
smalltalk.HLInspector.klass);
smalltalk.addMethod(
smalltalk.method({
selector: "inspectors",
category: 'accessing',
fn: function (){
var self=this;
function $OrderedCollection(){return smalltalk.OrderedCollection||(typeof OrderedCollection=="undefined"?nil:OrderedCollection)}
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@inspectors"];
if(($receiver = $2) == nil || $receiver == undefined){
self["@inspectors"]=_st($OrderedCollection())._new();
$1=self["@inspectors"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"inspectors",{},smalltalk.HLInspector.klass)})},
args: [],
source: "inspectors\x0a\x09^ inspectors ifNil: [ inspectors := OrderedCollection new ]",
messageSends: ["ifNil:", "new"],
referencedClasses: ["OrderedCollection"]
}),
smalltalk.HLInspector.klass);
smalltalk.addMethod(
smalltalk.method({
selector: "register:",
category: 'registration',
fn: function (anInspector){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._inspectors())._add_(anInspector);
return self}, function($ctx1) {$ctx1.fill(self,"register:",{anInspector:anInspector},smalltalk.HLInspector.klass)})},
args: ["anInspector"],
source: "register: anInspector\x0a\x09self inspectors add: anInspector",
messageSends: ["add:", "inspectors"],
referencedClasses: []
}),
smalltalk.HLInspector.klass);
smalltalk.addMethod(
smalltalk.method({
selector: "tabClass",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return "inspector";
}, function($ctx1) {$ctx1.fill(self,"tabClass",{},smalltalk.HLInspector.klass)})},
args: [],
source: "tabClass\x0a\x09^ 'inspector'",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspector.klass);
smalltalk.addMethod(
smalltalk.method({
selector: "tabLabel",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return "Inspector";
}, function($ctx1) {$ctx1.fill(self,"tabLabel",{},smalltalk.HLInspector.klass)})},
args: [],
source: "tabLabel\x0a\x09^ 'Inspector'",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspector.klass);
smalltalk.addMethod(
smalltalk.method({
selector: "tabPriority",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return (10);
}, function($ctx1) {$ctx1.fill(self,"tabPriority",{},smalltalk.HLInspector.klass)})},
args: [],
source: "tabPriority\x0a\x09^ 10",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLInspector.klass);
smalltalk.addMethod(
smalltalk.method({
selector: "unregister:",
category: 'registration',
fn: function (anInspector){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._inspectors())._remove_(anInspector);
return self}, function($ctx1) {$ctx1.fill(self,"unregister:",{anInspector:anInspector},smalltalk.HLInspector.klass)})},
args: ["anInspector"],
source: "unregister: anInspector\x0a\x09self inspectors remove: anInspector",
messageSends: ["remove:", "inspectors"],
referencedClasses: []
}),
smalltalk.HLInspector.klass);
smalltalk.addMethod(
smalltalk.method({
selector: "watchChanges",
category: 'initialization',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st((function(){
return smalltalk.withContext(function($ctx2) {
return _st(self._inspectors())._do_((function(each){
return smalltalk.withContext(function($ctx3) {
return _st(each)._refresh();
}, function($ctx3) {$ctx3.fillBlock({each:each},$ctx2)})}));
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}))._valueWithInterval_((500));
return self}, function($ctx1) {$ctx1.fill(self,"watchChanges",{},smalltalk.HLInspector.klass)})},
args: [],
source: "watchChanges\x0a\x09[ self inspectors do: [ :each | each refresh ] ]\x0a\x09\x09valueWithInterval: 500",
messageSends: ["valueWithInterval:", "do:", "refresh", "inspectors"],
referencedClasses: []
}),
smalltalk.HLInspector.klass);
|
class MVVM {
constructor(opt) {
this.$el = opt.el;
this.$data = opt.data;
this.init();
}
init() {
if (this.$el) {
// 数据劫持
new Observer(this.$data);
// 数据代理
proxyData(this, this.$data);
// 模版编译
new Compile(this.$el, this);
}
}
}
|
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
module('Integration | Component | range-slider', function(hooks) {
setupRenderingTest(hooks);
test('it renders', async function(assert) {
assert.expect(1);
await render(hbs`{{range-slider start=20}}`);
assert.dom('.noUi-base', this.element).exists();
});
});
|
module.exports = function (wallaby) {
return {
files: [
{pattern: 'node_modules/chai/chai.js', instrument: false},
'src/**/*.js'
],
tests: [
'test/**/*.js'
],
testFramework: 'mocha',
compilers: {
'**/*.js': wallaby.compilers.babel()
},
env: {
type: 'node'
}
};
};
|
import {Page, NavController, NavParams} from 'ionic-angular';
@Page({
templateUrl: 'build/pages/bicicleteria-details/bicicleteria-details.html'
})
export class BicicleteriaDetailsPage {
static get parameters() {
return [[NavController], [NavParams]];
}
constructor(nav, navParams, mostrarHorario) {
//inicialmente el horario esta oculto
var mostrarHorario = false;
this.mostrarHorario = mostrarHorario;
this.nav = nav;
// If we navigated to this page, we will have an item available as a nav param
this.selectedItem = navParams.get('item');
this.tabBarElement = document.querySelector('#tabs ion-tabbar-section');
}
onPageDidEnter() {
this.tabBarElement.style.display = 'none';
}
onPageWillLeave() {
this.tabBarElement.style.display = 'block';
}
toggleHorario(){
this.mostrarHorario = (this.mostrarHorario) ? false : true;
}
}
|
module.exports = (function () {
var fs = require("fs");
var path = require("path");
var stream = require("stream");
var gutil = require("gulp-util");
var Project = require("./project");
var PluginError = gutil.PluginError;
var Compiler = require("./compiler");
var normalizePath = require("normalize-path");
var PLUGIN_NAME = "gulp-typescript-closure-compiler";
function CompilationStream(compilationOptions, pluginOptions) {
stream.Transform.call(this, { objectMode: true });
this.fileList_ = [];
pluginOptions = pluginOptions || {};
this.compilationOptions = compilationOptions;
this.logger_ = pluginOptions.logger || gutil.log;
this.PLUGIN_NAME_ = pluginOptions.pluginName || PLUGIN_NAME;
if (compilationOptions instanceof Project) {
var project = compilationOptions;
this.compilationOptions = { project: compilationOptions.path };
compilationOptions = compilationOptions.compilerOptions;
if (!project.isValid()) {
this.emit("error", new PluginError(this.PLUGIN_NAME_, "Compilation error: \n" + project.error));
}
}
else {
this.compilationOptions = compilationOptions;
this.compilationOptions.entry = tryNormalizePath(this.compilationOptions.entry);
}
if (this.compilationOptions.externs) {
this.externs = this.compilationOptions.externs.map(function (extern) { return tryNormalizePath(extern); });
}
this.externsOutFile = tryNormalizePath(this.compilationOptions.externsOutFile);
this.outFile = tryNormalizePath(compilationOptions.outFile || compilationOptions.out);
}
CompilationStream.prototype = Object.create(stream.Transform.prototype);
CompilationStream.prototype._transform = function (file, enc, cb) {
if (file.isNull()) {
cb();
return;
}
if (file.isStream()) {
this.emit("error", new PluginError(this.PLUGIN_NAME_, "Streaming not supported"));
cb();
return;
}
this.fileList_.push(file);
cb();
};
CompilationStream.prototype._flush = function (cb) {
var inputFiles, jsonFiles, logger = this.logger_.warn ? this.logger_.warn : this.logger_;
if (this.fileList_.length > 0) {
jsonFiles = this.fileList_;
}
if (!this.compilationOptions.project) {
inputFiles = jsonFiles;
}
var stdOutData = "", stdErrData = "";
var compiler = new Compiler(this.compilationOptions, inputFiles, this.externs);
var compilerProcess = compiler.run();
compilerProcess.stdout.on("data", function (data) {
stdOutData += data;
});
compilerProcess.stderr.on("data", function (data) {
stdErrData += data;
});
compilerProcess.on("close", (function (code) {
var me = this;
var buildFile = function (file) {
var filePath;
if (!this.outFile && this.compilationOptions.outDir) {
filePath = path.resolve(this.compilationOptions.outDir, path.basename(file.path));
}
else {
filePath = file.path;
}
filePath = filePath.replace(path.extname(file.path), ".js");
if (fs.existsSync(filePath)) {
this.push(new gutil.File({
path: filePath,
contents: new Buffer(fs.readFileSync(filePath, "utf8"))
}));
}
}.bind(this);
if (code !== 0) {
if (stdErrData) {
this.emit("error", new PluginError(this.PLUGIN_NAME_, "Compilation error: " + stdErrData));
}
else if (stdOutData) {
logger(gutil.colors.yellow(this.PLUGIN_NAME_) + " Compilation error:\n" + stdOutData.trim());
}
return cb();
}
if (stdOutData.trim().length > 0) {
logger(gutil.colors.green(this.PLUGIN_NAME_) + ":\n" + stdOutData.trim());
if (!this.outFile) {
this.fileList_.forEach(buildFile);
}
else {
buildFile({ path: this.outFile });
}
if (this.externsOutFile && this.externsOutFile.length) {
if (!this.externsOutFile) {
this.externs.map(function (file) { return { path : file.replace(".d", "") }; }).forEach(buildFile);
}
else {
buildFile({ path: this.externsOutFile });
}
}
}
cb();
}).bind(this));
compilerProcess.on("error", (function (err) {
this.emit("error", new PluginError(this.PLUGIN_NAME_, "Process spawn error. Is tscc in the path?\n" + err.message));
cb();
}).bind(this));
compilerProcess.stdin.on("error", (function (err) {
this.emit("Error", new PluginError(this.PLUGIN_NAME_, "Error writing to stdin of the compiler.\n" + err.message));
cb();
}).bind(this));
var stdInStream = new stream.Readable({ read: function () { } });
stdInStream.pipe(compilerProcess.stdin);
};
function tryNormalizePath(filePath) {
if (filePath && !path.isAbsolute(filePath)) {
return path.resolve(process.cwd(), filePath);
}
return filePath;
}
function compile(compilationOptions, pluginOptions) {
return new CompilationStream(compilationOptions, pluginOptions);
};
compile.createProject = function (path) {
return new Project(path);
};
return compile;
})();
|
/**
* @ngdoc function
* @name angfirePlaygroundApp.directive:ngHideAuth
* @description
* # ngHideAuthDirective
* A directive that shows elements only when user is logged out. It also waits for Auth
* to be initialized so there is no initial flashing of incorrect state.
*/
angular.module('angfirePlaygroundApp')
.directive('ngHideAuth', ['Auth', '$timeout', function (Auth, $timeout) {
'use strict';
return {
restrict: 'A',
link: function(scope, el) {
el.addClass('ng-cloak'); // hide until we process it
function update() {
// sometimes if ngCloak exists on same element, they argue, so make sure that
// this one always runs last for reliability
$timeout(function () {
el.toggleClass('ng-cloak', !!Auth.$getAuth());
}, 0);
}
Auth.$onAuth(update);
update();
}
};
}]);
|
const chalk = require('chalk');
const _ = require('lodash');
const APP = require('./text/app.json');
module.exports = {
info: function () {
const log = createLog(arguments);
console.log(chalk.green.apply(null, log));
},
error: function () {
const log = createLog(arguments);
console.log(chalk.red.apply(null, log));
},
hint: function () {
const log = createLog(arguments);
console.log(chalk.yellow.apply(null, log));
}
};
const createLog = function (args) {
const text = _.toArray(args);
text.unshift(APP.NAME_CONSOLE);
return text;
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:d44ca40bafc8724cc111251e6438b81115f10085dde856c67a7c95f3b773c96a
size 915
|
describe('Rendering content to the page', function(){
it('should render the template to the view', function(){
loadFixtures('complete_pagination_dom.html');
var $canvas = $('.pagination_canvas');
var template = $('.pagination_container').data('template');
var response = {status: 'success',
data: [{"author":"Louie Mancini","comment":"here is a comment"},
{"author":"Robert Duval","comment":"The Godfather was the best movie ever"}]
}
ajaxPagination.buildDomElements($canvas, template, response);
expect($('.comment').length).toEqual(2);
});
});
|
var errorPrefix = 'Model#set(key[, value][, options][, cb]): ';
module.exports = function (Promise, utils, errors) {
var IllegalArgumentError = errors.IllegalArgumentError;
/**
* @doc method
* @id Model.instance_methods:set
* @name set
* @description
* Set (asynchronously) the given values on this instance.
*
* ## Signature:
* ```js
* Model#set(key[, value][, options][, cb])
* ```
*
* ## Examples:
*
* ### Promise-style:
* ```js
* var contact = new Contact({
* address: {
* city: 'New York'
* }
* });
*
* contact.set({
* firstName: 'John',
* lastName: 5
* }, { validate: true }).then(function (contact) {
* // Do something with contact
* })
* .catch(reheat.support.IllegalArgumentError, function (err) {
* res.send(400, err.errors);
* })
* .catch(reheat.support.ValidationError, function (err) {
* err.errors; // { lastName: { errors: ['type'] } }
* res.send(400, err.errors);
* })
* .error(function (err) {
* res.send(500, err.message);
* });
* ```
*
* ### Node-style:
* ```js
* var contact = new Contact({
* address: {
* city: 'New York'
* }
* });
*
* contact.set({
* firstName: 'John',
* lastName: 5
* }, { validate: true }, function (err, contact) {
* err; // { lastName: { errors: ['type'] } }
*
* contact.set('email', 'john.anderson@gmail.com', function (err, contact) {
* contact.get('email'); // 'john.anderson@gmail.com'
*
* contact.set({ lastName: 'Anderson' }, function (err, contact) {
* contact.get('lastName'); // 'Anderson'
*
* contact.toJSON(); // {
* // email: 'john.anderson@gmail.com',
* // lastName: 'Anderson'
* // address: {
* // city: 'New York'
* // }
* // }
* });
* });
* });
* ```
*
* ## Throws/Rejects with:
*
* - `{ValidationError}`
* - `{IllegalArgumentError}`
* - `{UnhandledError}`
*
* @param {string|object} key If a string, the key to be set to `value`. Supports nested keys, e.g. `"address.state"`.
* If an object, the object will be merged into this instance's attributes.
* @param {*} [value] The value to set. Used only if `key` is a string.
* @param {boolean|object=} options Optional configuration. May be set to `true` as shorthand for
* `{ validate: true }`. Properties:
*
* - `{boolean=false}` - `validate` - If `true` and the Model of this instance has a schema defined, ensure no schema
* validation errors occur with the new attribute(s) before setting, otherwise abort with the
* validation error.
*
* @param {function=} cb Optional callback function for Node-style usage. Signature: `cb(err, instance)`. Arguments:
*
* - `{ValidationError|UnhandledError}` - `err` - `null` if no error occurs. `ValidationError` if a validation error
* occurs and `UnhandledError` for any other error.
* - `{object}` - `instance` - If no error occurs, a reference to the instance on which
* `set(key[, value][, options][, cb])` was called.
* @returns {Promise} Promise.
*/
function set(key, value, options, cb) {
var _this = this;
// Check pre-conditions
if (utils.isFunction(value)) {
cb = value;
options = {};
} else if (utils.isFunction(options)) {
cb = options;
if (utils.isObject(key)) {
options = value;
} else {
options = {};
}
}
options = options ? (options === true ? { validate: true } : options) : {};
if (cb && !utils.isFunction(cb)) {
throw new IllegalArgumentError(errorPrefix + 'cb: Must be a function!', { actual: typeof cb, expected: 'function' });
}
return Promise.resolve().then(function sanitize() {
if (!utils.isObject(options)) {
throw new IllegalArgumentError(errorPrefix + 'options: Must be an object', { actual: typeof options, expected: 'object' });
} else if (!utils.isObject(key) && !utils.isString(key)) {
throw new IllegalArgumentError(errorPrefix + 'key: Must be a string or an object!', { actual: typeof key, expected: 'string|object' });
}
if (options.validate && _this.constructor.schema) {
var clone = utils.clone(_this.attributes),
deferred = Promise.defer();
if (utils.isObject(key)) {
utils.deepMixIn(clone, key);
} else {
utils.set(clone, key, value);
}
_this.constructor.schema.validate(clone, function (err) {
// Handle uncaught errors
if (err) {
_this.validationError = new errors.ValidationError(errorPrefix + 'key/value: Validation failed!', err);
throw _this.validationError;
} else {
if (utils.isObject(key)) {
utils.deepMixIn(_this.attributes, key);
} else {
utils.set(_this.attributes, key, value);
}
deferred.resolve(_this);
}
});
return deferred.promise;
} else {
if (utils.isObject(key)) {
utils.deepMixIn(_this.attributes, key);
} else {
utils.set(_this.attributes, key, value);
}
return _this;
}
}).nodeify(cb);
}
return set;
};
|
/** @jsxRuntime classic */
<font-face />;
|
export default {
el: {
datepicker: {
now: 'Sekarang',
today: 'Hari ini',
cancel: 'Batal',
clear: 'Kosongkan',
confirm: 'YA',
selectDate: 'Pilih tanggal',
selectTime: 'Pilih waktu',
startDate: 'Tanggal Mulai',
startTime: 'Waktu Mulai',
endDate: 'Tanggal Selesai',
endTime: 'Waktu Selesai',
year: 'Tahun',
month1: 'Januari',
month2: 'Februari',
month3: 'Maret',
month4: 'April',
month5: 'Mei',
month6: 'Juni',
month7: 'Juli',
month8: 'Agustus',
month9: 'September',
month10: 'Oktober',
month11: 'November',
month12: 'Desember',
// week: 'minggu',
weeks: {
sun: 'Min',
mon: 'Sen',
tue: 'Sel',
wed: 'Rab',
thu: 'Kam',
fri: 'Jum',
sat: 'Sab'
},
months: {
jan: 'Jan',
feb: 'Feb',
mar: 'Mar',
apr: 'Apr',
may: 'Mei',
jun: 'Jun',
jul: 'Jul',
aug: 'Agu',
sep: 'Sep',
oct: 'Okt',
nov: 'Nov',
dec: 'Des'
}
},
select: {
loading: 'Memuat',
noMatch: 'Tidak ada data yang cocok',
noData: 'Tidak ada data',
placeholder: 'Pilih'
},
cascader: {
noMatch: 'Tidak ada data yang cocok',
placeholder: 'Pilih'
},
pagination: {
goto: 'Pergi ke',
pagesize: '/page',
total: 'Total {total}',
pageClassifier: ''
},
messagebox: {
title: 'Pesan',
confirm: 'YA',
cancel: 'Batal',
error: 'Masukan ilegal'
},
upload: {
delete: 'Hapus',
preview: 'Pratinjau',
continue: 'Lanjutkan'
},
table: {
emptyText: 'Tidak Ada Data',
confirmFilter: 'Konfirmasi',
resetFilter: 'Atur Ulang',
clearFilter: 'Semua'
},
tree: {
emptyText: 'Tidak Ada Data'
}
}
};
|
"use strict";
var Mocha = require("mocha");
var path = require("path");
var fs = require("fs");
var _ = require("underscore");
var testsDir = path.resolve(__dirname, "tests");
function normalizeAdapter(adapter) {
if (!adapter.fulfilled) {
adapter.fulfilled = function (value) {
var tuple = adapter.pending();
tuple.fulfill(value);
return tuple.promise;
};
}
if (!adapter.rejected) {
adapter.rejected = function (reason) {
var tuple = adapter.pending();
tuple.reject(reason);
return tuple.promise;
};
}
}
module.exports = function (adapter, mochaOpts, cb) {
if (typeof mochaOpts === "function") {
cb = mochaOpts;
mochaOpts = {};
}
if (typeof cb !== "function") {
cb = function () { };
}
normalizeAdapter(adapter);
mochaOpts = _.defaults(mochaOpts, { reporter: "spec", timeout: 200, slow: Infinity });
fs.readdir(testsDir, function (err, testFileNames) {
if (err) {
cb(err);
return;
}
var mocha = new Mocha(mochaOpts);
testFileNames.forEach(function (testFileName) {
if (path.extname(testFileName) === ".js") {
var testFilePath = path.resolve(testsDir, testFileName);
mocha.addFile(testFilePath);
}
});
global.adapter = adapter;
mocha.run(function (failures) {
delete global.adapter;
if (failures > 0) {
var err = new Error("Test suite failed with " + failures + " failures.");
err.failures = failures;
cb(err);
} else {
cb(null);
}
});
});
};
module.exports.mocha = function (adapter) {
normalizeAdapter(adapter);
global.adapter = adapter;
var testFileNames = fs.readdirSync(testsDir);
testFileNames.forEach(function (testFileName) {
if (path.extname(testFileName) === ".js") {
|
photosApp.controller('loginPhotographerCtrl', ['$scope', '$state', '$filter', 'UserService',
function ($scope, $state, $filter, UserService) {
$scope.UserService = UserService ;
$scope.login = function () {
$scope.UserService.login($scope.email, $scope.password)
.then(function() {
$state.go("photographe.dashboard");
})
};
}]);
|
${namespace}.mapFunc=function () {
// see http://cookbook.mongodb.org/patterns/count_tags/
if (!this.tags) {
return;
}
for (index in this.tags) {
emit(this.tags[index], 1);
}
}
${namespace}.reduceFunc=function (previous, current) {
var count = 0;
for (index in current) {
count += current[index];
}
return count;
}
${namespace}.document=[
{
"title": "A blog post",
"author": "Kristina",
"content": "...",
"tags": [
"kkkkkkkkkkkkkkkkkk",
"Map/Reduce",
"Recipe"
]
},
{
"title": "A second blog post",
"author": "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn",
"content": "...",
"tags": [
"Map/Reduce"
]
}
]
|
import { dedupingMixin } from '../utils/mixin.js';
// Common implementation for mixin & behavior
function mutablePropertyChange(inst, property, value, old, mutableData) {
let isObject;
if (mutableData) {
isObject = (typeof value === 'object' && value !== null);
// Pull `old` for Objects from temp cache, but treat `null` as a primitive
if (isObject) {
old = inst.__dataTemp[property];
}
}
// Strict equality check, but return false for NaN===NaN
let shouldChange = (old !== value && (old === old || value === value));
// Objects are stored in temporary cache (cleared at end of
// turn), which is used for dirty-checking
if (isObject && shouldChange) {
inst.__dataTemp[property] = value;
}
return shouldChange;
}
export const MutableData = dedupingMixin(superClass => {
/**
* @polymer
* @mixinClass
* @implements {Polymer_MutableData}
*/
class MutableData extends superClass {
/**
* Overrides `Polymer.PropertyEffects` to provide option for skipping
* strict equality checking for Objects and Arrays.
*
* This method pulls the value to dirty check against from the `__dataTemp`
* cache (rather than the normal `__data` cache) for Objects. Since the temp
* cache is cleared at the end of a turn, this implementation allows
* side-effects of deep object changes to be processed by re-setting the
* same object (using the temp cache as an in-turn backstop to prevent
* cycles due to 2-way notification).
*
* @param {string} property Property name
* @param {*} value New property value
* @param {*} old Previous property value
* @return {boolean} Whether the property should be considered a change
* @protected
*/
_shouldPropertyChange(property, value, old) {
return mutablePropertyChange(this, property, value, old, true);
}
}
/** @type {boolean} */
MutableData.prototype.mutableData = false;
return MutableData;
});
export const OptionalMutableData = dedupingMixin(superClass => {
/**
* @mixinClass
* @polymer
* @implements {Polymer_OptionalMutableData}
*/
class OptionalMutableData extends superClass {
static get properties() {
return {
/**
* Instance-level flag for configuring the dirty-checking strategy
* for this element. When true, Objects and Arrays will skip dirty
* checking, otherwise strict equality checking will be used.
*/
mutableData: Boolean
};
}
/**
* Overrides `Polymer.PropertyEffects` to provide option for skipping
* strict equality checking for Objects and Arrays.
*
* When `this.mutableData` is true on this instance, this method
* pulls the value to dirty check against from the `__dataTemp` cache
* (rather than the normal `__data` cache) for Objects. Since the temp
* cache is cleared at the end of a turn, this implementation allows
* side-effects of deep object changes to be processed by re-setting the
* same object (using the temp cache as an in-turn backstop to prevent
* cycles due to 2-way notification).
*
* @param {string} property Property name
* @param {*} value New property value
* @param {*} old Previous property value
* @return {boolean} Whether the property should be considered a change
* @protected
*/
_shouldPropertyChange(property, value, old) {
return mutablePropertyChange(this, property, value, old, this.mutableData);
}
}
return OptionalMutableData;
});
// Export for use by legacy behavior
MutableData._mutablePropertyChange = mutablePropertyChange;
|
import Immutable from "immutable";
import Constants from "./Events/Constants.json";
import Predicates from "./Predicates";
function getFiltered (todos, filter) {
switch (filter) {
case Constants.FILTER_ACTIVE:
return todos.filterNot(Predicates.completed);
case Constants.FILTER_COMPLETED:
return todos.filter(Predicates.completed);
default:
return todos;
}
}
export default function (previousEntry) {
const state = previousEntry;
const allTodos = state.get("todos");
return Immutable.Map({
"filter": state.get("filter"),
"todos": Immutable.Map({
"all": allTodos,
"filtered": getFiltered(allTodos, state.get("filter")),
"completed": getFiltered(allTodos, Constants.FILTER_COMPLETED)
})
});
}
|
var s = require('./support');
var t = s.t;
describe('maroon.loadConfigs', function() {
it('should load configs from given directory', function() {
var maroon = s.getMaroon();
maroon.loadConfigs(__dirname + '/fixtures/config');
t.ok(maroon.conf.get('database'), 'load database config');
t.equal(maroon.conf.get('database').driver, 'memory');
t.ok(maroon.conf.get('foo'), 'load extra config');
t.equal(maroon.conf.get('foo'), 'bar');
t.notOk(maroon.conf.get('hello'));
});
});
|
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['2267',"Tlece.Recruitment.Models.RecruitmentPlanning Namespace","topic_0000000000000692.html"],['2333',"ApplicationDetailDto Class","topic_00000000000007D9.html"],['2334',"Properties","topic_00000000000007D9_props--.html"],['2343',"RemarkVideos Property","topic_00000000000007E2.html"]];
|
import {
defaultAction,
} from '../actions';
import {
DEFAULT_ACTION,
} from '../constants';
describe('ProfilePage actions', () => {
describe('Default Action', () => {
it('has a type of DEFAULT_ACTION', () => {
const expected = {
type: DEFAULT_ACTION,
};
expect(defaultAction()).toEqual(expected);
});
});
});
|
import { createSelector } from 'reselect';
/**
* Direct selector to the accountBox state domain
*/
const selectAccountBoxDomain = () => state => state.get('accountBox');
/**
* Other specific selectors
*/
/**
* Default selector used by AccountBox
*/
const selectAccountBox = () => createSelector(
selectAccountBoxDomain(),
(substate) => substate
);
export default selectAccountBox;
export {
selectAccountBoxDomain,
};
|
const Rebase = require('../../../src/rebase');
var React = require('react');
var ReactDOM = require('react-dom');
var firebase = require('firebase');
var database = require('firebase/database');
var invalidEndpoints = require('../../fixtures/invalidEndpoints');
var dummyObjData = require('../../fixtures/dummyObjData');
var invalidOptions = require('../../fixtures/invalidOptions');
var firebaseConfig = require('../../fixtures/config');
describe('listenTo()', function() {
var base;
var testEndpoint = 'test/listenTo';
var testApp;
var ref;
var app;
beforeAll(() => {
testApp = firebase.initializeApp(firebaseConfig, 'DB_CHECK');
ref = testApp.database().ref();
var mountNode = document.createElement('div');
mountNode.setAttribute('id', 'mount');
document.body.appendChild(mountNode);
});
afterAll(done => {
testApp.delete().then(done);
});
beforeEach(() => {
app = firebase.initializeApp(firebaseConfig);
var db = firebase.database(app);
base = Rebase.createClass(db);
});
afterEach(done => {
ReactDOM.unmountComponentAtNode(document.body);
firebase.Promise
.all([app.delete(), ref.child(testEndpoint).set(null)])
.then(done);
});
it('listenTo() returns a valid ref', function() {
var ref = base.listenTo(testEndpoint, {
context: this,
then(data) {}
});
expect(ref.id).toEqual(jasmine.any(Number));
});
it('listenTo() throws an error given a invalid endpoint', function() {
invalidEndpoints.forEach(endpoint => {
try {
base.listenTo(endpoint, {
context: this,
then(data) {}
});
} catch (err) {
expect(err.code).toEqual('INVALID_ENDPOINT');
}
});
});
it('listenTo() throws an error given an invalid options object', function() {
invalidOptions.forEach(option => {
try {
base.listenTo(testEndpoint, option);
} catch (err) {
expect(err.code).toEqual('INVALID_OPTIONS');
}
});
});
describe('Async tests', function() {
it("listenTo()'s .then method gets invoked when the Firebase endpoint changes", done => {
var didUpdate = false;
base.listenTo(testEndpoint, {
context: {},
then(data) {
if (didUpdate === true) {
expect(data).toEqual(dummyObjData);
done();
}
}
});
ref
.child(testEndpoint)
.set(dummyObjData)
.then(() => {
didUpdate = true;
});
});
it("listenTo's .then method gets invoked when the Firebase endpoint changes and correctly updates the component's state", done => {
var didUpdate = false;
class TestComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentWillMount() {
this.ref = base.listenTo(testEndpoint, {
context: this,
then(data) {
this.setState({ data });
}
});
}
componentDidMount() {
ref
.child(testEndpoint)
.set(dummyObjData)
.then(() => {
didUpdate = true;
});
}
componentDidUpdate() {
if (didUpdate) {
expect(this.state.data).toEqual(dummyObjData);
done();
}
}
render() {
return (
<div>
Name: {this.state.name} <br />
Age: {this.state.age}
</div>
);
}
}
ReactDOM.render(<TestComponent />, document.getElementById('mount'));
});
it("listenTo's .onFailure method gets invoked in the component context with error if permissions do not allow read", done => {
var didUpdate = false;
class TestComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentWillMount() {
this.ref = base.listenTo('/readFail', {
context: this,
onFailure(err) {
expect(err).not.toBeUndefined();
done();
},
then(data) {
done.fail(
'Database permissions should not allow read from this location'
);
}
});
}
render() {
return (
<div>
Name: {this.state.name} <br />
Age: {this.state.age}
</div>
);
}
}
ReactDOM.render(<TestComponent />, document.getElementById('mount'));
});
it('listenTo should return the data as an array if the asArray property of options is set to true', done => {
var didUpdate = false;
class TestComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentWillMount() {
this.ref = base.listenTo(testEndpoint, {
context: this,
then(data) {
this.setState({ data });
},
asArray: true
});
}
componentDidMount() {
ref
.child(testEndpoint)
.set(dummyObjData)
.then(() => {
didUpdate = true;
});
}
componentDidUpdate() {
if (didUpdate) {
expect(this.state.data.indexOf(25)).not.toBe(-1);
expect(this.state.data.indexOf('Tyler McGinnis')).not.toBe(-1);
done();
}
}
render() {
return (
<div>
Name: {this.state.name} <br />
Age: {this.state.age}
</div>
);
}
}
ReactDOM.render(<TestComponent />, document.getElementById('mount'));
});
it('listenTo should allow multiple components to listen to changes on the same endpoint', done => {
//set up mount points
var div1 = document.createElement('div');
div1.setAttribute('id', 'div1');
var div2 = document.createElement('div');
div2.setAttribute('id', 'div2');
document.body.appendChild(div1);
document.body.appendChild(div2);
function cleanUp(done) {
ReactDOM.unmountComponentAtNode(document.getElementById('div1'));
ReactDOM.unmountComponentAtNode(document.getElementById('div2'));
done();
}
var component1Updated = false;
var component2Updated = false;
class TestComponent1 extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount() {
this.ref = base.listenTo(testEndpoint, {
context: this,
then(data) {
this.setState({ data });
},
asArray: true
});
}
componentDidUpdate() {
expect(this.state.data.indexOf(25)).not.toBe(-1);
expect(this.state.data.indexOf('Tyler McGinnis')).not.toBe(-1);
component1Updated = true;
if (component1Updated && component2Updated) {
cleanUp(done);
}
}
render() {
return (
<div>
Name: {this.state.name} <br />
Age: {this.state.age}
</div>
);
}
}
class TestComponent2 extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentWillMount() {
this.ref = base.listenTo(testEndpoint, {
context: this,
then(data) {
this.setState({ data });
},
asArray: true
});
}
componentDidMount() {
ref.child(testEndpoint).set(dummyObjData);
}
componentDidUpdate() {
expect(this.state.data.indexOf(25)).not.toBe(-1);
expect(this.state.data.indexOf('Tyler McGinnis')).not.toBe(-1);
component2Updated = true;
if (component1Updated && component2Updated) {
cleanUp(done);
}
}
render() {
return (
<div>
Name: {this.state.name} <br />
Age: {this.state.age}
</div>
);
}
}
ReactDOM.render(<TestComponent1 />, document.getElementById('div1'));
ReactDOM.render(<TestComponent2 />, document.getElementById('div2'));
});
});
it('listeners are removed when component unmounts', done => {
spyOn(console, 'error');
var componentWillUnmountSpy = jasmine.createSpy('componentWillMountSpy');
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentWillMount() {
base.listenTo(testEndpoint, {
context: this,
then(data) {
this.setState({ data });
},
asArray: true
});
base.listenTo(`${testEndpoint}/secondListener`, {
context: this,
then(data) {
this.setState({ data });
},
asArray: true
});
base.listenTo(`${testEndpoint}/thirdListener`, {
context: this,
then(data) {
this.setState({ data });
},
asArray: true
});
}
componentWillUnmount() {
componentWillUnmountSpy('additional clean up performed');
}
render() {
return (
<div>
Name: {this.state.name} <br />
Age: {this.state.age}
</div>
);
}
}
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
showChild: true
};
}
setData(cb) {
Promise.all([
base.initializedApp
.database()
.ref()
.child(testEndpoint)
.set(dummyObjData),
base.initializedApp
.database()
.ref()
.child(`${testEndpoint}/secondListener`)
.set(dummyObjData),
base.initializedApp
.database()
.ref()
.child(`${testEndpoint}/thirdListener`)
.set(dummyObjData)
]).then(() => {
setTimeout(cb, 500);
});
}
componentDidMount() {
this.setState(
{
showChild: false
},
() => {
this.setData(() => {
expect(console.error).not.toHaveBeenCalled();
expect(componentWillUnmountSpy).toHaveBeenCalledWith(
'additional clean up performed'
);
done();
});
}
);
}
render() {
return <div>{this.state.showChild ? <ChildComponent /> : null}</div>;
}
}
ReactDOM.render(<ParentComponent />, document.getElementById('mount'));
});
});
|
export { default } from 'dsember-core/components/items/detailed/item-metadatum-row';
|
// { "framework": "Vue" }
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports, __webpack_require__) {
var __vue_exports__, __vue_options__
var __vue_styles__ = []
/* styles */
__vue_styles__.push(__webpack_require__(70)
)
/* script */
__vue_exports__ = __webpack_require__(71)
/* template */
var __vue_template__ = __webpack_require__(72)
__vue_options__ = __vue_exports__ = __vue_exports__ || {}
if (
typeof __vue_exports__.default === "object" ||
typeof __vue_exports__.default === "function"
) {
if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")}
__vue_options__ = __vue_exports__ = __vue_exports__.default
}
if (typeof __vue_options__ === "function") {
__vue_options__ = __vue_options__.options
}
__vue_options__.__file = "/Users/zhengjiangrong/Desktop/ok/src/recycler.vue"
__vue_options__.render = __vue_template__.render
__vue_options__.staticRenderFns = __vue_template__.staticRenderFns
__vue_options__._scopeId = "data-v-f9296058"
__vue_options__.style = __vue_options__.style || {}
__vue_styles__.forEach(function (module) {
for (var name in module) {
__vue_options__.style[name] = module[name]
}
})
if (typeof __register_static_styles__ === "function") {
__register_static_styles__(__vue_options__._scopeId, __vue_styles__)
}
module.exports = __vue_exports__
module.exports.el = 'true'
new Vue(module.exports)
/***/ }),
/***/ 70:
/***/ (function(module, exports) {
module.exports = {
"page": {
"backgroundColor": "#EFEFEF"
},
"refresh": {
"height": 128,
"width": 750,
"flexDirection": "row",
"alignItems": "center",
"justifyContent": "center"
},
"refreshText": {
"color": "#888888",
"fontWeight": "bold"
},
"indicator": {
"color": "#888888",
"height": 40,
"width": 40,
"marginRight": 30
},
"absolute": {
"position": "absolute",
"top": 0,
"width": 750,
"height": 377
},
"banner": {
"height": 377,
"flexDirection": "row"
},
"bannerInfo": {
"width": 270,
"alignItems": "center",
"justifyContent": "center"
},
"avatar": {
"width": 148,
"height": 108,
"borderRadius": 54,
"borderWidth": 4,
"borderColor": "#FFFFFF",
"marginBottom": 14
},
"name": {
"fontWeight": "bold",
"fontSize": 32,
"color": "#ffffff",
"lineHeight": 32,
"textAlign": "center",
"marginBottom": 16
},
"titleWrap": {
"width": 100,
"height": 24,
"marginBottom": 10,
"backgroundColor": "rgba(255,255,255,0.8)",
"borderRadius": 12,
"justifyContent": "center",
"alignItems": "center"
},
"title": {
"fontSize": 20,
"color": "#000000"
},
"bannerPhotoWrap": {
"width": 449,
"height": 305,
"backgroundColor": "#FFFFFF",
"borderRadius": 12,
"marginTop": 35,
"padding": 12,
"flexDirection": "row",
"justifyContent": "space-between",
"flexWrap": "wrap"
},
"bannerPhoto": {
"width": 137,
"height": 137,
"marginBottom": 6
},
"stickyHeader": {
"position": "sticky"
},
"header2": {
"position": "sticky",
"height": 94,
"flexDirection": "row",
"paddingBottom": 6
},
"stickyWrapper": {
"flexDirection": "row",
"backgroundColor": "#00cc99",
"justifyContent": "center",
"alignItems": "center",
"flex": 1
},
"stickyTextImageWrapper": {
"flex": 1,
"justifyContent": "center",
"alignItems": "center",
"flexDirection": "row"
},
"stickyText": {
"color": "#FFFFFF",
"fontWeight": "bold",
"fontSize": 32,
"marginRight": 12
},
"stickyImage": {
"width": 64,
"height": 64,
"borderRadius": 32
},
"cell": {
"paddingTop": 6,
"paddingBottom": 6
},
"item": {
"backgroundColor": "#FFFFFF",
"alignItems": "center"
},
"itemName": {
"fontSize": 28,
"color": "#333333",
"lineHeight": 42,
"textAlign": "left",
"marginTop": 24
},
"itemPhoto": {
"marginTop": 18,
"width": 220,
"height": 220,
"marginBottom": 18
},
"itemDesc": {
"fontSize": 24,
"margin": 12,
"color": "#999999",
"lineHeight": 36,
"textAlign": "left"
},
"itemClickBehaviour": {
"fontSize": 36,
"color": "#00cc99",
"lineHeight": 36,
"textAlign": "center",
"marginTop": 6,
"marginLeft": 24,
"marginRight": 24,
"marginBottom": 30
},
"footer": {
"height": 94,
"justifyContent": "center",
"alignItems": "center",
"backgroundColor": "#00cc99"
},
"fixedItem": {
"position": "fixed",
"width": 78,
"height": 78,
"backgroundColor": "#00cc99",
"right": 32,
"bottom": 32,
"borderRadius": 39,
"alignItems": "center",
"justifyContent": "center"
},
"fixedText": {
"fontSize": 32,
"color": "#FFFFFF",
"lineHeight": 32
}
}
/***/ }),
/***/ 71:
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
exports.default = {
data: function data() {
var items = [{
src: 'https://gw.alicdn.com/tps/TB1Jl1CPFXXXXcJXXXXXXXXXXXX-370-370.jpg',
name: 'Thomas Carlyle',
desc: 'Genius only means hard-working all one\'s life',
behaviourName: 'Change width',
behaviour: 'changeColumnWidth'
}, {
src: 'https://gw.alicdn.com/tps/TB1Hv1JPFXXXXa3XXXXXXXXXXXX-370-370.jpg',
desc: 'The man who has made up his mind to win will never say "impossible "',
behaviourName: 'Change gap',
behaviour: 'changeColumnGap'
}, {
src: 'https://gw.alicdn.com/tps/TB1eNKuPFXXXXc_XpXXXXXXXXXX-370-370.jpg',
desc: 'There is no such thing as a great talent without great will - power',
behaviourName: 'Change count',
behaviour: 'changeColumnCount'
}, {
src: 'https://gw.alicdn.com/tps/TB1DCh8PFXXXXX7aXXXXXXXXXXX-370-370.jpg',
name: 'Addison',
desc: 'Cease to struggle and you cease to live',
behaviourName: 'Show scrollbar',
behaviour: 'showScrollbar'
}, {
src: 'https://gw.alicdn.com/tps/TB1ACygPFXXXXXwXVXXXXXXXXXX-370-370.jpg',
desc: 'A strong man will struggle with the storms of fate',
behaviourName: 'Listen appear',
behaviour: 'listenAppear'
}, {
src: 'https://gw.alicdn.com/tps/TB1IGShPFXXXXaqXVXXXXXXXXXX-370-370.jpg',
name: 'Ruskin',
desc: 'Living without an aim is like sailing without a compass',
behaviourName: 'Set scrollable',
behaviour: 'setScrollable'
}, {
src: 'https://gw.alicdn.com/tps/TB1xU93PFXXXXXHaXXXXXXXXXXX-240-240.jpg',
behaviourName: 'waterfall padding',
behaviour: 'setPadding'
}, {
src: 'https://gw.alicdn.com/tps/TB19hu0PFXXXXaXaXXXXXXXXXXX-240-240.jpg',
name: 'Balzac',
desc: 'There is no such thing as a great talent without great will - power',
behaviourName: 'listen scroll',
behaviour: 'listenScroll'
}, {
src: 'https://gw.alicdn.com/tps/TB1ux2vPFXXXXbkXXXXXXXXXXXX-240-240.jpg',
behaviourName: 'Remove cell',
behaviour: 'removeCell'
}, {
src: 'https://gw.alicdn.com/tps/TB1tCCWPFXXXXa7aXXXXXXXXXXX-240-240.jpg',
behaviourName: 'Move cell',
behaviour: 'moveCell'
}];
var repeatItems = [];
for (var i = 0; i < 3; i++) {
repeatItems.push.apply(repeatItems, items);
}
return {
padding: 0,
refreshing: false,
refreshText: '↓ pull to refresh...',
columnCount: 3,
columnGap: 12,
columnWidth: 'auto',
contentOffset: '0',
showHeader: true,
showScrollbar: false,
scrollable: true,
showStickyHeader: false,
appearImage: null,
disappearImage: null,
stickyHeaderType: 'none',
// fixedRect:'',
banner: {
photos: [{ src: 'https://gw.alicdn.com/tps/TB1JyaCPFXXXXc9XXXXXXXXXXXX-140-140.jpg' }, { src: 'https://gw.alicdn.com/tps/TB1MwSFPFXXXXbdXXXXXXXXXXXX-140-140.jpg' }, { src: 'https://gw.alicdn.com/tps/TB1U8avPFXXXXaDXpXXXXXXXXXX-140-140.jpg' }, { src: 'https://gw.alicdn.com/tps/TB17Xh8PFXXXXbkaXXXXXXXXXXX-140-140.jpg' }, { src: 'https://gw.alicdn.com/tps/TB1cTmLPFXXXXXRXXXXXXXXXXXX-140-140.jpg' }, { src: 'https://gw.alicdn.com/tps/TB1oCefPFXXXXbVXVXXXXXXXXXX-140-140.jpg' }]
},
items: repeatItems
};
},
created: function created() {
// let self = this
// setTimeout(()=>{
// weex.requireModule('dom').getComponentRect(this.$refs.fixed, result=>{
// const x = result.size.left
// const y = result.size.top
// const width = result.size.width
// const height = result.size.height
// self.fixedRect = `${x}|${y}|${width}|${height}`
// })
// }, 3000)
},
methods: {
recylerScroll: function recylerScroll(e) {
this.contentOffset = e.contentOffset.y;
},
loadmore: function loadmore(e) {
console.log('receive loadmore event');
// this.$refs.waterfall.resetLoadmore()
},
showOrRemoveHeader: function showOrRemoveHeader() {
this.showHeader = !this.showHeader;
},
onItemclick: function onItemclick(behaviour, index) {
console.log('click...' + behaviour + ' at index ' + index);
switch (behaviour) {
case 'changeColumnCount':
this.changeColumnCount();
break;
case 'changeColumnGap':
this.changeColumnGap();
break;
case 'changeColumnWidth':
this.changeColumnWidth();
break;
case 'showScrollbar':
this.showOrHideScrollbar();
break;
case 'listenAppear':
this.listenAppearAndDisappear();
break;
case 'setScrollable':
this.setScrollable();
break;
case 'setPadding':
this.setRecyclerPadding();
break;
case 'listenScroll':
this.listenScrollEvent();
break;
case 'removeCell':
this.removeCell(index);
break;
case 'moveCell':
this.moveCell(index);
break;
}
},
itemAppear: function itemAppear(src) {
this.appearImage = src;
},
itemDisappear: function itemDisappear(src) {
this.disappearImage = src;
},
changeColumnCount: function changeColumnCount() {
if (this.columnCount === 2) {
this.columnCount = 3;
} else {
this.columnCount = 2;
}
},
changeColumnGap: function changeColumnGap() {
if (this.columnGap === 12) {
this.columnGap = 'normal';
} else {
this.columnGap = 12;
}
},
changeColumnWidth: function changeColumnWidth() {
if (this.columnWidth === 'auto') {
this.columnWidth = 600;
} else {
this.columnWidth = 'auto';
}
},
showOrHideScrollbar: function showOrHideScrollbar() {
this.showScrollbar = !this.showScrollbar;
},
setScrollable: function setScrollable() {
this.scrollable = !this.scrollable;
},
listenAppearAndDisappear: function listenAppearAndDisappear() {
this.stickyHeaderType = this.stickyHeaderType === 'appear' ? 'none' : 'appear';
},
listenScrollEvent: function listenScrollEvent() {
this.stickyHeaderType = this.stickyHeaderType === 'scroll' ? 'none' : 'scroll';
},
scrollToNext: function scrollToNext() {
weex.requireModule('dom').scrollToElement(this.$refs.footer, {});
},
setRecyclerPadding: function setRecyclerPadding() {
this.padding = this.padding == 0 ? 12 : 0;
},
removeCell: function removeCell(index) {
this.items.splice(index, 1);
},
moveCell: function moveCell(index) {
if (index == 0) {
this.items.splice(this.items.length - 1, 0, this.items.splice(index, 1)[0]);
} else {
this.items.splice(0, 0, this.items.splice(index, 1)[0]);
}
},
onrefresh: function onrefresh(event) {
var _this = this;
this.refreshing = true;
this.refreshText = "loading...";
setTimeout(function () {
_this.refreshing = false;
_this.refreshText = '↓ pull to refresh...';
}, 2000);
},
onpullingdown: function onpullingdown(event) {
// console.log(`${event.pullingDistance}`)
if (event.pullingDistance < -64) {
this.refreshText = '↑ release to refresh...';
} else {
this.refreshText = '↓ pull to refresh...';
}
}
}
};
module.exports = exports['default'];
/***/ }),
/***/ 72:
/***/ (function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('waterfall', {
ref: "waterfall",
staticClass: ["page"],
style: {
padding: _vm.padding
},
attrs: {
"testId": "waterfall",
"columnWidth": _vm.columnWidth,
"columnCount": _vm.columnCount,
"columnGap": _vm.columnGap,
"showScrollbar": _vm.showScrollbar,
"scrollable": _vm.scrollable,
"loadmoreoffset": "3000"
},
on: {
"scroll": _vm.recylerScroll,
"loadmore": _vm.loadmore
}
}, [(_vm.showHeader) ? _c('header', {
ref: "header",
staticClass: ["header"],
attrs: {
"testId": "header1"
}
}, [_c('div', {
staticClass: ["banner"]
}, [_c('image', {
staticClass: ["absolute"],
attrs: {
"src": "https://gw.alicdn.com/tps/TB1ESN1PFXXXXX1apXXXXXXXXXX-1000-600.jpg",
"resize": "cover"
}
}), _c('div', {
staticClass: ["bannerInfo"]
}, [_c('image', {
staticClass: ["avatar"],
attrs: {
"src": "https://gw.alicdn.com/tps/TB1EP9bPFXXXXbpXVXXXXXXXXXX-150-110.jpg",
"resize": "cover"
}
}), _c('text', {
staticClass: ["name"]
}, [_vm._v("Adam Cat")]), _c('div', {
staticClass: ["titleWrap"]
}, [_c('text', {
staticClass: ["title"]
}, [_vm._v("Genius")])])]), _c('div', {
staticClass: ["bannerPhotoWrap"]
}, _vm._l((_vm.banner.photos), function(photo) {
return _c('image', {
staticClass: ["bannerPhoto"],
attrs: {
"src": photo.src
}
})
}))])]) : _vm._e(), _c('header', {
staticClass: ["stickyHeader"]
}, [_c('div', {
staticClass: ["header2"],
attrs: {
"testId": "header2"
}
}, [(_vm.stickyHeaderType === 'none') ? _c('div', {
staticClass: ["stickyWrapper"]
}, [_c('text', {
staticClass: ["stickyText"],
attrs: {
"testId": "stickyText1"
}
}, [_vm._v("Sticky Header")])]) : _vm._e(), (_vm.stickyHeaderType === 'appear') ? _c('div', {
staticClass: ["stickyWrapper"]
}, [_c('div', {
staticClass: ["stickyTextImageWrapper"]
}, [_c('text', {
staticClass: ["stickyText"]
}, [_vm._v("Last Appear:")]), _c('image', {
staticClass: ["stickyImage"],
attrs: {
"src": _vm.appearImage
}
})]), _c('div', {
staticClass: ["stickyTextImageWrapper"]
}, [_c('text', {
staticClass: ["stickyText"]
}, [_vm._v("Last Disappear:")]), _c('image', {
staticClass: ["stickyImage"],
attrs: {
"src": _vm.disappearImage
}
})])]) : _vm._e(), (_vm.stickyHeaderType === 'scroll') ? _c('div', {
staticClass: ["stickyWrapper"]
}, [_c('text', {
staticClass: ["stickyText"]
}, [_vm._v("Content Offset:" + _vm._s(_vm.contentOffset))])]) : _vm._e()])]), _vm._l((_vm.items), function(item, index) {
return _c('cell', {
key: item.src,
ref: "index",
refInFor: true,
staticClass: ["cell"],
appendAsTree: true,
attrs: {
"testId": 'cell' + index,
"append": "tree"
}
}, [_c('div', {
staticClass: ["item"],
on: {
"click": function($event) {
_vm.onItemclick(item.behaviour, index)
},
"appear": function($event) {
_vm.itemAppear(item.src)
},
"disappear": function($event) {
_vm.itemDisappear(item.src)
}
}
}, [(item.name) ? _c('text', {
staticClass: ["itemName"]
}, [_vm._v(_vm._s(item.name))]) : _vm._e(), _c('image', {
staticClass: ["itemPhoto"],
attrs: {
"src": item.src
}
}), (item.desc) ? _c('text', {
staticClass: ["itemDesc"]
}, [_vm._v(_vm._s(item.desc))]) : _vm._e(), (item.behaviourName) ? _c('text', {
staticClass: ["itemClickBehaviour"]
}, [_vm._v(" " + _vm._s(item.behaviourName))]) : _vm._e()])])
}), _c('header', [_c('div', {
ref: "footer",
staticClass: ["footer"],
attrs: {
"testId": "footer1"
}
}, [_c('text', {
staticClass: ["stickyText"]
}, [_vm._v("Footer")])])]), _c('div', {
ref: "fixed",
staticClass: ["fixedItem"],
attrs: {
"testId": "fixed1"
},
on: {
"click": _vm.scrollToNext
}
}, [_c('text', {
staticClass: ["fixedText"]
}, [_vm._v("bot")])])], 2)
},staticRenderFns: []}
module.exports.render._withStripped = true
/***/ })
/******/ });
|
angular.module('phonegular.services')
.run(['popupManager', function(popupManager) {
if ('cordova' in window) {
// Replaces only the alert function. Use popupManager for the other implementation
/**
* @param {String} message
*/
window.alert = function(message) {
popupManager.alert(message);
};
}
}])
.service('popupManager', ['$q', '$timeout', function popupManager($q, $timeout) {
var self = this;
/**
*
* @param {String} message
* @param {String} [title]
* @param {String} [buttonName]
* @return {Promise}
*/
this.alert = function alert(message, title, buttonName) {
var def = $q.defer();
if (navigator != null && navigator.notification != null) {
navigator.notification.alert(message, function() {
$timeout(def.resolve);
}, title || 'Alert', buttonName);
}
else {
window.alert(message);
def.resolve();
}
return def.promise;
};
/**
*
* @param {String} message
* @param {String} [title]
* @return {Promise}
*/
this.error = function error(message, title) {
return self.alert(message, title || 'Error');
};
/**
*
* @param {String} message
* @param {String} [title]
* @param {String} [okLabel]
* @param {String} [cancelLabel]
* @return {Promise}
*/
this.confirm = function confirm(message, title, okLabel, cancelLabel) {
var def = $q.defer();
function confirmCallback(buttonIndex) {
if (buttonIndex === 1) {
// OK was clicked
def.resolve();
}
def.reject();
}
if (navigator != null && navigator.notification != null) {
navigator.notification.confirm(message, confirmCallback, title || 'Confirm', [okLabel || 'OK', cancelLabel || 'Cancel']);
}
else {
confirmCallback(window.confirm(message) ? 1 : 2);
}
return def.promise;
}
}]);
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.1-master-70cecda
*/
function MdWhiteframeDirective(e){function a(a,n,o){var d="";o.$observe("mdWhiteframe",function(a){a=parseInt(a,10)||m,a!=r&&(a>i||a<t)&&(e.warn("md-whiteframe attribute value is invalid. It should be a number between "+t+" and "+i,n[0]),a=m);var l=a==r?"":"md-whiteframe-"+a+"dp";o.$updateClass(l,d),d=l})}var r=-1,t=1,i=24,m=4;return{link:a}}goog.provide("ngmaterial.components.whiteframe"),goog.require("ngmaterial.core"),MdWhiteframeDirective.$inject=["$log"],angular.module("material.components.whiteframe",["material.core"]).directive("mdWhiteframe",MdWhiteframeDirective),ngmaterial.components.whiteframe=angular.module("material.components.whiteframe");
|
angular
.module('root')
.factory('CommunicationFactory', function(DatabaseService, UtilityFactory, Gparams) {
var _theData = {};
var _showFlag;
var query = "id=" + Gparams.curUserID;
DatabaseService.getRecipients(query)
.then(function successCallback(response) {
_theData = response.data.names;
return response;
}, function errorCallback(response) {
UtilityFactory.showAlertToast('<md-toast>Retrieval of recipients for ' + vm.fullName + ' failed with the error:' + response.data.error + '.' + vm.appName +' has been notified</md-toast>');
UtilityFactory.sendBugReport(response);
return response;
});
_saveRecipients = function() {
DatabaseService.setRecipients(vm.params.curUserID, vm.globalList)
.then(function successCallback(response) {
if (response.status=='200') {
return;
} else {
UtilityFactory.showAlertToast('<md-toast>Saving of recipients for ' + vm.fullName + ' failed with the error:' + response.data.error + '.' + vm.appName +' has been notified</md-toast>');
UtilityFactory.sendBugReport(response);
}
});
};
// public functions
setRecipients = function(theData) {
_theData = theData;
return;
}
getRecipients = function() {
return _theData;
}
return {
getRecipients : getRecipients,
setRecipients : setRecipients,
}
})
|
/**
* # Player type implementation of the game stages
* Copyright(c) {YEAR} {AUTHOR} <{AUTHOR_EMAIL}>
* MIT Licensed
*
* Each client type must extend / implement the stages defined in `game.stages`.
* Upon connection each client is assigned a client type and it is automatically
* setup with it.
*
* http://www.nodegame.org
* ---
*/
"use strict";
const ngc = require('nodegame-client');
module.exports = function(treatmentName, settings, stager, setup, gameRoom) {
// Make the player step through the steps without waiting for other players.
stager.setDefaultStepRule(ngc.stepRules.SOLO);
stager.setOnInit(function() {
// Initialize the client.
var header;
// Setup page: header + frame.
header = W.generateHeader();
W.generateFrame();
// Add widgets.
this.visuaStage = node.widgets.append('VisualStage', header);
this.visualRound = node.widgets.append('VisualRound', header);
this.visualTimer = node.widgets.append('VisualTimer', header, {
hidden: true // Initially hidden.
});
this.doneButton = node.widgets.append('DoneButton', header);
// No need to show the wait for other players screen in single-player
// games.
W.init({ waitScreen: false });
// Additional debug information while developing the game.
// this.debugInfo = node.widgets.append('DebugInfo', header)
});
stager.extendStep('instructions', {
frame: 'instructions.htm',
cb: function() {
var s;
// Note: we need to specify node.game.settings,
// and not simply settings, because this code is
// executed on the client.
s = node.game.settings;
// Replace variables in the instructions.
W.setInnerHTML('coins', s.COINS);
W.setInnerHTML('rounds', s.ROUNDS);
W.setInnerHTML('exchange-rate', (s.COINS * s.EXCHANGE_RATE));
}
});
stager.extendStep('quiz', {
cb: function() {
// Modify CSS rules on the fly.
W.cssRule('.choicetable-left, .choicetable-right ' +
'{ width: 200px !important; }');
W.cssRule('table.choicetable td { text-align: left !important; ' +
'font-weight: normal; padding-left: 10px; }');
},
// Make a widget step.
widget: {
name: 'ChoiceManager',
id: 'quiz',
options: {
mainText: 'Answer the following questions to check ' +
'your understanding of the game.',
forms: [
{
name: 'ChoiceTable',
id: 'howmany',
mainText: 'How many players are there in this game? ',
choices: [ 1, 2, 3 ],
correctChoice: 0
},
{
name: 'ChoiceTable',
id: 'coins',
mainText: 'How many coins can you win in each round?',
choices: [
settings.COINS,
settings.COINS + 100,
settings.COINS + 25,
'Not known'
],
correctChoice: 0
}
],
// Settings here apply to all forms.
formsOptions: {
shuffleChoices: true
}
}
}
});
stager.extendStep('guess', {
init: function() {
node.game.visualTimer.show();
},
widget: {
name: 'ChoiceTable',
ref: 'guess',
options: {
id: 'guess',
mainText: 'The system will generate a random number between ' +
'1 and 10. Will the random number be larger than 5?',
choices: [ 'Yes, larger than 5', 'Smaller than or equal to 5' ],
hint: '(A random decision will be made if timer expires)',
requiredChoice: true,
shuffleChoices: true,
panel: false,
title: false
}
},
done: function(values) {
return {
greater: values.value === 'Yes, larger than 5'
};
},
timeup: function() {
node.game.guess.setValues();
node.done();
}
});
stager.extendStep('results', {
frame: 'game.htm',
cb: function() {
// (re-) Hide the results div.
W.hide('results');
node.game.visualTimer.setToZero();
// Ask for the outcome to server.
node.get('result', function(data) {
// Display information to screen.
W.setInnerHTML('yourdecision', data.greater ?
'Greater than 5' : 'Smaller than or equal to 5');
W.setInnerHTML('randomnumber', data.randomnumber);
W.setInnerHTML('winlose', data.win ? 'You won!' : 'You lost!');
// Show the results div.
W.show('results');
// Leave the decision visible for up 5 seconds.
// If user clicks Done, it can advance faster.
node.game.visualTimer.restart(5000);
node.timer.wait(5000).done();
});
}
});
stager.extendStep('end', {
widget: {
name: 'EndScreen',
options: { askServer: true }
},
init: function() {
node.game.visualTimer.destroy();
node.game.doneButton.destroy();
}
});
};
|
function isolatedTwoWay() {
return {
restrict: 'E',
scope: {
dirName: '=name'
},
template: '<p>Name: <input ng-model="dirName" /></p>'
};
}
export default isolatedTwoWay;
export const name = 'nsIsolatedTwoWay';
|
/* global window */
import EventEmitter from '../sync/EventEmitter';
import SelectCoords from './SelectCoords';
import ActivityManager from './ActivityManager';
const ns = window.fivenations;
export default {
activate(entityManager, controlPanel) {
const activity = ActivityManager.getInstance().start(SelectCoords);
activity.on('select', (mousePointer) => {
const coords = mousePointer.getRealCoords();
EventEmitter.getInstance()
.synced.entities(':user:selected')
.patrol({
x: coords.x,
y: coords.y,
});
ns.game.GUI.putClickAnim(coords.x, coords.y);
controlPanel.selectMainPage();
});
// @TODO this should be unified as most of the buttons share this logic
controlPanel.selectCancelPage();
},
};
|
import Ember from 'ember';
import moment from 'moment';
import layout from '../templates/components/ui-date-picker';
const {
on,
computed,
generateGuid
} = Ember;
const { reads } = computed;
/**
* @module DatePickerDay
*
* Represents a day, binds computed properties to the date.
*/
const DatePickerDay = Ember.Object.extend({
value: reads('datePicker.value'),
month: reads('datePicker.currentMonth'),
/**
* Day is today's date
*
* @property isToday
*/
isToday: computed(function() {
return this.get('date').isSame(new Date(), 'day');
}),
/**
* Day is the selected day in `datePicker`
*
* @property isSelected
*/
isSelected: computed('value', function() {
return this.get('date').isSame(this.get('value') || null, 'day');
}),
/**
* Day is disabled
*
* @property isDisabled
*/
isDisabled: computed('minDate', 'maxDate', function() {
const date = this.get('date');
// Reading via computeds wouldn't pass tests, accessing directly
const minDate = this.get('datePicker.minDate') || null;
const maxDate = this.get('datePicker.maxDate') || null;
return date.isAfter(maxDate) || date.isBefore(minDate);
}),
/**
* Day is not in the current month
*
* @property isNotInMonth
*/
isNotInMonth: computed('value', 'month', function() {
return !this.get('date').isSame(this.get('month'), 'month');
})
});
/**
* @module UiDatePicker
*
* Date picker component
*/
export default Ember.Component.extend({
layout: layout,
classNames: ['tf-date-picker'],
classNameBindings: ['inline:tf-date-picker--inline'],
on: 'click focus',
flow: 'align-left',
/**
* Class applied to the date picker button
*
* @property btnClass
*/
btnClass: 'tf-btn--default',
datePickerId: computed(function () {
return generateGuid();
}),
/**
* The bound date value
*
* @property value
*/
value: null,
/**
* The class used to represent individual days. This is defined
* here so that it is overloadable, allowing `UiDateRangePicker` to
* define it's own `dayClass` with more specialized behavior.
*
* @property value
*/
dayClass: DatePickerDay,
actions: {
/**
* Sets the current month to the previous month
*
* @method previousMonth
*/
previousMonth() {
this.get('currentMonth').subtract(1, 'month').startOf('month');
// Since `subtract` mutates the moment object directly, no need to set it
this.propertyDidChange('currentMonth');
},
/**
* Sets the current month to the next month
*
* @method nextMonth
*/
nextMonth() {
this.get('currentMonth').add(1, 'month').startOf('month');
// Since `subtract` mutates the moment object directly, no need to set it
this.propertyDidChange('currentMonth');
},
/**
* Sets the current month to the currently selected date, or the passed
* in date. This ensure that the user will always have context when opening
* the calendar.
*
* @method previousMonth
* @param [value] The date to set currentMonth to
*/
setCurrentMonth(value) {
value = value || this.get('value');
if (value) {
this.set('currentMonth', moment(value).startOf('month'));
}
},
/**
* Selects a date and closes the dropdown menu.
*
* @method selectDate
* @param [date] The date to select
* @param [dropdown] Reference to the dropdown to close it
*/
selectDate(date, dropdown, isDisabled) {
if (isDisabled) { return; }
dropdown.deactivate();
this.set('value', date.toDate());
}
},
/**
* Initializes the calendar to the current month
*
* @method initializeMonth
*/
initializeMonth: on('init', function() {
this.send('setCurrentMonth', new Date());
}),
/**
* The first letter of each day of the week.
*
* @property dayNames
*/
dayNames: computed(function() {
const week = Ember.A();
const currentDay = moment().startOf('week');
for (let iDay = 0; iDay < 7; iDay++) {
week.push(currentDay.clone().toDate());
currentDay.add(1, 'day');
}
return Ember.A(week.map(function (day) {
return moment(day).format('dd').substr(0, 1);
}));
}),
/**
* The weeks of the current month. This instantiates a `dayClass`
* for each day, and then pushes the day onto a week.
*
* @property weeks
*/
weeks: computed('currentMonth', function() {
const currentMonth = this.get('currentMonth');
const endOfMonth = currentMonth.clone().endOf('month');
const currentDay = currentMonth.clone().startOf('week');
const weeks = Ember.A();
while (currentDay.isBefore(endOfMonth)) {
let week = Ember.A();
for (let iDay = 0; iDay < 7; iDay++) {
week.push(this.get('dayClass').create({
datePicker: this,
date: currentDay.clone()
}));
currentDay.add(1, 'day');
}
weeks.push(week);
}
return weeks;
})
});
|
/*
copy files from %scaffold% to newly created git repo
replace %scaffold% to appname
*/
var fs=require('fs');
var argv=process.argv;
var app=argv;
app.shift();app.shift();
var appname=app[0];
var forcecreate=app.length>2 &&app[2]=='--overwrite';
var templatepath=(app[1]||"kse") +'/';
var path=require('path');
var tobecopied=0;
if (!fs.existsSync(templatepath+'/%scaffold%')) {
console.log(templatepath+' has no scaffold template');
return;
}
var getgiturl=function() {
var url=fs.readFileSync(appname+'/.git/config','utf8');//.match(/url = (.*?)\n/);
url=url.substr(url.indexOf('url ='),100);
url=url.replace(/\r\n/g,'\n').substring(6,url.indexOf('\n'));
return url;
}
var die=function() {
console.log.apply(this,arguments)
process.exit(1);
}
if (!appname) die('node scaffold newappname template --overwrite');
if (!fs.existsSync(appname)) die('folder not exists');
if (!fs.existsSync(appname+'/.git')) die('not a git repository');
var giturl=getgiturl();
if (!forcecreate && fs.existsSync(appname+'/package.json')) {
die(giturl,'is not a brand new repo, add --overwrite at the end to force create, all files will be overwrite');
}
var walk = function(dir) {
var results = []
var list = fs.readdirSync(dir)
list.forEach(function(file) {
file = dir + '/' + file
var stat = fs.statSync(file)
if (stat && stat.isDirectory()) {
if (file.substring(file.length-4)!='test') {
results = results.concat(walk(file))
} else {
console.log('skip '+file)
}
}
else results.push(file)
})
return results
}
var mkdirParent = function(dirPath, mode, callback) {
fs.mkdir(dirPath, mode, function(error) {
if (error && error.errno === 34) {
mkdirParent(path.dirname(dirPath), mode, callback);
mkdirParent(dirPath, mode, callback);
}
callback && callback(error);
});
};
var textext=['.xml','.js','.json','.html','.css','.command','.cmd','.sh','.lst'];
var replaceid=function(source) {
var raw=fs.readFileSync(source);
var ext=source.substring(source.lastIndexOf('.'));
if (textext.indexOf(ext)==-1) {
//console.log('skip non text file',source)
return raw;
}
var raw=fs.readFileSync(source,'utf8');
var arr=raw.replace(/\r\n/g,'\n').split('\n');
for (var i in arr) {
arr[i]=arr[i].replace(/%scaffold%/g,appname);
if (source.indexOf('package.json')>-1) {
arr[i]=arr[i].replace(/%git%/g,giturl);
}
}
return arr.join('\n');
}
var copyfile=function(source) {
if (source.indexOf('%scaffold%')==-1) {
console.log('not scaffold',source)
return;
}
tobecopied++;
var stats = fs.lstatSync(source);
var target=source.replace(templatepath+'%scaffold%',appname);
var target=target.replace('%scaffold%',appname);
var targetpath=target;
var arr=null;
if (!stats.isDirectory()) {
arr=replaceid(source);
targetpath=path.dirname(target);
}
mkdirParent(targetpath,function(err){
tobecopied--;
if (stats.isDirectory()) return;
console.log('create',target)
fs.writeFileSync(target,arr,'utf8');
if (target.indexOf('.command')>-1 ||
target.indexOf('.sh')>-1){
fs.chmodSync(target,'0755');
}
});
if (stats.isDirectory()) {
var sourcefiles=walk(source);
for (var i in sourcefiles) copyfile(sourcefiles[i]);
}
}
console.log('create scaffold for git',giturl)
var deploy=require('./'+templatepath+'%scaffold%/deploy');
for (var i in deploy) {
for (var j in deploy[i]) {
copyfile(templatepath+deploy[i][j]);
}
}
copyfile(templatepath+'%scaffold%/deploy.json');
//build ydb for user
var timer=setInterval(function(){
console.log(tobecopied)
if (tobecopied==0) {
console.log('build database')
process.chdir(appname+'/xml/');
require('./'+appname+'/xml'+'/'+appname);
process.chdir('../..')
clearInterval(timer)
console.log('done');
}
},100)
|
var Fibers = Npm.require('fibers');
var Future = Npm.require('fibers/future');
var util = Npm.require('util');
var EventEmitter = Npm.require('events').EventEmitter;
function Cursor(query, collection, options) {
this._id = ++Cursor._instances;
this.setMaxListeners(0);
this._debug = Npm.require('debug')('sc:cursor:' + this._id);
var self = this;
if(query && collection) {
this.init(query, collection, options);
}
this._debug('created');
}
Cursor._instances = 0;
util.inherits(Cursor, EventEmitter);
Cursor.prototype.init = function(query, collection, options) {
this._query = query;
this._collection = collection;
this._transform = options.transform;
this._debug('init query:%d coll:%s options:%j', query._id, collection.name, options);
this._options = options;
this.emit('ready');
};
Cursor.prototype._forEach = function (callback, endCallback) {
this._debug('_forEach');
var self = this;
var cursor = this._query.getCursor();
var afterNextObjectBinded = afterNextObject;
if(Fibers.current) {
afterNextObjectBinded = Meteor.bindEnvironment(afterNextObject, function(err) {
Meteor._debug('error getting next object in _forEach', err.stack);
});
}
cursor.nextObject(afterNextObjectBinded);
function afterNextObject(err, item) {
if(err) {
endCallback(err);
} else if(item) {
var transformFunc = self._getTransformFunction();
if(transformFunc) {
item = transformFunc(item);
}
callback(item);
cursor.nextObject(afterNextObjectBinded);
} else {
endCallback();
}
}
};
Cursor.prototype._map = function _map(mapCallback, resultCallback) {
this._debug('_map');
var self = this;
var data = [];
var cursor = this._query.getCursor();
var afterNextObjectBinded = afterNextObject;
if(Fibers.current) {
afterNextObjectBinded = Meteor.bindEnvironment(afterNextObject, function(err) {
Meteor._debug('error getting next object in _map', err.stack);
});
}
cursor.nextObject(afterNextObjectBinded);
function afterNextObject(err, item) {
if(err) {
resultCallback(err);
} else if(item) {
var transformFunc = self._getTransformFunction();
if(transformFunc) {
item = transformFunc(item);
}
data.push(mapCallback(item));
cursor.nextObject(afterNextObjectBinded);
} else {
resultCallback(null, data);
}
}
};
Cursor.prototype._fetch = function _fetch(callback) {
this._debug('_fetch');
var self = this;
var cursor = this._query.getCursor();
var onResultBinded = onResult;
if(Fibers.current) {
onResultBinded = Meteor.bindEnvironment(onResult, function(err) {
Meteor._debug('error getting results in _fetch', err.stack);
});
}
cursor.toArray(onResultBinded);
function onResult(err, results) {
//if options.transform is === null, we should not do the transform
var transformFunc = self._getTransformFunction();
if(transformFunc && results) {
for(var lc=0; lc<results.length; lc++) {
results[lc] = transformFunc(results[lc]);
}
}
callback(err, results);
}
};
Cursor.prototype._count = function _count(callback) {
this._debug('count');
var cursor = this._query.getCursor();
cursor.count(callback);
};
Cursor.prototype.rewind = function rewind() {
this._debug('rewind');
};
Cursor.prototype._observeChanges = function _observeChanges(callbacks, endCallback) {
this._debug('adding observer');
var self = this;
var observer = new Meteor.SmartObserver(callbacks);
this._query.addObserver(observer, afterAdded);
var added = false;
function afterAdded(err) {
added = true;
if(err) {
if(endCallback) endCallback(err);
} else {
var observeHandler = new ObserveHandler(self, observer);
if(endCallback) endCallback(null, observeHandler);
}
}
};
Cursor.prototype._getTransformFunction = function() {
if(this._transform !== undefined) {
return this._transform ;
} else {
return this._collection._transform;
}
};
Cursor.prototype.__publishCursor = function(subscription, callback) {
this._debug('__publishCursor');
var self = this;
this._observeChanges({
added: function(id, doc) {
subscription.added(self._collection.name, id, doc);
},
changed: function(id, fields) {
subscription.changed(self._collection.name, id, fields);
},
removed: function(id) {
subscription.removed(self._collection.name, id);
}
}, function(err, observeHandler) {
if(err) {
if(callback) callback(err);
} else {
subscription.onStop(function() { observeHandler.stop(); });
if(callback) callback();
}
});
};
Cursor.prototype._getCollectionName = function() {
return this._collection.name;
};
//do both fiber and non-fiber support
['forEach', 'map', 'fetch', 'count', 'observeChanges', '_publishCursor'].forEach(function(method) {
Cursor.prototype[method] = function() {
var self = this;
var future;
if(Fibers.current) {
future = new Future();
Array.prototype.push.call(arguments, future.resolver());
doApply = Meteor.bindEnvironment(doApply, function(err) {
Meteor._debug('error in: ' + method, err.stack);
});
}
var args = arguments;
modifyArgs(args, method);
if(self._query) {
doApply();
} else {
self.once('ready', doApply);
}
if(future) future.wait();
if(future) {
return future.value;
}
function doApply() {
self['_' + method].apply(self, args);
}
};
});
function modifyArgs(args, method) {
if(method == 'observeChanges') {
var callbacks = args[0];
['added', 'changed', 'removed'].forEach(function(event) {
var callbackFunc = callbacks[event];
if(typeof(callbackFunc) == 'function') {
callbacks[event] = Meteor.bindEnvironment(callbackFunc, onModifyArgsError);
}
});
}
function onModifyArgsError(err) {
console.error('error when modifyArgs of ', method, {error: err});
}
}
/***** ObserveHandler ******/
function ObserveHandler(cursor, observer) {
this._cursor = cursor;
this._observer = observer;
}
ObserveHandler.prototype.stop = function stop() {
this._cursor._debug('remove observer');
this._cursor._query.removeObserver(this._observer);
};
Meteor.SmartCursor = Cursor;
|
dm.VerticalListContentView = dm.View.clone().newSlots({
type: "dm.VerticalListContentView",
items: [],
selectedItemIndex: null,
itemHMargin: 15,
itemVMargin: 15,
confirmsRemove: true,
closeButton: null,
}).setSlots({
init: function()
{
dm.View.init.call(this);
this.setItems(this.items().copy());
if(dm.Window.inited())
{
var closeButton = dm.ImageButton.clone().newSlot("itemView", null);
this.setCloseButton(closeButton);
closeButton.setDelegate(this);
closeButton.setDelegatePrefix("closeButton");
closeButton.setImageUrl("http://f.cl.ly/items/3P3Y2Z2B31222w0l1K0E/gray-close.png");
closeButton.setWidth(12);
closeButton.setHeight(12);
closeButton.setX(this.width() - closeButton.width() - closeButton.width()/2);
closeButton.setResizesLeft(true);
closeButton.setZIndex(1);
closeButton.hide();
this.addSubview(closeButton);
}
},
addItemWithText: function(text)
{
var hMargin = dm.VerticalListContentView.itemHMargin();
var vMargin = dm.VerticalListContentView.itemVMargin();
var itemView = dm.Button.clone().newSlots({
type: "dm.ItemView",
label: null
}).clone();
itemView.setTracksMouse(true);
itemView.setDelegate(this);
itemView.setWidth(this.width());
itemView.setResizesWidth(true);
var label = dm.Label.clone();
itemView.setLabel(label);
label.setColor(dm.Color.Gray);
label.setText(text);
label.setWidth(this.width() - hMargin - 2*this.closeButton().width());
label.sizeHeightToFit();
label.setX(hMargin);
itemView.setHeight(label.height() + hMargin);
itemView.addSubview(label);
itemView.addSubview(label);
label.centerVertically();
this.addItem(itemView);
},
itemViewMouseEntered: function(itemView, previousView)
{
if (!this.closeButton().contains(previousView))
{
var closeButton = this.closeButton();
closeButton.centerYOver(itemView);
closeButton.moveDown(1);
closeButton.show();
closeButton.setItemView(itemView);
}
},
itemViewMouseExited: function(itemView, nextView)
{
if (!this.closeButton().contains(nextView))
{
var closeButton = this.closeButton();
closeButton.hide();
closeButton.setItemView(null);
}
},
itemViewClicked: function(button)
{
if (this.selectedItemIndex() !== null)
{
var selectedItem = this.selectedItem();
if (selectedItem)
{
var l = selectedItem.label();
l.setColor(dm.Color.Gray);
l.setFontWeight("normal");
}
}
var l = button.label();
l.setColor(dm.Color.Black);
l.setFontWeight("bold");
this.setSelectedItemIndex(this.items().indexOf(button));
this.delegatePerform("selectedItem", button);
},
addItem: function(itemView)
{
var hMargin = dm.VerticalListContentView.itemHMargin();
itemView.setY(this.items().length * itemView.height());
this.setHeight(itemView.bottomEdge());
this.addSubview(itemView);
this.items().append(itemView);
},
removeLastItem: function()
{
var item = this.items().pop();
this.removeSubview(item);
this.setHeight(this.height() - item.height());
},
selectItem: function(item)
{
this.itemViewClicked(item);
},
removeItem: function(item)
{
if (this.confirmsRemove())
{
if (!confirm("Remove " + item.label().text() + "?"))
{
return;
}
}
var selectedItem = this.selectedItem();
var itemIndex = this.items().indexOf(item);
this.items().remove(item);
this.items().slice(itemIndex).forEach(function(itemToMove){
itemToMove.setY(itemToMove.y() - item.height());
});
this.removeSubview(item);
this.setHeight(this.height() - item.height());
if (selectedItem == item)
{
var itemToSelect = this.items()[itemIndex] || this.items().last();
if (itemToSelect)
{
this.selectItem(itemToSelect);
}
}
var newItemAtIndex = this.items()[itemIndex];
if (newItemAtIndex)
{
this.itemViewMouseEntered(newItemAtIndex, null);
}
this.delegatePerform("removedItem", item);
},
closeButtonClicked: function(closeButton)
{
this.removeItem(closeButton.itemView());
},
selectedItem: function()
{
return this.items()[this.selectedItemIndex()];
},
removeSelectedItem: function()
{
this.removeItem(this.selectedItem());
}
});
|
import React from 'react';
import ReactTestRenderer from 'react-test-renderer';
import 'styled-components-test-utils/lib/jest';
import theme from '../src/theme';
import InlineText from '../src/InlineText';
import * as utils from '../src/utils/';
describe('InlineText', () => {
test('should render a InlineText', () => {
const component = ReactTestRenderer.create(<InlineText theme={theme} />);
expect(component).toBeDefined();
expect(component.toJSON()).toMatchSnapshot();
});
test('should have a span tag', () => {
const component = ReactTestRenderer.create(<InlineText theme={theme} />).toJSON();
expect(component.type).toEqual('span');
});
test('should have a color', () => {
const spy = jest.spyOn(utils, 'getTextColor');
const component = ReactTestRenderer.create(
<InlineText
theme={theme}
textColor="white"
/>,
);
expect(component).toHaveStyleRule('color', 'white');
expect(spy).toHaveBeenCalled();
});
test('should have opacity', () => {
const spy = jest.spyOn(utils, 'getOpacity');
const component = ReactTestRenderer.create(
<InlineText
theme={theme}
opacity={0.75}
/>,
);
expect(component).toHaveStyleRule('opacity', '0.75');
expect(spy).toHaveBeenCalled();
});
test('should be important', () => {
const component = ReactTestRenderer.create(
<InlineText
theme={theme}
important
/>,
);
expect(component).toHaveStyleRule('font-weight', '800');
});
test('should not be important', () => {
const component = ReactTestRenderer.create(
<InlineText
theme={theme}
/>,
);
expect(component).toHaveStyleRule('font-weight', '400');
});
});
|
//Kata: Rock Paper Scissors!
//Problem Description
//We need a function rockPaperScissors() that can receive two parameters with the move of each of the two players in the game "Rock Paper Scissors".
//The possible values are : "PAPER", "SCISSORS" or "ROCK"
//If the function is called with only one parameter the move of the second player should be randomly generated.
//>> rockPaperScissors("PAPER","SCISSORS")
//"PAPER vs SCISSORS => SCISSORS wins!"
//>> rockPaperScissors("ROCK","ROCK")
//"ROCK vs ROCK => tie!"
//>> rockPaperScissors("PAPER")
//"PAPER vs ROCK => PAPER wins!"
//>> rockPaperScissors("PAPER")
//"PAPER vs PAPER => tie!"
function rockPaperScissors( player1, player2 ) {
// We exit with error when received no parameters
if ( player1 == undefined ){
return 'ERROR!';
}
// Exit with error when player1 is not valid
if ( ( player1 != 'PAPER') && ( player1 != 'SCISSORS') && ( player1 != 'ROCK') ){
return 'ERROR!';
}
// If only player1 is available => create player2
if ( player2 == undefined ){
player2 = Math.floor(Math.random() * 3) + 1
}
switch(player2){
case 1:
player2 = 'PAPER';
break;
case 2:
player2 = 'SCISSORS';
break;
case 3:
player2 = 'ROCK';
break;
}
// Exit with error when player2 is not valid
if ( ( player2 != 'PAPER') && ( player2 != 'SCISSORS') && ( player2 != 'ROCK') ){
return 'ERROR!';
}
// Tie!
if ( player1 == player2 ){
return player1+' vs '+player2+' => tie!';
}
// Possible outcomes
if ( ( player1 == 'PAPER') && ( player2 == 'SCISSORS') ) {
return 'PAPER vs SCISSORS => SCISSORS wins!';
}
if ( ( player1 == 'PAPER') && ( player2 == 'ROCK') ) {
return 'PAPER vs ROCK => PAPER wins!';
}
if ( ( player1 == 'ROCK') && ( player2 == 'PAPER') ) {
return 'ROCK vs PAPER => PAPER wins!';
}
if ( ( player1 == 'ROCK') && ( player2 == 'SCISSORS') ) {
return 'ROCK vs SCISSORS => ROCK wins!';
}
if ( ( player1 == 'SCISSORS') && ( player2 == 'PAPER') ) {
return 'SCISSORS vs PAPER => SCISSORS wins!';
}
if ( ( player1 == 'SCISSORS') && ( player2 == 'ROCK') ) {
return 'SCISSORS vs ROCK => ROCK wins!';
}
}
|
'use strict'
const { encode, isFunction, isObject, isString } = require('./helpers')
module.exports = class Redemptions {
constructor (client, promotionsNamespace) {
this.client = client
this.promotions = promotionsNamespace
}
redeem (code, params, callback) {
let context = {}
const qs = {}
let isDeprecated = false
if (isObject(code) && isObject(params)) {
return this.promotions.tiers.redeem(code.id, params, callback)
}
if (isObject(code)) {
isDeprecated = true
console.warn('This redeem method invocation is deprecated. First argument should be always a code, check docs for more details. In next major update this method invocation will not be available.')
if (isObject(params)) {
console.warn('This redeem method invocation is deprecated. Params being an object will be ignored. In next major update this method invocation will not be available.')
}
context = code
code = context.voucher
delete context.voucher
} else {
context = params || {}
}
if (isFunction(params)) {
callback = params
context = isDeprecated ? context : null
} else if (isString(params) && params.length > 0) {
// FIXME put to body: {customer: tracking_id}, test it with working API
qs.tracking_id = encode(params)
}
return this.client.post(`/vouchers/${encode(code)}/redemption`, context, callback, { qs })
}
list (params, callback) {
if (isFunction(params)) {
callback = params
params = {}
}
return this.client.get('/redemptions', params, callback)
}
getForVoucher (code, callback) {
return this.client.get(`/vouchers/${encode(code)}/redemption`, null, callback)
}
rollback (redemptionId, params, callback) {
if (isFunction(params)) {
callback = params
params = null
}
let qs = {}
let payload = {}
if (isString(params)) {
qs.reason = encode(params)
} else if (isObject(params)) {
const { reason, tracking_id: trackingId, customer } = params
qs = {
reason: reason ? encode(reason) : undefined,
tracking_id: trackingId ? encode(trackingId) : undefined // eslint-disable-line camelcase
}
payload = { customer }
}
return this.client.post(
`/redemptions/${encode(redemptionId)}/rollback`,
payload, callback, { qs }
)
}
}
|
'use strict';
var
url = require('url'),
App = require('boomerang-app'),
Scheduler = require('boomerang-scheduler');
require('rdf-jsonify')(rdf);
var BoomerangModule = function (config) {
var
self = this,
events,
jsonify,
context = {'@vocab': 'https://ns.bergnet.org/boomerang#'};
if (!('boomerang' in config)) {
config.boomerang = {};
}
if (!('apps' in config.boomerang)) {
config.boomerang.apps = [];
}
/**
* Start an app with new app utils and scheduler
* @param appConfig
* @returns {*}
*/
var startApp = function (appConfig) {
appConfig.app = new App(events.store, appConfig.base);
appConfig.scheduler = new Scheduler(events.store, {
scheduleBaseIri: appConfig.scheduleBaseIri,
taskListIri: appConfig.taskListIri,
tasksPerAgent: 10
});
// start application
require(appConfig.path)(appConfig.app);
return Promise.resolve();
};
/**
* Clean the task list, scheduler and result of an app
* @param appConfig
* @returns {*|Promise}
*/
var cleanApp = function (appConfig) {
return appConfig.scheduler.clean()
.then(function () {
return appConfig.app.clean();
})
.then(function () {
return jsonify.get(appConfig.base, context);
})
.then(function (appGraph) {
if ('result' in appGraph) {
delete appGraph.result;
return jsonify.put(appGraph);
} else {
return Promise.resolve();
}
});
};
/**
* Clean and restart an app
* @param appConfig
* @returns {*|Promise}
*/
var resetApp = function (appConfig) {
return cleanApp(appConfig)
.then(function () { return startApp(appConfig); });
};
/**
* Start all app configurations
* @param app
* @returns {*}
*/
this.start = function (app) {
config.boomerang.apps.forEach(function (appConfig) {
startApp(appConfig);
});
return Promise.resolve(app);
};
/**
* Init the server and all app APIs
* @param app
* @returns {*|Promise}
*/
this.initApi = function (app) {
var initApp = function (appConfig) {
// set all app IRIs
appConfig.releaseAssignedTasksIri = appConfig.base + 'releaseAssignedTasks';
appConfig.resetIri = appConfig.base + 'reset';
appConfig.scheduleBaseIri = appConfig.base + 'data/schedule';
appConfig.taskListIri = appConfig.base + 'data/tasks#list';
// redirect to the agent schedule list
app.get(url.parse(appConfig.scheduleBaseIri).path, function (req, res) {
res.redirect(appConfig.scheduler.getScheduleIri(req.session.agent));
});
// add schedule listener
events.addListener('beforeGraph', function (iri, options) {
if (iri.indexOf(appConfig.scheduleBaseIri) === 0 && iri !== appConfig.scheduleBaseIri) {
return appConfig.scheduler.schedule(options);
} else {
return Promise.resolve();
}
});
// release assigned tasks
app.get(url.parse(appConfig.releaseAssignedTasksIri).path, function (req, res) {
appConfig.scheduler.releaseAssignedTasks()
.then(function () {
res.satusCode = 204;
res.end();
})
.catch(function (error) {
res.statusCode = 500;
res.end(error.stack.toString());
});
});
// reset application
app.get(url.parse(appConfig.resetIri).path, function (req, res) {
resetApp(appConfig)
.then(function () {
res.satusCode = 204;
res.end();
})
.catch(function (error) {
res.statusCode = 500;
res.end(error.stack.toString());
});
});
// publish app API as Linked Data
return jsonify.put({
'@context': context,
'@id': appConfig.base,
'releaseAssignedTasks': {'@id': appConfig.releaseAssignedTasksIri},
'reset': {'@id': appConfig.resetIri},
'openTasks': {'@id': appConfig.scheduleBaseIri}
});
};
// publish server API as Linked Data
return jsonify.put({
'@context': context,
'@id': config.boomerang.url,
'hosts': config.boomerang.apps.map(function (appConfig) {
return {'@id': appConfig.base};
})
})
.then(function () {
return Promise.all(config.boomerang.apps.map(function (appConfig) {
return initApp(appConfig);
}));
})
.then(function () {
return Promise.resolve(app);
});
};
/**
* Init BoomeranJS LDApp module
* @param app
* @returns {*|Promise}
*/
this.init = function (app) {
events = app.get('graphModule').events;
jsonify = new rdf.JSONify(events.store);
app.set('boomerangModule', self);
return self.initApi(app)
.then(function (app) { return self.start(app); });
}
};
module.exports = BoomerangModule;
|
// Generated on 2014-10-04 using generator-angular 0.9.5
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Configurable paths for the application
var appConfig = {
app: require('./app/bower.json').appPath || 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: appConfig,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
jsTest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['newer:jshint:test', 'karma']
},
styles: {
files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= yeoman.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: '0.0.0.0',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: 9001,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
dist: {
options: {
open: true,
base: '<%= yeoman.dist %>'
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git*'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
options: {
cwd: '<%= yeoman.app %>'
},
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: /\.\.\//
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on filerev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
options: {
assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
}
},
// The following *-min tasks will produce minified files in the dist folder
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
conservativeCollapse: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true,
removeOptionalTags: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html', 'views/{,*/}*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
// ngmin tries to make the code safe for minification automatically by
// using the Angular long form for dependency injection. It doesn't work on
// things like resolve or inject so those have to be done manually.
ngmin: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'*.html',
'views/{,*/}*.html',
'images/{,*/}*.{webp}',
'fonts/*'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
cwd: 'bower_components/bootstrap/dist',
src: 'fonts/*',
dest: '<%= yeoman.dist %>'
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'test/karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve:' + target]);
});
grunt.registerTask('test', [
'clean:server',
'concurrent:test',
'autoprefixer',
'connect:test',
'karma'
]);
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'ngmin',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
|
import {MeshPhongMaterial} from 'three';
import {CelestialFoundry} from './CelestialFoundry';
import {
PlaneModule
} from '@ammo:modules';
import {
Plane
} from '@whs+meshes';
import {
PointLight,
DirectionalLight,
HemisphereLight
} from '@whs+lights';
/**
* StarSystem Class
*/
export class StarSystem {
/**
* Default constructor
*
* @param {CelestialFoundry} cf
*/
constructor(cf) {
const SYSTEM_HELPER_PLANE_FACTOR = 20.0;
// Star
let star = cf.createStar(cf.star());
// Planets
const planets = cf.createPlanets(star);
// console.log(planets[5].planet.setAngularVelocity(new THREE.Vector3(0.0, 7.292115*Math.pow(10,-5), 0.0)));
// console.log(planets[5].planet.applyForce(new THREE.Vector3(29800, 0.0, 29800 )));
// System Plane
this.system_helper_plane = StarSystem.createSystemHelperPlane(cf);
// Set CelestialFoundry
Object.assign(this, {
SYSTEM_HELPER_PLANE_FACTOR: SYSTEM_HELPER_PLANE_FACTOR,
cf: cf,
star: star,
planets: planets
});
// Star Light
this.star_system_light = StarSystem.createStarLight(cf, star);
}
/**
* Get system astronomical unit
*
* @return {Number}
*/
au() {
return this.cf.au();
}
/**
* Add all system components to game
*
* @param {App} game
*/
addTo(game) {
// Add star
this.star.addTo(game);
// Add star system lighting
this.star_system_light.addTo(game);
this.system_helper_plane.addTo(game);
// Add planets
for (const planet of this.planets) {
planet.addTo(game);
planet.starAccelerationLoop.start(game);
}
}
/**
* Create system helper plane component
*
* @param {CelestialFoundry} cf
* @return {Plane}
*/
static createSystemHelperPlane(cf) {
return new Plane({
geometry: {
width: cf.au()*20.0,
height: cf.au()*20.0,
wSegments: 128,
hSegments: 128
},
material: new MeshPhongMaterial({color: 0x447F8B, wireframe: true}),
rotation: {
x: -Math.PI / 2
}
});
}
/**
* Create star light (not working!)
*
* @param {CelestialFoundry} cf
* @param {Star} star
* @return {DirectionalLight}
*/
static createStarLight(cf, star) {
return new DirectionalLight({
light: {
color: 0xffffff,
intensity: 1.0
},
position: {
x: star.position.x,
y: star.position.y,
z: star.position.z
}
});
}
}
|
let { Cc, Ci } = require('chrome');
var hashModule = (function () {
var converter = Cc['@mozilla.org/intl/scriptableunicodeconverter'].createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = 'UTF-8';
// result is an out parameter,
// result.value will contain the array length
var result = {};
function toHexString(charCode) {
// return the two-digit hexadecimal code for a byte
return ('0' + charCode.toString(16)).slice(-2);
}
return {
convert: function (strValue) {
// data is an array of bytes
var data = converter.convertToByteArray(strValue, result);
var ch = Cc['@mozilla.org/security/hash;1'].createInstance(Ci.nsICryptoHash);
ch.init(ch.SHA256);
ch.update(data, data.length);
var hash = ch.finish(false);
// convert the binary hash data to a hex string.
return Array.from(hash, (c, i) => toHexString(hash.charCodeAt(i))).join('');
}
};
})();
exports.sha256 = hashModule;
|
/*
* Definition of the array for zoom degree ranges. Used in zoomFromBounds.
*/
lvl_to_degree = [
360.0,
180.0,
90.0,
45.0,
22.5,
11.25,
5.625,
2.813,
1.406,
0.703,
0.352,
0.176,
0.088,
0.044,
0.022,
0.011,
0.005,
0.003,
0.001,
0.0005,
]
/*
* Load file from address and then call 'callback' function on received
* response.
* Args:
* file: string with filename or address.
* callback: pointer to function to call after receiving response.
*/
function load_file(file, callback) {
// Create request
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', file, true);
// Add callback function.
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
/*
* Function which receive json data of the route and returns OpenLayers feature.
* Args:
* json_data: GeoJSON object.
* Retunrs:
* Array of ol.Feature's
*/
function create_route(json_data, ses_id, color=[100, 200, 50]){
var route = new ol.format.GeoJSON().readFeatures(json_data, {
featureProjection: 'EPSG:3857'
});
// Get element from the array and set type
route = route[0];
// Get coordinates for further points generation
routeCoords = route.getGeometry().getCoordinates();
// Create line
var line = new ol.geom.LineString(routeCoords);
var lineFeature = new ol.Feature(line);
lineFeature.set('type', 'route');
lineFeature.setStyle(
new ol.style.Style({
stroke: new ol.style.Stroke({
width: 5,
color: 'rgba(' + color[0] + ', ' + color[1] + ', ' + color[2] + ', 0.5)'
}),
})
);
// Array of points. Used for keyboard orientation on the map.
var features = Array();
features.push(lineFeature);
// Create points
for(i = 0; i < routeCoords.length; i++){
var point = new ol.Feature({
geometry: new ol.geom.Point(routeCoords[i]),
type: 'point',
});
point.id = i
point.ses_id = ses_id
point.setStyle(
new ol.style.Style({
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: 'rgba(' + color[0] + ', ' + color[1] + ', ' + color[2] +
', 1)'
}),
stroke: new ol.style.Stroke({
color: '#555',
width: 1
})
})
})
)
features.push(point);
}
return features;
}
/*
* Adds feature to the map.
* Args:
* feat_data: GeoJSON reponse.
*/
function add_route(feat_data, ses_id, color=[100, 200, 50]){
var features = create_route(feat_data, ses_id, color);
vec_layer.getSource().addFeatures(features);
}
/*
* Create popup message.
* Args:
* feature: ol.Feature object.
* element: html element which is used as content container (div).
*/
function create_popup(feature, element){
if (feature && feature.get('type') == 'point') {
var coordinates = feature.getGeometry().getCoordinates();
console.log(coordinates);
get_address(coordinates);
popup.setPosition(coordinates);
var hdms = ol.coordinate.toStringHDMS(ol.proj.transform(
coordinates, 'EPSG:3857', 'EPSG:4326'));
content = '<p>Information:</p><code>' + hdms +
'</code><p>Session:</p><code>' + feature.ses_id +'</code>';
content = content + '<p id="hidden_id">' + feature.id + '</p>'
// Add coordinates to Point information table
var point_coords_table = document.getElementById('point_coords');
if(point_coords_table){
point_coords_table.innerHTML = '<code>' + hdms + '</code>';
}
var point_ses_table = document.getElementById('point_ses_id');
if(point_ses_table){
point_ses_table.innerHTML = feature.ses_id;
}
$(element).popover({
'placement': 'top',
'html': true,
'content': function (){
return content;
}
});
$(element).popover('show');
} else {
$(element).popover('destroy');
}
}
/*
* Listener used for moving popup box from point to point by keyboard.
* Args:
* e: keyboard event.
*/
function key_listener(e) {
// If popup already exists
if ($(popup_element).data()['bs.popover'].tip().hasClass('in')){
// Get id from hidden HTML code
var id = parseInt(document.getElementById('hidden_id').innerText);
// Decide which key pressed
if (e.keyCode == 37){
console.log("Left " + id);
create_popup(points[id - 1], $(popup_element))
create_popup(
new ol.Feature({
geometry: new ol.geom.Point([id])
}), $(popup_element))
} else if (e.keyCode == 39){
console.log("Right " + id);
create_popup(points[id + 1], $(popup_element))
} else {
console.log("Not implemented.");
}
}
}
/*
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
* Args:
* min: integer number
* max: integer number
* Retunrs:
* Integer number between two values.
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/*
* Function to calculate apropriate zoom level for received coordinates bounds.
* Because we need to know how many tiles are shown we perform this calculation
* here.
* Args:
* bounds: Array of coordinates bounds [[min_lon, max_lon], [min_lat, max_lat]]
* Returns:
* Integer number from 1 to 20.
*/
function zoomFromBounds(bounds){
var diff_lon = bounds[0][1] - bounds[0][0];
var diff_lat = bounds[1][1] - bounds[1][0];
var zoom_lvl = 20;
// Get number of shown tiles
var map_el = document.getElementsByClassName('ol-unselectable')[0];
var width_visible_tiles = Math.floor(map_el.offsetWidth/256);
var height_visible_tiles = Math.floor(map_el.offsetHeight/256);
for(i = 0; i < lvl_to_degree.length; i++){
var degree_range = lvl_to_degree[lvl_to_degree.length - 1 - i];
if (diff_lat > (degree_range/2)*height_visible_tiles){
continue;
}
else{
var new_zoom_level = lvl_to_degree.indexOf(degree_range);
if (new_zoom_level < zoom_lvl){
zoom_lvl = new_zoom_level;
}
break;
}
}
for(i = 0; i < lvl_to_degree.length; i++){
var degree_range = lvl_to_degree[lvl_to_degree.length - 1 - i];
if (diff_lon > degree_range*width_visible_tiles){
prev_degree_range = degree_range;
}
else{
var new_zoom_level = lvl_to_degree.indexOf(degree_range);
if (new_zoom_level < zoom_lvl){
zoom_lvl = new_zoom_level;
}
break;
}
}
return zoom_lvl;
}
/*
* Function for setting zoom level of the map.
* Args:
* center: array with two numbers representing coordinates of the focus center.
* level: zoom level from 1 to 20.
*/
function set_zoom(center, level){
var view = map.getView();
console.log('Center ' + center);
console.log('Zoom level ' + level);
var width = document.getElementsByClassName('ol-unselectable')[0].offsetWidth;
console.log(Math.floor(width/256));
view.setCenter(ol.proj.fromLonLat(center));
view.setZoom(level);
}
/*
* Function for map initialization. This function create global variable 'map'
* which can be user for further interaction with map.
* Args:
* center: array with to point which will be map center
*/
function init_map(center){
// Create styles
styles = {
'point': new ol.style.Style({
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: 'rgba(60, 160, 10, 0.9)'
}),
stroke: new ol.style.Stroke({
color: '#555',
width: 1
})
})
}),
'route': new ol.style.Style({
stroke: new ol.style.Stroke({
width: 5,
color: 'rgba(100, 200, 50, 0.9)'
}),
})
};
// Create vector layear
vec_layer = new ol.layer.Vector({
source: new ol.source.Vector(),
rendererOptions: { zIndexing: true }
});
vec_layer.setStyle(styles);
// Create aerospace layer
aerospace_layer = new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'http://2.tile.maps.openaip.net/geowebcache/service/tms/1.0.0/openaip_basemap@EPSG%3A900913@png/{z}/{x}/{-y}.png'
})
});
aerospace_layer.setVisible(false);
// Create Map
map = new ol.Map({
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat(center),
zoom: 15,
minZoom: 2,
maxZoom: 19
}),
// Add layers
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'https://api.mapbox.com/styles/v1/mapbox/streets-v9/tiles/' +
'256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic25hc2hlIiwiYSI6ImRF' +
'WFVLLWcifQ.IcYEbFzFZGuPmMDAGfx4ew'
})
}),
aerospace_layer,
vec_layer
],
});
// Create popup and add overlay layer to the map
popup_element = document.getElementById('popup');
popup = new ol.Overlay({
element: popup_element,
positioning: 'bottom-center',
stopEvent: false,
offset: [-2, -8]
});
map.addOverlay(popup);
// Add listener to the map to react on the mouse click.
map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) {
return feature;
}
)
create_popup(feature, popup_element)
});
// Add keyboard listener. To allow user to manipulate with popup box with key
// arrows.
window.addEventListener("keydown", key_listener, false);
};
/*
* Gets address for the coordinates.
* Args:
* coords: array with to float numbers, latitude and longitude.
*/
function get_address(coords){
// Get response from API
coords = ol.proj.transform(coords, 'EPSG:3857', 'EPSG:4326');
lon = coords[0];
lat = coords[1];
load_file(
'http://open.mapquestapi.com/nominatim/v1/reverse.php?key=xKWXF' +
'zDoNFf4q9DbKXh6zPpfOkqAwb5A&format=json&lat=' + lat + '&lon=' +
lon,
function(data){
data = JSON.parse(data);
console.log(data['display_name'])
var element = document.getElementById('point_address');
if(element){
element.textContent = data['display_name'];
}
}
);
}
/*
* Loads route from address. As a response should be received GeoJSON object.
* Args:
* address: string representing address which should be requested for a data.
*/
function load_route(address){
load_file(address, add_route);
}
//=============================================================================
// Deprecated
//=============================================================================
// Call response function when loading is finished
function draw_map(response, center){
// Some initial information
var zoom = 15;
// var center = [14.398977756500244, 50.07859060687297];
var center = JSON.parse(center);
// Load data
var geojsonObject = JSON.parse(response);
console.log(response);
// var lineFeature = add_route(geojsonObject);
routeCoords = lineFeature.getGeometry().getCoordinates();
routeLength = routeCoords.length;
// Define styles for features
// Styles for points
var styles = {
'start_marker': new ol.style.Style({
// graphicZIndex: 100,
// zIndex: 100,
image: new ol.style.Circle({
radius: 7,
snapToPixel: false,
fill: new ol.style.Fill({color: '#13E821'}),
stroke: new ol.style.Stroke({
color: '#888', width: 2
})
})
}),
'end_marker': new ol.style.Style({
// graphicZIndex: 100,
// zIndex: 100,
image: new ol.style.Circle({
radius: 7,
snapToPixel: false,
fill: new ol.style.Fill({color: 'yellow'}),
stroke: new ol.style.Stroke({
color: '#888', width: 2
})
})
}),
'point': new ol.style.Style({
// graphicZIndex: 99,
// zIndex: 99,
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
//color: '#800',
color: 'rgba(60, 160, 10, 0.9)'
}),
stroke: new ol.style.Stroke({
color: '#555',
width: 1
})
})
}),
'line': new ol.style.Style({
stroke: new ol.style.Stroke({
width: 5,
color: 'rgba(100, 200, 50, 0.9)'
}),
})
};
// Create start and end marker
var startMarker = new ol.Feature({
type: 'start_marker',
geometry: new ol.geom.Point(routeCoords[0])
});
var endMarker = new ol.Feature({
type: 'end_marker',
geometry: new ol.geom.Point(routeCoords[routeLength - 1])
});
// Set styles
startMarker.setStyle(styles['start_marker']);
endMarker.setStyle(styles['end_marker']);
lineFeature.setStyle(styles['line']);
// Create vector layear
var vector_layer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [lineFeature, startMarker, endMarker]
}),
rendererOptions: { zIndexing: true }
});
// Array of points. Used for keyboard orientation on the map.
var points = Array();
// Create features
for(i = 0; i < routeCoords.length; i++){
var point = new ol.Feature({
geometry: new ol.geom.Point(routeCoords[i]),
type: 'point',
});
point.id = i
point.setStyle(styles['point']);
vector_layer.getSource().addFeature(point);
points.push(point);
}
// Create map
var map = new ol.Map({
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat(center),
zoom: zoom,
minZoom: 2,
maxZoom: 19
}),
// Add layers
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'https://api.mapbox.com/styles/v1/mapbox/streets-v9/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic25hc2hlIiwiYSI6ImRFWFVLLWcifQ.IcYEbFzFZGuPmMDAGfx4ew'
})
}),
vector_layer
],
});
// Load airspaces
load_file('../static/polygon.gml', function (response){
var airspaces_layer = new ol.layer.Vector({
source: new ol.source.Vector(),
style: new ol.style.Style({
strokeColor: '#bada55'
})
});
// console.log(response);
response = (new DOMParser()).parseFromString(response, 'text/xml');
var airspaces = new ol.format.WMSGetFeatureInfo().readFeatures(response);
console.log('Airspaces:');
console.log(airspaces);
console.log('Create airspaces layer.');
airspaces_layer.getSource().addFeatures(airspaces);
console.log('Adding airspaces layer to the map.');
map.addLayer(airspaces_layer);
});
var element = document.getElementById('popup');
var popup = new ol.Overlay({
element: element,
positioning: 'bottom-center',
stopEvent: false,
offset: [-2, -8]
});
map.addOverlay(popup);
function create_popup(feature, element){
if (feature && feature.get('type') == 'point') {
var coordinates = feature.getGeometry().getCoordinates();
console.log(coordinates);
get_address(coordinates);
popup.setPosition(coordinates);
var hdms = ol.coordinate.toStringHDMS(ol.proj.transform(
coordinates, 'EPSG:3857', 'EPSG:4326'));
content = '<p>Information:</p><code>' + hdms +
'</code>';
content = content + '<p id="hidden_id">' + feature.id + '</p>'
// Add coordinates to Point information table
var point_table = document.getElementById('point_coords');
point_table.innerHTML = '<code>' + hdms + '</code>';
$(element).popover({
'placement': 'top',
'html': true,
'content': function (){
return content;
}
});
$(element).popover('show');
} else {
$(element).popover('destroy');
}
}
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(e) {
// If popup already exists
if ($(element).data()['bs.popover'].tip().hasClass('in')){
// Get id from hidden HTML code
var id = parseInt(document.getElementById('hidden_id').innerText);
// Decide which key pressed
if (e.keyCode == 37){
console.log("Left " + id);
create_popup(points[id - 1], $(element))
} else if (e.keyCode == 39){
console.log("Right " + id);
create_popup(points[id + 1], $(element))
} else {
console.log("Upside-down");
}
}
}
// map.on('keydown', function(e){
//console.log(e.keyCode);
//});
// display popup on click
map.on('click', function(evt) {
// console.log(evt);
// var pos = evt.coordinate;
// var point = new ol.geom.Point(pos.lon, pos.lat);
// var closest = Math.min(vector_layer.getSource().getFeatures().map(
// function(feature) {
// console.log(feature.getGeometry().getClosestPoint(pos));
// return feature.getGeometry().getClosestPoint(point);
// }));
// var closest = lineFeature.getGeometry().getClosestPoint(pos);
// console.log(pos);
// console.log(closest);
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) {
return feature;
})
create_popup(feature, element)
});
};
|
'use strict';
const jsonParser = require('body-parser').json();
const debug = require('debug')('decor8:comment-router');
const fs = require('fs');
const path = require('path');
const del = require('del');
const AWS = require('aws-sdk');
const multer = require('multer');
const Router = require('express').Router;
const createError = require('http-errors');
const bearerAuth = require('../lib/bearer-auth-middleware.js');
const Comment = require('../model/comment.js');
const Post = require('../model/post.js');
AWS.config.setPromisesDependency(require('bluebird'));
const s3 = new AWS.S3();
const dataDir = `${__dirname}/../data`;
const upload = multer({ dest: dataDir });
const commentRouter = module.exports = Router();
function s3uploadProm(params) {
debug('s3uploadProm');
return new Promise((resolve, reject) => {
s3.upload(params, (err, s3data) => {
if (err) return reject(err);
resolve(s3data);
});
});
}
commentRouter.post('/api/post/:postId/comment', bearerAuth, upload.single('image'), jsonParser, function(req, res, next) {
debug('/api/post/:postId/comment');
if(!req.body.message) return next(createError(400, 'expected a message'));
let ext = path.extname(req.file.originalname);
let params = {
ACL: 'public-read',
Bucket: process.env.AWS_BUCKET,
Key: `${req.file.filename}${ext}`,
Body: fs.createReadStream(req.file.path)
};
Post.findById(req.params.postId)
.then(() => s3uploadProm(params))
.then(s3data => {
del([`${dataDir}/*`]);
let commentData = {
message: req.body.message,
objectKey: s3data.Key,
imageURI: s3data.Location,
userId: req.user._id,
postId: req.params.postId
};
return Post.findByIdAndAddComment(req.params.postId, commentData);
})
.then(comment => res.json(comment))
.catch(err => next(err));
});
commentRouter.get('/api/comment/:id', bearerAuth, function(req, res, next) {
debug('GET: api/comment/:id');
Comment.findById(req.params.id)
.then(comment => {
if ( comment.userId.toString() !== req.user._id.toString()){
return next(createError(401, 'invalid user'));
}
res.json(comment);
})
.catch(next);
});
commentRouter.put('/api/comment/:id', bearerAuth, jsonParser, function(req, res, next){
debug('PUT api/comment/:id');
if(!req.body.message) return next(createError(400, 'expected an message.'));
Comment.findByIdAndUpdate(req.params.id, req.body, { new: true })
.then( comment => {
res.json(comment);
})
.catch(next);
});
commentRouter.put('/api/comment/:id/upvote', bearerAuth, jsonParser, function(req, res, next) {
debug('PUT api/comment/:id/upvote');
if(!req.body.message) return next(createError(400, 'expected an message.'));
Comment.findById(req.params.id)
.then( comment => {
comment.upVote += 1;
comment.message = req.body.message;
return Comment.findByIdAndUpdate(req.params.id, comment, { new: true });
})
.then( comment => {
res.json(comment);
})
.catch(err => console.log(err));
});
commentRouter.delete('/api/post/:postId/comment/:id', bearerAuth, function(req, res, next) {
debug('DELETE api/comment/:id');
Post.findByIdAndRemoveComment(req.params.postId, req.params.id);
Comment.findByIdAndRemove(req.params.id)
.then( comment => {
if(!comment) return next(createError(404, 'comment not found'));
res.sendStatus(204);
})
.catch(next);
});
|
import {
fetchUser,
fetchUserOrgs,
fetchSearch,
fetchChangeFollowStatus,
fetchStarCount,
v3,
} from 'api';
import {
GET_USER,
GET_ORGS,
GET_IS_FOLLOWING,
GET_IS_FOLLOWER,
GET_REPOSITORIES,
GET_FOLLOWERS,
GET_FOLLOWING,
SEARCH_USER_REPOS,
CHANGE_FOLLOW_STATUS,
GET_STAR_COUNT,
} from './user.type';
const getUser = user => {
return (dispatch, getState) => {
const accessToken = getState().auth.accessToken;
dispatch({ type: GET_USER.PENDING });
return fetchUser(user, accessToken)
.then(data => {
dispatch({
type: GET_USER.SUCCESS,
payload: data,
});
})
.catch(error => {
dispatch({
type: GET_USER.ERROR,
payload: error,
});
});
};
};
const getOrgs = user => {
return (dispatch, getState) => {
const accessToken = getState().auth.accessToken;
dispatch({ type: GET_ORGS.PENDING });
return fetchUserOrgs(user, accessToken)
.then(data => {
dispatch({
type: GET_ORGS.SUCCESS,
payload: data,
});
})
.catch(error => {
dispatch({
type: GET_ORGS.ERROR,
payload: error,
});
});
};
};
const checkFollowStatusHelper = (user, followedUser, actionSet) => {
return (dispatch, getState) => {
const accessToken = getState().auth.accessToken;
dispatch({ type: actionSet.PENDING });
v3
.head(`/users/${user}/following/${followedUser}`, accessToken)
.then(data => {
dispatch({
type: actionSet.SUCCESS,
payload: data.status !== 404,
});
})
.catch(error => {
dispatch({
type: actionSet.ERROR,
payload: error,
});
});
};
};
export const getIsFollowing = (user, auth) => {
return dispatch => {
dispatch(checkFollowStatusHelper(auth, user, GET_IS_FOLLOWING));
};
};
export const getIsFollower = (user, auth) => {
return dispatch => {
dispatch(checkFollowStatusHelper(user, auth, GET_IS_FOLLOWER));
};
};
export const getFollowers = user => {
return (dispatch, getState) => {
const accessToken = getState().auth.accessToken;
dispatch({ type: GET_FOLLOWERS.PENDING });
v3
.getJson(`/users/${user.login}/followers?per_page=100`, accessToken)
.then(data => {
dispatch({
type: GET_FOLLOWERS.SUCCESS,
payload: data,
});
})
.catch(error => {
dispatch({
type: GET_FOLLOWERS.ERROR,
payload: error,
});
});
};
};
export const getUserInfo = user => {
return dispatch => {
Promise.all([dispatch(getUser(user)), dispatch(getOrgs(user))]);
};
};
export const getStarCount = user => {
return (dispatch, getState) => {
const accessToken = getState().auth.accessToken;
dispatch({ type: GET_STAR_COUNT.PENDING });
fetchStarCount(user, accessToken)
.then(data => {
dispatch({
type: GET_STAR_COUNT.SUCCESS,
payload: data,
});
})
.catch(error => {
dispatch({
type: GET_STAR_COUNT.ERROR,
payload: error,
});
});
};
};
export const changeFollowStatus = (user, isFollowing) => {
return (dispatch, getState) => {
const accessToken = getState().auth.accessToken;
const authUser = getState().auth.user.login;
dispatch({ type: CHANGE_FOLLOW_STATUS.PENDING });
fetchChangeFollowStatus(user, isFollowing, accessToken)
.then(() => {
dispatch({
type: CHANGE_FOLLOW_STATUS.SUCCESS,
changeTo: !isFollowing,
authUser,
});
})
.catch(error => {
dispatch({
type: CHANGE_FOLLOW_STATUS.ERROR,
payload: error,
});
});
};
};
export const getRepositories = user => {
return (dispatch, getState) => {
const { accessToken, user: authUser } = getState().auth;
const isAuthUser = user.login === authUser.login;
dispatch({ type: GET_REPOSITORIES.PENDING });
const url = isAuthUser
? '/user/repos?affiliation=owner&sort=updated&per_page=50'
: `/users/${user.login}/repos?sort=updated&per_page=50`;
v3
.getJson(url, accessToken)
.then(data => {
dispatch({
type: GET_REPOSITORIES.SUCCESS,
payload: data,
});
})
.catch(error => {
dispatch({
type: GET_REPOSITORIES.ERROR,
payload: error,
});
});
};
};
export const getFollowing = user => {
return (dispatch, getState) => {
const accessToken = getState().auth.accessToken;
dispatch({ type: GET_FOLLOWING.PENDING });
v3
.getJson(`/users/${user.login}/following?per_page=100`, accessToken)
.then(data => {
dispatch({
type: GET_FOLLOWING.SUCCESS,
payload: data,
});
})
.catch(error => {
dispatch({
type: GET_FOLLOWING.ERROR,
payload: error,
});
});
};
};
export const searchUserRepos = (query, user) => {
return (dispatch, getState) => {
const accessToken = getState().auth.accessToken;
dispatch({ type: SEARCH_USER_REPOS.PENDING });
return fetchSearch(
'repositories',
query,
accessToken,
`+user:${user.login}+fork:true`
)
.then(data => {
dispatch({
type: SEARCH_USER_REPOS.SUCCESS,
payload: data.items,
});
})
.catch(error => {
dispatch({
type: SEARCH_USER_REPOS.ERROR,
payload: error,
});
});
};
};
|
/**
* tangular
* @version v0.1.0 - 2014-03-20
* @link http://hall5714.github.io/tangular
* @author Justin Hall ()
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
'use strict';
angular.module('hall5714.tng', ['hall5714.tng.relative']);
|
import path from 'path';
export default function chrome() {
return {
get command() {
return path.resolve(__dirname, '../runners/chrome_runner');
},
output: 'stderr'
};
}
|
var app = angular.module("config", []);
/**
* Constants
*/
app.constant("config", {
appName: "IVE",
appSubname: "CMS",
appDevelopers: [{
name: "Nico Steffens",
github: "nsteffens"
}],
appGithub: "https://github.com/nsteffens/IVE",
appVersion: "v1.0",
appLanguage: 'en_US',
appYear: moment().format("YYYY"),
apiURL: "http://localhost:5000/api",
// apiURL: "http://f3e6c7de.ngrok.io/api",
imageFolder: '/images',
videoFolder: '/videos',
debugMode: true,
html5Mode: true,
creatorLogin: {
username: 'admin',
password: 'pass'
},
thumbnailFolder: '/thumbnails',
thumbnailSpeed: 50,
walkingSpeed: 1.42 // meters per second
});
|
'use strict';
const h = require('highland');
class Bounded {
constructor(input) {
this._input = input;
}
apply() {
return h.through(h(this._input.getStream()));
}
};
exports.from = (input) => {
return new Bounded(input);
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:a271e640e3b29b53e33fb8d011774f398b1b02c39882915edd2c365c2e87af90
size 1109
|
var assert = require("assert");
var roust = require(__dirname + '/../index.js');
describe('roust', function () {
it('should return -1 when the value is not present', function () {
var res = {
send: function (value) {
this.sent.push(value);
},
sent: []
};
assert(roust);
assert.equal(typeof(roust()), 'function');
roust()(null, res);
assert.equal(res.sent[0], 'hello world');
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.