commit stringlengths 40 40 | subject stringlengths 1 3.25k | old_file stringlengths 4 311 | new_file stringlengths 4 311 | old_contents stringlengths 0 26.3k | lang stringclasses 3
values | proba float64 0 1 | diff stringlengths 0 7.82k |
|---|---|---|---|---|---|---|---|
ace48d57e2db1ec33fd2f0599bc7161774db0ae2 | Fix flex-basis for checkbox | src/components/Checkbox/Checkbox.js | src/components/Checkbox/Checkbox.js | import React, {PropTypes, Component} from 'react'
import {colors, iconSizes} from '../../variables'
import {CheckIcon} from '../../icons'
const defaultContainerStyle = {
display: 'flex'
}
const defaultLabelStyle = {
display: 'block',
fontWeight: 600,
marginBottom: '0.5rem',
maxWidth: '100%'
}
const defaultCheckboxStyle = {
display: 'block',
backgroundColor: colors.white,
border: '1px solid',
boxSizing: 'border-box',
padding: '0.1rem',
borderRadius: '2px',
cursor: 'pointer',
borderColor: 'currentColor',
position: 'relative',
height: '1.8rem',
width: '1.8rem',
margin: '0.2rem 0 0 0',
fontSize: '0px', // fixes weird white-space issues
userSelect: 'none' // fixes text select on multi-click
}
const checkedStyle = {
color: colors.white,
backgroundColor: colors.pacificBlue,
borderColor: colors.pacificBlue
}
const disabledStyle = {
color: colors.white,
cursor: 'not-allowed',
borderColor: colors.silver
}
/**
* with label, description and hint
*/
class Checkbox extends Component {
constructor (props) {
super(props)
this.state = {}
// we need a state for this because it can be controlled or non-controlled
// i.e. - given a 'checked' or 'defaultChecked' (or both - 'checked' wins)
if (props.checked !== undefined) {
this.state.checked = props.checked
} else if (props.defaultChecked !== undefined) {
this.state.checked = props.defaultChecked
} else {
this.state.checked = false
}
}
componentWillReceiveProps (nextProps) {
if (nextProps.checked !== undefined) {
this.setState({checked: nextProps.checked})
}
}
render () {
const {error, warning, labelStyle, disabled, label, description, hint, style} = this.props
let computerContainerStyle = Object.assign({}, defaultContainerStyle, style)
let textColorStyle = Object.assign({},
warning ? {color: colors.goldenTainoi} : {},
error ? {color: colors.amaranth} : {}
)
let computedLabelStyle = Object.assign({}, defaultLabelStyle, labelStyle)
let computedHintStyle = Object.assign({}, textColorStyle)
let computedCheckboxStyle = Object.assign({},
defaultCheckboxStyle,
this.state.checked ? checkedStyle : {},
disabled ? disabledStyle : {},
this.state.checked && disabled ? {backgroundColor: colors.silver} : {}
)
return (
<div style={computerContainerStyle}>
<div style={{flex: '0 1 auto', marginRight: '0.7rem'}}>
<label
onClick={this._toggleCheckbox}
htmlFor={this.refs.checkboxInput}
style={computedCheckboxStyle}
>
{this.state.checked === true
? <CheckIcon style={{strokeWidth: '3.5px', width: '1.4rem', height: '1.4rem', verticalAlign: 'none'}} />
: null
}
<input
ref='checkboxInput'
style={{visibility: 'hidden', position: 'absolute', left: 0}}
type='checkbox'
disabled={disabled}
checked={this.state.checked}
onChange={this._onChange}
/>
</label>
</div>
<div style={{flex: '1 1 auto'}}>
{label
? <label style={computedLabelStyle}>{label}</label>
: null
}
{description
? <div style={{marginBottom: '0.5rem'}}>{description}</div>
: null
}
{hint
? <div style={computedHintStyle}>{hint}</div>
: null
}
</div>
</div>
)
}
_toggleCheckbox = (e) => {
e.preventDefault()
if (!this.props.disabled) {
this.setState(
{checked: !this.state.checked},
() => {
this.props.onChange(this.state.checked)
}
)
}
}
_onChange = (e) => {
// with a controlled input, react requires an onchange handler - do nothing
}
}
Checkbox.propTypes = {
checked: PropTypes.bool,
defaultChecked: PropTypes.bool,
disabled: PropTypes.bool,
error: PropTypes.bool,
hint: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
label: PropTypes.string,
labelStyle: PropTypes.object,
onChange: PropTypes.func.isRequired,
warning: PropTypes.bool
}
export default Checkbox
| JavaScript | 0.000005 | @@ -3186,21 +3186,16 @@
ex: '1 1
- auto
'%7D%7D%3E%0A
|
cda20c21456df5a2a1baf7e9285613a87674c0fc | Fix clone() | src/helpers/GridHelper.js | src/helpers/GridHelper.js | /**
* @author mrdoob / http://mrdoob.com/
*/
import { LineSegments } from '../objects/LineSegments.js';
import { VertexColors } from '../constants.js';
import { LineBasicMaterial } from '../materials/LineBasicMaterial.js';
import { Float32BufferAttribute } from '../core/BufferAttribute.js';
import { BufferGeometry } from '../core/BufferGeometry.js';
import { Color } from '../math/Color.js';
function GridHelper( size, divisions, color1, color2 ) {
size = size || 10;
divisions = divisions || 10;
color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
var center = divisions / 2;
var step = size / divisions;
var halfSize = size / 2;
var vertices = [], colors = [];
for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
vertices.push( - halfSize, 0, k, halfSize, 0, k );
vertices.push( k, 0, - halfSize, k, 0, halfSize );
var color = i === center ? color1 : color2;
color.toArray( colors, j ); j += 3;
color.toArray( colors, j ); j += 3;
color.toArray( colors, j ); j += 3;
color.toArray( colors, j ); j += 3;
}
var geometry = new BufferGeometry();
geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
var material = new LineBasicMaterial( { vertexColors: VertexColors } );
LineSegments.call( this, geometry, material );
}
GridHelper.prototype = Object.create( LineSegments.prototype );
GridHelper.prototype.constructor = GridHelper;
export { GridHelper };
| JavaScript | 0 | @@ -449,16 +449,115 @@
r2 ) %7B%0A%0A
+%09this.parameters = %7B%0A%09%09size: size,%0A%09%09divisions: divisions,%0A%09%09color1: color1,%0A%09%09color2: color2%0A%09%7D;%0A%0A
%09size =
@@ -1582,16 +1582,31 @@
totype =
+ Object.assign(
Object.
@@ -1641,55 +1641,351 @@
pe )
-;%0AGridHelper.prototype.constructor = GridHelper
+, %7B%0A%0A%09constructor: GridHelper,%0A%0A%09copy( source ) %7B%0A%0A%09%09LineSegments.prototype.copy.call( this, source );%0A%0A%09%09Object.assign( this.parameters, source.parameters );%0A%0A%09%09return this;%0A%0A%09%7D,%0A%0A%09clone() %7B%0A%0A%09%09var paramters = this.parameters;%0A%0A%09%09return new this.constructor( paramters.size, paramters.divisions, paramters.color1, paramters.color2 );%0A%0A%09%7D%0A%0A%7D )
;%0A%0Ae
|
47897abc3427b6a23b331435f5ed79231e4bc876 | validate on current value not last value | src/components/Form/Inputs/Input.js | src/components/Form/Inputs/Input.js | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import View from './InputView'
import Validators from './Validators'
export default class TextInput extends Component {
static propTypes = {
autocomplete: PropTypes.string,
defaultValue: PropTypes.string,
formId: PropTypes.string,
hidden: PropTypes.bool,
id: PropTypes.string,
label: PropTypes.string,
placeholder: PropTypes.string,
required: PropTypes.bool,
set: PropTypes.func,
store: PropTypes.object,
validator: PropTypes.string,
}
static defaultProps = {
validator: 'noEmpty',
}
state = {
error: null,
invalid: null,
serverError: null,
}
componentDidMount() {
this.validator = Validators[this.props.validator]
this.setValue(this.value || this.props.defaultValue || '')
}
componentWillReceiveProps(nextProps) {
const { store, formId } = nextProps
if (store[formId] && store[formId].error && store[formId].error.fields) {
this.parseErrors(store[formId].error.fields)
} else if (store[formId] && (this.state.error || this.state.serverError)) {
if (store[formId].submitted) {
this.setState({ error: null, serverError: null })
}
}
}
parseErrors(errors) {
const fieldError = errors.find(error => error.ID === this.props.id)
if (fieldError) this.setState({ serverError: fieldError.ErrorText })
}
get isInput() { return true }
onChange = (event) => {
const value = event.target.value
if (this.state.invalid) this.isValid()
this.setValue(value)
}
onBlur = (event) => {
this.isValid()
}
setValue(value) {
const { formId, id } = this.props
this.props.set(formId, id, value)
}
isValid = () => {
const { required } = this.props
if (required && !this.validator.regEx.test(this.value)) {
this.setState({ error: this.validator.error, serverError: null, invalid: true })
return false
} else {
this.setState({ error: null, serverError: null, invalid: false })
return true
}
}
get isDisabled() {
const { formId, store } = this.props
return store[formId] && (store[formId].fetching || store[formId].submitted)
}
get value() {
const { formId, store, id } = this.props
if (store[formId] && store[formId].fields[id]) {
return store[formId].fields[id]
} else {
return ''
}
}
get inputProps() {
return {
autoComplete: this.props.autocomplete,
disabled: this.isDisabled,
hidden: this.props.hidden,
id: this.props.id,
name: this.props.id,
onBlur: this.onBlur,
onChange: this.onChange,
placeholder: this.props.placeholder,
required: this.props.required,
value: this.value,
}
}
get label() {
let label = this.props.label
if (this.props.required) label += '*'
return label
}
get errorHTML() {
const error = this.state.error || this.state.serverError
return <span dangerouslySetInnerHTML={{ __html: ` (${error})` }} />
}
render() {
const { error, serverError } = this.state
return (
<View error={error || serverError} inputProps={this.inputProps}>
{this.label}
{(error || serverError) && this.errorHTML}
</View>
)
}
}
| JavaScript | 0.000005 | @@ -1547,24 +1547,29 @@
his.isValid(
+value
)%0A this.s
@@ -1750,16 +1750,21 @@
alid = (
+value
) =%3E %7B%0A
@@ -1845,16 +1845,25 @@
Ex.test(
+value %7C%7C
this.val
|
6c2775aad92b709958389b3144b48ca1f0d47f80 | Fix syntax errors made in previous commit | src/components/Header/HeaderView.js | src/components/Header/HeaderView.js | import classNames from 'classnames';
import React, { PropTypes } from 'react';
const HeaderView = ({
items,
githubLink,
onLabelClick
}) => (<div className="github-embed-nav">
{items.map(({ shown, label }, index) =>
<a
className={classNames({
'github-embed-nav-link': true,
'github-embed-nav-link-shown': shown
})}
key={index}
onClick={() => onLabelClick(index)}
>
{label}
</a>
)}
<a
className="github-embed-nav-on-github"
target="_blank"
rel="noopener noreferrer"
href={githubLink}
>
On Github
</div>
</nav>);
HeaderView.propTypes = {
items: PropTypes.arrayOf(PropTypes.shape({
label: PropTypes.string.isRequired,
shown: PropTypes.bool.isRequired
})),
onLabelClick: PropTypes.func.isRequired,
githubLink: PropTypes.string.isRequired
};
export default HeaderView;
| JavaScript | 0 | @@ -683,17 +683,15 @@
%3C/
-div
+a
%3E%0A%3C/
-na
+di
v%3E);
|
63634cab1ec749671899524c4d7b5f2d83679df0 | optimize brotli for text | src/http/compress-file.js | src/http/compress-file.js | const zlib = require('zlib');
module.exports = ({ req, res, realContentType, headers, data }) => {
const accept = req.headers['accept-encoding'] || '';
const supportGzip = /\bgzip\b/.test(accept);
const supportBrotli = /\bbr\b/.test(accept);
const shouldCompress =
(supportGzip || supportBrotli)
&& !/^image|^binary/i.test(realContentType) && headers.Size >= 200 // gzipping below this size can make files bigger
;
if (!shouldCompress) return false;
let compressor, contentEncoding;
if (supportBrotli) {
compressor = zlib.brotliCompress;
contentEncoding = 'br';
} else {
compressor = zlib.gzip;
contentEncoding = 'gzip';
}
compressor(data, function (err, compressBuffer) {
if (err) {
// if compression fails, log it and move on. no need to fail request
return void res.end(data);
}
res.setHeader('Content-Encoding', contentEncoding);
res.end(compressBuffer);
});
return true;
};
| JavaScript | 0.999999 | @@ -483,16 +483,32 @@
pressor,
+ compressorOpts,
content
@@ -606,16 +606,285 @@
= 'br';%0A
+ compressorOpts = %7B%0A chunkSize: 32 * 1024,%0A params: %7B%0A %5Bzlib.constants.BROTLI_PARAM_MODE%5D: zlib.constants.BROTLI_MODE_TEXT,%0A %5Bzlib.constants.BROTLI_PARAM_QUALITY%5D: 4,%0A %5Bzlib.constants.BROTLI_PARAM_SIZE_HINT%5D: data.length%0A %7D%0A %7D%0A
%7D else
@@ -944,16 +944,43 @@
'gzip';%0A
+ compressorOpts = null;%0A
%7D%0A co
@@ -993,16 +993,32 @@
or(data,
+ compressorOpts,
functio
|
f71c89b71e74bc942fb2eadb0351ac2c13120ed4 | Add ref for file upload dropZone | src/components/file-upload/index.js | src/components/file-upload/index.js | import { h, Component } from 'preact';
import Dropzone from 'react-dropzone';
import style from './style';
export default class FileUpload extends Component {
constructor(props) {
super(props);
this.state = {
isFileSelected: false,
file: false,
};
this.handleFileDrop = this.handleFileDrop.bind(this);
}
handleFileDrop(acceptedFiles, rejectedFiles) {
this.setState({
...this.state,
isFileSelected: true,
file: acceptedFiles[0],
});
this.props.confirmChooseFile(this.state.file);
}
render(props, state) {
return (
<div class={`${style['file-upload']} container`}>
<div class="offset-by-three one column">
<Dropzone
onDrop={this.handleFileDrop}
multiple={false}
class={style['file']}
className={style['file']}
accept=".stl"
>
<div class={style['file__text']}>Přidejte model ve formátu STL přetáhnutím souboru nebo kliknutím</div>
</Dropzone>
</div>
{/*<div class={`one column offset-by-two ${style['button']}`}>*/}
{/*<button class="button-primary disabled" disabled={!state.isFileSelected} onClick={this.handleAnalyzeButtonClick} type="button">Go to details</button>*/}
{/*</div>*/}
</div>
);
}
}
| JavaScript | 0 | @@ -195,16 +195,45 @@
rops);%0A%0A
+ this.dropzoneRef = null;%0A
this
@@ -905,16 +905,73 @@
=%22.stl%22%0A
+ ref=%7B(node) =%3E %7B this.dropzoneRef = node; %7D%7D%0A
|
f8f865e7678c1cd52518300dd4d0d5a801d582bc | Update Help Props So Popup Remains On-Screen | src/components/help/help.stories.js | src/components/help/help.stories.js | import React from 'react';
import { storiesOf } from '@storybook/react';
import { text, select } from '@storybook/addon-knobs';
import OptionsHelper from '../../utils/helpers/options-helper';
import notes from './notes.md';
import Help from './help';
storiesOf('Help', module)
.add('default', () => {
const children = text('children', 'This is help text');
const tooltipPosition = children ? select(
'tooltipPosition',
OptionsHelper.positions,
Help.defaultProps.tooltipPosition
) : undefined;
const tooltipAlign = children ? select(
'tooltipAlign',
OptionsHelper.alignAroundEdges,
Help.defaultProps.tooltipAlign
) : undefined;
const href = text('href', '');
return (
<Help
tooltipPosition={ tooltipPosition }
tooltipAlign={ tooltipAlign }
href={ href }
>
{children}
</Help>
);
}, {
notes: { markdown: notes }
});
| JavaScript | 0 | @@ -470,41 +470,15 @@
-Help.defaultProps.tooltipPosition
+'right'
%0A
|
38294f9ad271cbec65950b751bd113ede1cf096a | fix table header alignment | apps/app/src/components/Table.js | apps/app/src/components/Table.js | import * as React from "react";
import styled, { x } from "@xstyled/styled-components";
import { LinkBlock } from "./Link";
export const Table = (props) => (
<x.table w={1} borderCollapse="collapse" textAlign="left" {...props} />
);
export const Tr = (props) => (
<x.tr borderBottom={1} borderColor="border" {...props} />
);
export const Thead = styled.theadBox`
background-color: highlight-background;
tr {
border-bottom: 0;
}
`;
export const Tbody = (props) => <x.tbody {...props} />;
export const Th = styled.thBox`
padding: 2 4;
font-weight: 500;
&:first-of-type {
padding-left: 4;
}
&:last-of-type {
padding-right: 4;
}
`;
export const Td = styled.tdBox`
padding: 2;
font-weight: 500;
&:first-of-type {
padding-left: 4;
}
&:last-of-type {
padding-right: 4;
}
`;
export const TdLink = (props) => (
<x.a
as={LinkBlock}
display="flex"
py={4}
px={2}
border={1}
borderColor={{ _: "background", hover: "background-hover" }}
{...props}
/>
);
| JavaScript | 0.000074 | @@ -544,18 +544,16 @@
dding: 2
- 4
;%0A font
|
b31e16593b7b902daf8fe4a4662892e5934e1580 | add React Router | src/components/skills/MainSkills.js | src/components/skills/MainSkills.js | import React from 'react'
class MainSkills extends React.Component {
render () {
return (
<div>
<dl className="skill-list">
<dt className="category">Programmiersprachen /<br />Plattformen</dt>
<dd className="details">
<ul>
<li className="high">JavaScript (inkl. ES6) (8 Jahre)</li>
<li className="high">Node.js (3 Jahre)</li>
<li className="middle">Python (3 Jahre)</li>
<li className="middle">UNIX shell scripting (4 Jahre)</li>
<li className="low">Java (5 Jahre)</li>
<li className="low">PHP5 (3 Jahre)</li>
<li className="low">XSLT (5 Jahre)</li>
</ul>
</dd>
</dl>
<dl className="skill-list">
<dt className="category">Datenbanken</dt>
<dd className="details">
<ul className="row">
<li className="middle">Redis,</li>
<li className="middle">MongoDB,</li>
<li className="middle">MySQL,</li>
<li className="low">SQLite</li>
</ul>
</dd>
</dl>
<dl className="skill-list">
<dt className="category">Server</dt>
<dd className="details">
<ul className="row">
<li className="middle">nginx,</li>
<li className="low">Apache,</li>
<li className="low">Tomcat</li>
</ul>
</dd>
</dl>
<dl className="skill-list">
<dt className="category">Frameworks</dt>
<dd className="details">
<ul>
<li className="middle">qooxdoo (JavaScript - Core-Team Mitglied),</li>
<li className="middle">CherryPy (Python),</li>
<li className="middle">Flask (Python),</li>
<li className="middle">Django (Python),</li>
<li className="low">AngularJS 1 (JS),</li>
<li className="low">AngularJS 2 (JS),</li>
<li className="low">Pustefix (Java)</li>
<li className="low">Spring (Java)</li>
</ul>
</dd>
</dl>
<dl className="skill-list">
<dt className="category">Libraries</dt>
<dd className="details">
<ul className="row">
<li className="high">React,</li>
<li className="high">Redux,</li>
<li className="high">Relay</li>
</ul>
</dd>
</dl>
<style jsx>{`
`}</style>
</div>
)
}
}
export default MainSkills
| JavaScript | 0.000001 | @@ -2399,32 +2399,86 @@
gh%22%3ERedux,%3C/li%3E%0A
+ %3Cli className=%22high%22%3EReact Router,%3C/li%3E%0A
%3Cl
|
62b122f979e40abe9fcdc05999b360f8c92df1cb | Update ng-context-menu.js | src/ng-context-menu.js | src/ng-context-menu.js | /**
* ng-context-menu - v0.1.4 - An AngularJS directive to display a context menu when a right-click event is triggered
*
* @author Ian Kennington Walter (http://ianvonwalter.com)
*/
angular
.module('ng-context-menu', [])
.factory('ContextMenuService', function() {
return {
element: null,
menuElement: null
};
})
.directive('contextMenu', ['$document', 'ContextMenuService', function($document, ContextMenuService) {
return {
restrict: 'A',
scope: {
'callback': '&contextMenu',
'disabled': '&contextMenuDisabled'
},
link: function($scope, $element, $attrs) {
var opened = false;
function open(event, menuElement) {
menuElement.addClass('open');
var doc = $document[0].documentElement;
var docLeft = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0),
docTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0),
elementHeight = menuElement[0].scrollHeight;
var docHeight = doc.clientHeight + docTop,
totalHeight = elementHeight + event.pageY,
top = Math.max(event.pageY - docTop, 0);
if (totalHeight > docHeight) {
top = top - (totalHeight - docHeight);
}
menuElement.css('top', top + 'px');
menuElement.css('left', Math.max(event.pageX - docLeft, 0) + 'px');
opened = true;
}
function close(menuElement) {
menuElement.removeClass('open');
opened = false;
}
$element.bind('contextmenu', function(event) {
if (!$scope.disabled()) {
if (ContextMenuService.menuElement !== null) {
close(ContextMenuService.menuElement);
}
ContextMenuService.menuElement = angular.element(document.getElementById($attrs.target));
ContextMenuService.element = event.target;
console.log('set', ContextMenuService.element);
event.preventDefault();
event.stopPropagation();
$scope.$apply(function() {
$scope.callback({ $event: event });
open(event, ContextMenuService.menuElement);
});
}
});
function handleKeyUpEvent(event) {
//console.log('keyup');
if (!$scope.disabled() && opened && event.keyCode === 27) {
$scope.$apply(function() {
close(ContextMenuService.menuElement);
});
}
}
function handleClickEvent(event) {
if (!$scope.disabled() &&
opened &&
(event.button !== 2 || event.target !== ContextMenuService.element)) {
$scope.$apply(function() {
close(ContextMenuService.menuElement);
});
}
}
$document.bind('keyup', handleKeyUpEvent);
// Firefox treats a right-click as a click and a contextmenu event while other browsers
// just treat it as a contextmenu event
$document.bind('click', handleClickEvent);
$document.bind('contextmenu', handleClickEvent);
$scope.$on('$destroy', function() {
//console.log('destroy');
$document.unbind('keyup', handleKeyUpEvent);
$document.unbind('click', handleClickEvent);
$document.unbind('contextmenu', handleClickEvent);
});
}
};
}]); | JavaScript | 0 | @@ -1953,16 +1953,18 @@
+//
console.
@@ -3447,8 +3447,9 @@
;%0A %7D%5D);
+%0A
|
64e1b0ff9b61b5ac28ccb8d7d323b86101d74bd7 | fix bug about using es6 import | src/containers/Performance/index.js | src/containers/Performance/index.js | import React, { Component } from 'react';
import Helmet from 'react-helmet';
import Perf from 'react-addons-perf';
import { connect } from 'react-redux';
import * as articleActions from '../../actions/articleActions';
import * as performanceActions from '../../actions/performanceActions';
import Article from './Article';
export class Performance extends Component {
constructor(props) {
super(props);
this.state = {
idle: true
}
this.startPerf = this.startPerf.bind(this);
this.stopPerf = this.stopPerf.bind(this);
this.handleDeleteArticle = this.handleDeleteArticle.bind(this);
}
componentDidMount() {
this.props.getArticleLatest(500);
}
startPerf() {
this.setState({
idle: false
});
Perf.start();
}
stopPerf() {
this.setState({
idle: true
});
Perf.stop();
Perf.printOperations();
Perf.printWasted();
}
handleDeleteArticle(id) {
this.props.deleteArticle(id);
}
render() {
return (
<div>
<Helmet title="Performance Tool" />
<div className="col-xs-12">
<div className="row">
<div className="col-xs-12">
{ this.state.idle ? <button onClick={this.startPerf}>Start Recording</button> : <button onClick={this.stopPerf}>Stop and View Results</button> }
</div>
</div>
<div className="row">
{ this.props.articles.map((article, index) => {
return <Article key={ article.id } article={article} handleDeleteArticle={ this.handleDeleteArticle } />
}) }
</div>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
articles: state.articleLatest
}
}
export default connect(mapStateToProps, {...articleActions, ...performanceActions})(Performance); | JavaScript | 0 | @@ -1605,22 +1605,24 @@
%0A%7D%0A%0A
-export default
+module.exports =
con
|
e2fb49da71cba3462830513d777dcfe7ec362fd8 | fix ie9 Sky.startup ("Enhanced Support Across A Broad Diversity Of Customer Platform") | packages/startup/startup_client.js | packages/startup/startup_client.js | if (typeof Sky === "undefined") Sky = {};
(function() {
var queue = [];
var loaded = document.readyState === "loaded" ||
document.readyState == "complete";
var ready = function() {
loaded = true;
while (queue.length)
(queue.shift())();
};
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', ready, false);
window.addEventListener('load', ready, false);
} else {
document.attachEvent('onreadystatechange', function () {
if (document.readyState === "complete")
ready();
});
window.attachEvent('load', ready);
}
Sky.startup = function (cb) {
var doScroll = document.documentElement.doScroll;
if (!doScroll || window !== top) {
if (loaded)
cb();
else
queue.push(cb);
} else {
try { doScroll('left'); }
catch (e) {
setTimeout(function() { Sky.startup(cb); }, 50);
return;
};
cb();
}
};
})();
| JavaScript | 0 | @@ -649,16 +649,52 @@
Scroll =
+ !document.addEventListener &&%0A
documen
|
9d269914032336e81f7b2a3f15d202454902c238 | Add ObjectRoleModel.roleUsers for user/role mapping | src/objectRoleModel.js | src/objectRoleModel.js | import {BaseModel} from 'nxus-storage'
export default BaseModel.extend({
attributes: {
role: {
model: 'users-role'
},
object: {
model: 'subclass-must-define'
},
user: {
model: 'users-user'
}
}
})
| JavaScript | 0 | @@ -229,15 +229,337 @@
'%0A %7D%0A
+ %7D,%0A%0A roleUsers(object) %7B%0A return this.find(%7Bobject: object%7D).populate('role').populate('user').then((roles) =%3E %7B%0A let ret = %7B%7D%0A for (let r of roles) %7B%0A let name = r.role.role%0A if (!ret%5Bname%5D) %7B%0A ret%5Bname%5D = %5B%5D%0A %7D%0A ret%5Bname%5D.push(r.user)%0A %7D%0A return ret%0A %7D)%0A
%7D%0A%7D)%0A
|
d0940596360658a29215d99fba1ce348586a4c29 | update vote arrays on post document | app/imports/api/votesMethods.js | app/imports/api/votesMethods.js | import { Posts } from '/imports/collections/posts.js';
export const doVote = new ValidatedMethod({
name: 'Votes.methods.vote',
validate: new SimpleSchema({
postId: {
type: String,
},
voteValue: {
type: String,
},
}).validator(),
run({postId, voteValue}) {
console.log(voteValue);
}
});
| JavaScript | 0 | @@ -203,123 +203,1095 @@
-voteValue: %7B%0A type: String,%0A %7D,%0A %7D).validator(),%0A%0A run(%7BpostId, voteValue%7D) %7B%0A console.log(voteValue);
+fingerprint: %7B%0A type: String,%0A %7D,%0A voteValue: %7B%0A type: String,%0A %7D,%0A upVotes: %7B%0A type: %5BString%5D,%0A %7D,%0A downVotes: %7B%0A type: %5BString%5D,%0A %7D,%0A %7D).validator(),%0A%0A run(%7BpostId, fingerprint, voteValue, upVotes, downVotes%7D) %7B%0A const upVoted = upVotes.indexOf( fingerprint ) %3E -1 ? true : false;%0A const downVoted = downVotes.indexOf( fingerprint ) %3E -1 ? true : false;%0A%0A if (upVoted) %7B%0A Posts.update(%7B_id: postId%7D, %7B $pull: %7B upVotes: fingerprint %7D %7D );%0A%0A if (voteValue === 'down') %7B%0A Posts.update(%7B_id: postId%7D, %7B $push: %7B downVotes: fingerprint %7D %7D );%0A %7D%0A %7D else if (downVoted)%7B%0A Posts.update(%7B_id: postId%7D, %7B $pull: %7B downVotes: fingerprint %7D %7D );%0A%0A if (voteValue === 'up') %7B%0A Posts.update(%7B_id: postId%7D, %7B $push: %7B upVotes: fingerprint %7D %7D );%0A %7D%0A %7D else %7B%0A if (voteValue === 'up') %7B%0A Posts.update(%7B_id: postId%7D, %7B $push: %7B upVotes: fingerprint %7D %7D );%0A %7D else if (voteValue === 'down') %7B%0A Posts.update(%7B_id: postId%7D, %7B $push: %7B downVotes: fingerprint %7D %7D );%0A %7D%0A %7D
%0A %7D
|
344b5f45a1370d45dd59ab4edba72634ba54aee7 | Remove unnecessary trace | app/js/controllers/searchbox.js | app/js/controllers/searchbox.js | var searchCtrl = function ($scope, $http, $location) {
$scope.results = [];
$scope.moreCount = 0;
$scope.$watch('searchTarget', function(newValue) {
if (newValue && newValue.length > 0) {
console.log(newValue);
$http.get('api/search?q=' + newValue).success(function (data) {
$scope.results = data.results;
$scope.moreCount = data.moreCount;
$scope.errorClass = $scope.results.length === 0 ? "error" : "";
}).error(function () {
console.log("an error happened");
});
} else {
$scope.errorClass = "";
$scope.results = [];
}
},true);
$scope.$on("$routeChangeStart", function (event, next) {
$scope.searchTarget = '';
});
};
| JavaScript | 0.00016 | @@ -207,43 +207,8 @@
) %7B%0A
- console.log(newValue);%0A
@@ -525,25 +525,29 @@
og(%22
-an e
+E
rror
-happened
+in searchbox.js
%22);%0A
|
eb4cc657500fc5f642ed5147a65f4ffc31cb5d82 | Fix issue with .val() returning back the placeholder value. | src/jquery.placeholder.js | src/jquery.placeholder.js | (function ($) {
"use strict";
$.extend({
placeholder: {
settings: {
focusClass: 'placeholderFocus',
activeClass: 'placeholder',
overrideSupport: false,
preventRefreshIssues: true
}
}
});
// check browser support for placeholder
$.support.placeholder = 'placeholder' in document.createElement('input');
// Replace the val function to never return placeholders
$.fn.plVal = $.fn.val;
$.fn.val = function (value) {
if (typeof value === 'undefined') {
return $.fn.plVal.call(this);
} else {
var el = $(this[0]);
var currentValue = el.plVal();
var returnValue = $(this).plVal(value);
if (el.hasClass($.placeholder.settings.activeClass) && currentValue === el.attr('placeholder')) {
el.removeClass($.placeholder.settings.activeClass);
return returnValue;
}
if (el.hasClass($.placeholder.settings.activeClass) && el.plVal() === el.attr('placeholder')) {
return '';
}
return $.fn.plVal.call(this, value);
}
};
// Clear placeholder values upon page reload
$(window).bind('beforeunload.placeholder', function () {
var els = $('input.' + $.placeholder.settings.activeClass);
if (els.length > 0) {
els.val('').attr('autocomplete', 'off');
}
});
// plugin code
$.fn.placeholder = function (opts) {
opts = $.extend({}, $.placeholder.settings, opts);
// we don't have to do anything if the browser supports placeholder
if (!opts.overrideSupport && $.support.placeholder) {
return this;
}
return this.each(function () {
var $el = $(this);
// skip if we do not have the placeholder attribute
if (!$el.is('[placeholder]')) {
return;
}
// we cannot do password fields, but supported browsers can
if ($el.is(':password')) {
return;
}
// Prevent values from being reapplied on refresh
if (opts.preventRefreshIssues) {
$el.attr('autocomplete', 'off');
}
$el.bind('focus.placeholder', function () {
var $el = $(this);
if (this.value === $el.attr('placeholder') && $el.hasClass(opts.activeClass)) {
$el.val('').removeClass(opts.activeClass).addClass(opts.focusClass);
}
});
$el.bind('blur.placeholder', function () {
var $el = $(this);
$el.removeClass(opts.focusClass);
if (this.value === '') {
$el.val($el.attr('placeholder')).addClass(opts.activeClass);
}
});
$el.triggerHandler('blur');
// Prevent incorrect form values being posted
$el.parents('form').submit(function () {
$el.triggerHandler('focus.placeholder');
});
});
};
}(jQuery)); | JavaScript | 0.000845 | @@ -1,16 +1,172 @@
+/*! jQuery Placeholder Plugin - v0.7.0 - 2012-12-03%0A* http://andrew-jones.com/jquery-placeholder-plugin%0A* Copyright (c) 2012 Andrew Jones; Licensed MIT */%0A%0A
(function ($) %7B%0A
@@ -629,24 +629,38 @@
n (value) %7B%0A
+ var el;%0A
if (type
@@ -683,24 +683,178 @@
defined') %7B%0A
+ el = $(this%5B0%5D);%0A%0A if (el.hasClass($.placeholder.settings.activeClass) && el.plVal() === el.attr('placeholder')) %7B%0A return '';%0A %7D%0A%0A
return
@@ -896,20 +896,16 @@
%7B%0A
-var
el = $(t
@@ -1152,32 +1152,32 @@
s.activeClass);%0A
+
return r
@@ -1201,138 +1201,8 @@
%7D%0A%0A
- if (el.hasClass($.placeholder.settings.activeClass) && el.plVal() === el.attr('placeholder')) %7B%0A return '';%0A %7D%0A%0A
|
8adc44fd3aa11333c1daaa6048372e52f6fae467 | Use oneOf for hover style props | src/js/components/Tile.js | src/js/components/Tile.js | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import Props from '../utils/Props';
import Box from './Box';
const CLASS_ROOT = "tile";
export default class Tile extends Component {
render () {
const { children, className, onClick, wide, status, selected, hoverStyle, hoverColorIndex, hoverBorder } = this.props;
if (selected) {
console.log('Selected option has been deprecated, please use selected option at the Tiles level.');
}
const statusClass = status ? status.toLowerCase() : undefined;
const classes = classnames(
CLASS_ROOT,
className,
{
[`${CLASS_ROOT}--status-${statusClass}`]: status,
[`${CLASS_ROOT}--wide`]: wide,
[`${CLASS_ROOT}--selectable`]: onClick,
[`${CLASS_ROOT}--selected`]: selected,
[`hover-color-index-${hoverColorIndex}--${hoverStyle}${(hoverStyle == 'border') ? ((hoverBorder) ? '-large' : '-small') : ''}`]: hoverStyle
}
);
const boxProps = Props.pick(this.props, Object.keys(Box.propTypes));
return (
<Box {...boxProps} className={classes}>
{children}
</Box>
);
}
}
Tile.propTypes = {
selected: PropTypes.bool,
wide: PropTypes.bool,
hoverStyle: PropTypes.string,
hoverColorIndex: PropTypes.string,
...Box.propTypes
};
Tile.defaultProps = {
pad: 'none',
direction: 'column',
align: 'center',
hoverStyle: 'background',
hoverColorIndex: 'disabled'
};
| JavaScript | 0 | @@ -1331,30 +1331,55 @@
: PropTypes.
-string
+oneOf(%5B'border', 'background'%5D)
,%0A hoverCol
|
c8fae8c411e6f29e43eec5194a4e3a0c9a24889b | add on_files_page function | app/assets/javascripts/pages.js | app/assets/javascripts/pages.js | // on messaging page?
var on_messaging_page = function() {
var on_page = false;
if ($("#messaging_page").length > 0) {
on_page = true;
}
return on_page;
};
// on edit profile page?
var on_profile_page = function() {
var on_page = false;
if ($("#edit_profile_page").length > 0) {
on_page = true;
}
return on_page;
};
// on transcripts page?
var on_transcripts_page = function() {
var on_page = false;
if ($("#transcripts_page").length > 0) {
on_page = true;
}
return on_page;
};
// on transcript page?
var on_transcript_page = function() {
var on_page = false;
if ($("#transcript_page").length > 0) {
on_page = true;
}
return on_page;
};
// on new transcript page?
var on_new_transcript_page = function() {
var on_page = false;
if ($("#new_transcript_page").length > 0) {
on_page = true;
}
return on_page;
};
// on new manage users page?
var on_manage_users_page = function() {
var on_page = false;
if ($("#manage_users_page").length > 0) {
on_page = true;
}
return on_page;
};
var signed_in = function() {
var signed_in = false;
if (on_messaging_page() ||
on_profile_page() ||
on_transcript_page() ||
on_transcripts_page() ||
on_new_transcript_page() ||
on_manage_users_page()) {
signed_in = true;
}
return signed_in;
};
| JavaScript | 0.000002 | @@ -1051,16 +1051,185 @@
e; %0A%7D;%0A%0A
+// on new manage users page?%0Avar on_files_page = function() %7B%0A var on_page = false;%0A if ($(%22#files_page%22).length %3E 0) %7B%0A on_page = true;%0A %7D%0A return on_page; %0A%7D;%0A%0A
var sign
|
48a26e718fc1c79f21ede4f1b218702b276a96b8 | fix typo | commands/pushall.js | commands/pushall.js | var async = require('async');
var exec = require('child_process').exec;
/*
* this command is called pushall as there is a weird Node bug when calling the command 'push' - try bosco push to see.
*/
module.exports = {
name: 'pushall',
description: 'Will push any changes across all repos - useful for batch updates, typicall used after bosco commit',
usage: '[-r <repoPattern>]',
};
function confirm(bosco, message, next) {
bosco.prompt.start();
bosco.prompt.get({
properties: {
confirm: {
description: message,
},
},
}, function(err, result) {
if (!result) return next({message: 'Did not confirm'});
if (result.confirm === 'Y' || result.confirm === 'y') {
next(null, true);
} else {
next(null, false);
}
});
}
function countCommitsAhead(bosco, orgPath, next) {
exec('git log origin/master..master | xargs cat | wc -l', {
cwd: orgPath,
}, function(err, stdout, stderr) {
if (err) {
bosco.error(orgPath.blue + ' >> ' + stderr);
} else {
if (stdout) return next(null, parseInt(stdout, 10));
}
next(err, 0);
});
}
function push(bosco, orgPath, repo, next) {
if (!bosco.exists([orgPath, '.git'].join('/'))) {
bosco.warn('Doesn\'t seem to be a git repo: ' + orgPath.blue);
return next();
}
countCommitsAhead(bosco, orgPath, function(err, commitsAhead) {
if (err) return next(err);
if (!commitsAhead) {
bosco.log('Nothing to push for ' + repo.blue);
return next();
}
confirm(bosco, 'Confirm you want to push: ' + orgPath.blue + ' [y/N]', function(err, confirmed) {
if (err) return next(err);
if (!confirmed) {
bosco.log('Not pushing ' + repo.blue);
return next();
}
exec('git push origin master', {
cwd: orgPath,
}, function(err, stdout, stderr) {
if (err) {
bosco.error(orgPath.blue + ' >> ' + stderr);
} else {
if (stdout) bosco.log(orgPath.blue + ' >> ' + stdout);
}
next(err);
});
});
});
}
function cmd(bosco) {
var repos = bosco.getRepos();
if (!repos) return bosco.error('You are repo-less :( You need to initialise bosco first, try \'bosco clone\'.');
var regex = bosco.options.repo;
bosco.log('Running git push across all repos that match ' + regex + '...');
function pushRepos(cb) {
async.mapSeries(repos, function repoPush(repo, repoCb) {
var repoPath = bosco.getRepoPath(repo);
if (repo.match(regex)) {
bosco.log('Running git push on ' + repo.blue);
push(bosco, repoPath, repo, repoCb);
} else {
repoCb();
}
}, function() {
cb();
});
}
pushRepos(function() {
bosco.log('Complete');
});
}
module.exports.cmd = cmd;
| JavaScript | 0.999991 | @@ -323,16 +323,17 @@
typicall
+y
used af
|
f14c029c211db032caa369815d42ff9d5da5a3eb | Fix catalog issue | app/catalog-tab/launch/route.js | app/catalog-tab/launch/route.js | import EmberObject from '@ember/object';
import { hash } from 'rsvp';
import { inject as service } from '@ember/service';
import Route from '@ember/routing/route';
import { get/* , set */ } from '@ember/object';
export default Route.extend({
modalService: service('modal'),
catalog: service(),
scope: service(),
clusterStore: service(),
parentRoute: 'catalog-tab',
actions: {
cancel() {
get(this, 'modalService').toggleModal();
},
},
model: function(params/*, transition*/) {
var store = get(this, 'store');
var clusterStore = get(this, 'clusterStore');
var dependencies = {
tpl: get(this, 'catalog').fetchTemplate(params.template),
namespaces: clusterStore.findAll('namespace')
};
if ( params.upgrade )
{
dependencies.upgrade = get(this, 'catalog').fetchTemplate(`${params.template}-${params.upgrade}`, true);
}
if (params.appId) {
dependencies.app = store.find('app', params.appId);
}
if ( params.namespaceId )
{
dependencies.namespace = clusterStore.find('namespace', params.namespaceId);
}
return hash(dependencies, 'Load dependencies').then((results) => {
if ( !results.namespace )
{
let neuNSN = results.tpl.get('displayName');
let dupe = results.namespaces.findBy('id', neuNSN);
if ( dupe ) {
neuNSN = `${get(dupe, 'displayName')}-${Math.random().toString(36).substring(7)}`; // generate a random 5 char string for the dupename
}
results.namespace = clusterStore.createRecord({
type: 'namespace',
name: neuNSN,
projectId: this.modelFor('authenticated.project').get('project.id'),
});
}
let templateBase = this.modelFor(get(this, 'parentRoute')).get('templateBase');
let kind = templateBase === 'kubernetes' ? 'helm' : 'native';
let neuApp = null;
var links;
links = results.tpl.versionLinks;
var verArr = Object.keys(links).filter((key) => {
// Filter out empty values for rancher/rancher#5494
return !!links[key];
}).map((key) => {
return {version: key, sortVersion: key, link: links[key]};
});
if ( results.upgrade )
{
verArr.unshift({
sortVersion: results.upgrade.version,
version: results.upgrade.version + ' (current)',
link: results.upgrade.links.self
});
}
if (results.app) {
neuApp = results.app;
} else {
neuApp = store.createRecord({
type: 'app',
name: results.namespace.name,
});
}
return EmberObject.create({
allTemplates: this.modelFor(get(this, 'parentRoute')).get('catalog'),
catalogApp: neuApp,
namespace: results.namespace,
templateBase: templateBase,
tpl: results.tpl,
tplKind: kind,
upgradeTemplate: results.upgrade,
versionLinks: links,
versionsArray: verArr,
});
});
},
setupController(controller, model) {
this._super(controller, model);
if (model.upgradeTemplate) {
controller.set('showName', false);
}
},
resetController: function (controller, isExiting/*, transition*/) {
if (isExiting)
{
controller.set('namespaceId', null);
controller.set('upgrade', null);
controller.set('catalog', null);
controller.set('namespaceId', null);
}
}
});
| JavaScript | 0.000001 | @@ -173,19 +173,13 @@
get
-/*
, set
- */
%7D f
@@ -2210,25 +2210,24 @@
if (
-
results.
upgrade
@@ -2222,155 +2222,118 @@
lts.
-upgrade )%0A %7B%0A verArr.unshift(%7B%0A sortVersion: results.upgrade.version,%0A version: results.upgrade.version + ' (current)
+app) %7B%0A neuApp = results.app;%0A %7D else %7B%0A neuApp = store.createRecord(%7B%0A type: 'app
',%0A
@@ -2341,20 +2341,20 @@
-link
+name
: result
@@ -2359,26 +2359,23 @@
lts.
-upgrade.links.self
+namespace.name,
%0A
@@ -2398,35 +2398,35 @@
%0A%0A if (
-results.app
+ neuApp.id
) %7B%0A
@@ -2429,146 +2429,175 @@
-neuApp = results.app;%0A %7D else %7B%0A neuApp = store.createRecord(%7B%0A type: 'app',%0A name: results.namespace.name,%0A
+verArr.filter(ver =%3E ver.version === get(neuApp, 'externalIdInfo.version'))%0A .forEach(ver =%3E %7B%0A set(ver, 'version', %60$%7Bver.version%7D (current)%60);%0A
@@ -2594,33 +2594,32 @@
%60);%0A %7D)
-;
%0A %7D%0A%0A
|
61d6047a9fdad4e8978a17e5cf958b4f426716c5 | Add test messages for gender | app/models/user.server.model.js | app/models/user.server.model.js | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
crypto = require('crypto');
/**
* A Validation function for local strategy properties
*/
var validateLocalStrategyProperty = function(property) {
return ((this.provider !== 'local' && !this.updated) || property.length);
};
var validateMaxLength = function(property) {
if (this.provider !== 'local')
return false;
if (property.length >= 51)
return false;
if (property.length <= 0)
return false;
return true;
};
var validateGender = function(gender) {
if (gender === 'male' || gender === 'female') {
return true;
}
return false;
};
/**
* A Validation function for local strategy password
*/
var validateLocalStrategyPassword = function(password) {
return (this.provider !== 'local' || (password && password.length > 6 && password.length < 51));
};
var validateBirthday = function(birthday) {
var age = (new Date().getYear()) - birthday.getYear();
return (this.provider !== 'local' || age > 18);
};
var validateUsername = function(username) {
if (this.provider !== 'local')
return false;
else if (username.length <= 0)
return false;
else if (username.length >= 51)
return false;
else if (!username.match(/^[A-Za-z0-9_]+$/))
return false;
return true;
};
/**
* User Schema
*/
var UserSchema = new Schema({
firstName: {
type: String,
trim: true,
default: '',
validate: [validateMaxLength, 'Please fill in your first name and it should not be longer than 50 characters.']
},
lastName: {
type: String,
trim: true,
default: '',
validate: [validateMaxLength, 'Please fill in your last name and it should not be longer than 50 characters.']
},
gender: {
type: [{
type: String,
enum: ['male', 'female']
}],
validate: [validateGender, 'Please input your gender.']
},
salutation: {
type: String,
default: '',
validate: [validateLocalStrategyProperty, 'Please input your salutation.']
},
birthday: {
type: Date,
trim: true,
validate: [validateBirthday, 'Only ages 18 and older are allowed to register.']
},
// email: {
// type: String,
// trim: true,
// default: '',
// validate: [validateLocalStrategyProperty, 'Please fill in your email'],
// match: [/.+\@.+\..+/, 'Please fill a valid email address']
// },
username: {
type: String,
unique: 'testing error message',
required: 'Please fill in a username',
trim: true,
validate: [validateUsername, 'Your username is either existing or longer than 50 characters. Should also be alphanumeric.']
},
password: {
type: String,
default: '',
validate: [validateLocalStrategyPassword, 'Password should be more than 6 characters and not longer than 50 characters.']
},
description: {
type: String,
default: ''
},
salt: {
type: String
},
provider: {
type: String,
required: 'Provider is required'
},
providerData: {},
additionalProvidersData: {},
roles: {
type: [{
type: String,
enum: ['user', 'admin']
}],
default: ['user']
},
updated: {
type: Date
},
created: {
type: Date,
default: Date.now
},
/* For reset password */
resetPasswordToken: {
type: String
},
resetPasswordExpires: {
type: Date
}
});
/**
* Hook a pre save method to hash the password
*/
UserSchema.pre('save', function(next) {
if (this.password && this.password.length > 6) {
this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
this.password = this.hashPassword(this.password);
}
next();
});
/**
* Create instance method for hashing a password
*/
UserSchema.methods.hashPassword = function(password) {
if (this.salt && password) {
return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
} else {
return password;
}
};
/**
* Create instance method for authenticating user
*/
UserSchema.methods.authenticate = function(password) {
return this.password === this.hashPassword(password);
};
/**
* Find possible not used username
*/
UserSchema.statics.findUniqueUsername = function(username, suffix, callback) {
var _this = this;
var possibleUsername = username + (suffix || '');
_this.findOne({
username: possibleUsername
}, function(err, user) {
if (!err) {
if (!user) {
callback(possibleUsername);
} else {
return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
}
} else {
callback(null);
}
});
};
mongoose.model('User', UserSchema); | JavaScript | 0.000039 | @@ -568,24 +568,46 @@
n(gender) %7B%0A
+%09console.log(gender);%0A
%09if (gender
@@ -639,24 +639,58 @@
'female') %7B%0A
+%09%09console.log('test: ' + gender);%0A
%09%09return tru
|
4d705da1c13434363693d22435efb0ac993d191a | fix wine list html strucuture | app/client/js/views/wineview.js | app/client/js/views/wineview.js | /* global Marionette, Handlebars */
/**
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License,version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
var Weinstein = Weinstein || {};
(function (Weinstein, Marionette, Handlebars) {
'use strict';
Weinstein.Views = Weinstein.Views || {};
var WINE_TABLE_TEMPLATE = '' +
'<table class="table table-striped table-condensed">' +
' <thead>' +
' <tr>' +
' <th class="text-center">Dateinummer</th>' +
' <th>Betrieb</th>' +
' <th>Verein</th>' +
' <th>Marke</th>' +
' <th>Sorte</th>' +
' <th>Jahr</th>' +
' <th class="text-center">Qualität</th>' +
' <th class="text-center">Alk.</th>' +
' <th class="text-center">Alk. ges.</th>' +
' <th class="text-center">Zucker</th>' +
' {{#if show_rating1 }}<th class="text-center">1. Bewertung</th>{{/if}}' +
' {{#if show_rating2 }}<th class="text-center">2. Bewertung</th>{{/if}}' +
' {{#if show_kdb }}<th class="text-center">KdB</th>{{/if}}' +
' {{#if show_excluded }}<th class="text-center">Ex</th>{{/if}}' +
' {{#if show_sosi }}<th class="text-center">SoSi</th>{{/if}}' +
' {{#if show_chosen }}<th class="text-center">Ausschank</th>{{/if}}' +
' {{#if show_edit_wine}}<th></th>{{/if}}' +
' {{#if show_enrollment_pdf_export}}' +
' <th class="text-center">Formular</th>' +
' {{/if}}' +
' </tr>' +
' </thead>' +
' <tbody id="wine_list">' +
' </tbody>' +
'</table>';
var WINE_TEMPLATE = '' +
'<td class="text-center">{{#if nr}}<a href="/wines/{{id}}">{{nr}}</a>{{else}}-{{/if}}</td>' +
'<td><a href="/settings/applicant/{{applicant.id}}">{{applicant.label}} {{applicant.lastname}}</a></td>' +
'<td><a href="/settings/association/{{applicant.association.id}}">{{applicant.association.name}}</a></td>' +
'<td>{{ label }}</td>' +
'<td><{{ winesort.name }}</td>' +
'<td>{{ vintage }}</td>' +
'<td class="text-center">' +
' {{#if winequality}}{{ winequality.abbr }}{{else}}-{{/if}}' +
'</td>' +
'<td class="text-center">{{ l10nFloat alcohol }}</td>' +
'<td class="text-center">{{#if alcoholtot}}{{ l10nFloat alcoholtot }}{{else}}-{{/if}}</td>' +
'<td class="text-center">{{ l10nFloat sugar }}</td>' +
'{{#if show_rating1 }}<td class="text-center">{{#if rating1}}{{ l10nFloat rating1 }}{{else}}-{{/if}}</td>{{/if}}' +
'{{#if show_rating2 }}<td class="text-center">{{#if rating2}}{{ l10nFloat rating2 }}{{else}}-{{/if}}</td>{{/if}}' +
'{{#if show_kdb }}<td class="text-center">' +
' {{#if kdb}}' +
' <span class="glyphicon glyphicon-ok"></span>' +
' {{else}}' +
' -' +
' {{/if}}' +
'</td>{{/if}}' +
'{{#if show_excluded }}<td class="text-center">' +
' {{#if excluded}}' +
' <span class="glyphicon glyphicon-ok"></span>' +
' {{else}}' +
' -' +
' {{/if}}' +
'</td>{{/if}}' +
'{{#if show_sosi }}<td class="text-center">' +
' {{#if sosi}}' +
' <span class="glyphicon glyphicon-ok"></span>' +
' {{else}}' +
' -' +
' {{/if}}' +
'</td>{{/if}}' +
'{{#if show_chosen }}<td class="text-center">' +
' {{#if chosen}}' +
' <span class="glyphicon glyphicon-ok"></span>' +
' {{else}}' +
' -' +
' {{/if}}' +
'</td>{{/if}}' +
'{{#if show_edit_wine }}<td>|</td>{{/if}}' +
'{{#if show_enrollment_pdf_export}}' +
'<td class="text-center">' +
' ' +
'</td>' +
'{{/if}}';
var WineView = Marionette.View.extend({
tagName: 'tr',
template: Handlebars.compile(WINE_TEMPLATE),
_tableOptions: {},
initialize: function (options) {
this._tableOptions = options.tableOptions;
},
viewContext: function () {
return this._tableOptions;
}
});
var WineListView = Marionette.CollectionView.extend({
tagName: 'tbody',
childView: WineView,
_tableOptions: {},
initialize: function (options) {
this._tableOptions = options.tableOptions;
},
childViewOptions: function () {
return {
tableOptions: this._tableOptions
};
}
});
var WineView = Marionette.CompositeView.extend({
template: Handlebars.compile(WINE_TABLE_TEMPLATE),
_wines: null,
_tableOptions: {},
/**
* @param {object} options
*/
initialize: function (options) {
this._wines = options.wines;
this._tableOptions = options.tableOptions;
},
viewContext: function () {
return this._tableOptions;
},
onRender: function () {
var listView = new WineListView({
el: this.$('#wine_list'),
collection: this._wines,
tableOptions: this._tableOptions
});
listView.render();
}
});
Weinstein.Views.WineView = WineView;
})(Weinstein, Marionette, Handlebars);
| JavaScript | 0.000013 | @@ -2416,17 +2416,16 @@
%0A%09%09'%3Ctd%3E
-%3C
%7B%7B wines
|
287f23cfc681a1ef122cbd5b23390375cec0784e | Add comment | app/modules/common.factories.js | app/modules/common.factories.js | (function() {
'use strict';
angular.module('common.factories', [])
/**
* Clone Object
*
* @param {array|object} will be clone
* @return {array|object} cloned
*/
.factory('objectUtilities', [function() {
var cloneObject = function(object) {
return JSON.parse(JSON.stringify(object));
}
var isArrayEmpty = function(array) {
if ( ! array || array.length <= 0) {
return true;
} else {
return false;
}
}
return {
'cloneObject': cloneObject,
'isArrayEmpty': isArrayEmpty
}
}]);
})(); | JavaScript | 0 | @@ -79,16 +79,174 @@
*%0A *
+ Object utilities%0A *%0A * Useful object's function for handling object %0A *%0A */%0A .factory('objectUtilities', %5Bfunction() %7B%0A%0A /**%0A *
Clone O
@@ -252,26 +252,30 @@
Object%0A
-*%0A
+ *%0A
* @para
@@ -306,16 +306,18 @@
e clone%0A
+
* @
@@ -354,57 +354,13 @@
+
*/%0A
- .factory('objectUtilities', %5Bfunction() %7B%0A
@@ -452,24 +452,185 @@
t));%0A %7D
+%0A%0A /**%0A * Check array empty%0A *%0A * @param %7Barray%7D %0A * @return %7Bboolean%7D array is empty --%3E true, array not empty --%3E false%0A */
%0A var i
|
3cc108e5008c69166c9fc4ad56c90ccb4d0b78ff | Fix import in employee.new controller | app/controllers/employee/new.js | app/controllers/employee/new.js | import EmployeeController from '../employee.js';
var EmployeeNewController = EmployeeController;
export default EmployeeNewController;
| JavaScript | 0.000001 | @@ -40,11 +40,8 @@
oyee
-.js
';%0D%0A
|
818782dace5ddd87ae9cbc34412573d78ba983f9 | standardize json error object to return { status, msg } | app/resources/services/geoip.js | app/resources/services/geoip.js | const request = require('request')
const redis = require('redis')
const config = require('config')
const chalk = require('chalk')
const logger = require('../../../lib/logger.js')()
const util = require('../../../lib/util.js')
const IP_GEOLOCATION_TIMEOUT = 500
exports.get = function (req, res) {
// Prevent this service from being accessed by third parties
if (req.headers.referer === undefined || new URL(req.headers.referer).host !== config.app_host_port) {
res.status(403).json({ status: 403, error: 'I’m sorry — you do not have access to this service.' })
return
}
// If API key environment variable has not been provided, return an error.
if (!config.geoip.api_key) {
logger.warn(chalk.yellow(
'A request to ' + chalk.gray('/services/geoip') +
' cannot be fulfilled because the ' + chalk.gray('IPSTACK_API_KEY') +
' environment variable is not set.'
))
res.status(500).json({ status: 500, error: 'The server does not have access to the IP geolocation provider.' })
return
}
const requestGeolocation = function (isRedisConnected = true) {
let url = `${config.geoip.protocol}${config.geoip.host}`
url += (req.hostname === 'localhost') ? 'check' : ip
url += `?access_key=${config.geoip.api_key}`
request(url, { timeout: IP_GEOLOCATION_TIMEOUT }, function (error, response, body) {
if (error) {
logger.error(error)
res.status(503).json({ status: 503, error: 'The IP geolocation provider is unavailable.' })
return
}
const data = JSON.parse(body)
// If ipstack returns an error, catch it and return a generic error.
// Log the error so we can examine it later.
// Do not use a falsy check here. A succesful response from ipstack does
// not contain the `success` property. It is only present when it fails.
if (data.success === false) {
logger.error(data)
res.status(500).json({ status: 500, error: 'The IP geolocation provider returned an error.' })
return
}
if (isRedisConnected && ip) {
client.set(ip, body, redis.print)
}
res.status(200).json(data)
})
}
const ip = util.requestIp(req)
const client = req.redisClient
// If Redis is connected and Streetmix is not being run locally, check
// to see if there is a matching key in Redis to the current IP address.
if (client.connected && req.hostname !== 'localhost') {
client.get(ip, function (error, reply) {
if (error || !reply) {
if (error) {
logger.error(error)
}
// If no matching key or Streetmix is being run locally,
// or an error occurred, request geolocation from ipstack.
requestGeolocation()
} else {
res.status(200).json(JSON.parse(reply))
}
})
} else {
// If Redis is not connected and/or Streetmix is being run locally,
// automatically request geolocation from ipstack and do not save to Redis.
requestGeolocation(false)
}
}
| JavaScript | 0.999999 | @@ -500,21 +500,19 @@
s: 403,
-error
+msg
: 'I%E2%80%99m s
@@ -933,29 +933,27 @@
tatus: 500,
-error
+msg
: 'The serve
@@ -1441,21 +1441,19 @@
s: 503,
-error
+msg
: 'The I
@@ -1947,21 +1947,19 @@
s: 500,
-error
+msg
: 'The I
|
2a3aee6fc2642a152bdcad8e049436d19e274bc3 | define a "dummy" Symbol | runtime/js/runtime.js | runtime/js/runtime.js | // Copyright (c) 2015 Tzvetan Mikov.
// Licensed under the Apache License v2.0. See LICENSE in the project
// root for complete license information.
// Global
function isNaN (number)
{
return __asm__({},["result"],[["number", Number(number)]],[],
"%[result] = js::makeBooleanValue(isnan(%[number].raw.nval))"
);
}
function isFinite (number)
{
return __asm__({},["result"],[["number", Number(number)]],[],
"%[result] = js::makeBooleanValue(isfinite(%[number].raw.nval))"
);
}
function parseInt (string, radix)
{
var inputString = String(string);
var R = radix === undefined ? 0 : radix | 0;
if (R !== 0 && (R < 2 || R > 36))
return NaN;
return __asm__({},["res"],[["inputString",inputString],["radix",radix]],[],
"const char * s = %[inputString].raw.sval->getStr();\n" +
"%[res] = js::makeNumberValue(js::parseInt(%[%frame], s, (int)%[radix].raw.nval));"
);
}
function parseFloat (string)
{
var inputString = String(string);
return __asm__({},["res"],[["inputString",inputString]],[],
"const char * s = %[inputString].raw.sval->getStr();\n" +
"%[res] = js::makeNumberValue(js::parseFloat(%[%frame], s));"
);
}
function decodeURI (encodedURI)
{
var uriString = String(encodedURI);
__asmh__({}, '#include "jsc/uri.h"');
var res = __asm__({},["res"],[["uriString", uriString]],[],
"const js::StringPrim * s = %[uriString].raw.sval;\n" +
"const js::StringPrim * res = js::uriDecode(%[%frame], s->_str, s->_str + s->byteLength, &js::uriDecodeSet);\n" +
"%[res] = res ? js::makeStringValue(res) : JS_NULL_VALUE;"
);
if (res === null)
throw new URIError("Invalid URI string to decode");
return res;
}
function decodeURIComponent (encodedURI)
{
var uriString = String(encodedURI);
__asmh__({}, '#include "jsc/uri.h"');
var res = __asm__({},["res"],[["uriString", uriString]],[],
"const js::StringPrim * s = %[uriString].raw.sval;\n" +
"const js::StringPrim * res = js::uriDecode(%[%frame], s->_str, s->_str + s->byteLength, &js::uriEmptySet);\n" +
"%[res] = res ? js::makeStringValue(res) : JS_NULL_VALUE;"
);
if (res === null)
throw new URIError("Invalid URI string to decode");
return res;
}
function encodeURI (uri)
{
var uriString = String(uri);
__asmh__({}, '#include "jsc/uri.h"');
var res = __asm__({},["res"],[["uriString", uriString]],[],
"const js::StringPrim * s = %[uriString].raw.sval;\n" +
"const js::StringPrim * res = js::uriEncode(%[%frame], s->_str, s->_str + s->byteLength, &js::uriEncodeSet);\n" +
"%[res] = res ? js::makeStringValue(res) : JS_NULL_VALUE;"
);
if (res === null)
throw new URIError("Invalid URI string to encode");
return res;
}
function encodeURIComponent (uri)
{
var uriString = String(uri);
__asmh__({}, '#include "jsc/uri.h"');
var res = __asm__({},["res"],[["uriString", uriString]],[],
"const js::StringPrim * s = %[uriString].raw.sval;\n" +
"const js::StringPrim * res = js::uriEncode(%[%frame], s->_str, s->_str + s->byteLength, &js::uriEncodeComponentSet);\n" +
"%[res] = res ? js::makeStringValue(res) : JS_NULL_VALUE;"
);
if (res === null)
throw new URIError("Invalid URI string to encode");
return res;
}
// SyntaxError
//
// NOTE: Error and TypeError are system-declared but the rest of the errors aren't
function SyntaxError (message)
{
return Error.call(this !== void 0 ? this : Object.create(SyntaxError.prototype), message);
}
function InternalError (message)
{
return Error.call(this !== void 0 ? this : Object.create(InternalError.prototype), message);
}
function RangeError (message)
{
return Error.call(this !== void 0 ? this : Object.create(RangeError.prototype), message);
}
function URIError (message)
{
return Error.call(this !== void 0 ? this : Object.create(URIError.prototype), message);
}
var Math;
var RegExp;
var Date;
var JSON;
var global;
var process;
var console;
var buffer;
var Buffer;
// A few "dummy" symbols needed by some external modules designed to also work in browsers
var window;
var define;
var self;
| JavaScript | 0.023771 | @@ -4107,16 +4107,86 @@
uffer;%0A%0A
+var Symbol; // FIXME: this is just a dummy to facilitate compilation%0A%0A
// A few
|
45ff1e8a0024ea054e7ca594b7f33591615940cd | add other action types | client/constants/ActionTypes.js | client/constants/ActionTypes.js | export const ADD_MESSAGE = 'ADD_MESSAGE';
export const RECEIVE_MESSAGE = 'RECEIVE_MESSAGE';
export const LOAD_MESSAGES = 'LOAD_MESSAGES';
export const LOAD_MESSAGES_SUCCESS = 'LOAD_MESSAGES_SUCCESS';
export const LOAD_MESSAGES_FAIL = 'LOAD_MESSAGES_FAIL';
export const RECEIVE_MESSAGES = 'RECEIVE_MESSAGES';
export const CREATE_GROUP_SUCCESS = 'CREATE_GROUP_SUCCESS';
export const CHANGE_GROUP = 'CHANGE_GROUP';
export const RECEIVE_GROUPS_SUCCESS = 'RECEIVE_GROUPS_SUCCESS';
export const SELECT_GROUP = 'SELECT_GROUP';
export const LOAD_GROUPS = 'LOAD_GROUPS';
export const LOAD_GROUPS_FAIL = 'LOAD_GROUPS_FAIL';
export const GET_GROUP_MESSAGES_SUCCESS = 'GET_GROUP_MESSAGES_SUCCESS';
export const ADD_MESSAGE_TO_GROUP_SUCCESS = 'ADD_MESSAGE_TO_GROUP_SUCCESS';
export const SIGNUP_USER = 'SIGNUP_USER';
export const SIGNIN_USER = 'SIGNIN_USER';
export const SIGNOUT_USER = 'SIGNOUT_USER';
export const SIGNOUT_SUCCESS = 'SIGNOUT_SUCCESS';
export const SET_CURRENT_USER = 'SET_CURRENT_USER';
export const ADD_MEMBERS_SUCCESS = 'ADD_MEMBERS_SUCCESS';
export const REMOVE_USER_FROM_GROUP = 'REMOVE_USER_FROM_GROUP';
export const SAVE_USERNAME = 'SAVE_USERNAME';
export const RECEIVE_USER = 'RECEIVE_USER';
| JavaScript | 0.000026 | @@ -10,184 +10,44 @@
nst
-ADD_MESSAGE = 'ADD_MESSAGE';%0Aexport const RECEIVE_MESSAGE = 'RECEIVE_MESSAGE';%0Aexport const LOAD_MESSAGES = 'LOAD_MESSAGES';%0Aexport const LOAD_MESSAGES_SUCCESS = 'LOAD_MESSAGES
+CREATE_GROUP_SUCCESS = 'CREATE_GROUP
_SUC
@@ -70,48 +70,52 @@
nst
-LOAD_MESSAGES
+CREATE_GROUP
_FAIL
+URE
= '
-LOAD_MESSAGES
+CREATE_GROUP
_FAIL
+URE
';%0Ae
@@ -138,65 +138,14 @@
IVE_
-MESSAGES = 'RECEIVE_MESSAGES';%0A%0Aexport const CREATE_
GROUP
+S
_SUC
@@ -148,36 +148,38 @@
_SUCCESS = '
-C
RE
-AT
+CEIV
E_GROUP
+S
_SUCCESS';%0Ae
@@ -181,52 +181,8 @@
S';%0A
-export const CHANGE_GROUP = 'CHANGE_GROUP';%0A
expo
@@ -201,37 +201,38 @@
EIVE_GROUPS_
-SUCCESS
+FAILURE
= 'RE
+A
CEIVE_GROUPS
@@ -224,39 +224,39 @@
REACEIVE_GROUPS_
-SUCCESS
+FAILURE
';%0Aexport const
@@ -303,33 +303,63 @@
nst
-LOAD
+GET
_GROUP
+_MESSAGES_SUCCES
S = '
-LOAD
+GET
_GROUP
+_MESSAGES_SUCCES
S';%0A
@@ -375,48 +375,67 @@
nst
-LOAD
+GET
_GROUP
+_MESSAGE
S_FAIL
+URE
= '
-LOAD
+GET
_GROUP
+_MESSAGE
S_FAIL
+URE
';%0A
-%0A
expo
@@ -447,56 +447,60 @@
nst
-GET_GROUP_MESSAGES_SUCCESS = 'GET_GROUP_MESSAGES
+ADD_MESSAGE_TO_GROUP_SUCCESS = 'ADD_MESSAGE_TO_GROUP
_SUC
@@ -532,39 +532,39 @@
ESSAGE_TO_GROUP_
-SUCCESS
+FAILURE
= 'ADD_MESSAGE_
@@ -564,39 +564,39 @@
ESSAGE_TO_GROUP_
-SUCCESS
+FAILURE
';%0Aexport const
@@ -602,24 +602,32 @@
SIGNUP_USER
+_SUCCESS
= 'SIGNUP_U
@@ -625,24 +625,32 @@
'SIGNUP_USER
+_SUCCESS
';%0Aexport co
@@ -657,33 +657,30 @@
nst
-SIGNIN_USER = 'SIGNIN_USE
+LOG_ERROR = ' LOG_ERRO
R';%0A
@@ -700,24 +700,31 @@
SIGN
-OUT
+IN
_USER
+_SUCCESS
= 'SIGN
OUT_
@@ -723,20 +723,26 @@
SIGN
-OUT
+IN
_USER
+_SUCCESS
';%0A
-%0A
expo
@@ -754,24 +754,29 @@
nst SIGNOUT_
+USER_
SUCCESS = 'S
@@ -782,16 +782,21 @@
SIGNOUT_
+USER_
SUCCESS'
@@ -789,33 +789,32 @@
_USER_SUCCESS';%0A
-%0A
export const SET
@@ -907,17 +907,16 @@
CCESS';%0A
-%0A
export c
@@ -924,60 +924,53 @@
nst
-REMOVE_USER_FROM_GROUP = 'REMOVE_USER_FROM_GROUP
+ADD_MEMBERS_FAILURE = 'ADD_MEMBERS_FAILURE
';%0A
-%0A
expo
@@ -982,42 +982,51 @@
nst
-SAVE_USERNAME = 'SAVE_USERNAME
+FETCH_USER_SUCCESS = 'FETCH_USER_SUCCESS
';%0A
-%0A
expo
@@ -1038,35 +1038,65 @@
nst
-RECEIVE_USER = 'RECEIVE_USER
+FETCH_GROUP_MEMBERS_SUCCESS = 'FETCH_GROUP_MEMBERS_SUCCESS
';%0A
|
dc12d2cea4f9f15e395f5893c4f25541842160a9 | update blog url | app/scripts/controllers/blog.js | app/scripts/controllers/blog.js | 'use strict';
angular.module('scoreWebsiteApp')
.controller('BlogCtrl', function () {
window.location.replace('http://blog.openscore.io');
//_.forEach($('.navbar-collapse'), function(target) {
// $(target).collapse({'toggle': false});
//});
//
//$rootScope.sections = [];
//$rootScope.navSwitch = { uri: '', title: $rootScope.messages.navBackToSiteTitle };
});
| JavaScript | 0 | @@ -133,17 +133,18 @@
log.
-openscore
+cloudslang
.io'
|
bf4d02a6573b5913288fd34ca3fde5bb9d019a13 | refresh global status after task status changed | app/scripts/controllers/main.js | app/scripts/controllers/main.js | (function () {
'use strict';
angular.module('ariaNg').controller('MainController', ['$rootScope', '$scope', '$route', '$location', '$interval', 'ariaNgCommonService', 'ariaNgSettingService', 'aria2TaskService', 'aria2SettingService', function ($rootScope, $scope, $route, $location, $interval, ariaNgCommonService, ariaNgSettingService, aria2TaskService, aria2SettingService) {
var globalStatRefreshPromise = null;
var refreshGlobalStat = function (silent) {
return aria2SettingService.getGlobalStat(function (result) {
$scope.globalStat = result;
}, silent);
};
$scope.isTaskSelected = function () {
return $rootScope.taskContext.getSelectedTaskIds().length > 0;
};
$scope.isSpecifiedTaskSelected = function () {
var selectedTasks = $rootScope.taskContext.getSelectedTasks();
if (selectedTasks.length < 1) {
return false;
}
for (var i = 0; i < selectedTasks.length; i++) {
for (var j = 0; j < arguments.length; j++) {
if (selectedTasks[i].status == arguments[j]) {
return true;
}
}
}
return false;
};
$scope.isSpecifiedTaskShowing = function () {
var tasks = $rootScope.taskContext.list;
if (tasks.length < 1) {
return false;
}
for (var i = 0; i < tasks.length; i++) {
for (var j = 0; j < arguments.length; j++) {
if (tasks[i].status == arguments[j]) {
return true;
}
}
}
return false;
};
$scope.changeTasksState = function (state) {
var gids = $rootScope.taskContext.getSelectedTaskIds();
if (!gids || gids.length < 1) {
return;
}
var invoke = null;
if (state == 'start') {
invoke = aria2TaskService.startTasks;
} else if (state == 'pause') {
invoke = aria2TaskService.pauseTasks;
} else {
return;
}
$rootScope.loadPromise = invoke(gids, function (result) {
$route.reload();
});
};
$scope.removeTasks = function () {
var tasks = $rootScope.taskContext.getSelectedTasks();
if (!tasks || tasks.length < 1) {
return;
}
ariaNgCommonService.confirm('Confirm Remove', 'Are you sure you want to remove the selected task?', 'warning', function () {
$rootScope.loadPromise = aria2TaskService.removeTasks(tasks, function (result) {
if ($location.path() == '/stopped') {
$route.reload();
} else {
$location.path('/stopped');
}
});
});
};
$scope.clearStoppedTasks = function () {
ariaNgCommonService.confirm('Confirm Clear', 'Are you sure you want to clear stopped tasks?', 'warning', function () {
$rootScope.loadPromise = aria2TaskService.clearStoppedTasks(function (result) {
if ($location.path() == '/stopped') {
$route.reload();
} else {
$location.path('/stopped');
}
});
});
};
$scope.selectAllTasks = function () {
$rootScope.taskContext.selectAll();
};
$scope.changeDisplayOrder = function (type, autoSetReverse) {
var oldType = ariaNgCommonService.parseOrderType(ariaNgSettingService.getDisplayOrder());
var newType = ariaNgCommonService.parseOrderType(type);
if (autoSetReverse && newType.type == oldType.type) {
newType.reverse = !oldType.reverse;
}
ariaNgSettingService.setDisplayOrder(newType.getValue());
};
$scope.isSetDisplayOrder = function (type) {
var orderType = ariaNgCommonService.parseOrderType(ariaNgSettingService.getDisplayOrder());
var targetType = ariaNgCommonService.parseOrderType(type);
return orderType.equals(targetType);
};
if (ariaNgSettingService.getGlobalStatRefreshInterval() > 0) {
globalStatRefreshPromise = $interval(function () {
refreshGlobalStat(true);
}, ariaNgSettingService.getGlobalStatRefreshInterval());
}
$scope.$on('$destroy', function () {
if (globalStatRefreshPromise) {
$interval.cancel(globalStatRefreshPromise);
}
});
refreshGlobalStat(false);
}]);
})();
| JavaScript | 0 | @@ -2341,32 +2341,74 @@
tion (result) %7B%0A
+ refreshGlobalStat(false);%0A
@@ -2416,32 +2416,32 @@
route.reload();%0A
-
%7D);%0A
@@ -2874,32 +2874,78 @@
tion (result) %7B%0A
+ refreshGlobalStat(false);%0A
@@ -3350,32 +3350,32 @@
, function () %7B%0A
-
@@ -3446,32 +3446,78 @@
tion (result) %7B%0A
+ refreshGlobalStat(false);%0A
|
9da0267a8e5503fa87f35747cd38174c06f66ef5 | fix post message twice | app/scripts/controllers/main.js | app/scripts/controllers/main.js | 'use strict';
var shell = require('shell');
var remote = require('remote');
var appConfig = remote.require('./lib/app-config');
/**
* @ngdoc function
* @name hipslackApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the hipslackApp
*/
angular.module('hipslackApp')
.controller('MainCtrl', function ($scope, $http, $modal, $location, $sce, config, Messages, Rooms, Members) {
$scope.openedRooms = [];
$scope.isLoading = false;
$scope._activeMessageParam = null;
$scope.roomsClick = function() {
var roomsModal = $modal.open({
animation: true,
size: 'lg',
templateUrl: 'roomsModal.html',
controller: 'RoomsModalCtrl'
});
roomsModal.result.then(function (selectedItem){
$scope.roomClick(selectedItem);
});
};
$scope.roomClick = function(room) {
$scope._loadRoom(room, function() {
$scope._saveStates();
});
};
$scope._loadRoom = function(room, callback) {
$scope.isLoading = true;
$scope._activeMessageParam = room;
Rooms.open(room, function() {
Members.setActive(null);
$scope.activeRoomProperty = Rooms.activeRoomProperty;
$scope._update();
if (callback !== undefined) {
callback();
}
});
};
$scope.membersClick = function() {
var directMessagesModal = $modal.open({
animation: true,
size: 'lg',
templateUrl: 'directMessagesModal.html',
controller: 'DirectMessagesModalCtrl'
});
directMessagesModal.result.then(function (selectedItem){
$scope.memberClick(selectedItem);
});
};
$scope.memberClick = function(member) {
$scope._loadMember(member, function() {
$scope._saveStates();
});
};
$scope._loadMember = function(member, callback) {
$scope.isLoading = true;
$scope._activeMessageParam = member;
Members.open(member, function() {
Rooms.setActive(null);
$scope.activeRoomProperty = null;
$scope._update();
if (callback !== undefined) {
callback();
}
});
};
$scope._redraw = function() {
if ($scope._activeMessageParam === null) {
return;
}
if ($scope.activeRoomProperty) {
$scope._loadRoom($scope._activeMessageParam);
} else {
$scope._loadMember($scope._activeMessageParam);
}
};
$scope._update = function() {
$scope.groupMessages = Messages.messages;
$scope.openedRooms = Rooms.openedItems;
$scope.openedMembers = Members.openedItems;
var last = Messages.getLast();
if (last) {
$location.hash('message-' + last.id);
}
$scope.isLoading = false;
};
$scope.closeRoom = function(room) {
Rooms.close(room);
$scope.openedRooms = Rooms.openedItems;
};
$scope.closeMember = function(member) {
Members.close(member);
$scope.openedMembers = Members.openedItems;
};
$scope.sendMessage = function() {
var getUrl = function () {
if ($scope.activeRoomProperty) {
var roomId = Rooms.getActiveId();
return config.backend + '/v2/room/' + roomId + '/message';
} else {
var roomId2 = Members.getActiveId();
return config.backend + '/v2/user/' + roomId2 + '/message';
}
};
var uri = getUrl();
$http({
method: 'POST',
url: uri,
data: { message: $scope.inputText },
headers: { 'Authorization': 'Bearer ' + config.authkey }
}).success(function() {
$scope.inputText = "";
$scope._redraw();
});
};
$scope.linkClick = function(url) {
shell.openExternal(url);
return false;
};
$scope.toTrusted = function(htmlCode) {
return $sce.trustAsHtml(htmlCode);
};
$scope._saveStates = function() {
appConfig.save({
rooms: $scope.openedRooms,
members: $scope.openedMembers,
isRoom: $scope.activeRoomProperty,
active: $scope._activeMessageParam
});
};
$scope._loadStates = function() {
appConfig.load(function(config) {
Rooms.openedItems = config.rooms;
Members.openedItems = config.members;
if (config.isRoom) {
$scope._loadRoom(config.active);
} else {
$scope._loadMember(config.active);
}
});
};
$scope._redrawHookEvent = function() {
$scope._redraw();
setTimeout($scope._redrawHookEvent, 30000);
};
$scope._redrawHookEvent();
$scope._loadStates();
});
| JavaScript | 0.000006 | @@ -3048,32 +3048,99 @@
= function() %7B%0A
+ var message = $scope.inputText;%0A $scope.inputText = %22%22;%0A
var getUrl
@@ -3573,32 +3573,23 @@
essage:
-$scope.inputText
+message
%7D, %0A
|
1d2c660523a47694e29a0b3b066109c5043b6308 | update cancel display message | src/ui/a.grade-importer.picker.controller.client.js | src/ui/a.grade-importer.picker.controller.client.js | var DEVELOPER_KEY = 'AIzaSyCgyLaEarqrUnu9jmF82pl2R4WD_ywry2Q';
var DIALOG_DIMENSIONS = {width: 600, height: 425};
var pickerApiLoaded = false;
/**
* Loads the Google Picker API.
*/
function onApiLoad() {
gapi.load('picker', {
'callback': function() {
pickerApiLoaded = true;
}
});
google.script.run
.withSuccessHandler(createPicker)
.withFailureHandler(showError)
.getOAuthToken();
}
/**
* Creates a Picker that can access the user's spreadsheets. This function
* uses advanced options to hide the Picker's left navigation panel and
* default title bar.
*
* @param {string} token An OAuth 2.0 access token that lets Picker access
* the file type specified in the addView call.
*/
function createPicker(token) {
if (pickerApiLoaded && token) {
var picker = new google.picker.PickerBuilder()
// Allow user to upload documents to My Drive folder.
.addView(new google.picker.DocsUploadView()
.setIncludeFolders(true))
// Instruct Picker to display *.csv files only.
.addView(new google.picker.View(google.picker.ViewId.DOCS)
.setQuery('*.csv'))
// Allow user to select files from Google Drive.
.addView(new google.picker.DocsView()
.setIncludeFolders(true)
.setOwnedByMe(true))
// Allow user to choose more than one document in the picker.
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
// Hide title bar since an Apps Script dialog already has a title.
.hideTitleBar()
.setOAuthToken(token)
.setDeveloperKey(DEVELOPER_KEY)
.setCallback(pickerCallback)
.setOrigin(google.script.host.origin)
// Instruct Picker to fill the dialog, minus 2 px for the border.
.setSize(DIALOG_DIMENSIONS.width - 2,
DIALOG_DIMENSIONS.height - 2)
.build();
picker.setVisible(true);
} else {
showError(
'<p>Unable to load the file picker. Please try again.</p>' +
closeButton()
);
}
}
/**
* A callback function that extracts the chosen document's metadata from the
* response object. For details on the response object, see
* https://developers.google.com/picker/docs/results
*
* @param {object} data The response object.
*/
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
updateDisplay('<em>Importing...</em>');
google.script.run
.withSuccessHandler(updateDisplay)
.loadSelectedFiles(data.docs);
} else if (data.action == google.picker.Action.CANCEL) {
var close = '<p>Load gradebooks canceled. You may close this window.</p>';
close += closeButton();
updateDisplay(close);
}
} | JavaScript | 0.000001 | @@ -2006,19 +2006,49 @@
ror(
-%0A
+'%3Cdiv class=%22msg msg-error%22%3E' +%0A
'
-%3Cp%3E
Unab
@@ -2092,19 +2092,32 @@
y again.
-%3C/p
+' +%0A '%3C/div
%3E' +%0A
@@ -2132,21 +2132,16 @@
Button()
-%0A
);%0A %7D%0A%7D
@@ -2698,18 +2698,61 @@
ose = '%3C
-p%3E
+div class=%22msg msg-information%22%3E' +%0A '
Load gra
@@ -2799,27 +2799,34 @@
dow.
-%3C/p%3E';%0A close +=
+' +%0A '%3C/div%3E' +%0A
clo
|
8385633bb28bd63782e1caabe27b0947ac5edccc | Fix button display | app/scripts/services/session.js | app/scripts/services/session.js | 'use strict';
/**
* @ngdoc service
* @name waxeangularApp.Session
* @description
* # Session
* Factory in the waxeangularApp.
*/
angular.module('waxeApp')
.service('Session', ['$http', '$q', '$route', 'Utils', 'UserProfile', 'AccountProfile', 'NavbarService', function ($http, $q, $route, Utils, UserProfile, AccountProfile, NavbarService) {
// The variables defined here should not be reset during the navigation.
// It's like a cache
// The current path we open/save file. It's used in the modal
this.currentPath = null;
// Need to be defined since the init is not always called before displaying the navbar
this.files = [];
this.filesSelected = [];
// The interval object when editing a file. We need it to cancel it
// when we quit the editor.
this.autosave_interval = null;
this.init = function(login, accountUsable) {
this.login = login;
// Should be true when we can use the account data
this.accountUsable = accountUsable;
this.currentFile = null;
this.user = null;
this.breadcrumbFiles = [];
// Use to apply action on multiple files in the menu
this.files = [];
this.filesSelected = [];
// Special handler when we click on the save button
this.submitForm = null;
// The filename we are editing
// TODO: we should store a File object
this.filename = null;
// XML form
// NOTE: it enables the 'save as' button
this.form = null;
this.from = $route.current.params.from;
this.editor = (typeof $route.current.$$route.editor !== 'undefined');
this.diff = (typeof $route.current.$$route.diff !== 'undefined');
this.showSource = this.editor || this.diff;
this.sourceEnabled = false;
if(this.editor && typeof this.from !== 'undefined') {
this.sourceEnabled = true;
}
this.showDiff = (AccountProfile.has_versioning && (this.diff || this.editor));
this.diffEnabled = false;
if(this.diff && typeof this.from !== 'undefined') {
this.diffEnabled = true;
}
NavbarService.enable(this.accountUsable);
NavbarService.setVisible(this.accountUsable);
// Will be set when editing a file
NavbarService.setEditFile(false);
if (this.accountUsable) {
var path = '(new file)';
if (typeof $route.current.$$route.noAutoBreadcrumb === 'undefined') {
path = $route.current.params.path;
}
this.setBreadcrumbFiles(path);
}
};
this.load = function() {
if(angular.isDefined(AccountProfile.login)) {
this.init(AccountProfile.login, true);
}
else{
this.init(UserProfile.login, false);
}
};
this.unSelectFiles = function() {
for (var i=0,len=this.filesSelected.length; i < len; i++) {
this.filesSelected[i].selected = false;
}
this.filesSelected = [];
};
this.setBreadcrumbFiles = function(file) {
if (file && this.currentFile === file) {
// Nothing to do the breadcrumb is already generated
return;
}
this.currentFile = file;
// TODO: we have a problem when this.currentFile is a list.
// Perhaps we should chec this.currentFile is string to dislay it.
// It's the case when making a diff of many files.
this.breadcrumbFiles = Utils.getBreadcrumbFiles(this.currentFile);
};
this.setFilename = function(filename) {
this.filename = filename;
this.setBreadcrumbFiles(filename);
};
}]);
| JavaScript | 0.000001 | @@ -2519,16 +2519,23 @@
ditFile(
+false,
false);%0A
|
b4ead312a75f2f3bac4dc67f6ee00a36e5e31bce | Fix for temperature points duplicating due to Collection.set | examples/svg/js/app.js | examples/svg/js/app.js | var template = require('../templates/svg_view.mustache');
var TungstenBackboneBase = require('tungstenjs/adaptors/backbone');
var elem = document.getElementById('appwrapper');
var DemoModel = TungstenBackboneBase.Model.extend({
relations: {
clock: TungstenBackboneBase.Model,
chart: TungstenBackboneBase.Model.extend({
relations: {
temperatures: TungstenBackboneBase.Collection
}
})
}
});
var MarkerView = TungstenBackboneBase.View.extend({
events: {
'click': function() {
console.log('the temperature point clicked was', this.model.toJSON());
}
}
});
var ChartView = TungstenBackboneBase.View.extend({
events: {
'change .js-city-select': 'changeCity',
'change .js-degree-type': 'changeType'
},
childViews: {
'js-marker': MarkerView
},
setChart: function() {
var index = this.model.get('selectedCityIndex');
var type = this.model.get('degreeType');
var city = this.model.get('cities')[index];
var active = this.model.get('getCity')(city.temperatures, type);
this.model.set(active);
},
changeCity: function(evt) {
this.model.set('selectedCityIndex', evt.currentTarget.selectedIndex);
this.setChart();
},
changeType: function(evt) {
this.model.set('degreeType', evt.currentTarget.value);
this.setChart();
}
});
var DemoView = TungstenBackboneBase.View.extend({
childViews: {
'js-chart-view': ChartView
}
});
window.app = module.exports = new DemoView({
el: elem,
template: template,
model: new DemoModel(window.data),
dynamicInitialize: elem.childNodes.length === 0
});
var clockModel = window.app.model.get('clock');
setInterval(function() {
clockModel.set('datetime', new Date());
}, 1000);
| JavaScript | 0 | @@ -319,105 +319,8 @@
odel
-.extend(%7B%0A relations: %7B%0A temperatures: TungstenBackboneBase.Collection%0A %7D%0A %7D)
%0A %7D
|
865f95aaf593b70e60184d2f6920c3618409606e | Add citation | app/static/game/js/common.js | app/static/game/js/common.js | //javascript file to put commonly used functions between webpages in.
//Generates a random number between min (inclusive) and max (exclusive)
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
//function for determining if an image was correctly chosen
function isCorrect(choice, correctAnswer) {
if(choice === correctAnswer) {
alert("Good Job! 10 pts");
return 10;
}
alert("Whoops Try again!");
return 0;
}
//Gets JSON data from our website
function getJSON(specifiedAlbum) {
var images = [];
$.ajax({
async: false,
url: "http://recognize.bitbutt.io/json/albums/",
success: function(data) {
for(var i = 0; i < data.albums.length; i++) {
for(var j = 0; j < data.albums[i].images.length; j++) {
if(specifiedAlbum === data.albums[i].title) {
images.push(data.albums[i].images[j]);
}
}
}
}
});
return images;
}
//Gets 3 random answer choices for a question image.
function getAnswerChoices(questionImage, images) {
var answerChoices = [];
var randPos = randomNumber(0, images.length);
answerChoices.push(questionImage);
var counter = 1;
while(counter < 3) {
console.log(counter);
var choice = images[randomNumber(0, images.length)];
if(choice != questionImage && contains(answerChoices, choice) === false) {
answerChoices.push(choice);
counter++;
}
}
answerChoices = randomize(answerChoices);
return answerChoices;
}
//checks whether an array contains a value.
function contains(array, value) {
for(var i = 0; i < array.length; i++) {
if(array[i] === value) {
return true;
}
}
return false;
}
//Source: http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
//Randomizes the contents of an array.
function randomize(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
| JavaScript | 0.000001 | @@ -497,16 +497,101 @@
website%0A
+//Based on http://stackoverflow.com/questions/955217/synchronous-jquery-json-request%0A
function
|
92765e05b929ba133820f166d5182688d4bcc788 | allow number keys to be used in input field | app/app/controllers/evolve.js | app/app/controllers/evolve.js | import Ember from 'ember';
var Population = require('asNEAT/population')['default'];
var MINUS_CODE = "-".charCodeAt(),
MULT_CODE = "*".charCodeAt(),
PLUS_CODE = "+".charCodeAt(),
DEC_CODE = ".".charCodeAt(),
ENTER_CODE = 13;
export default Ember.Controller.extend({
needs: ['application'],
// set by route
// networks is a history of networks (list of list of networks)
// and the top one is currently the parent set
// {instrumentParams: [[{instrumentNetwork:asNEAT.Network, isLive, selected}, ...],[...],...]}
content: null,
// (optional) An instrument that all the shown
// instruments are evolved from
branchedParent: null,
noPreviousParents: function() {
return this.get('content.instrumentParams').length <= 1;
}.property('content.instrumentParams.@each'),
parentInstrumentParams: function() {
var networks = this.get('content.instrumentParams');
return networks[networks.length-1];
}.property('content.instrumentParams.@each'),
childInstrumentParams: function() {
var numChildren = 9,
parentInstrumentParams = this.get('parentInstrumentParams'),
newPopulation, children = [], i, child;
newPopulation = Population.generateFromParents(
_.map(parentInstrumentParams, function(element){
return element.instrumentNetwork;
}), {
populationCount: numChildren,
numberOfNewParentMutations: 4,
crossoverRate: 0.2
});
for (i=0; i<numChildren; ++i) {
child = newPopulation.networks[i];
children.push(Ember.Object.create({
instrumentNetwork: child,
isLive: i===0,
selected: false,
index: i
}));
}
this.get('controllers.application')
.set('activeInstrument', children[0]);
return children;
}.property('parentInstrumentParams.@each'),
selectedNetworks: function() {
var selectedParents = _.filter(this.get('parentInstrumentParams'), 'selected');
var selectedChildren = _.filter(this.get('childInstrumentParams'), 'selected');
return _.union(selectedParents, selectedChildren);
}.property('parentInstrumentParams.@each.selected', 'childInstrumentParams.@each.selected'),
noNetworksSelected: function() {
return this.get('selectedNetworks').length <= 0;
}.property('selectedNetworks.@each'),
onkeyPressHandler: null,
setupKeyEvents: function() {
var self = this;
var onkeyPressHandler = function(e) {
// one to one mapping of numpad to the layout on screen
var index = -1;
if (e.keyCode === 49) index = 6;
else if (e.keyCode === 50) index = 7;
else if (e.keyCode === 51) index = 8;
else if (e.keyCode === 52) index = 3;
else if (e.keyCode === 53) index = 4;
else if (e.keyCode === 54) index = 5;
else if (e.keyCode === 55) index = 0;
else if (e.keyCode === 56) index = 1;
else if (e.keyCode === 57) index = 2;
if (index>=0) {
e.preventDefault();
self.get('controllers.application')
.send('makeLive',
self.get('childInstrumentParams')[index]);
}
// Reset parents
if (e.keyCode === DEC_CODE) {
e.preventDefault();
self.send('resetParents');
}
// Go back a generation
else if (e.keyCode === MINUS_CODE && !self.get('noPreviousParents')){
e.preventDefault();
self.send('backGeneration');
}
// Refresh current children
else if (e.keyCode === MULT_CODE) {
e.preventDefault();
self.send('refreshGeneration');
}
// Goto next generation
else if (e.keyCode === PLUS_CODE && !self.get('noNetworksSelected')) {
e.preventDefault();
self.send('nextGeneration');
}
// Toggle selected
else if (e.keyCode === ENTER_CODE) {
e.preventDefault();
var instrument = self.get('controllers.application.activeInstrument');
instrument.set('selected', !instrument.get('selected'));
}
};
this.set('onkeyPressHandler', onkeyPressHandler);
// setting up events from document because we can't
// get focus on multiple piano-keys at once for key events
// to fire correctly
$(document).keypress(onkeyPressHandler);
}.on('init'),
willDestroy: function() {
this._super();
$(document).off('keypress', this.get('onkeyPressHandler'));
},
actions: {
resetParents: function() {
this.set('content.instrumentParams', [[]]);
},
refreshGeneration: function() {
this.notifyPropertyChange('childInstrumentParams');
},
backGeneration: function() {
this.get('content.instrumentParams').popObject();
scrollToBottom();
},
nextGeneration: function() {
var selected = this.get('selectedNetworks');
// reset selected and isLive
_.forEach(selected, function(network) {
network.set('selected', false);
network.set('isLive', false);
});
// push the currently selected networks on top
this.get('content.instrumentParams').pushObject(selected);
scrollToBottom();
}
}
});
function scrollToBottom() {
Ember.run.scheduleOnce('afterRender', function() {
$(document).scrollTop($(document).height());
});
}
| JavaScript | 0.000001 | @@ -3170,36 +3170,8 @@
) %7B%0A
- e.preventDefault();%0A
@@ -3197,24 +3197,24 @@
tParents');%0A
+
%7D%0A
@@ -3319,36 +3319,8 @@
))%7B%0A
- e.preventDefault();%0A
@@ -3440,36 +3440,8 @@
) %7B%0A
- e.preventDefault();%0A
@@ -3595,36 +3595,8 @@
) %7B%0A
- e.preventDefault();%0A
@@ -3661,16 +3661,16 @@
elected%0A
+
el
@@ -3708,36 +3708,8 @@
) %7B%0A
- e.preventDefault();%0A
|
a24e754c803fa7e79dda922c4bbbd799db6ed8f8 | Fix documentation of historyRecords property. | guacamole/src/main/webapp/app/settings/directives/guacSettingsConnectionHistory.js | guacamole/src/main/webapp/app/settings/directives/guacSettingsConnectionHistory.js | /*
* Copyright (C) 2015 Glyptodon LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* A directive for viewing connection history records.
*/
angular.module('settings').directive('guacSettingsConnectionHistory', [function guacSettingsConnectionHistory() {
return {
// Element only
restrict: 'E',
replace: true,
scope: {
},
templateUrl: 'app/settings/templates/settingsConnectionHistory.html',
controller: ['$scope', '$injector', function settingsConnectionHistoryController($scope, $injector) {
// Get required types
var FilterToken = $injector.get('FilterToken');
var SortOrder = $injector.get('SortOrder');
// Get required services
var $routeParams = $injector.get('$routeParams');
var $translate = $injector.get('$translate');
var historyService = $injector.get('historyService');
/**
* The identifier of the currently-selected data source.
*
* @type String
*/
$scope.dataSource = $routeParams.dataSource;
/**
* The identifier of the currently-selected data source.
*
* @type String
*/
$scope.historyRecords = null;
/**
* The search terms to use when filtering the history records.
*
* @type String
*/
$scope.searchString = '';
/**
* The date format for use for start/end dates.
*
* @type String
*/
$scope.dateFormat = null;
/**
* SortOrder instance which stores the sort order of the history
* records.
*
* @type SortOrder
*/
$scope.order = new SortOrder([
'username',
'startDate',
'endDate',
'connectionName'
]);
// Get session date format
$translate('SETTINGS_CONNECTION_HISTORY.FORMAT_DATE')
.then(function dateFormatReceived(retrievedDateFormat) {
// Store received date format
$scope.dateFormat = retrievedDateFormat;
});
/**
* Returns true if the connection history records have been loaded,
* indicating that information needed to render the page is fully
* loaded.
*
* @returns {Boolean}
* true if the history records have been loaded, false
* otherwise.
*
*/
$scope.isLoaded = function isLoaded() {
return $scope.historyRecords !== null
&& $scope.dateFormat !== null;
};
/**
* Query the API for the connection record history, filtered by
* searchString, and ordered by order.
*/
$scope.search = function search() {
// Clear current results
$scope.historyRecords = null;
// Tokenize search string
var tokens = FilterToken.tokenize($scope.searchString);
// Transform tokens into list of required string contents
var requiredContents = [];
angular.forEach(tokens, function addRequiredContents(token) {
// Transform depending on token type
switch (token.type) {
// For string literals, use parsed token value
case 'LITERAL':
requiredContents.push(token.value);
// Ignore whitespace
case 'WHITESPACE':
break;
// For all other token types, use the relevant portion
// of the original search string
default:
requiredContents.push(token.consumed);
}
});
// Fetch history records
historyService.getConnectionHistory(
$scope.dataSource,
requiredContents,
$scope.order.predicate
)
.success(function historyRetrieved(historyRecords) {
// Store retrieved permissions
$scope.historyRecords = historyRecords;
});
};
// Initialize search results
$scope.search();
}]
};
}]);
| JavaScript | 0 | @@ -2236,60 +2236,116 @@
*
-The identifier of the currently-selected data source
+All matching connection history records, or null if these%0A * records have not yet been retrieved
.%0A
@@ -2370,38 +2370,56 @@
* @type
-String
+ConnectionHistoryEntry%5B%5D
%0A */
|
3f77e9f3fe0ff27e8e2b5ca1e6c7252332e5d795 | squish the time/date | app/assets/javascripts/app.js | app/assets/javascripts/app.js | function setup(data, percentages, strategies, strategy_ids) {
var options = {
series: {
lines: { show: true },
points: { show: true },
},
xaxis: { mode: 'time',
timezone: 'browser',
timeformat: "%m/%d %I%p",
tickSize: [1, "hour"]},
legend: { position: 'nw',
container: '#legend'},
yaxis: { tickFormatter: formatter},
grid: {clickable: true}
};
var dset = []
dset.push({label: "profit $",
data: strategies,
yaxis: 2,
color: 'grey',
bars: {show: true, lineWidth: 3},
lines: {show: false},
points: {radius: 0}})
dset.push({label: "profit %",
data: percentages,
yaxis: 3,
color: 'grey',
bars: {show: false, barWidth: 3},
lines: {show: false},
points: {radius: 5, fill: true, fillColor: 'grey'}})
var color_index = 0;
for(var market_id in data) {
dset.push({label: data[market_id][0]+" ask",
data: data[market_id][2],
color: color_index,
points: {radius: 5}})
dset.push({label: data[market_id][0]+" bid",
data: data[market_id][1],
color: color_index,
})
color_index = color_index + 1;
}
$.plot($("#chart"), dset, options);
$("#chart").bind('plotclick', function(e,p,i){strategyClick(e,p,i,strategy_ids)})
}
function chart_setup(data) {
var options = {
series: {
lines: { show: true },
points: { show: true },
},
};
var dset = []
for(var id in data) {
dset.push({label: data[id][0],
data: data[id][1],
})
}
console.log(dset)
$.plot($("#chart"), dset, options);
}
function strategyClick(event, point, item, strategy_ids) {
console.log(item.dataIndex);
console.log(item.seriesIndex);
if(item.seriesIndex == 0) {
window.location = "/strategies/"+strategy_ids[item.dataIndex]
}
}
function formatter(val, axis) {
if(axis.n == 1)
return "$"+val.toFixed(2);
if(axis.n == 2)
return "$"+val.toFixed(2);
if(axis.n == 3)
return val.toFixed(2)+"%";
}
| JavaScript | 0.999997 | @@ -250,17 +250,21 @@
: %22%25
-m/%25d %25I%25p
+I%25p%3Cbr/%3E%25m/%25d
%22,%0A
|
5211ac2b30e72971b365448a396da687a1b43843 | add geocoder to address so map shows exact location of shop | app/assets/javascripts/map.js | app/assets/javascripts/map.js |
var address = "1600 Amphitheatre Parkway, Mountain View";
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: {lat: -34.397, lng: 150.644}
});
var geocoder = new google.maps.Geocoder();
geocodeAddress(geocoder, map);
}
function geocodeAddress(geocoder, resultsMap) {
// var address = document.getElementById('address').value;
var address = "401 N Franklin St, Chicago"
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
} | JavaScript | 0 | @@ -338,11 +338,8 @@
%7B%0A
- //
var
@@ -388,60 +388,18 @@
s').
-value;%0A var address = %22401 N Franklin St, Chicago%22
+innerHTML;
%0A g
|
9a3c156e5e427139316941ea1d58322c45024cd8 | fix osx build warnings | tasks/pack.js | tasks/pack.js | module.exports = function (gulp, packageJson) { 'use strict';
const _ = require('underscore');
const electronPackager = require('electron-packager');
const RELEASE_SETTINGS = {
dir: '.',
name: packageJson.name,
out: 'release',
'appVersion': packageJson.version,
'appCopyright': 'Copyright (c) 2016 ' + packageJson.author,
'version-string': {
ProductName : packageJson.name,
CompanyName: packageJson.author,
FileDescription: packageJson.name,
OriginalFilename: packageJson.name + '.exe',
ProductVersion : packageJson.version,
'file-version': packageJson.version,
'product-version': packageJson.version,
LegalCopyright: 'Copyright (c) 2016 ' + packageJson.author
},
win32metadata : {
ProductName : packageJson.name,
CompanyName: packageJson.author,
FileDescription: packageJson.name,
OriginalFilename: packageJson.name + '.exe',
ProductVersion : packageJson.version,
'file-version': packageJson.version,
'product-version': packageJson.version,
LegalCopyright: 'Copyright (c) 2016 ' + packageJson.author
},
ignore : /.idea|release|resources|tasks|.gitignore|.eslintrc.json|gulpfile.js|screenshot.png|README.md|CHANGELOG.md$/,
appPath : packageJson.main,
overwrite: true,
asar: true,
prune: true
};
gulp.task('pack-linux32', (next) => {
electronPackager(_.extend(RELEASE_SETTINGS, {
platform: 'linux',
arch: 'ia32'
}), next);
});
gulp.task('pack-linux64', (next) => {
electronPackager(_.extend(RELEASE_SETTINGS, {
platform: 'linux',
arch: 'x64'
}), next);
});
gulp.task('pack-windows32', (next) => {
electronPackager(_.extend(RELEASE_SETTINGS, {
platform: 'win32',
arch: 'ia32',
icon: 'resources/icons/kongdash-256x256.ico'
}), next);
});
gulp.task('pack-windows64', (next) => {
electronPackager(_.extend(RELEASE_SETTINGS, {
platform: 'win32',
arch: 'x64',
icon: 'resources/icons/kongdash-256x256.ico'
}), next);
});
gulp.task('pack-osx', (next) => {
electronPackager(_.extend(RELEASE_SETTINGS, {
'app-bundle-id': 'io.kongdash',
platform: 'darwin',
arch: 'all',
icon: 'resources/icons/kongdash-256x256.icns'
}), next);
});
};
| JavaScript | 0.000001 | @@ -2456,23 +2456,19 @@
-'
app
--b
+B
undle
--id'
+Id
: 'i
|
987d23b4c07b4ea687dd7b2c70919b1fd2bd70f2 | Clean up in beamChannel.js | app/directives/beamChannel.js | app/directives/beamChannel.js | angular.module('beam.directives')
.directive('beamChannel', function() {
return {
restrict: 'E',
templateUrl: '../templates/beamChannel.html',
scope: {
channel: '@',
connection: '@'
},
controller: function($scope) {
this.channel = $scope.channel;
this.setTopic = function(channel, topic, nick, message) {
if (channel === this.channel) {
this.topic = topic;
$scope.$apply();
}
};
$scope.$parent.clientCtrl.connection.on('topic', this.setTopic.bind(this));
},
controllerAs: 'channelCtrl'
};
});
| JavaScript | 0.000001 | @@ -486,24 +486,35 @@
%7D%0A %7D
+.bind(this)
;%0A $s
@@ -573,16 +573,159 @@
setTopic
+);%0A $scope.$on('$destroy', function() %7B%0A $scope.$parent.clientCtrl.connection.removeListener('topic', this.setTopic);%0A %7D
.bind(th
@@ -730,17 +730,16 @@
this));%0A
-%0A
%7D,
|
7ea6718ef736b20cf7333db064bf471034ac086e | update output data | src/helpers/data_printer.js | src/helpers/data_printer.js | var fs = require('fs');
var path = require('path');
var data = require('../../data/data.json');
exports.printPopulationInfo = function (population, mark) {
var i;
var result;
var bestResult = [];
var worstResult = [];
var best = population[0];
var worst = population[population.length - 1];
for (i = 0; i < data.length; i++) {
bestResult.push({
arg: data[i].arg,
val: best.evaluate(data[i].arg)
});
worstResult.push({
arg: data[i].arg,
val: worst.evaluate(data[i].arg)
});
}
result = {
best: bestResult,
worst: worstResult
};
fs.writeFile(path.join(process.cwd(), 'logs', 'data-' + mark + '.json'),
JSON.stringify(result, null, '\t'), function (error) {
if (error) {
console.error('ERROR: unable to write results to file.', err);
}
});
};
| JavaScript | 0.000036 | @@ -616,33 +616,186 @@
st:
-bestResult,%0A worst
+%7B%0A expression: best.root.getEvalString(),%0A data: bestResult%0A %7D,%0A worst: %7B%0A expression: worst.root.getEvalString(),%0A data
: wo
@@ -800,24 +800,34 @@
worstResult%0A
+ %7D%0A
%7D;%0A%0A
|
777c48bb5ea7d06e7a4104371abfc2da05173dc9 | Add the oneof keyword | src/languages/protobuf.js | src/languages/protobuf.js | /*
Language: Protocol Buffers
Author: Dan Tao <daniel.tao@gmail.com>
Description: Protocol buffer message definition format
Category: protocols
*/
function(hljs) {
return {
keywords: {
keyword: 'package import option optional required repeated group',
built_in: 'double float int32 int64 uint32 uint64 sint32 sint64 ' +
'fixed32 fixed64 sfixed32 sfixed64 bool string bytes',
literal: 'true false'
},
contains: [
hljs.QUOTE_STRING_MODE,
hljs.NUMBER_MODE,
hljs.C_LINE_COMMENT_MODE,
{
className: 'class',
beginKeywords: 'message enum service', end: /\{/,
illegal: /\n/,
contains: [
hljs.inherit(hljs.TITLE_MODE, {
starts: {endsWithParent: true, excludeEnd: true} // hack: eating everything after the first title
})
]
},
{
className: 'function',
beginKeywords: 'rpc',
end: /;/, excludeEnd: true,
keywords: 'rpc returns'
},
{
begin: /^\s*[A-Z_]+/,
end: /\s*=/, excludeEnd: true
}
]
};
}
| JavaScript | 0.999973 | @@ -255,16 +255,22 @@
ed group
+ oneof
',%0A
|
2464d13414c522eacecfa7400894fdd65dde8303 | fix FeatureGroup e.layer empty in old IE, close #1938 | src/layer/FeatureGroup.js | src/layer/FeatureGroup.js | /*
* L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods
* shared between a group of interactive layers (like vectors or markers).
*/
L.FeatureGroup = L.LayerGroup.extend({
includes: L.Mixin.Events,
statics: {
EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose'
},
addLayer: function (layer) {
if (this.hasLayer(layer)) {
return this;
}
if ('on' in layer) {
layer.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
}
L.LayerGroup.prototype.addLayer.call(this, layer);
if (this._popupContent && layer.bindPopup) {
layer.bindPopup(this._popupContent, this._popupOptions);
}
return this.fire('layeradd', {layer: layer});
},
removeLayer: function (layer) {
if (!this.hasLayer(layer)) {
return this;
}
if (layer in this._layers) {
layer = this._layers[layer];
}
layer.off(L.FeatureGroup.EVENTS, this._propagateEvent, this);
L.LayerGroup.prototype.removeLayer.call(this, layer);
if (this._popupContent) {
this.invoke('unbindPopup');
}
return this.fire('layerremove', {layer: layer});
},
bindPopup: function (content, options) {
this._popupContent = content;
this._popupOptions = options;
return this.invoke('bindPopup', content, options);
},
setStyle: function (style) {
return this.invoke('setStyle', style);
},
bringToFront: function () {
return this.invoke('bringToFront');
},
bringToBack: function () {
return this.invoke('bringToBack');
},
getBounds: function () {
var bounds = new L.LatLngBounds();
this.eachLayer(function (layer) {
bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
});
return bounds;
},
_propagateEvent: function (e) {
if (!e.layer) {
e.layer = e.target;
}
e.target = this;
this.fire(e.type, e);
}
});
L.featureGroup = function (layers) {
return new L.FeatureGroup(layers);
};
| JavaScript | 0 | @@ -1838,37 +1838,40 @@
%0D%0A%09%09
-if (!e.layer)
+e = L.extend(%7B%7D, e,
%7B%0D%0A%09%09%09
-e.
layer
- =
+:
e.t
@@ -1879,36 +1879,33 @@
rget
-;
+,
%0D%0A%09%09
-%7D%0D%0A%09%09e.
+%09
target
- =
+:
this
-;
%0D%0A
+%09%09%7D);
%0D%0A%09%09
|
607cf7063cbcb2e5b5c0f0ca4afd1149e815b456 | remove trailing comma | generators/entity/templates/src/main/webapp/app/entities/_entity-management.js | generators/entity/templates/src/main/webapp/app/entities/_entity-management.js | 'use strict';
angular.module('<%=angularAppName%>')
.config(function ($stateProvider) {
$stateProvider
.state('<%= entityStateName %>', {
parent: 'entity',
url: '/<%= entityUrl %>',
data: {
authorities: ['ROLE_USER'],
pageTitle: <% if (enableTranslation){ %>'<%= angularAppName %>.<%= entityTranslationKey %>.home.title'<% }else{ %>'<%= entityClassPlural %>'<% } %>
},
views: {
'content@': {
templateUrl: 'app/entities/<%= entityFolderName %>/<%= entityFileName %>.html',
controller: '<%= entityClass %>ManagementController'
}
},
resolve: {<% if (enableTranslation){ %>
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('<%= entityInstance %>');<%
for (var fieldIdx in fields) {
if (fields[fieldIdx].fieldIsEnum == true) { %>
$translatePartialLoader.addPart('<%= fields[fieldIdx].enumInstance %>');<% }} %>
$translatePartialLoader.addPart('global');
return $translate.refresh();
}]<% } %>
}
})
.state('<%= entityStateName %>-detail', {
parent: 'entity',
url: '/<%= entityUrl %>/{id:<%= entityUrlType %>}',
data: {
authorities: ['ROLE_USER'],
pageTitle: <% if (enableTranslation){ %>'<%= angularAppName %>.<%= entityTranslationKey %>.detail.title'<% }else{ %>'<%= entityClass %>'<% } %>
},
views: {
'content@': {
templateUrl: 'app/entities/<%= entityFolderName %>/<%= entityFileName %>-detail.html',
controller: '<%= entityClass %>ManagementDetailController'
}
},
resolve: {<% if (enableTranslation){ %>
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('<%= entityInstance %>');<%
for (var fieldIdx in fields) {
if (fields[fieldIdx].fieldIsEnum == true) { %>
$translatePartialLoader.addPart('<%= fields[fieldIdx].enumInstance %>');<% }} %>
return $translate.refresh();
}],<% } %>
entity: ['$stateParams', '<%= entityClass %>', function($stateParams, <%= entityClass %>) {
return <%= entityClass %>.get({id : $stateParams.id});
}]
}
})
.state('<%= entityStateName %>.new', {
parent: '<%= entityStateName %>',
url: '/new',
data: {
authorities: ['ROLE_USER'],
},
onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
$uibModal.open({
templateUrl: 'app/entities/<%= entityFolderName %>/<%= entityFileName %>-dialog.html',
controller: '<%= entityClass %>ManagementDialogController',
size: 'lg',
resolve: {
entity: function () {
return {
<%_ for (fieldId in fields) { _%>
<%_ if (fields[fieldId].fieldType == 'Boolean' && fields[fieldId].fieldValidate == true && fields[fieldId].fieldValidateRules.indexOf('required') != -1) { _%>
<%= fields[fieldId].fieldName %>: false,
<%_ } else { _%>
<%= fields[fieldId].fieldName %>: null,
<%_ if (fields[fieldId].fieldType == 'byte[]' && fields[fieldId].fieldTypeBlobContent != 'text') { _%>
<%= fields[fieldId].fieldName %>ContentType: null,
<%_ } _%>
<%_ } _%>
<%_ } _%>
id: null
};
}
}
}).result.then(function(result) {
$state.go('<%= entityStateName %>', null, { reload: true });
}, function() {
$state.go('<%= entityStateName %>');
})
}]
})
.state('<%= entityStateName %>.edit', {
parent: '<%= entityStateName %>',
url: '/{id:<%= entityUrlType %>}/edit',
data: {
authorities: ['ROLE_USER'],
},
onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
$uibModal.open({
templateUrl: 'app/entities/<%= entityFolderName %>/<%= entityFileName %>-dialog.html',
controller: '<%= entityClass %>ManagementDialogController',
size: 'lg',
resolve: {
entity: ['<%= entityClass %>', function(<%= entityClass %>) {
return <%= entityClass %>.get({id : $stateParams.id});
}]
}
}).result.then(function(result) {
$state.go('<%= entityStateName %>', null, { reload: true });
}, function() {
$state.go('^');
})
}]
})
.state('<%= entityStateName %>.delete', {
parent: '<%= entityStateName %>',
url: '/{id:<%= entityUrlType %>}/delete',
data: {
authorities: ['ROLE_USER'],
},
onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
$uibModal.open({
templateUrl: 'app/entities/<%= entityFolderName %>/<%= entityFileName %>-delete-dialog.html',
controller: '<%= entityClass %>ManagementDeleteController',
size: 'md',
resolve: {
entity: ['<%= entityClass %>', function(<%= entityClass %>) {
return <%= entityClass %>.get({id : $stateParams.id});
}]
}
}).result.then(function(result) {
$state.go('<%= entityStateName %>', null, { reload: true });
}, function() {
$state.go('^');
})
}]
});
});
| JavaScript | 0.999551 | @@ -3199,33 +3199,32 @@
s: %5B'ROLE_USER'%5D
-,
%0A
|
3c722af642212ccf7afcf88b2309219166fe3c0b | return only uploaded photos for the moment | social-mirror-fb.js | social-mirror-fb.js | 'use strict';
function SocialMirrorFB(fb, async, q) {
this.fb = fb;
this.async = async;
this.q = q;
}
SocialMirrorFB.prototype.getOne = function(resource, fields, accessToken, mapFunction) {
var deferred = this.q.defer();
var self = this;
this.fb.api(resource, { fields: fields, access_token: accessToken },
function(response) {
if (response.error) { deferred.reject(response.error) }
else { deferred.resolve(response.data.map(mapFunction)) }
});
return deferred.promise;
};
SocialMirrorFB.prototype.getAll = function(resource, fields, accessToken, mapFunction) {
var deferred = this.q.defer();
var data = [];
var after = '';
var self = this;
self.async.doWhilst(function (callback) {
self.fb.api(resource, {
fields: fields,
limit: '200',
// type: 'uploaded',
after: after,
access_token: accessToken
}, function(response) {
// console.log(response);
if (/*!response || */response.error) {
callback(response.error);
} else {
data = data.concat(response.data.map(mapFunction));
if (response.paging && response.paging.next) { // next is the best indicator to know if there are more
after = response.paging.cursors.after;
} else {
after = undefined;
}
callback();
}
});
},
function () {
return after !== undefined;
},
function (error) {
if (error) { deferred.reject(error) }
else { deferred.resolve(data) }
});
return deferred.promise;
};
SocialMirrorFB.prototype.getAllPhotos = function(accessToken, profileId = 'me') {
var photoMapFunction = function(photo) {
return {
id: photo.id,
title: photo.name,
thumb: photo.picture,
album_id: (photo.album ? photo.album.id : '__no_album__'),
source: (photo.images[0].source),
height: (photo.images[0].height),
width: (photo.images[0].width),
creation: photo.created_time,
link: photo.link,
reactions: (photo.reactions ? photo.reactions.data.length : 0),
comments: (photo.comments ? photo.comments.data.length : 0)
}
};
return this.getAll('/' + profileId + '/photos', 'id,name,picture,album{id},images{source,width,height},created_time,link,reactions.limit(99){type},comments.limit(99){id}', accessToken, photoMapFunction);
};
SocialMirrorFB.prototype.getAllAlbums = function(accessToken, profileId = 'me') {
var albumMapFunction = function(album) {
return {
id: album.id,
title: album.name,
description: album.description,
creation: album.created_time,
count: album.count,
thumb_photo_id: album.cover_photo.id,
link: album.link,
reactions: (album.reactions ? album.reactions.data.length : 0),
comments: (album.comments ? album.comments.data.length : 0)
}
};
return this.getAll('/' + profileId + '/albums', 'id,name,description,created_time,count,cover_photo{id},link,reactions.limit(99){type},comments.limit(99){id}', accessToken, albumMapFunction);
};
SocialMirrorFB.prototype.getAllAccounts = function(accessToken) {
var profileMapFunction = function(profile) {
return {
id: profile.id,
title: profile.name,
thumb: profile.picture.data.url,
}
};
return this.getAll('/me/accounts', 'id,name,picture{url}', accessToken, profileMapFunction);
};
SocialMirrorFB.prototype.getMe = function(accessToken) {
var profileMapFunction = function(profile) {
return {
id: profile.id,
title: profile.name,
thumb: profile.picture.data.url,
}
};
return this.getOne('/me', 'id,name,picture{url}', accessToken, profileMapFunction);
};
SocialMirrorFB.prototype.getAllProfiles = function(accessToken) {
var promises = [ this.getMe(accessToken) ].concat(this.getAllAccounts(accessToken));
return this.q.all(promises);
};
/*
SocialMirrorFB.prototype.getData = function(accessToken) {
var deferred = this.q.defer();
var self = this;
this.async.parallel({
photos: function(callback) {
self.getAllPhotos(accessToken).then(
function(d) { callback(null, d) },
function(e) { callback(e) }
);
},
albums: function(callback) {
self.getAllAlbums(accessToken).then(
function(d) { callback(null, d) },
function(e) { callback(e) }
);
},
accounts: function(callback) {
self.getAllAccounts(accessToken).then(
function(d) { callback(null, d) },
function(e) { callback(e) }
);
}
}, function(error, data) {
if (error) { deferred.reject(error) }
else { deferred.resolve(data) }
});
return deferred.promise;
};
*/
module.exports = SocialMirrorFB;
| JavaScript | 0 | @@ -1774,16 +1774,50 @@
lbum_id:
+ photo.album.id, //if !uploaded -%3E
(photo.
@@ -2230,16 +2230,25 @@
'/photos
+/uploaded
', 'id,n
|
6f3f5fc359c403e07e5123038f38bd46f3010cff | update userFollowing | src/documentModels/userFollowing.js | src/documentModels/userFollowing.js | 'use strict';
const objectSorter = require('../helpers/objectSorter');
const moment = require('moment');
class UserFollowing {
constructor(document, db, config) {
if (document == null || db == null || config == null) {
throw new Error('missing arguments');
}
this.document = document;
this.db = db;
}
// TODO: 各種操作用メソッドの追加
serialize() {
const res = {};
Object.assign(res, this.document);
// createdAt
res.createdAt = parseInt(moment(res._id.getTimestamp()).format('X'));
// id
res.id = res._id.toString();
delete res._id;
Object.keys(res).sort();
return objectSorter(res);
}
// 最新の情報を取得して同期する
async fetchAsync() {
this.document = (await this.db.userFollowings.findByIdAsync(this.document._id)).document;
}
async removeAsync() {
await this.db.userFollowings.removeAsync({_id: this.document._id});
this.document = null;
}
// static methods
static async findBySrcDestAsync(source, destination, db, config) {
if (source == null || destination == null || db == null || config == null) {
throw new Error('missing arguments');
}
return db.userFollowings.findAsync({source: source, destination: destination});
}
}
module.exports = UserFollowing;
| JavaScript | 0 | @@ -917,16 +917,18 @@
ySrcDest
+Id
Async(so
@@ -931,29 +931,28 @@
c(source
-, destination
+Id, targetId
, db, co
@@ -971,16 +971,18 @@
(source
+Id
== null
@@ -985,27 +985,24 @@
null %7C%7C
-destination
+targetId
== null
@@ -1139,34 +1139,28 @@
urce
-, destination: destination
+Id, target: targetId
%7D);%0A
|
ce2c882ba4cf289c70d23b5108050c8fed54670f | Fix discussion card highlight below lollipop | app/views/discussion-item.js | app/views/discussion-item.js | import React from "react-native";
import Colors from "../../colors.json";
import NotificationBadgeContainer from "../containers/notification-badge-container";
import Card from "./card";
import CardTitle from "./card-title";
import CardSummary from "./card-summary";
import DiscussionFooter from "./discussion-footer";
import Embed from "./embed";
import TouchFeedback from "./touch-feedback";
import Modal from "./modal";
import Icon from "./icon";
import Link from "./link";
import Linking from "../modules/linking";
import Clipboard from "../modules/clipboard";
import Share from "../modules/share";
import routes from "../utils/routes";
import textUtils from "../lib/text-utils";
import config from "../store/config";
const {
ToastAndroid,
StyleSheet,
TouchableOpacity,
View
} = React;
const styles = StyleSheet.create({
image: {
marginVertical: 4,
height: 180,
width: null
},
item: {
marginHorizontal: 16
},
footer: {
marginVertical: 12
},
topArea: {
flexDirection: "row"
},
title: {
flex: 1,
marginTop: 16
},
badge: {
margin: 12
},
expand: {
marginHorizontal: 16,
marginVertical: 12,
color: Colors.fadedBlack
},
hidden: {
opacity: 0.3
}
});
export default class DiscussionItem extends React.Component {
shouldComponentUpdate(nextProps) {
return (
this.props.hidden !== nextProps.hidden ||
this.props.thread.title !== nextProps.thread.title ||
this.props.thread.text !== nextProps.thread.text ||
this.props.thread.from !== nextProps.thread.from
);
}
_copyToClipboard(text) {
Clipboard.setText(text);
ToastAndroid.show("Copied to clipboard", ToastAndroid.SHORT);
}
_showMenu() {
const { thread } = this.props;
const menu = {};
menu["Copy title"] = () => this._copyToClipboard(thread.title);
const metadata = textUtils.getMetadata(thread.text);
if (metadata && metadata.type === "image") {
menu["Open image in browser"] = () => Linking.openURL(metadata.url);
menu["Copy image link"] = () => this._copyToClipboard(metadata.url);
} else {
menu["Copy summary"] = () => this._copyToClipboard(thread.text);
}
menu["Share discussion"] = () => {
const { protocol, host } = config.server;
const { id, to, title } = thread;
Share.shareItem("Share discussion", `${protocol}//${host}/${to}/${id}/${title.toLowerCase().trim().replace(/['"]/g, "").replace(/\W+/g, "-")}`);
};
if (this.props.isCurrentUserAdmin()) {
if (this.props.hidden) {
menu["Unhide discussion"] = () => this.props.unhideText();
} else {
menu["Hide discussion"] = () => this.props.hideText();
}
if (thread.from !== this.props.currentUser) {
if (this.props.isUserBanned()) {
menu["Unban " + thread.from] = () => this.props.unbanUser();
} else {
menu["Ban " + thread.from] = () => this.props.banUser();
}
}
}
Modal.showActionSheetWithItems(menu);
}
_onPress() {
this.props.navigator.push(routes.chat({
thread: this.props.thread.id,
room: this.props.thread.to
}));
}
render() {
const { thread, hidden } = this.props;
const trimmedText = thread.text.trim();
const links = Link.parseLinks(trimmedText, 1);
const metadata = textUtils.getMetadata(trimmedText);
let cover, hideSummary;
if (metadata && metadata.type === "photo") {
cover = (
<Embed
url={metadata.url}
data={metadata}
thumbnailStyle={styles.image}
showTitle={false}
showSummary={false}
/>
);
hideSummary = true;
} else if (links.length) {
cover = (
<Embed
url={links[0]}
thumbnailStyle={styles.image}
showTitle={false}
showSummary={false}
/>
);
}
return (
<Card {...this.props}>
<TouchFeedback onPress={this._onPress.bind(this)}>
<View style={hidden ? styles.hidden : null}>
<View style={styles.topArea}>
<CardTitle
style={[ styles.item, styles.title ]}
text={this.props.thread.title}
/>
<NotificationBadgeContainer thread={this.props.thread.id} style={styles.badge} />
<TouchableOpacity onPress={this._showMenu.bind(this)}>
<Icon
name="expand-more"
style={styles.expand}
size={20}
/>
</TouchableOpacity>
</View>
{cover}
{hideSummary ? null :
<CardSummary style={styles.item} text={trimmedText} />
}
<DiscussionFooter style={[ styles.item, styles.footer ]} thread={thread} />
</View>
</TouchFeedback>
</Card>
);
}
}
DiscussionItem.propTypes = {
thread: React.PropTypes.shape({
id: React.PropTypes.string.isRequired,
title: React.PropTypes.string.isRequired,
text: React.PropTypes.string.isRequired,
from: React.PropTypes.string.isRequired,
to: React.PropTypes.string.isRequired
}).isRequired,
navigator: React.PropTypes.object.isRequired,
currentUser: React.PropTypes.string.isRequired,
hidden: React.PropTypes.bool.isRequired,
isCurrentUserAdmin: React.PropTypes.func.isRequired,
isUserBanned: React.PropTypes.func.isRequired,
hideText: React.PropTypes.func.isRequired,
unhideText: React.PropTypes.func.isRequired,
banUser: React.PropTypes.func.isRequired,
unbanUser: React.PropTypes.func.isRequired
};
| JavaScript | 0.000002 | @@ -713,16 +713,56 @@
config%22;
+%0Aimport colors from %22../../colors.json%22;
%0A%0Aconst
@@ -3772,24 +3772,53 @@
.bind(this)%7D
+ pressColor=%7Bcolors.underlay%7D
%3E%0A%09%09%09%09%09%3CView
|
efedb907d8ef3d255eaa02e997fd89e9d54d1935 | Add username to getuserRepos function call | javascript/controllers/twitter-controller.js | javascript/controllers/twitter-controller.js | angular.module('Gistter')
.controller('TwitterController', function($scope, $q, twitterService, $http) {
$scope.tweets = [];
$scope.repos = [];
twitterService.initialize();
// using the OAuth authorization result get the latest 20+ tweets from twitter for the user
$scope.refreshTimeline = function(maxId) {
var has_gist = [];
twitterService.getLatestTweets(maxId).then(function(data) {
$scope.tweets = $scope.tweets.concat(data);
// go through each tweet and find gists
angular.forEach($scope.tweets, function(tweet, i) {
if (tweet.entities.urls[0]) {
if (tweet.entities.urls[0].expanded_url.indexOf("github") > -1) {
$scope.findRepos(tweet.entities.urls[0].expanded_url);
has_gist.push(tweet);
}
}
});
$scope.tweets = has_gist;
});
};
// Query tweet that contains gist for git user's repos
$scope.findRepos = function(gist) {
var username = gist.split('/')[3];
if ($scope.repos.length === 0) {
getUserRepos();
} else {
var getOut = 0;
for(var i; i < $scope.repos.length ;i++){
if (username === $scope.repos[i]) {
getOut++;
break;
}
}
if (getOut === 0) {
getUserRepos();
}
}
};
var getUserRepos = function(username){
$http.get("https://api.github.com/users/" + username + "/repos")
.then(onRepos, onError);
};
var onRepos = function(response) {
$scope.repos.push(response.data);
};
var onError = function(reason) {
$scope.error = "Could not fetch the data";
};
//when the user clicks the connect twitter button, the popup authorization window opens
$scope.connectButton = function() {
twitterService.connectTwitter().then(function() {
if (twitterService.isReady()) {
//if the authorization is successful, hide the connect button and display the tweets
$('#connectButton').fadeOut(function() {
$('#getTimelineButton, #signOut').fadeIn();
$scope.refreshTimeline();
$scope.connectedTwitter = true;
});
} else {
alert("We could not connect you successfully.");
}
});
};
//sign out clears the OAuth cache, the user will have to reauthenticate when returning
$scope.signOut = function() {
twitterService.clearCache();
$scope.tweets.length = 0;
$('#getTimelineButton, #signOut').fadeOut(function() {
$('#connectButton').fadeIn();
$scope.$apply(function() {
$scope.connectedTwitter = false;
});
});
};
//if the user is a returning user, hide the sign in button and display the tweets
if (twitterService.isReady()) {
$('#connectButton').hide();
$('#getTimelineButton, #signOut').show();
$scope.connectedTwitter = true;
$scope.refreshTimeline();
}
});
| JavaScript | 0 | @@ -1034,24 +1034,32 @@
etUserRepos(
+username
);%0A %7D els
@@ -1058,24 +1058,66 @@
%7D else %7B%0A
+ // make sure usernmae doesn't exist%0A
var ge
@@ -1320,16 +1320,24 @@
erRepos(
+username
);%0A
|
f145415eb54c158d08a50e47dab68e3926841f5b | set country to location.country for new members | app/javascript/consent/index.js | app/javascript/consent/index.js | import React from 'react';
import { render } from 'react-dom';
import ComponentWrapper from '../components/ComponentWrapper';
import ConsentComponent from './ConsentComponent';
import {
setPreviouslyConsented,
changeCountry,
changeMemberEmail,
changeMemberId,
changeVariant,
} from '../state/consent';
// TODO: Listen for member ID (new members)
export default function ConsentFeature(options) {
if (!options) {
throw new Error(
'ConsentFeature must be initialized with an options object'
);
}
const store = window.champaign.store;
const member = window.champaign.personalization.member;
const variant = options.variant;
const $countrySelect = $('.petition-bar__main select[name=country]');
const $emailInput = $('.petition-bar__main input[name=email]');
// set member id, and email
if (member) {
store.dispatch(setPreviouslyConsented(member.consented));
store.dispatch(changeMemberEmail(member.email));
store.dispatch(changeMemberId(member.id));
store.dispatch(changeCountry(member.country));
}
if (options.variant) store.dispatch(changeVariant(options.variant));
// listen for changes to country
$countrySelect.on('change', () =>
store.dispatch(changeCountry($countrySelect.val() || null))
);
// listen for changes to email
$emailInput.on('change', () =>
store.dispatch(changeMemberEmail($emailInput.val() || null))
);
render(
<ComponentWrapper store={window.champaign.store} locale={I18n.locale}>
<ConsentComponent />
</ComponentWrapper>,
options.container
);
}
| JavaScript | 0.00002 | @@ -564,23 +564,37 @@
%0A const
+ %7B
member
+, location %7D
= windo
@@ -624,15 +624,8 @@
tion
-.member
;%0A
@@ -1051,16 +1051,36 @@
.country
+ %7C%7C location.country
));%0A %7D%0A
|
cd6d08285e3e85b2abbd6d2ed05f1663535484fc | Allow CORS for Authorization header | config/cors.js | config/cors.js | /**
* Cross-Origin Resource Sharing (CORS) Settings
* (sails.config.cors)
*
* CORS is like a more modern version of JSONP-- it allows your server/API
* to successfully respond to requests from client-side JavaScript code
* running on some other domain (e.g. google.com)
* Unlike JSONP, it works with POST, PUT, and DELETE requests
*
* For more information on CORS, check out:
* http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
*
* Note that any of these settings (besides 'allRoutes') can be changed on a per-route basis
* by adding a "cors" object to the route configuration:
*
* '/get foo': {
* controller: 'foo',
* action: 'bar',
* cors: {
* origin: 'http://foobar.com,https://owlhoot.com'
* }
* }
*
* For more information on this configuration file, see:
* http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.cors.html
*
*/
module.exports.cors = {
/***************************************************************************
* *
* Allow CORS on all routes by default? If not, you must enable CORS on a *
* per-route basis by either adding a "cors" configuration object to the *
* route config, or setting "cors:true" in the route config to use the *
* default settings below. *
* *
***************************************************************************/
allRoutes: true,
/***************************************************************************
* *
* Which domains which are allowed CORS access? This can be a *
* comma-delimited list of hosts (beginning with http:// or https://) or *
* "*" to allow all domains CORS access. *
* *
***************************************************************************/
origin: '*',
/***************************************************************************
* *
* Allow cookies to be shared for CORS requests? *
* *
***************************************************************************/
// credentials: true,
/***************************************************************************
* *
* Which methods should be allowed for CORS requests? This is only used in *
* response to preflight requests (see article linked above for more info) *
* *
***************************************************************************/
// methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
/***************************************************************************
* *
* Which headers should be allowed for CORS requests? This is only used in *
* response to preflight requests. *
* *
***************************************************************************/
// headers: 'content-type'
};
| JavaScript | 0 | @@ -3569,19 +3569,16 @@
****/%0A%0A
- //
headers
@@ -3592,14 +3592,29 @@
ent-type
+, authorization
'%0A%0A%7D;%0A
|
41184c8825ece6c471c3484a078c45231a450d31 | Fix `t/listener.t.js`. | compassion.colleague/t/listener.t.js | compassion.colleague/t/listener.t.js | require('proof/redux')(3, require('cadence')(prove))
function prove (async, assert) {
var Vizsla = require('vizsla')
var ua = new Vizsla
var abend = require('abend')
var conduit = require('compassion.conduit/conduit.bin'), program
async(function () {
program = conduit([ '--bind', '127.0.0.1:8888', '--id', '1' ], {}, async())
}, function () {
var Listener = require('../listener')
var listener = new Listener({
islandName: 'island',
colleagueId: 1,
request: function (type, message, callback) {
assert(type, 'kibitz', 'request type')
assert(message, {
islandName: 'island',
colleagueId: 1,
key: 'value'
}, 'request message')
callback(null, { called: true })
}
})
async(function () {
listener.listen('127.0.0.1:8888', { key: 'x' }, abend)
listener.listening.enter(async())
}, function () {
ua.fetch({
url: 'http://127.0.0.1:8888/kibitz',
raise: true,
post: { islandName: 'island', colleagueId: 1, key: 'value' }
}, async())
}, function (body) {
assert(body.called, 'called')
listener.stop()
listener.stop()
})
}, function () {
program.emit('SIGINT')
})
}
| JavaScript | 0 | @@ -1016,13 +1016,12 @@
ing.
-enter
+wait
(asy
|
fee9b6504822182292d96a228d942f93e77f65ec | Update export icons | js/app/handlers/menu-presentation-actions.js | js/app/handlers/menu-presentation-actions.js | ds.actions.register('presentation-actions', [
ds.models.action({
name: 'time-spans',
display: 'View across time spans...',
icon: 'fa fa-clock-o',
hide: ds.app.Mode.TRANSFORM,
handler: function(action, item) {
ds.manager.apply_transform(ds.models.transform.TimeSpans(), item)
}
}),
ds.models.action({
name: 'time-shifts',
display: 'Time shift...',
icon: 'fa fa-clock-o',
hide: ds.app.Mode.TRANSFORM,
handler: function(action, item) {
ds.manager.apply_transform(ds.models.transform.TimeShift(), item)
}
}),
ds.models.action({
name: 'isolate',
display: 'Isolate...',
icon: 'fa fa-eye',
hide: ds.app.Mode.TRANSFORM,
handler: function(action, item) {
ds.manager.apply_transform(ds.models.transform.Isolate(), item)
}
}),
ds.models.action({
hide: ds.app.Mode.TRANSFORM,
divider: true
}),
ds.models.action({
name: 'open-in-graphite',
display: 'Open in Graphite...',
icon: 'fa fa-bar-chart-o',
handler: function(action, item) {
var composer_url = ds.charts.graphite.composer_url(item, { showTitle: true });
window.open(composer_url);
}
}),
ds.models.action({
name: 'export-png',
display: 'Export PNG...',
icon: 'fa fa-picture-o',
handler: function(action, item) {
var image_url = ds.charts.graphite.chart_url(item, { showTitle: true });
window.open(image_url);
}
}),
ds.models.action({
name: 'export-png',
display: 'Export SVG...',
icon: 'fa fa-code',
handler: function(action, item) {
var image_url = ds.charts.graphite.chart_url(item, { showTitle: true, format: 'svg' });
window.open(image_url);
}
}),
ds.models.action({
name: 'export-csv',
display: 'Export CSV...',
icon: 'fa fa-table',
handler: function(action, item) {
var image_url = ds.charts.graphite.chart_url(item, { showTitle: true, format: 'csv' });
window.open(image_url);
}
})
])
$(document).on('click', 'ul.ds-action-menu li', function(event) {
var presentation_id = $(this).parent().parent().parent().parent().parent()[0].id;
var item = ds.manager.current.dashboard.get_item(presentation_id);
var action = ds.actions.get('presentation-actions', this.getAttribute('data-ds-action'))
action.handler(action, item)
/* prevents resetting scroll position */
return false
});
| JavaScript | 0 | @@ -1301,14 +1301,17 @@
fa-
-pictur
+file-imag
e-o'
@@ -1505,34 +1505,34 @@
ame: 'export-
-pn
+sv
g',%0A display:
@@ -1573,12 +1573,19 @@
fa-
+file-
code
+-o
',%0A
@@ -1859,13 +1859,20 @@
fa-
-table
+file-excel-o
',%0A
|
edfacd0ede45a99d86c70b511f50c68699fd6a02 | Create string dir, see https://github.com/phetsims/chipper/issues/1308 | js/scripts/make-conglomerate-string-files.js | js/scripts/make-conglomerate-string-files.js | // Copyright 2022, University of Colorado Boulder
/**
* This script makes a JSON file for each repo subdirectory in phetsims/babel. These files contain a locale object for
* each locale that has a string file in phetsims/babel. Each locale object has every string key / translated value
* pair we have for that locale.
*
* @author Liam Mulhall
*/
// imports
const fs = require( 'fs' );
const path = require( 'path' );
( () => {
try {
// OS-independent path to babel repo.
const babelPath = path.join( __dirname, '..', '..', '..', 'babel' );
// Array of files (mostly subdirectories whose names are repos) in the babel repo.
const babelFiles = fs.readdirSync( babelPath );
// We don't care about these files for the purposes of this script.
const babelFilesToIgnore = [ '.git', '.gitignore', 'LICENSE', 'README.md' ];
const babelFilesToIterateThrough = babelFiles.filter( file => !babelFilesToIgnore.includes( file ) );
// For each file (i.e. each repo subdirectory) in the babel repo...
for ( const file of babelFilesToIterateThrough ) {
// Create a file name for the conglomerate string file.
const conglomerateStringFileName = `${file}_all_locales_strings.json`;
// Create an empty object for the conglomerate string file that we will add to later.
const conglomerateStringObject = {};
// Get an array of files (string files) in the repo subdirectory.
const filePath = path.join( babelPath, file );
const stringFiles = fs.readdirSync( filePath );
// Regex for extracting locale from file name.
const localeRegex = /(?<=_)(.*)(?=.json)/;
// For each string file in the repo subdirectory...
for ( const stringFile of stringFiles ) {
// Extract the locale.
const localeMatches = stringFile.match( localeRegex );
const locale = localeMatches[ 0 ];
// Get the contents of the string file.
const stringFilePath = path.join( filePath, stringFile );
const stringFileContents = fs.readFileSync( stringFilePath, 'utf8' );
// Parse the string file contents.
const parsedStringFileContents = JSON.parse( stringFileContents );
// Add only the values of the string file to the new conglomerate string file.
// That is, we ignore the string key's history.
const objectToAddToLocale = {};
for ( const stringKey of Object.keys( parsedStringFileContents ) ) {
objectToAddToLocale[ stringKey ] = {
value: parsedStringFileContents[ stringKey ].value
};
}
// Add the string file contents minus the history to the locale object of the conglomerate string object.
conglomerateStringObject[ locale ] = objectToAddToLocale;
}
// TODO: Remove when done. See https://github.com/phetsims/chipper/issues/1308.
if ( conglomerateStringFileName === 'acid-base-solutions_all_locales_strings.json' ) {
const outputPath = path.join( __dirname, '..', '..', 'dist', 'strings', conglomerateStringFileName );
fs.writeFileSync( outputPath, JSON.stringify( conglomerateStringObject, null, 2 ) );
return;
}
}
}
catch( e ) {
console.error( e );
}
} )(); | JavaScript | 0.000002 | @@ -2957,24 +2957,25 @@
s.json' ) %7B%0A
+%0A
cons
@@ -2982,20 +2982,19 @@
t output
-Path
+Dir
= path.
@@ -3039,16 +3039,103 @@
strings'
+ );%0A fs.mkdirSync( outputDir );%0A%0A const outputPath = path.join( outputDir
, conglo
@@ -3154,24 +3154,25 @@
FileName );%0A
+%0A
fs.w
|
03e8fe2a2c6545186f15c58d93f048d982439f97 | update config files | config/gulp.js | config/gulp.js | var _ = require('lodash');
var argv = require('yargs').argv;
var SERVER = './server/';
var TEST = './test/';
var CONFIG = './config/';
var CLIENT = './client/';
var CLIENT_JS = CLIENT + 'js/';
var CLIENT_CSS = CLIENT + 'css/';
var ASSETS = './public/assets/';
var JS_ASSETS = ASSETS + 'js/';
var CSS_ASSETS = ASSETS + 'css/';
var FONT_ASSETS = ASSETS + 'fonts/';
var config = {
args: {
isProduction: argv.production === true,
isOnlyWatching: argv.watch === true
},
filters: {
jsDeep: '**/*.js',
cssDeep: '**/*.css',
css: '*.css',
fonts: '**/glyphicons-*'
},
paths: {
server: SERVER,
test: TEST,
config: CONFIG,
client: CLIENT,
clientJs: CLIENT_JS,
clientCss: CLIENT_CSS,
assets: ASSETS,
jsAssets: JS_ASSETS,
cssAssets: CSS_ASSETS,
fontAssets: FONT_ASSETS
}
};
var taskConfigs = {
browserify: {
debug: !config.args.isProduction,
noParse: [
'jquery', 'bootstrap'
],
bundles: [
{
required: [
'jquery', 'bootstrap'
],
dest: config.paths.jsAssets,
outputName: 'common.ui.js'
},
{
entries: config.paths.clientJs + 'app.js',
externalBundles: [
'common.ui.js'
],
dest: config.paths.jsAssets,
outputName: 'app.js',
isWatching: true
}
]
},
bobr: {
},
watcher: {
watchers: [
{
src: [config.paths.clientCss + config.filters.css],
tasks: ['build-app-src']
}
]
}
};
_.assign(config, taskConfigs);
module.exports = config;
| JavaScript | 0.000001 | @@ -1,637 +1,74 @@
-var _ = require('lodash');%0Avar argv = require('yargs').argv;%0A%0Avar SERVER = './server/';%0Avar TEST = './test/';%0Avar CONFIG = './config/';%0Avar CLIENT = './client/';%0Avar CLIENT_JS = CLIENT + 'js/';%0Avar CLIENT_CSS = CLIENT + 'css/';%0Avar ASSETS = './public/assets/';%0Avar JS_ASSETS = ASSETS + 'js/';%0Avar CSS_ASSETS = ASSETS + 'css/';%0Avar FONT_ASSETS = ASSETS + 'fonts/';%0A%0Avar config = %7B%0A args: %7B%0A isProduction: argv.production === true,%0A isOnlyWatching: argv.watch === true%0A %7D,%0A %0A filters: %7B%0A jsDeep: '**/*.js',%0A cssDeep: '**/*.css',%0A css: '*.css',%0A fonts: '**/glyphicons-*
+'use strict';%0A%0Avar config = %7B%0A filters: %7B%0A jsDeep: '**/*.js
'%0A %7D,%0A
-
%0A p
@@ -83,966 +83,101 @@
-server: SERVER,%0A test: TEST,%0A config: CONFIG,%0A client: CLIENT,%0A clientJs: CLIENT_JS,%0A clientCss: CLIENT_CSS,%0A assets: ASSETS,%0A jsAssets: JS_ASSETS,%0A cssAssets: CSS_ASSETS,%0A fontAssets: FONT_ASSETS%0A %7D%0A%7D;%0A%0Avar taskConfigs = %7B%0A browserify: %7B%0A debug: !config.args.isProduction,%0A noParse: %5B%0A 'jquery', 'bootstrap'%0A %5D,%0A bundles: %5B%0A %7B%0A required: %5B%0A 'jquery', 'bootstrap'%0A %5D,%0A dest: config.paths.jsAssets,%0A outputName: 'common.ui.js'%0A %7D,%0A %7B%0A entries: config.paths.clientJs + 'app.js',%0A externalBundles: %5B%0A 'common.ui.js'%0A %5D,%0A dest: config.paths.jsAssets,%0A outputName: 'app.js',%0A isWatching: true%0A %7D%0A %5D%0A %7D,%0A %0A bobr: %7B%0A %7D,%0A %0A watcher: %7B%0A watchers: %5B%0A %7B%0A src: %5Bconfig.paths.clientCss + config.filters.css%5D,%0A tasks: %5B'build-app-src'%5D%0A %7D%0A %5D%0A %7D%0A%7D;%0A%0A_.assign(config, taskConfigs)
+config: './config/',%0A gulp: './tasks/',%0A server: './server/',%0A test: './test/'%0A %7D%0A%7D
;%0A%0Am
|
0e8872114d8122dcc3c95de5a072160f67479e99 | handle odd input names properly. | src/lib/dependshandler.js | src/lib/dependshandler.js | define([
"jquery",
"./depends_parse"
], function($, parser) {
function DependsHandler($el, expression) {
var $context = $el.closest("form");
if (!$context.length)
$context=$(document);
this.$el=$el;
this.$context=$context;
this.ast=parser.parse(expression); // TODO: handle parse exceptions here
}
DependsHandler.prototype = {
_findInputs: function(name) {
var $input = this.$context.find(":input[name="+name+"]");
if (!$input.length)
$input=$("#"+name);
return $input;
},
_getValue: function(name) {
var $input = this._findInputs(name);
if (!$input.length)
return null;
if ($input.attr("type")==="radio" || $input.attr("type")==="checkbox")
return $input.filter(":checked").val() || null;
else
return $input.val();
},
getAllInputs: function() {
var todo = [this.ast],
$inputs = $(),
node;
while (todo.length) {
node=todo.shift();
if (node.input)
$inputs=$inputs.add(this._findInputs(node.input));
if (node.children && node.children.length)
todo.push.apply(todo, node.children);
}
return $inputs;
},
_evaluate: function(node) {
var value = node.input ? this._getValue(node.input) : null,
i;
switch (node.type) {
case "NOT":
return !this._evaluate(node.children[0]);
case "AND":
for (i=0; i<node.children.length; i++)
if (!this._evaluate(node.children[i]))
return false;
return true;
case "OR":
for (i=0; i<node.children.length; i++)
if (this._evaluate(node.children[i]))
return true;
return false;
case "comparison":
switch (node.operator) {
case "=":
return node.value==value;
case "!=":
return node.value!=value;
case "<=":
return value<=node.value;
case "<":
return value<node.value;
case ">":
return value>node.value;
case ">=":
return value>=node.value;
}
break;
case "truthy":
return !!value;
}
},
evaluate: function() {
return this._evaluate(this.ast);
}
};
return DependsHandler;
});
| JavaScript | 0.000002 | @@ -493,16 +493,17 @@
ame=
+'
%22+name+%22
%5D%22);
@@ -498,16 +498,17 @@
%22+name+%22
+'
%5D%22);%0A
|
9e19789b120bd7d5bed90a536474d0d27e7cd484 | remove card from previos list after updating | app/js/factories/cardFactory.js | app/js/factories/cardFactory.js | app.factory('cardFactory', function () {
var service = {};
var cards = [
{
id: 1,
description: 'Fix bug in player',
list_id: 1,
sortIndex: 0
},
{
id: 2,
description: 'Add feature with D3',
list_id: 1,
sortIndex: 1
},
{
id: 3,
description: 'Learn AngularJS',
list_id: 3,
sortIndex: 0
}
];
service.getCards = function (list) {
return _.filter(cards, {list_id: list.id});
};
service.createCard = function (list, cardDescription) {
cards.push({
id: _.uniqueId('card_'),
description: cardDescription,
list_id: list.id,
sortIndex: getSortIndex(list)
});
};
service.deleteCard = function (card) {
_.pull(cards, card);
changeSortIndicesAfterRemovingCard(card);
};
service.updateCard = function (updatingCard, list) {
var card = _.find(cards, {id: updatingCard.id});
card.description = updatingCard.description;
if (card.list_id !== updatingCard.list_id) {
card.sortIndex = getSortIndex(list);
//console.log(card, 'card');
// todo change this.arrOfCards
changeSortIndicesAfterRemovingCard(card);
}
card.list_id = updatingCard.list_id;
};
service.changeSortIndicesInsideList = function (source, destination) {
var destIndex = destination.index;
source.itemScope.modelValue.sortIndex = destIndex;
if (source.index > destination.index) {
destIndex++;
while ((destIndex < destination.sortableScope.modelValue.length)
&& (destination.sortableScope.modelValue[destIndex].sortIndex < destination.sortableScope.modelValue.length - 1)) {
destination.sortableScope.modelValue[destIndex].sortIndex++;
destIndex++;
}
} else {
destIndex--;
while ((destIndex > -1) && (destination.sortableScope.modelValue[destIndex].sortIndex > 0)) {
destination.sortableScope.modelValue[destIndex].sortIndex--;
destIndex--;
}
}
};
service.changeSortIndicesBetweenLists = function (source, destination) {
source.itemScope.modelValue.list_id = destination.sortableScope.$parent.$ctrl.list.id;
destination.sortableScope.modelValue[destination.index].sortIndex = destination.index;
if (source.index < source.sortableScope.modelValue.length) {
for (var i = source.index; i < source.sortableScope.modelValue.length; i++) {
source.sortableScope.modelValue[i].sortIndex--;
}
}
if (destination.index < destination.sortableScope.modelValue.length - 1) {
for (i = ++destination.index; i < destination.sortableScope.modelValue.length; i++) {
destination.sortableScope.modelValue[i].sortIndex++;
}
}
};
var getSortIndex = function (list) {
return service.getCards(list).length;
};
var changeSortIndicesAfterRemovingCard = function (card) {
var removedIndex = card.sortIndex;
var cardsFromCurrentList = _.filter(cards, {list_id: card.list_id});
console.log(cardsFromCurrentList, 'cardsFromCurrentList');
if (removedIndex < cardsFromCurrentList.length) {
for (var i = removedIndex; i < cardsFromCurrentList.length; i++) {
cardsFromCurrentList[i].sortIndex--;
}
}
};
return service;
});
| JavaScript | 0 | @@ -1023,17 +1023,28 @@
ngCard,
-l
+destinationL
ist) %7B%0A
@@ -1095,24 +1095,25 @@
gCard.id%7D);%0A
+%0A
card
@@ -1223,181 +1223,151 @@
c
-ard.sortIndex =
+han
ge
-t
SortInd
-ex(list);%0A //console.log(card, 'card');%0A // todo change this.arrOfCards%0A changeSortIndicesAfterRemovingCard(card);
+icesAfterRemovingCard(card);%0A card.sortIndex = getSortIndex(destinationList);%0A // todo change this.arrOfCards
%0A
@@ -3240,17 +3240,16 @@
card) %7B%0A
-%0A
@@ -3364,74 +3364,8 @@
%7D);%0A
- console.log(cardsFromCurrentList, 'cardsFromCurrentList');
%0A
|
384eb4d18584cc1b07fc53aba971589883c39fe3 | Update home screen filter | scripts/HomeScreen.js | scripts/HomeScreen.js | var HomeScreen = {
$rightView: null,
$artists: null,
$recommendations: null,
$playlists: null,
menuItem: null,
tabs: null,
page: 0,
hasMore: true,
FILTER: [
'dignitasApollo',
'mrcoolvideoboy',
'huskystarcraft',
'husky',
'day9tv'
],
init: function() {
var self = HomeScreen;
self.$rightView = $('#right > .home');
self.$recommendations = self.$rightView.find('.pane.recommendations');
self.$playlists = self.$rightView.find('.pane.playlists');
self.$artists = self.$rightView.find('.pane.artists');
self.menuItem = new MenuItem({
cssClasses: ['home'],
title: TranslationSystem.get('Home'),
$contentPane: self.$rightView,
onSelected: function() {
HomeScreen.show();
},
translatable: true
});
Menu.getGroup('misc').addMenuItem(self.menuItem);
self.tabs = new Tabs(self.$rightView, {
'artists': self.loadArtists,
'playlists': self.loadTopPlaylists,
'recommendations': self.loadRecommendedArtists
});
// Continous scroll for "Popular artists"
(function() {
var timeout;
self.$rightView.scroll(function(event) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
if (self.$rightView.scrollTop() >= (self.$artists.height() - self.$rightView.height()) && self.hasMore) {
self.loadArtists(true);
}
}, 100);
});
}());
},
show: function(tab) {
var self = HomeScreen;
tab = tab || 'artists';
history.pushState(null, null, '/');
self.$rightView.find('.tabs .' + tab).click();
$('#right > div').hide();
self.$rightView.show();
},
loadRecommendedArtists: function() {
var self = HomeScreen;
var $content = self.$recommendations.find('.content');
history.pushState(null, null, '/recommendations');
$content.html('');
self.$recommendations.find('.help-box').hide();
if (!UserManager.isLoggedIn()) {
self.$recommendations.find('.help-box.not-logged-in').show();
} else if (!UserManager.currentUser.lastfmUserName) {
self.$recommendations.find('.help-box.not-connected-to-lastfm').show();
} else {
Recommendations.findRecommendedArtists(function(artists) {
$.each(artists, function(i, artist) {
if (artist.name) {
var artistSuggestion = new ArtistSuggestion({
name: artist.name,
imageUrl: artist.image[2]['#text'],
mbid: artist.mbid
});
$content.append(artistSuggestion.getSmallView()).show();
}
});
});
}
},
loadTopPlaylists: function() {
var self = HomeScreen;
self.$playlists.html('');
history.pushState(null, null, '/toplist/playlists');
LoadingBar.show();
$.get('/api/toplists/playlists', function(playlists) {
$.each(playlists, function(index, item) {
var playlist = new Playlist(item.title, item.videos, item.remoteId, item.owner, item.isPrivate, item.followers);
if (playlist.videos.length) {
self.$playlists.append(PlaylistView.createSmallPlaylistView(playlist));
}
});
LoadingBar.hide();
});
},
addArtist: function(externalUser) {
var self = this;
if (!externalUser.avatar_url) {
return;
}
if ($.inArray(externalUser.username, self.FILTER) !== -1) {
return;
}
var $item = $('<div class="item"/>'),
$title = $('<div class="title"/>'),
image = new Image();
image.onload = function() {
$item.css({'opacity': '1'});
};
image.src = externalUser.avatar_url;
$item.css({'background-image': 'url('+ externalUser.avatar_url + ')'});
$item.click(function() {
ExternalUserPage.load(externalUser.type, externalUser.username);
});
$title.text(externalUser.username);
$item.append($title);
self.$artists.append($item);
},
loadArtists: function(loadMore) {
var self = HomeScreen,
i = 0,
artist = null,
pageSize = 50;
if (!loadMore) {
self.$artists.html('');
self.page = 0;
self.hasMore = true;
history.pushState(null, null, '/');
}
LoadingBar.show();
$.getJSON('/api/external_users/top/' + pageSize, {page: self.page}, function(data) {
var i,
externalUser;
LoadingBar.hide();
self.page += 1;
if (data.length < pageSize) {
self.hasMore = false;
}
for (i = loadMore ? 1 : 0; i < data.length; i += 1) {
self.addArtist(data[i]);
}
// Load more automatically if we haven't filled the entire screen
if (data.length > 0 && self.$artists.height() < self.$rightView.height() && self.page < 50) {
self.loadArtists(true);
}
});
}
};
| JavaScript | 0 | @@ -277,24 +277,48 @@
'husky',%0A
+ 'collegehumor',%0A
'day
@@ -3945,32 +3945,161 @@
urn;%0A %7D%0A%0A
+ // If they block us, we block them :)%0A if (externalUser.username.match(/VEVO$/)) %7B%0A return;%0A %7D%0A%0A
if ($.in
|
975667e56f72779495859d181bc40ff9cad139e6 | Update middleware | app/middlewares/requireLogin.js | app/middlewares/requireLogin.js | //
// Require Login
//
module.exports = function(req, res, next) {
if (req.session.userID) {
next();
} else {
res.redirect('/login');
}
}; | JavaScript | 0.000001 | @@ -115,21 +115,26 @@
-%7D else %7B
+ return;
%0A
+%7D%0A
@@ -157,16 +157,10 @@
ogin');%0A
- %7D%0A
%7D;
|
25a614f4e02bfc99208716f68da8cac5ec7f39e5 | Make change lock view consistent with style guide | lib/assets/javascripts/cartodb/new_dashboard/dialogs/change_lock_view_model.js | lib/assets/javascripts/cartodb/new_dashboard/dialogs/change_lock_view_model.js | var Backbone = require('backbone');
var _ = require('underscore');
var batchProcessItems = require('new_common/batch_process_items');
/**
* View model for change lock view.
* Manages the life cycle states for the change lock view.
*/
module.exports = Backbone.Collection.extend({
initialize: function(models) {
if (_.chain(models)
.map(function(item) { return item.get('locked'); })
.uniq().value().length > 1) {
var errorMsg = 'It is assumed that all items have the same locked state, a user should never be able to ' +
'select a mixed item with current UI. If you get an error with this message something is broken';
if (window.trackJs && window.trackJs.track) {
window.trackJs.track(errorMsg);
} else {
throw new Error(errorMsg);
}
}
this.setState('ConfirmChangeLock');
this._initialLockValue = models[0].get('locked');
},
state: function() {
return this._state;
},
setState: function(newState) {
this._state = newState;
this.trigger('change');
this.trigger(newState);
},
initialLockValue: function() {
return this._initialLockValue;
},
inverseLock: function() {
this.setState('ProcessingItems');
batchProcessItems({
howManyInParallel: 5,
items: this.toArray(),
processItem: this._lockItem.bind(this, !this.initialLockValue()),
done: this.setState.bind(this, 'ProcessItemsDone'),
fail: this.setState.bind(this, 'ProcessItemsFail')
});
},
_lockItem: function(newLockedValue, item, callback) {
item.save({ locked: newLockedValue })
.done(function() { callback(); })
.fail(function() { callback('something failed'); });
}
});
| JavaScript | 0 | @@ -1622,32 +1622,40 @@
one(function() %7B
+%0A
callback(); %7D)%0A
@@ -1650,16 +1650,22 @@
lback();
+%0A
%7D)%0A
@@ -1684,16 +1684,24 @@
tion() %7B
+%0A
callbac
@@ -1722,16 +1722,22 @@
ailed');
+%0A
%7D);%0A %7D
|
607d3c819a97b9868843470d7dd5bff5997935d2 | Fix test | lib/assets/test/spec/cartodb/common/dialogs/delete_row/delete_row_view.spec.js | lib/assets/test/spec/cartodb/common/dialogs/delete_row/delete_row_view.spec.js | var DeleteRowView = require('../../../../../../javascripts/cartodb/common/dialogs/delete_row/delete_row_view');
describe('common/dialogs/delete_row/delete_row_view', function() {
beforeEach(function() {
this.row = new cdb.admin.Row({
cartodb_id: 100,
the_geom: JSON.stringify({ type: 'point', coordinates: [2,1] })
});
this.table = TestUtil.createTable('test', [['the_geom', 'geometry']]);
this.table.data().add(this.row);
spyOn(this.row, 'destroy');
this.view = new DeleteRowView({
table: this.table,
row: this.row
});
this.view.render();
});
it('should render the view', function() {
expect(this.innerHTML()).toContain('Ok, delete');
expect(this.innerHTML()).toContain("You are about to delete one row");
expect(this.innerHTML()).toContain("Are you sure you want to delete it?");
});
describe('when click ok to delete row', function() {
it('should call to destroy the model', function() {
var server = sinon.fakeServer.create();
server.respondWith("DELETE", "/api/v1/tables/" + this.table.get('name') + "/records/100", [ 204, { "Content-Type": "application/json" }, '' ]);
var succeded = false;
this.table.bind('removing:row', function() {
succeded = true;
});
this.view.$('.ok').click();
server.respond();
expect(succeded).toBeTruthy();
});
});
afterEach(function() {
this.view.clean();
});
});
| JavaScript | 0.000004 | @@ -770,11 +770,9 @@
ete
-one
+a
row
|
9dd69adac87321f41f3ac1eaeb24ec8eff57ea51 | Remove duplicated namespace | lib/node_modules/@stdlib/math/base/blas/dasum/benchmark/benchmark.set_value.js | lib/node_modules/@stdlib/math/base/blas/dasum/benchmark/benchmark.set_value.js | 'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/math/base/random/randu' );
var pow = require( '@stdlib/math/base/special/pow' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var pkg = require( './../package.json' ).name;
var wasm = require( './../lib/wasm.js' )();
// FUNCTIONS //
/**
* Creates a benchmark function for measuring vanilla JavaScript.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark1( len ) {
var x;
var i;
x = new Float64Array( len );
for ( i = 0; i < x.length; i++ ) {
x[ i ] = ( randu()*10000.0 ) - 20000.0;
}
return benchmark;
/**
* Benchmark function.
*
* @private
* @param {Benchmark} b - benchmark instance
*/
function benchmark( b ) {
var v;
var i;
var j;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
for ( j = 0; j < len; j++ ) {
v = ( randu()*10000.0 ) - 20000.0;
x[ j ] = v;
}
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
} // end FUNCTION benchmark()
} // end FUNCTION createBenchmark1()
/**
* Creates a benchmark function for measuring WASM heap `setValue` method.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark2( len ) {
var x;
var i;
x = new Float64Array( len );
for ( i = 0; i < x.length; i++ ) {
x[ i ] = ( randu()*10000.0 ) - 20000.0;
}
return benchmark;
/**
* Benchmark function.
*
* @private
* @param {Benchmark} b - benchmark instance
*/
function benchmark( b ) {
var nbytes;
var bytes;
var v;
var i;
var j;
nbytes = x.length * x.BYTES_PER_ELEMENT;
bytes = wasm.malloc( nbytes );
bytes.set( new Uint8Array( x.buffer ) );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
for ( j = 0; j < len; j++ ) {
v = ( randu()*10000.0 ) - 20000.0;
bytes.setValue( j * x.BYTES_PER_ELEMENT, v );
}
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
wasm.free( bytes );
b.end();
} // end FUNCTION benchmark()
} // end FUNCTION createBenchmark2()
/**
* Creates a benchmark function for measuring WASM view.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark3( len ) {
var x;
var i;
x = new Float64Array( len );
for ( i = 0; i < x.length; i++ ) {
x[ i ] = ( randu()*10000.0 ) - 20000.0;
}
return benchmark;
/**
* Benchmark function.
*
* @private
* @param {Benchmark} b - benchmark instance
*/
function benchmark( b ) {
var nbytes;
var bytes;
var view;
var v;
var i;
var j;
nbytes = x.length * x.BYTES_PER_ELEMENT;
bytes = wasm.malloc( nbytes );
bytes.set( new Uint8Array( x.buffer ) );
view = new Float64Array( bytes.buffer, bytes.byteOffset, x.length );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
for ( j = 0; j < len; j++ ) {
v = ( randu()*10000.0 ) - 20000.0;
view[ j ] = v;
}
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
wasm.free( bytes );
b.end();
} // end FUNCTION benchmark()
} // end FUNCTION createBenchmark3()
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark1( len );
bench( pkg+'::set-value,main:len='+len, f );
f = createBenchmark2( len );
bench( pkg+'::set-value,wasm,set-value:len='+len, f );
f = createBenchmark3( len );
bench( pkg+'::set-value,wasm,view:len='+len, f );
}
} // end FUNCTION main()
main();
| JavaScript | 0.000397 | @@ -3890,18 +3890,8 @@
wasm
-,set-value
:len
|
105e85777676d4ceec1d50323d5e5a5764681d16 | Allow param name to be edited in scenario detail view (closes #162) | app/scenario/scenario-detail.js | app/scenario/scenario-detail.js | 'use strict';
/* Controller for Scenario Detail View */
angular.module('lcaApp.scenario.detail',
['lcaApp.resources.service', 'lcaApp.status.service', 'lcaApp.models.scenario', 'lcaApp.models.param'])
.controller('ScenarioDetailController', ['$scope', '$window', 'StatusService', '$state', '$stateParams',
'ScenarioModelService', 'FragmentService', 'ParamModelService', 'PARAM_TYPE_NAME',
'PARAM_VALUE_STATUS', '$q',
function($scope, $window, StatusService, $state, $stateParams,
ScenarioModelService, FragmentService, ParamModelService, PARAM_TYPE_NAME,
PARAM_VALUE_STATUS, $q) {
$scope.scenario = null;
$scope.fragment = null;
$scope.editScenario = function() {
$state.go(".edit");
};
$scope.hideEdit = function(scenario) {
return ! (scenario && ScenarioModelService.canUpdate(scenario));
};
$scope.gridData = []; // Data source for ngGrid
$scope.gridColumns = []; // ngGrid column definitions
/**
* Function to check if Apply Changes button should be disabled.
* @returns {boolean}
*/
$scope.canApply = function () {
return ($scope.scenario &&
ScenarioModelService.canUpdate($scope.scenario) &&
( ParamModelService.canApplyChanges( $scope.gridData) ||
paramNameChanged($scope.gridData))
);
};
/**
* Function to determine if Revert Changes button should be enabled.
* @returns {boolean}
*/
$scope.canRevert = function () {
return ($scope.scenario &&
ScenarioModelService.canUpdate($scope.scenario) &&
( ParamModelService.canRevertChanges( $scope.gridData) ||
paramNameChanged($scope.gridData))
);
};
/**
* Gather changes and apply
*/
$scope.applyChanges = function () {
var changedParams = $scope.gridData.filter(function (d) {
return d.paramWrapper.editStatus === PARAM_VALUE_STATUS.changed ||
!angular.equals( d.paramWrapper.paramResource.name, d.name);
});
StatusService.startWaiting();
ParamModelService.updateResources($scope.scenario.scenarioID, changedParams.map(changeParam),
refreshParameters, StatusService.handleFailure);
};
$scope.revertChanges = function () {
ParamModelService.revertChanges( $scope.gridData);
};
function refreshParameters() {
ParamModelService.getResources($scope.scenario.scenarioID).then(displayParameters,
StatusService.handleFailure);
}
function paramNameChanged(data) {
return data.some(function (d) {
return !angular.equals( d.paramWrapper.paramResource.name, d.name);
});
}
function changeParam(p) {
var paramResource = p.paramWrapper.paramResource;
if (p.paramWrapper.value) {
paramResource.value = +p.paramWrapper.value;
} else {
paramResource.value = null;
}
if (p.name) {
paramResource.name = p.name;
}
return paramResource;
}
function setGridColumns() {
$scope.gridColumns = [
{field: 'type', displayName: 'Parameter Type', enableCellEdit: false, width: 125},
{field: 'name', displayName: 'Parameter Name', enableCellEdit: false, width: 400},
{field: 'defaultValue', displayName: 'Default Value', enableCellEdit: false}
];
$scope.params = { targetIndex : 2,
canUpdate : $scope.scenario && ScenarioModelService.canUpdate($scope.scenario) };
}
function displayParameters(params) {
var gridData = [];
StatusService.stopWaiting();
params.forEach(function (p) {
var rowObj = { name: null, type: null, defaultValue: p.defaultValue, paramWrapper: ParamModelService.wrapParam(p)};
if (p.hasOwnProperty("name")) {
rowObj.name = p.name;
}
if (p.hasOwnProperty("paramTypeID")) {
rowObj.type = PARAM_TYPE_NAME[p.paramTypeID];
}
gridData.push(rowObj);
});
setGridColumns();
$scope.gridData = gridData;
}
function displayScenario() {
var scenario;
StatusService.stopWaiting();
scenario = ScenarioModelService.get($stateParams.scenarioID);
if (scenario) {
$scope.scenario = scenario;
$scope.fragment = FragmentService.get(scenario.topLevelFragmentID);
StatusService.startWaiting();
ParamModelService.getResources(scenario.scenarioID).then(displayParameters,
StatusService.handleFailure);
} else {
StatusService.handleFailure("Invalid Scenario ID parameter.");
}
}
StatusService.startWaiting();
$q.all([ScenarioModelService.load(), FragmentService.load()]).then (
displayScenario, StatusService.handleFailure);
}]); | JavaScript | 0 | @@ -2508,32 +2508,346 @@
= function () %7B%0A
+ $scope.gridData.forEach(function (e) %7B%0A var origParam = e.paramWrapper.paramResource;%0A if ( origParam && e.hasOwnProperty(%22name%22)) %7B%0A e.name = origParam.name;%0A %7D else %7B%0A e.name = null;%0A %7D%0A %7D);%0A
Para
@@ -3741,24 +3741,121 @@
Columns() %7B%0A
+ var canUpdate = $scope.scenario && ScenarioModelService.canUpdate($scope.scenario);%0A%0A
@@ -4047,36 +4047,40 @@
enableCellEdit:
-fals
+canUpdat
e, width: 400%7D,%0A
@@ -4266,74 +4266,17 @@
e :
-$scope.scenario && ScenarioModelService.canUpdate($scope.scenario)
+canUpdate
%7D;%0A
|
582526e5d126ba31e65708453876fb0aa48aab89 | fix pip z-index related click issues | src/plugins/pip/pip.js | src/plugins/pip/pip.js | // Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var BaseObject = require('../../base/base_object');
var $ = require("jquery");
var _ = require('underscore');
var PipPlugin = BaseObject.extend({
name: 'pip',
initialize: function(core) {
this.core = core;
this.pipStyle = {width: "24%", height: "24%", "z-index": 20, bottom: "7px", right: "7px",
"border-width": "3px", "border-style": "solid", "border-color": "rgba(255,255,255, .3)",
"background-clip": "padding-box", "-webkit-background-clip": "padding-box", "cursor": "pointer"};
this.masterStyle = {width: "100%", height: "100%", bottom: "0px", right: "0px", border: "none", "cursor" : "default"};
this.masterContainer = core.containers[0];
if (core.containers.length === 2) {
this.pipContainer = core.containers[1];
this.pipContainer.setStyle(this.pipStyle);
this.pipContainer.play();
this.pipContainer.setVolume(0);
this.listenToPipClick();
this.core.mediaControl.setContainer(this.masterContainer);
this.core.mediaControl.render();
}
this.listenTo(this.core.mediaControl, 'mediacontrol:show', this.onMediaControlShow);
this.listenTo(this.core.mediaControl, 'mediacontrol:hide', this.onMediaControlHide);
},
getExternalInterface: function() {
return {
addPip: this.addPip,
discardPip: this.discardPip,
addMaster: this.addMaster,
addMasterContainer: this.addMasterContainer,
changeMaster: this.changeMaster,
pipToMaster: this.pipToMaster,
hasPip: this.hasPip
};
},
hasPip: function() {
return !!this.pipContainer;
},
addPip: function(source) {
this.discardPip();
this.core.createContainer(source).then(this.addPipCallback.bind(this));
},
addPipCallback: function(container) {
this.pipContainer = _(container).isArray() ? container[0] : container;
this.onContainerReady();
if (this.core.params.onPipLoaded)
this.core.params.onPipLoaded(this.pipContainer.playback.src);
},
onContainerReady: function() {
this.pipContainer.setVolume(0);
this.pipContainer.setStyle(this.pipStyle);
this.pipContainer.play();
this.stopListening(this.pipContainer);
this.listenToPipClick();
},
discardPip: function() {
if (this.pipContainer) {
this.stopListening(this.pipContainer);
this.discardContainer(this.pipContainer);
this.pipContainer = undefined;
}
},
discardMaster: function() {
if (this.masterContainer) {
this.discardContainer(this.masterContainer);
this.masterContainer = undefined;
}
},
addMaster: function(source) {
if (this.masterContainer) {
this.tmpContainer = this.masterContainer;
this.tmpContainer.setStyle({'z-index': 2000});
this.core.createContainer(source).then(this.addMasterCallback.bind(this));
}
},
addMasterContainer: function(container) {
if (this.masterContainer) {
this.tmpContainer = this.masterContainer;
this.tmpContainer.setStyle({'z-index': 2000});
this.addMasterCallback(container);
}
},
addMasterCallback: function(container) {
this.masterContainer = container;
if(this.pipContainer) {
this.discardPip();
}
this.masterContainer.play();
this.pipContainer = this.tmpContainer;
this.tmpContainer = undefined;
this.pipContainer.setVolume(0);
this.pipContainer.trigger("container:pip", true);
if (this.pipContainer.playback.name === 'hls_playback') { //flash breaks on animate
this.pipContainer.setStyle(this.pipStyle);
if (this.core.params.onMasterLoaded)
this.core.params.onMasterLoaded(this.masterContainer.playback.src);
} else {
this.pipContainer.animate(this.pipStyle, {
complete: function() {
if(this.pipContainer) {
this.pipContainer.setStyle(this.pipStyle);
}
if (this.core.params.onMasterLoaded)
this.core.params.onMasterLoaded(this.masterContainer.playback.src);
}.bind(this)
});
}
this.core.mediaControl.setContainer(this.masterContainer);
this.listenToPipClick();
},
changeMaster: function(source) {
if (this.masterContainer) {
this.tmpContainer = this.masterContainer;
this.tmpContainer.setStyle({'z-index': 2000});
this.core.createContainer(source).then(this.changeMasterCallback.bind(this));
}
},
changeMasterCallback: function(container) {
this.masterContainer.destroy();
this.masterContainer = container;
this.masterContainer.play();
this.tmpContainer = undefined;
this.core.mediaControl.setContainer(this.masterContainer);
if (this.core.params.onMasterLoaded)
this.core.params.onMasterLoaded(this.masterContainer.playback.src);
},
listenToPipClick: function() {
if (this.pipContainer) {
this.stopListening(this.pipContainer);
this.listenTo(this.pipContainer, "container:click", this.pipToMaster.bind(this));
}
},
discardContainer: function(container) {
container.destroy();
},
pipToMaster: function() {
if (this.pipContainer) {
this.pipContainer.animate(this.masterStyle, {complete: this.pipToMasterCallback.bind(this)});
}
return this;
},
pipToMasterCallback: function() {
this.discardMaster();
this.pipContainer.setVolume(100);
this.pipContainer.trigger("container:pip", false);
this.pipContainer.trigger('container:play');
this.masterContainer = this.pipContainer;
this.masterContainer.setStyle({"z-index": 20});
this.pipContainer = undefined;
this.core.mediaControl.setContainer(this.masterContainer);
this.core.enableMediaControl();
if (this.core.params.onPipToMaster)
this.core.params.onPipToMaster(this.masterContainer.playback.src);
},
onMediaControlShow: function () {
if (!this.pipContainer || this.pipContainer.$el.is(':animated')) return;
this.pipContainer.animate({ bottom: 47 }, 400);
},
onMediaControlHide: function () {
if (!this.pipContainer || this.pipContainer.$el.is(':animated')) return;
this.pipContainer.animate({ bottom: 7 }, 400);
}
});
module.exports = PipPlugin;
| JavaScript | 0.000001 | @@ -439,18 +439,19 @@
index%22:
-20
+999
, bottom
|
3fbf0430d2d6ea824d284c3bc48400756f408e59 | fix simple view on build | config-overrides.js | config-overrides.js | const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
module.exports = function override (config, env) {
// remove the css loader to simplify things
config.module.rules[1].oneOf = config.module.rules[1].oneOf.filter(function (l) {
const test = l.test && l.test.toString()
return test !== /\.css$/
})
// compile sass, this comes first and compresses css as well as loading sass/scss
// https://github.com/facebookincubator/create-react-app/issues/2498
config.module.rules[1].oneOf.splice(0, 0,
{
test: /\.(sass|scss|css)$/,
use: [
'style-loader',
'css-loader',
{
loader: 'sass-loader',
options: {
outputStyle: 'compressed'
}
}
]
},
)
if (env === 'production') {
// set the output filename to just socket.js
config.output.filename = 'static/socket.js'
config.output.chunkFilename = 'static/socket.[chunkhash:8].chunk.js'
// if run with `ANALYSE=1 yarn build` create report.js size report
if (process.env.ANALYSE) {
config.plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: 'static',
reportFilename: 'report.html',
})
)
}
} else {
// add another output file at localhost:3000/foobar/
config.plugins.splice(2, 0,
new HtmlWebpackPlugin({
inject: true,
template: path.resolve(__dirname, 'public', 'index.html'),
filename: 'foobar/index.html'
})
)
config.plugins.splice(2, 0,
new HtmlWebpackPlugin({
inject: true,
template: path.resolve(__dirname, 'public', 'simple/index.html'),
filename: 'simple/index.html'
})
)
}
// console.dir(config, { depth: 10, colors: true })
return config
}
| JavaScript | 0 | @@ -1362,18 +1362,9 @@
%0A %7D
- else %7B%0A
+%0A
//
@@ -1395,237 +1395,17 @@
at
-localhost:3000/foobar/%0A config.plugins.splice(2, 0,%0A new HtmlWebpackPlugin(%7B%0A inject: true,%0A template: path.resolve(__dirname, 'public', 'index.html'),%0A filename: 'foobar/index.html'%0A %7D)%0A )%0A
+/simple/%0A
co
@@ -1430,26 +1430,24 @@
e(2, 0,%0A
-
-
new HtmlWebp
@@ -1464,18 +1464,16 @@
%7B%0A
-
inject:
@@ -1484,18 +1484,16 @@
,%0A
-
-
template
@@ -1556,18 +1556,16 @@
,%0A
-
filename
@@ -1594,22 +1594,14 @@
-
-
%7D)%0A
- )%0A %7D
+)
%0A /
|
e9f5c063006f3f0d6022c5fc53370a7c2a3903be | Comment out writing_intensive=false for now, as the ASR API doesn't support it yet. | app/scripts/controllers/main.js | app/scripts/controllers/main.js | 'use strict';
/**
* @ngdoc function
* @name libedMeApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the libedMeApp
*/
angular.module('libedMeApp')
.controller('MainCtrl', ["$scope", "$http", function ($scope, $http) {
$scope.showDetails = false;
$scope.showAdvanced = false;
$scope.errorMessage = '';
$scope.selected = {
libed: '',
subject: '',
theme: '',
writing_intensive: false,
course: null
};
$scope.courses = [];
$scope.options = {
libeds: [
{ code: '', title: 'any' },
{ code: 'AH', title: 'my Arts & Humanities' },
{ code: 'BIOL', title: 'my Biological Sciences'},
{ code: 'HIS', title: 'my Historical Perspectives' },
{ code: 'LITR', title: 'my Literature' },
{ code: 'MATH', title: 'my Mathematical Thinking' },
{ code: 'Phys', title: 'my Physical Sciences' },
{ code: 'Socs', title: 'my Social Sciences' }
],
themes: [
{ code: '', title: 'Any' },
{ code: 'GP', title: 'Global Perspectives' },
{ code: 'TS', title: 'Technology and Society' },
{ code: 'CIV', title: 'Civic Life and Ethics' },
{ code: 'DSJ', title: 'Diversity and Social Justice in the U.S.' },
{ code: 'ENV', title: 'The Environment' }
],
writing_intensive: [
{ val: null, label: 'is or isn\'t' },
{ val: true, label: 'is'},
{ val: false, label: 'isn\'t' }
]
};
$scope.buildUrlFromSelection = function () {
var baseUrl = 'https://apps.asr.umn.edu/liberal_education_courses/courses.json?q=';
var params = [];
if ($scope.selected.libed != '') {
params.push('diversified_core=' + $scope.selected.libed);
}
if ($scope.selected.theme != '') {
params.push('designated_theme=' + $scope.selected.theme);
}
if ($scope.selected.writing_intensive != null) {
params.push('writing_intensive='+$scope.selected.writing_intensive);
}
return baseUrl + params.join(",");
};
$scope.findForMe = function () {
$scope.errorMessage = "";
$scope.selected.course = null;
return $http.get($scope.buildUrlFromSelection())
.success(function (response) {
if (response.courses.length == 0) {
$scope.errorMessage = "No courses could be found to fulfill your requirements.";
}
$scope.courses = response.courses;
$scope.suggestACourse();
})
.error(function (response) {
$scope.errorMessage = "An error occured while trying to find relevant courses. Try again in a bit!"
});
};
$scope.suggestACourse = function () {
$scope.showDetails = false;
$scope.selected.course = _.sample($scope.courses);
};
}]);
| JavaScript | 0 | @@ -447,21 +447,20 @@
ensive:
-false
+null
,%0A
@@ -1534,24 +1534,26 @@
+//
%7B val: false
|
97140e693b356b8f8ef3325dc8939724514bef9e | corrected missing semi-colon | tests/libs/phantomjs/phantomjs_jasminexml_runner.js | tests/libs/phantomjs/phantomjs_jasminexml_runner.js | var htmlrunner,
resultdir,
page,
fs;
phantom.injectJs("phantomjs-jasminexml-example/utils/core.js")
if ( phantom.args.length !== 2 ) {
console.log("Usage: phantom_test_runner.js HTML_RUNNER RESULT_DIR");
phantom.exit();
} else {
htmlrunner = phantom.args[0];
resultdir = phantom.args[1];
page = require("webpage").create();
fs = require("fs");
// Echo the output of the tests to the Standard Output
page.onConsoleMessage = function(msg, source, linenumber) {
console.log(msg);
};
page.open(htmlrunner, function(status) {
if (status === "success") {
utils.core.waitfor(function() { // wait for this to be true
return page.evaluate(function() {
return typeof(jasmine.phantomjsXMLReporterPassed) !== "undefined";
});
}, function() { // once done...
// Retrieve the result of the tests
var f = null, i, len;
suitesResults = page.evaluate(function(){
return jasmine.phantomjsXMLReporterResults;
});
// Save the result of the tests in files
for ( i = 0, len = suitesResults.length; i < len; ++i ) {
try {
f = fs.open(resultdir + '/' + suitesResults[i]["xmlfilename"], "w");
f.write(suitesResults[i]["xmlbody"]);
f.close();
} catch (e) {
console.log(e);
console.log("phantomjs> Unable to save result of Suite '"+ suitesResults[i]["xmlfilename"] +"'");
}
}
// Return the correct exit status. '0' only if all the tests passed
phantom.exit(page.evaluate(function(){
return jasmine.phantomjsXMLReporterPassed ? 0 : 1; //< exit(0) is success, exit(1) is failure
}));
}, function() { // or, once it timesout...
phantom.exit(1);
});
} else {
console.log("phantomjs> Could not load '" + htmlrunner + "'.");
phantom.exit(1);
}
});
}
| JavaScript | 0.999996 | @@ -105,16 +105,17 @@
ore.js%22)
+;
%0A%0Aif ( p
|
c774413a3394a03993385912ef983732b2d59f07 | Implement for for Issue #4 to keep context menu on screen if it is opened at bottomor left boundaries. | contextMenu.js | contextMenu.js | angular.module('ui.bootstrap.contextMenu', [])
.directive('contextMenu', ["$parse", "$q", function ($parse, $q) {
var contextMenus = [];
var removeContextMenus = function (level) {
while (contextMenus.length && (!level || contextMenus.length > level)) {
contextMenus.pop().remove();
}
if (contextMenus.length == 0 && $currentContextMenu) {
$currentContextMenu.remove();
}
};
var $currentContextMenu = null;
var renderContextMenu = function ($scope, event, options, model, level) {
if (!level) { level = 0; }
if (!$) { var $ = angular.element; }
$(event.currentTarget).addClass('context');
var $contextMenu = $('<div>');
if ($currentContextMenu) {
$contextMenu = $currentContextMenu;
} else {
$currentContextMenu = $contextMenu;
}
$contextMenu.addClass('dropdown clearfix');
var $ul = $('<ul>');
$ul.addClass('dropdown-menu');
$ul.attr({ 'role': 'menu' });
$ul.css({
display: 'block',
position: 'absolute',
left: event.pageX + 'px',
top: event.pageY + 'px',
"z-index": 10000
});
angular.forEach(options, function (item, i) {
var $li = $('<li>');
if (item === null) {
$li.addClass('divider');
} else {
var nestedMenu = angular.isArray(item[1])
? item[1] : angular.isArray(item[2])
? item[2] : angular.isArray(item[3])
? item[3] : null;
var $a = $('<a>');
$a.css("padding-right", "8px");
$a.attr({ tabindex: '-1', href: '#' });
var text = typeof item[0] == 'string' ? item[0] : item[0].call($scope, $scope, event, model);
$q.when(text).then(function (text) {
$a.text(text);
if (nestedMenu) {
$a.css("cursor", "default");
$a.append($('<strong style="font-family:monospace;font-weight:bold;float:right;">></strong>'));
}
});
$li.append($a);
var enabled = angular.isFunction(item[2]) ? item[2].call($scope, $scope, event, model, text) : true;
if (enabled) {
var openNestedMenu = function ($event) {
removeContextMenus(level + 1);
var ev = {
pageX: event.pageX + $ul[0].offsetWidth - 1,
pageY: $ul[0].offsetTop + $li[0].offsetTop - 3
};
renderContextMenu($scope, ev, nestedMenu, model, level + 1);
}
$li.on('click', function ($event) {
$event.preventDefault();
$scope.$apply(function () {
if (nestedMenu) {
openNestedMenu($event);
} else {
$(event.currentTarget).removeClass('context');
removeContextMenus();
item[1].call($scope, $scope, event, model, text);
}
});
});
$li.on('mouseover', function ($event) {
$scope.$apply(function () {
if (nestedMenu) {
openNestedMenu($event);
}
});
});
} else {
$li.on('click', function ($event) {
$event.preventDefault();
});
$li.addClass('disabled');
}
}
$ul.append($li);
});
$contextMenu.append($ul);
var height = Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.body.clientHeight, document.documentElement.clientHeight
);
$contextMenu.css({
width: '100%',
height: height + 'px',
position: 'absolute',
top: 0,
left: 0,
zIndex: 9999
});
$(document).find('body').append($contextMenu);
$contextMenu.on("mousedown", function (e) {
if ($(e.target).hasClass('dropdown')) {
$(event.currentTarget).removeClass('context');
removeContextMenus();
}
}).on('contextmenu', function (event) {
$(event.currentTarget).removeClass('context');
event.preventDefault();
removeContextMenus(level);
});
$scope.$on("$destroy", function () {
removeContextMenus();
});
contextMenus.push($ul);
};
return function ($scope, element, attrs) {
element.on('contextmenu', function (event) {
event.stopPropagation();
$scope.$apply(function () {
event.preventDefault();
var options = $scope.$eval(attrs.contextMenu);
var model = $scope.$eval(attrs.model);
if (options instanceof Array) {
if (options.length === 0) { return; }
renderContextMenu($scope, event, options, model);
} else {
throw '"' + attrs.contextMenu + '" not an array';
}
});
});
};
}]);
| JavaScript | 0 | @@ -1232,32 +1232,60 @@
000%0A %7D);%0A
+ var $promises = %5B%5D;%0A
angular.
@@ -1918,16 +1918,27 @@
+ $promise =
$q.when
@@ -1943,16 +1943,83 @@
en(text)
+%0A $promises.push($promise);%0A $promise
.then(fu
@@ -4662,32 +4662,1299 @@
($contextMenu);%0A
+%0A //calculate if drop down menu would go out of screen at left or bottom%0A // calculation need to be done after element has been added (and all texts are set; thus thepromises)%0A // to the DOM the get the actual height%0A $q.all($promises).then(function()%7B%0A if(level === 0)%7B%0A var topCoordinate = event.pageY;%0A var menuHeight = angular.element($ul%5B0%5D).prop('offsetHeight');%0A var winHeight = event.view.innerHeight;%0A if (topCoordinate %3E menuHeight && winHeight - topCoordinate %3C menuHeight) %7B%0A topCoordinate = event.pageY - menuHeight;%0A %7D%0A%0A var leftCoordinate = event.pageX;%0A var menuWidth = angular.element($ul%5B0%5D).prop('offsetWidth');%0A var winWidth = event.view.innerWidth;%0A if(leftCoordinate %3E menuWidth && winWidth - leftCoordinate %3C menuWidth)%7B%0A leftCoordinate = event.pageX - menuWidth;%0A %7D%0A%0A $ul.css(%7B%0A display: 'block',%0A position: 'absolute',%0A left: leftCoordinate + 'px',%0A top: topCoordinate + 'px'%0A %7D);%0A %7D %0A %7D);%0A%0A
$context
|
1ce396d93acc2711cd78154137944213bacf5de7 | Reformat minimax placeChip calls onto multiple lines | app/scripts/models/ai-player.js | app/scripts/models/ai-player.js | 'use strict';
var Grid = require('./grid');
var Player = require('./player');
var Chip = require('./chip');
// An AI player that can think for itself; every AI player inherits from the
// base Player model
function AIPlayer(args) {
Player.call(this, args);
}
AIPlayer.prototype = Object.create(Player.prototype);
AIPlayer.prototype.type = 'ai';
// The duration to wait (in ms) for the user to process the AI player's actions
AIPlayer.waitDelay = 150;
// The maximum number of grid moves to look ahead (this determines the AI's
// intelligence)
AIPlayer.maxComputeDepth = 3;
// Wait for a short moment to give the user time to see and process the AI
// player's actions
AIPlayer.prototype.wait = function (callback) {
setTimeout(function () {
callback();
}, AIPlayer.waitDelay);
};
// Compute the column where the AI player should place its next chip
AIPlayer.prototype.computeNextMove = function (game) {
var bestMove = this.maximizeMove(
game.grid, game.getOtherPlayer(this), AIPlayer.maxComputeDepth,
Grid.minScore, Grid.maxScore);
game.emitter.emit('ai-player:compute-next-move', this, bestMove);
return bestMove;
};
// Choose a column that will maximize the AI player's chances of winning
AIPlayer.prototype.maximizeMove = function (grid, minPlayer, depth, alpha, beta) {
var gridScore = grid.getScore({
currentPlayer: this,
currentPlayerIsMaxPlayer: true
});
// If max search depth was reached or if winning grid was found
if (depth === 0 || Math.abs(gridScore) === Grid.maxScore) {
return {column: null, score: gridScore};
}
var maxMove = {column: null, score: Grid.minScore};
for (var c = 0; c < grid.columnCount; c += 1) {
// Continue to next possible move if this column is full
if (grid.columns[c].length === grid.rowCount) {
continue;
}
// Clone the current grid and place a chip to generate a new permutation
var nextGrid = new Grid(grid);
nextGrid.placeChip({column: c, chip: new Chip({player: this})});
// Minimize the opponent human player's chances of winning
var minMove = this.minimizeMove(nextGrid, minPlayer, depth - 1, alpha, beta);
// If a move yields a lower opponent score, make it the tentative max move
if (minMove.score > maxMove.score) {
maxMove.column = c;
maxMove.score = minMove.score;
alpha = minMove.score;
} else if (maxMove.column === null) {
// Ensure that obvious column choices are not forgotten
maxMove.column = minMove.column;
maxMove.score = minMove.score;
alpha = minMove.score;
}
// Stop if there are no moves better than the current max move
if (alpha >= beta) {
break;
}
}
return maxMove;
};
// Choose a column that will minimize the human player's chances of winning
AIPlayer.prototype.minimizeMove = function (grid, minPlayer, depth, alpha, beta) {
var gridScore = grid.getScore({
currentPlayer: minPlayer,
currentPlayerIsMaxPlayer: false
});
// If max search depth was reached or if winning grid was found
if (depth === 0 || Math.abs(gridScore) === Grid.maxScore) {
return {column: null, score: gridScore};
}
var minMove = {column: null, score: Grid.maxScore};
for (var c = 0; c < grid.columnCount; c += 1) {
// Continue to next possible move if this column is full
if (grid.columns[c].length === grid.rowCount) {
continue;
}
var nextGrid = new Grid(grid);
// The human playing against the AI is always the first player
nextGrid.placeChip({column: c, chip: new Chip({player: minPlayer})});
// Maximize the AI player's chances of winning
var maxMove = this.maximizeMove(nextGrid, minPlayer, depth - 1, alpha, beta);
// If a move yields a higher AI score, make it the tentative max move
if (maxMove.score < minMove.score) {
minMove.column = c;
minMove.score = maxMove.score;
beta = maxMove.score;
} else if (minMove.column === null) {
// Ensure that obvious column choices are not forgotten
minMove.column = maxMove.column;
minMove.score = maxMove.score;
beta = maxMove.score;
}
// Stop if there are no moves better than the current min move
if (alpha >= beta) {
break;
}
}
return minMove;
};
module.exports = AIPlayer;
| JavaScript | 0 | @@ -1942,32 +1942,41 @@
Grid.placeChip(%7B
+%0A
column: c, chip:
@@ -1961,32 +1961,40 @@
column: c,
+%0A
chip: new Chip(
@@ -2008,16 +2008,21 @@
: this%7D)
+%0A
%7D);%0A
@@ -3534,16 +3534,25 @@
ceChip(%7B
+%0A
column:
@@ -3553,16 +3553,24 @@
lumn: c,
+%0A
chip: n
@@ -3597,16 +3597,21 @@
Player%7D)
+%0A
%7D);%0A
|
546c6fe1a4e289efa01bd7b4e512b7200f6ecfbf | style(options-services.js) Add missing semicolon | app/scripts/options-services.js | app/scripts/options-services.js | 'use strict';
/* globals angular */
angular.module('optionsApp')
.service('optionsService', function () {
var options = {
mapsAutocomplete: {
type: 'checkbox',
value: true,
label: 'Address autocomplete',
description: 'Add autocomplete to address fields. It will also add a text field in the Extra Stop page.',
disabled: false
},
mapsDirections: {
type: 'checkbox',
value: true,
label: 'Directions',
description: 'Add a Directions button in the Charges page. Directions can include a parking lot address and extra stops.',
disabled: false
},
mapsParkingLot: {
type: 'checkbox',
value: true,
label: 'Parking lot',
description: 'Include the parking lot address as a starting point in directions.',
disabled: '!options.mapsDirections.value'
},
mapsParkingLotAddress: {
type: 'text',
value: 'E 133rd St and Wiloow Ave, The Bronx',
placeholder: 'Enter the parking lot address',
class: 'form-control',
label: 'Parking lot address',
labelClass: 'sr-only',
description: 'The address of the parking lot. It will be included as the starting point in directions.',
disabled: '!(options.mapsDirections.value && options.mapsParkingLot.value)'
},
mapsExtraStops: {
type: 'checkbox',
value: true,
label: 'Extra stops',
description: 'Include extra stops between the origin and the destination in directions. Up to six extrastops can be added. Each extra stop address has to be enclosed in brackets (i.e. [Times Square, Manhattan, New York, NY 10036]).',
disabled: '!options.mapsDirections.value'
},
emailSearch: {
type: 'checkbox',
value: true,
label: 'Search in email',
description: 'Add link to search for coversations in email on Charges page. Currently only Gmail is supported.',
disabled: false
}
};
this.getOptions = function() {
return options;
}
this.getOption = function(optionName) {
return options[optionName];
}
});
| JavaScript | 0.999677 | @@ -2187,32 +2187,33 @@
options;%0A %7D
+;
%0A %0A th
@@ -2289,24 +2289,25 @@
me%5D;%0A %7D
+;
%0A %0A
|
c21bc11cfd8eccfd1f4cb2a4c551c2db19730138 | fix auth routes | app/scripts/services/account.js | app/scripts/services/account.js | (function () {
'use strict';
angular
.module('app.services', [])
.factory('AccountService', AccountService);
AccountService.$inject = ['$http', '$q', 'moment', 'OpenSenseBoxAPI', 'AuthenticationService'];
function AccountService ($http, $q, moment, OpenSenseBoxAPI, AuthenticationService) {
var service = {
signup: signup,
login: login,
logout: logout,
requestReset: requestReset,
reset: reset,
isAuthed: isAuthed,
refreshAuth: refreshAuth,
refreshTokenExists: refreshTokenExists,
getUserDetails: getUserDetails,
getUsersBoxes: getUsersBoxes,
getScript: getScript,
updateAccount: updateAccount,
updateBox: updateBox,
confirmEmail: confirmEmail,
deleteBox: deleteBox,
postNewBox: postNewBox,
deleteAccount: deleteAccount
};
return service;
////
function success (response) {
AuthenticationService.saveToken(response.data.token);
AuthenticationService.saveRefreshToken(response.data.refreshToken);
return response.data;
}
function failed (error) {
return $q.reject(error.data);
}
function signup (data) {
return $http.post(OpenSenseBoxAPI.url + '/users/register', data)
.then(success)
.catch(failed);
}
function login (data) {
return $http.post(OpenSenseBoxAPI.url + '/users/sign-in', data)
.then(success)
.catch(failed);
}
function logout () {
return $http.post(OpenSenseBoxAPI.url + '/users/sign-out', {auth: true})
.then(function (response) {
AuthenticationService.logout && AuthenticationService.logout();
})
.catch(failed);
}
function requestReset (data) {
return $http.post(OpenSenseBoxAPI.url + '/users/request-password-reset', data)
.then(function (response) {
return response;
})
.catch(failed);
}
function reset (data) {
return $http.post(OpenSenseBoxAPI.url + '/users/password-reset', data)
.then(function (response) {
return response;
})
.catch(failed);
}
function isAuthed () {
var token = AuthenticationService.getToken();
if(token) {
var params = AuthenticationService.parseJwt(token);
return moment.utc() <= moment.utc(params.exp * 1000);
} else {
return false;
}
}
function refreshAuth () {
var data = {
token: AuthenticationService.getRefreshToken()
};
return $http.post(OpenSenseBoxAPI.url + '/users/refresh-auth', data)
.then(success)
.catch(refreshAuthFailed);
function refreshAuthFailed (error) {
AuthenticationService.logout && AuthenticationService.logout();
return $q.reject(error);
}
}
function refreshTokenExists () {
return angular.isDefined(AuthenticationService.getRefreshToken());
}
function getUserDetails () {
return $http.get(OpenSenseBoxAPI.url + '/users/me', {auth: true})
.then(getUserDetailsComplete)
.catch(getUserDetailsFailed);
function getUserDetailsComplete (response) {
return response.data;
}
function getUserDetailsFailed (error) {
return $q.reject(error.data);
}
}
function getUsersBoxes () {
return $http.get(OpenSenseBoxAPI.url + '/users/me/boxes', {auth: true})
.then(getUsersBoxesComplete)
.catch(getUsersBoxesFailed);
function getUsersBoxesComplete (response) {
return response.data;
}
function getUsersBoxesFailed (error) {
return $q.reject(error.data);
}
}
function updateAccount (data) {
return $http.put(OpenSenseBoxAPI.url + '/users/me', data, {auth: true})
.then(updateAccountComplete)
.catch(updateAccountFailed);
function updateAccountComplete (response) {
return response.data;
}
function updateAccountFailed (error) {
return $q.reject(error.data);
}
}
function updateBox (boxId, data) {
return $http.put(OpenSenseBoxAPI.url + '/boxes/' + boxId, data, {auth: true})
.then(function (response) {
return response.data;
})
.catch(failed);
}
function getScript (boxId) {
return $http.get(OpenSenseBoxAPI.url + '/boxes/' + boxId + '/script', {auth: true})
.then(function (response) {
return response.data;
})
.catch(failed);
}
function confirmEmail (data) {
return $http.post(OpenSenseBoxAPI.url + '/users/confirm-email', data)
.then(function (response) {
return response.data;
})
.catch(failed);
}
function deleteBox (boxId) {
return $http.delete(OpenSenseBoxAPI.url+'/boxes/' + boxId, {auth: true})
.then(function (response) {
return response.data;
})
.catch(failed);
}
function postNewBox (data) {
return $http.post(OpenSenseBoxAPI.url + '/boxes', data, {auth: true})
.then(function (response) {
return response.data;
})
.catch(failed);
}
function deleteAccount (data) {
return $http.delete(OpenSenseBoxAPI.url + '/users/me',
{
data: data,
auth: true,
headers: {
'Content-type': 'application/json;charset=utf-8'
}
})
.then(function (response) {
return response.data;
})
.catch(failed);
}
}
})();
| JavaScript | 0.000009 | @@ -1548,16 +1548,20 @@
gn-out',
+ %7B%7D,
%7Bauth:
@@ -4863,28 +4863,129 @@
+ boxId,
- %7Bauth: true
+%0A %7B%0A headers: %7B%0A 'Content-type': 'application/json;charset=utf-8'%0A %7D%0A
%7D)%0A
|
8d3b1eb5bef8b642fe7ebdd1ec546959ceaf5e82 | fix api root | app/scripts/services/apiRoot.js | app/scripts/services/apiRoot.js | 'use strict';
angular.module('BaubleApp')
.factory('apiRoot', ['$location', function($location) {
// AngularJS will instantiate a singleton by calling "new" on this function
var stagingHosts = ['app-staging.bauble.io'];
var productionHosts = ['app.bauble.io'];
var host = $location.host();
if(stagingHosts.indexOf(host) !== -1) {
//return 'https://api-staging.bauble.io/v1';
return 'https://api-baubleio.rhcloud.com/v1';
}
if(productionHosts.indexOf(host) !== -1) {
return 'https://api.nextglass.co/v1';
}
return 'http://localhost:9090/v1';
}]);
| JavaScript | 0.000001 | @@ -583,20 +583,77 @@
/api
-.nextglass.c
+-baubleio.rhcloud.com/v1';%0A //return 'https://api.bauble.i
o/v1
|
89e19133848fbbb508bcded584f3c9286a5f6154 | Update docs | docs/examples/PaginationTable.js | docs/examples/PaginationTable.js | import React from 'react';
import { Table, Column, Cell, HeaderCell, TablePagination } from '../../src';
import fakeData from '../data/users';
const DateCell = ({ rowData, dataKey, ...props }) => (
<Cell {...props}>
{rowData[dataKey].toLocaleString()}
</Cell>
);
function formatLengthMenu(lengthMenu) {
return (
<div className="table-length">
<span> 每页 </span>
{lengthMenu}
<span> 条 </span>
</div>
);
}
function formatInfo(total, activePage) {
return (
<span>共 <i>{total}</i> 条数据</span>
);
}
const PaginationTable = React.createClass({
getInitialState() {
return {
displayLength: 100,
data: fakeData
};
},
handleChangePage(dataKey) {
const { displayLength } = this.state;
this.setState({
data: fakeData
});
},
handleChangeLength(dataKey) {
this.setState({
displayLength: dataKey,
data: fakeData
});
},
render() {
const { data } = this.state;
return (
<div>
<Table height={400} data={data} resizable>
<Column width={50} align="center" fixed>
<HeaderCell>Id</HeaderCell>
<Cell dataKey="id" />
</Column>
<Column width={100} fixed resizable >
<HeaderCell>First Name</HeaderCell>
<Cell dataKey="firstName" />
</Column>
<Column width={100} resizable>
<HeaderCell>Last Name</HeaderCell>
<Cell dataKey="lastName" />
</Column>
<Column width={200} resizable>
<HeaderCell>City</HeaderCell>
<Cell dataKey="city" />
</Column>
<Column width={200} resizable>
<HeaderCell>Street</HeaderCell>
<Cell dataKey="street" />
</Column>
<Column width={200} resizable>
<HeaderCell>Company Name</HeaderCell>
<Cell dataKey="companyName" />
</Column>
<Column width={200} resizable>
<HeaderCell>Email</HeaderCell>
<Cell dataKey="email" />
</Column>
<Column width={200} align="right" resizable>
<HeaderCell>Date</HeaderCell>
<DateCell dataKey="date" />
</Column>
</Table>
<TablePagination
formatLengthMenu={formatLengthMenu}
formatInfo={formatInfo}
displayLength={100}
total={500}
onChangePage={this.handleChangePage}
onChangeLength={this.handleChangeLength}
/>
</div>
);
}
});
export default PaginationTable;
| JavaScript | 0.000001 | @@ -1026,25 +1026,16 @@
=%7Bdata%7D
-resizable
%3E%0A%0A
|
d27f75714681820a9fa68f056a894d83d025f534 | update main.js file to run on dom ready | app/templates/assets/js/main.js | app/templates/assets/js/main.js | // Edit this file as you wish!
console.log('Hello World!'); | JavaScript | 0 | @@ -1,8 +1,39 @@
+'use strict';%0A%0A(function() %7B%0A
// Edit
@@ -55,16 +55,18 @@
u wish!%0A
+
console.
@@ -85,8 +85,14 @@
orld!');
+%0A%7D)();
|
f7b999d54c52820454bf9e299b55765ebc4594b4 | update test conffig | app/templates/test/test-main.js | app/templates/test/test-main.js | var allTestFiles = [];
var TEST_REGEXP = /app\/src\/\w*\/\w*\.spec\.js$/;
var pathToModule = function(path) {
return path.replace(/^\/base\//, '../../').replace(/\.js$/, '');
};
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
allTestFiles.push(pathToModule(file));
}
});
requirejs.config({
// Karma serves files from '/app'
baseUrl: 'base/app/src',
// configurations
paths: {
'angular': '../bower_components/angular/angular',
/*require angular mocks for testing*/
'angular-mocks': '../bower_components/angular-mocks/angular-mocks',
/*require angular resource for easily handling sending and receiving request*/
'angular-resource': '../bower_components/angular-resource/angular-resource',<% if (includeAngularAnimate) { %>
/*require angular animate for easily handling animation. I recommend to use this with tweenmax (bower install --save greensock)*/
'angular-animate': '../bower_components/angular-animate/angular-animate', <% } %>
/*require angular for better handling and binding controller*/
'angular-ui-router': '../bower_components/angular-ui-router/release/angular-ui-router',<% if (includeBindonce) { %>
/*require bindonce to optimize watch for angular binding [https://github.com/Pasvaz/bindonce]*/
'bindonce': '../bower_components/angular-bindonce/bindonce',<% } %><% if (includeUIBootstrap) { %>
/*require ui-bootstrap with the embeded template [http://angular-ui.github.io/bootstrap/]*/
'ui-bootstrap-tpls': '../bower_components/angular-bootstrap/ui-bootstrap-tpls',<% }%>
/*require jquery*/
'jquery': '../bower_components/jquery/dist/jquery',<% if (includeLodash) { %>
/*require lodash library [http://lodash.com/docs]*/
'lodash': '../bower_components/lodash/dist/lodash',<% } %><% if (cssFramework === 'SASSBootstrap') { %>
/*require bootstrap.js to make bootstrap components work*/
'bootstrap': '../bower_components/sass-bootstrap/dist/js/bootstrap',<% } %>
/*require home module*/
'home': 'home/home'
},
shim: {
'angular': { exports: 'angular', deps: ['jquery'] },
'anuglar-mocks': ['angular'],<% if (includeLodash) { %>
'lodash': { exports: '_' },<% } %>
'angular-resource': ['angular'],<% if (includeAngularAnimate) { %>
'angular-animate': ['angular'],<% } %>
'angular-ui-router': ['angular'],<% if (includeBindonce) { %>
'bindonce': ['angular'],<% } %><% if (includeUIBootstrap) { %>
'ui-bootstrap-tpls': ['angular'],<% } %><% if (cssFramework === 'SASSBootstrap') { %>
'bootstrap': ['jquery']<% } %>
},
// ask Require.js to load these files (all our tests)
deps: allTestFiles,
// start test run, once Require.js is done
callback: window.__karma__.start
});
| JavaScript | 0.000001 | @@ -2133,25 +2133,24 @@
otstrap'
-,
%3C%25 %7D %25%3E%0A
@@ -2145,68 +2145,8 @@
%25%3E%0A
- /*require home module*/%0A 'home': 'home/home'%0A
|
8b41fd4423ddf06b9d0f7544193f290cc7ac6bba | Make the regex for dates more lenient. Partial solution to #2244 | app/view/js/src/obj-datetime.js | app/view/js/src/obj-datetime.js | /**
* DateTime object
*/
bolt.datetimes = function () {
var is24h;
function evaluate(field) {
var date = moment(field.date.datepicker('getDate')),
time = moment([2001, 11, 24]),
hours = 0,
minutes = 0;
// Process time field
if (field.time.length) {
res = field.time.val().match(/^\s*(?:(?:([01]?[0-9]|2[0-3])[:,.]([0-5]?[0-9]))|(1[012]|0?[1-9])[:,.]([0-5]?[0-9])(?:\s*([AP])[. ]?M\.?))\s*$/i);
if (res) {
hours = parseInt(res[1] ? res[1] :res[3]);
minutes = parseInt(res[2] ? res[2] :res[4]);
if ((res[5] === 'p' || res[5] === 'P') && hours !== 12) {
hours += 12;
} else if ((res[5] === 'a' || res[5] === 'A') && hours === 12) {
hours -= 12;
}
time = moment([2001, 11, 24, hours, minutes]);
}
}
// Set data field
if (date.isValid()) {
field.data.val(date.format('YYYY-MM-DD') + ' ' + time.format('HH:mm:00'));
} else if (field.date.val() === '') {
field.data.val('');
} else {
// Error
}
}
function display(field) {
var date = '',
time = '',
hour,
match;
// Correct no depublish date
if (field.data.attr('id') === 'datedepublish' && field.data.val() === '1900-01-01 00:00:00') {
field.data.val('');
}
// If data is a valid datetime
match = field.data.val().match(/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})$/);
if (match) {
date = match[1];
time = match[2];
}
// Set date field
field.date.datepicker('setDate', (date === '' || date === '0000-00-00') ? '' : $.datepicker.parseDate('yy-mm-dd', date));
// Set time field
if (field.time.length) {
if (time === '') {
time = '';
} else if (bolt.datetimes.is24h) {
time = field.data.val().slice(11, 16);
} else {
hour = parseInt(time.slice(0, 2));
time = (hour % 12 || 12) + time.slice(2, 5) + (hour < 12 ? ' AM' : ' PM');
}
field.time.val(time);
}
}
function bindDatepicker(field) {
var fieldOptions = field.date.data('field-options'),
options = {
showOn: 'none'
};
for (key in fieldOptions) {
if (fieldOptions.hasOwnProperty(key)) {
options[key] = fieldOptions[key];
}
}
// Bind datepicker button
field.date.datepicker(options);
// Bind show button
field.show.click(function () {
// Set the date to "today", if nothing has been picked yet.
if (!field.date.datepicker('getDate')) {
field.date.datepicker('setDate', "+0");
}
field.date.datepicker('show');
});
// Bind clear button
field.clear.click(function () {
field.data.val('');
display(field);
});
}
return {
init: function () {
// Set global datepicker locale
$.datepicker.setDefaults($.datepicker.regional[bolt.locale.long]);
// Find out if locale uses 24h format
this.is24h = moment.localeData()._longDateFormat.LT.replace(/\[.+?\]/gi, '').match(/A/) ? false : true;
// Initialize each available date/datetime field
$('.datepicker').each(function () {
var id = $(this).attr('id').replace(/-date$/, ''),
field = {
data: $('#' + id),
date: $(this),
time: $('#' + id + '-time'),
show: $('#' + id + '-show'),
clear: $('#' + id + '-clear')
};
// For debug purpose make hidden datafields visible
if (false) {
field.data.attr('type', 'text');
}
// Bind datepicker to date field and set options from field in contenttypes.yml
bindDatepicker(field);
display(field);
// Bind change action to date and time field
field.date.change(function () {
evaluate(field);
display(field);
});
field.time.change(function () {
evaluate(field);
display(field);
});
});
},
update: function () {
$('.datepicker').each(function () {
var id = $(this).attr('id').replace(/-date$/, ''),
field = {
data: $('#' + id),
date: $(this),
time: $('#' + id + '-time')
};
display(field);
});
}
};
}();
| JavaScript | 0.999986 | @@ -1548,20 +1548,22 @@
lid date
+(
time
+)
%0A
@@ -1615,18 +1615,18 @@
%7D-%5Cd%7B2%7D)
-
(
+
%5Cd%7B2%7D:%5Cd
@@ -1635,16 +1635,17 @@
%7D:%5Cd%7B2%7D)
+?
$/);%0A
|
c6f8f43d675837ef32bc9ee94e058bd2b2a39f4c | make load faster | src/editor/components/seDropdown.js | src/editor/components/seDropdown.js | /* eslint-disable node/no-unpublished-import */
import ListComboBox from 'elix/define/ListComboBox.js';
import NumberSpinBox from 'elix/define/NumberSpinBox.js';
// import Input from 'elix/src/base/Input.js';
import {defaultState} from 'elix/src/base/internal.js';
import {templateFrom, fragmentFrom} from 'elix/src/core/htmlLiterals.js';
import {internal} from 'elix';
/**
* @class Dropdown
*/
class Dropdown extends ListComboBox {
/**
* @function get
* @returns {PlainObject}
*/
get [defaultState] () {
return Object.assign(super[defaultState], {
inputPartType: NumberSpinBox,
src: './images/logo.svg',
inputsize: '100%'
});
}
/**
* @function get
* @returns {PlainObject}
*/
get [internal.template] () {
const result = super[internal.template];
const source = result.content.getElementById('source');
// add a icon before our dropdown
source.prepend(fragmentFrom.html`
<img src="./images/logo.svg" alt="icon" width="18" height="18"></img>
`.cloneNode(true));
// change the style so it fits in our toolbar
result.content.append(
templateFrom.html`
<style>
[part~="source"] {
grid-template-columns: 20px 1fr auto;
}
::slotted(*) {
padding: 4px;
background: #E8E8E8;
border: 1px solid #B0B0B0;
width: 100%;
}
[part~="popup"] {
width: 150%;
}
</style>
`.content
);
return result;
}
/**
* @function observedAttributes
* @returns {any} observed
*/
static get observedAttributes () {
return ['title', 'src', 'inputsize', 'value'];
}
/**
* @function attributeChangedCallback
* @param {string} name
* @param {string} oldValue
* @param {string} newValue
* @returns {void}
*/
attributeChangedCallback (name, oldValue, newValue) {
if (oldValue === newValue) return;
switch (name) {
case 'title':
// this.$span.setAttribute('title', `${newValue} ${shortcut ? `[${shortcut}]` : ''}`);
break;
case 'src':
this.src = newValue;
break;
case 'inputsize':
this.inputsize = newValue;
break;
default:
super.attributeChangedCallback(name, oldValue, newValue);
break;
}
}
/**
* @function [internal.render]
* @param {PlainObject} changed
* @returns {void}
*/
[internal.render] (changed) {
super[internal.render](changed);
if (this[internal.firstRender]) {
this.$img = this.shadowRoot.querySelector('img');
this.$input = this.shadowRoot.getElementById('input');
}
if (changed.src) {
this.$img.setAttribute('src', this[internal.state].src);
}
if (changed.inputsize) {
this.$input.shadowRoot.querySelector('[part~="input"]').style.width = this[internal.state].inputsize;
}
if (changed.inputPartType) {
// Wire up handler on new input.
this.addEventListener('close', (e) => {
e.preventDefault();
const value = e.detail?.closeResult?.getAttribute('value');
if (value) {
const closeEvent = new CustomEvent('change', {detail: {value}});
this.dispatchEvent(closeEvent);
}
});
}
}
/**
* @function src
* @returns {string} src
*/
get src () {
return this[internal.state].src;
}
/**
* @function src
* @returns {void}
*/
set src (src) {
this[internal.setState]({src});
}
/**
* @function inputsize
* @returns {string} src
*/
get inputsize () {
return this[internal.state].inputsize;
}
/**
* @function src
* @returns {void}
*/
set inputsize (inputsize) {
this[internal.setState]({inputsize});
}
/**
* @function value
* @returns {string} src
*/
get value () {
return this[internal.state].value;
}
/**
* @function value
* @returns {void}
*/
set value (value) {
this[internal.setState]({value});
}
}
// Register
customElements.define('se-dropdown', Dropdown);
/*
{TODO
min: 0.001, max: 10000, step: 50, stepfunc: stepZoom,
function stepZoom (elem, step) {
const origVal = Number(elem.value);
if (origVal === 0) { return 100; }
const sugVal = origVal + step;
if (step === 0) { return origVal; }
if (origVal >= 100) {
return sugVal;
}
if (sugVal >= origVal) {
return origVal * 2;
}
return origVal / 2;
}
*/
| JavaScript | 0 | @@ -213,22 +213,21 @@
ort
-%7BdefaultState%7D
+* as internal
fro
@@ -334,39 +334,8 @@
js';
-%0Aimport %7Binternal%7D from 'elix';
%0A%0A/*
@@ -466,16 +466,25 @@
%0A get %5B
+internal.
defaultS
@@ -525,16 +525,25 @@
n(super%5B
+internal.
defaultS
|
9f66abd8fffa00586cb3742829c7f8ccf765343e | correct passing of function | packages/mjml-core/src/index.js | packages/mjml-core/src/index.js | import { get, identity, map, omit, reduce } from 'lodash'
import juice from 'juice'
import { html as htmlBeautify } from 'js-beautify'
import { minify as htmlMinify } from 'html-minifier'
import MJMLParser from 'mjml-parser-xml'
import MJMLValidator from 'mjml-validator'
import components, { initComponent, registerComponent } from './components'
import mergeOutlookConditionnals from './helpers/mergeOutlookConditionnals'
import defaultSkeleton from './helpers/skeleton'
import traverseMJML from './helpers/traverseMJML'
class ValidationError extends Error {
constructor(message, errors) {
super(message)
this.errors = errors
}
}
export default function mjml2html(mjml, options = {}) {
let content = ''
let errors = []
if(typeof options.skeleton === 'string') {
options.skeleton = (opt) => require(options.skeleton)
}
const {
beautify = false,
fonts = {
'Open Sans':
'https://fonts.googleapis.com/css?family=Open+Sans:300,400,500,700',
'Droid Sans':
'https://fonts.googleapis.com/css?family=Droid+Sans:300,400,500,700',
Lato: 'https://fonts.googleapis.com/css?family=Lato:300,400,500,700',
Roboto: 'https://fonts.googleapis.com/css?family=Roboto:300,400,500,700',
Ubuntu: 'https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700',
},
keepComments,
minify = false,
skeleton = (opt) => defaultSkeleton,
validationLevel = 'soft',
} = options
const globalDatas = {
breakpoint: '480px',
classes: {},
classesDefault: {},
defaultAttributes: {},
fonts,
inlineStyle: [],
mediaQueries: {},
preview: '',
style: [],
title: '',
}
if (typeof mjml === 'string') {
mjml = MJMLParser(mjml, {
keepComments,
components,
})
}
const validatorOptions = {
components,
}
switch (validationLevel) {
case 'skip':
break
case 'strict':
errors = MJMLValidator(mjml, validatorOptions)
if (errors.length > 0) {
throw new ValidationError(
`ValidationError: \n ${errors
.map(e => e.formattedMessage)
.join('\n')}`,
errors,
)
}
break
case 'soft':
default:
errors = MJMLValidator(mjml, validatorOptions)
break
}
const mjBody = traverseMJML(mjml, child => child.tagName === 'mj-body')
const mjHead = traverseMJML(mjml, child => child.tagName === 'mj-head')
const processing = (node, context, parseMJML = identity) => {
if (!node) {
return
}
const component = initComponent({
name: node.tagName,
initialDatas: {
...parseMJML(node),
context,
},
})
if (component !== null) {
if ('handler' in component) {
component.handler()
}
if ('render' in component) {
return component.render() // eslint-disable-line consistent-return
}
}
}
const applyAttributes = mjml => {
const parse = (mjml, parentMjClass='') => {
const { attributes, tagName, children } = mjml
const classes = get(mjml.attributes, 'mj-class', '').split(' ')
const attributesClasses = reduce(
classes,
(acc, value) => ({
...acc,
...globalDatas.classes[value],
}),
{},
)
const defaultAttributesForClasses = reduce(
parentMjClass.split(' '),
(acc, value) => ({
...acc,
...get(globalDatas.classesDefault, `${value}.${tagName}`),
}),
{}
)
const nextParentMjClass = get(attributes, 'mj-class', parentMjClass)
return {
...mjml,
attributes: {
...globalDatas.defaultAttributes[tagName],
...globalDatas.defaultAttributes['mj-all'],
...attributesClasses,
...defaultAttributesForClasses,
...omit(attributes, ['mj-class']),
},
children: map(
children, (mjml) => parse(
mjml,
nextParentMjClass
)
),
}
}
return parse(mjml)
}
const bodyHelpers = {
addMediaQuery(className, { parsedWidth, unit }) {
globalDatas.mediaQueries[
className
] = `{ width:${parsedWidth}${unit} !important; }`
},
processing: (node, context) => processing(node, context, applyAttributes),
}
const headHelpers = {
add(attr, ...params) {
if (Array.isArray(globalDatas[attr])) {
globalDatas[attr].push(...params)
} else if (globalDatas[attr]) {
if (params.length > 1) {
globalDatas[attr][params[0]] = params[1]
} else {
globalDatas[attr] = params[0]
}
} else {
throw Error(
`An mj-head element add an unkown head attribute : ${attr} with params ${Array.isArray(
params,
)
? params.join('')
: params}`,
)
}
},
}
processing(mjHead, headHelpers)
content = processing(mjBody, bodyHelpers, applyAttributes)
if (globalDatas.inlineStyle.length > 0) {
content = juice(content, {
applyStyleTags: false,
extraCss: globalDatas.inlineStyle.join(''),
insertPreservedExtraCss: false,
removeStyleTags: false,
})
}
content = skeleton({
content,
...globalDatas,
})
content = beautify
? htmlBeautify(content, {
indent_size: 2,
wrap_attributes_indent_size: 2,
max_preserve_newline: 0,
preserve_newlines: false,
})
: content
content = minify
? htmlMinify(content, {
collapseWhitespace: true,
minifyCSS: true,
removeEmptyAttributes: true,
})
: content
content = mergeOutlookConditionnals(content)
return {
html: content,
errors,
}
}
export { components, initComponent, registerComponent }
export { BodyComponent, HeadComponent } from './createComponent'
| JavaScript | 0.000032 | @@ -805,25 +805,16 @@
eleton =
- (opt) =%3E
require
@@ -1378,17 +1378,8 @@
on =
- (opt) =%3E
def
|
cb63fbe51c71e51f44272db919bd3bab05e93f86 | add code review revisions | config/base.js | config/base.js | module.exports = {
parserOptions: {
ecmaVersion: 6,
sourceType: 'module'
},
/*
plugins: [
'ember-suave',
'turbopatent'
],
*/
extends: [
'eslint:recommended',
// Contains only recommended settings for custom rules defined in the
// eslint-plugin-ember addon
'plugin:ember/base'
],
env: {
'es6': true
},
rules: {
'array-bracket-spacing': [ 'error', 'always' ],
'arrow-parens': 'error',
'arrow-spacing': 'error',
'block-spacing': 'error',
'brace-style': 'error',
'camelcase': 'error',
'comma-dangle': 'error',
'comma-spacing': 'error',
'comma-style': 'error',
'computed-property-spacing': 'error',
'curly': 'error',
'dot-notation': 'error',
'eqeqeq': 'error',
'func-call-spacing': 'error',
'indent': [ 'error', 2 ],
'keyword-spacing': [ 'error', { 'before': true, 'after': true } ],
'new-cap': 'error',
'new-parens': 'error',
'no-duplicate-imports': 'error',
'no-global-assign': 'error',
'no-loop-func': 'error',
'no-multiple-empty-lines': 'error',
'no-nested-ternary': 'error',
'no-restricted-globals': [ 'error', 'event' ],
'no-self-compare': 'error',
'no-sequences': 'error',
'no-tabs': 'error',
'no-throw-literal': 'error',
'no-trailing-spaces': 'error',
'no-unneeded-ternary': 'error',
'no-unused-vars': [ 'error', { vars: 'all', args: 'none' } ],
'no-var': 'error',
'no-whitespace-before-property': 'error',
'object-curly-spacing': [ 'error', 'always' ],
'object-shorthand': 'error',
'one-var': [ 'error', 'never' ],
'operator-linebreak': [ 'error', 'after' ],
'prefer-spread': 'error',
'prefer-template': 'error',
'quotes': 'off',
'radix': 'error',
'rest-spread-spacing': 'error',
'space-before-function-paren': [ 'error', 'never' ],
'space-in-parens': 'error',
'space-infix-ops': 'error',
'template-curly-spacing': 'error',
// Custom rules
'ember/alias-model-in-controller': 'off',
'ember/closure-actions': 'error',
'ember/named-functions-in-promises': 'off',
'ember/no-observers': 'off',
'ember/order-in-routes': 'off',
'ember/order-in-models': 'off',
'ember/order-in-controllers': 'off',
'ember/order-in-components': 'off',
'ember/routes-segments-snake-case': 'off',
'ember/use-ember-get-and-set': 'off',
'ember/use-brace-expansion': 'error'
}
};
| JavaScript | 0 | @@ -85,13 +85,8 @@
%7D,%0A
- /*%0A
pl
@@ -108,45 +108,15 @@
mber
--suave',%0A 'turbopatent
'%0A %5D,%0A
- */%0A
ex
@@ -152,140 +152,8 @@
ded'
-,%0A // Contains only recommended settings for custom rules defined in the%0A // eslint-plugin-ember addon%0A 'plugin:ember/base'
%0A %5D
@@ -1834,39 +1834,49 @@
er/a
-lias-model-in-controller': 'off
+void-leaking-state-in-components': 'error
',%0A
@@ -1927,207 +1927,186 @@
ber/
-named-functions-in-promises': 'off',%0A 'ember/no-observers': 'off',%0A 'ember/order-in-routes': 'off',%0A 'ember/order-in-models': 'off',%0A 'ember/order-in-controllers': 'off',%0A 'ember/order
+jquery-ember-run': 'error',%0A 'ember/local-modules': 'error',%0A 'ember/no-empty-attrs': 'error',%0A 'ember/no-function-prototype-extensions': 'error',%0A 'ember/no-on-calls
-in-
@@ -2115,27 +2115,29 @@
mponents': '
-off
+error
',%0A 'embe
@@ -2142,83 +2142,32 @@
ber/
-routes-segments-snake-case': 'off',%0A 'ember/use-ember-get-and-set': 'off
+no-side-effects': 'error
',%0A
|
84ccb5b539e2d16f85df3c32683c54170b0f1210 | Add all headers | config/cors.js | config/cors.js | /**
* Cross-Origin Resource Sharing (CORS) Settings
* (sails.config.cors)
*
* CORS is like a more modern version of JSONP-- it allows your server/API
* to successfully respond to requests from client-side JavaScript code
* running on some other domain (e.g. google.com)
* Unlike JSONP, it works with POST, PUT, and DELETE requests
*
* For more information on CORS, check out:
* http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
*
* Note that any of these settings (besides 'allRoutes') can be changed on a per-route basis
* by adding a "cors" object to the route configuration:
*
* '/get foo': {
* controller: 'foo',
* action: 'bar',
* cors: {
* origin: 'http://foobar.com,https://owlhoot.com'
* }
* }
*
* For more information on this configuration file, see:
* http://sailsjs.org/#/documentation/reference/sails.config/sails.config.cors.html
*
*/
module.exports.cors = {
/***************************************************************************
* *
* Allow CORS on all routes by default? If not, you must enable CORS on a *
* per-route basis by either adding a "cors" configuration object to the *
* route config, or setting "cors:true" in the route config to use the *
* default settings below. *
* *
***************************************************************************/
allRoutes: true,
/***************************************************************************
* *
* Which domains which are allowed CORS access? This can be a *
* comma-delimited list of hosts (beginning with http:// or https://) or *
* "*" to allow all domains CORS access. *
* *
***************************************************************************/
origin: 'https://staging.mathmlcloud.org, http://mathmlcloud.org, http://localhost:1337',
//origin: '*',
/***************************************************************************
* *
* Allow cookies to be shared for CORS requests? *
* *
***************************************************************************/
credentials: false,
/***************************************************************************
* *
* Which methods should be allowed for CORS requests? This is only used in *
* response to preflight requests (see article linked above for more info) *
* *
***************************************************************************/
methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
/***************************************************************************
* *
* Which headers should be allowed for CORS requests? This is only used in *
* response to preflight requests. *
* *
***************************************************************************/
// headers: 'content-type'
};
| JavaScript | 0.000003 | @@ -2167,21 +2167,21 @@
oud.org,
-
http
+s
://mathm
@@ -2191,17 +2191,16 @@
oud.org,
-
http://l
@@ -3656,19 +3656,16 @@
****/%0A%0A
- //
headers
@@ -3679,14 +3679,47 @@
ent-type
+,ocp-apim-subscription-key,accept
'%0A%0A%7D;%0A
|
42cf7de1aeb12c621264e6f1b7bdb90e03575d5f | Update app/pages/Logs.js | app/pages/Logs.js | app/pages/Logs.js | import React from 'react';
import { Header, Feed, Divider, Label, Icon } from 'semantic-ui-react';
import { capitalize, toLower } from 'lodash/string';
const { ipcRenderer } = require('electron');
const remote = require('@electron/remote');
const config = remote.getGlobal('config');
const STATUS_COLOR_MAP = {
success: 'green',
info: 'blue',
warning: 'yellow',
error: 'red',
debug: 'darkgrey',
};
const STATUS_ICON_MAP = {
success: 'check',
info: 'info circle',
warning: 'warning sign',
error: 'x',
debug: 'code',
};
const determineLabelColor = (status) => STATUS_COLOR_MAP[status] || 'grey';
const determineLabelIcon = (status) => STATUS_ICON_MAP[status] || 'question';
class Logs extends React.Component {
constructor() {
super();
this.state = { entries: [] };
}
componentDidMount() {
ipcRenderer.on('logupdated', (event, message) => {
this.update(message);
});
this.setState({ entries: ipcRenderer.sendSync('logGetEntries') });
}
componentWillUnmount() {
ipcRenderer.removeAllListeners('logupdated');
}
update(entries) {
this.setState({ entries });
}
render() {
const LogEntries = this.state.entries.map((entry) => {
if (entry.type !== 'debug' || config.Config.App.debug) {
return (
<Feed key={entry.id} className="log" size="small">
<Feed.Event>
<Feed.Content>
<Feed.Summary>
<Label color={determineLabelColor(entry.type)} image horizontal>
<Icon name={determineLabelIcon(entry.type)} />
{capitalize(entry.source)}
{entry.name && <Label.Detail>{entry.name}</Label.Detail>}
</Label>
<Feed.Date>{entry.date}</Feed.Date>
</Feed.Summary>
<Feed.Extra>
<div dangerouslySetInnerHTML={{ __html: entry.message }} />
</Feed.Extra>
</Feed.Content>
</Feed.Event>
</Feed>
);
}
});
return (
<div>
<Header as="h1">Logs</Header>
{LogEntries}
</div>
);
}
}
module.exports = Logs;
| JavaScript | 0 | @@ -1996,32 +1996,54 @@
%3C/Feed.Event%3E%0A
+ %3CDivider /%3E%0A
%3C/Feed
|
d0f982932c1b3fa362262133334f4936870720d0 | Update api.js | app/routes/api.js | app/routes/api.js | import express from 'express'
import { secret } from '../../config'
import { } from '../models'
import { sign } from 'jsonwebtoken'
import jwt from 'express-jwt'
const router = express.Router()
router.route('/')
.get((request, response) => {
response.json({
api: 'Kratelabs',
ok: true,
status: 200,
message: 'Demonstrates the Kratelabs API',
http: [
{ url: '/product', method: 'GET'},
{ url: '/token', method: 'GET'},
{ url: '/user', method: 'GET'}
]
})
})
export default router
| JavaScript | 0.000001 | @@ -364,16 +364,17 @@
labs API
+.
',%0A
|
9a47eb44830d0f7a605a9bbc559f887ddb51ad6e | fix sporadic dataset navigation error | layout/explore/explore-datasets/component.js | layout/explore/explore-datasets/component.js | import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import debounce from 'lodash/debounce';
import { Link } from 'routes';
import classnames from 'classnames';
// Responsive
import MediaQuery from 'react-responsive';
import { breakpoints } from 'utils/responsive';
// Utils
import { logEvent } from 'utils/analytics';
// Components
import Paginator from 'components/ui/Paginator';
import Icon from 'components/ui/icon';
import { TOPICS } from 'layout/explore/explore-topics/constants';
// Explore components
import ExploreDatasetsSort from 'layout/explore/explore-datasets-header/explore-datasets-sort';
import DatasetList from './list';
import ExploreDatasetsActions from './explore-datasets-actions';
// Styles
import './styles.scss';
function ExploreDatasetsComponent(props) {
const {
datasets: {
selected,
list,
total,
limit,
page,
loading
},
responsive,
selectedTags,
search
} = props;
const relatedDashboards =
TOPICS.filter(topic => selectedTags.find(tag => tag.id === topic.id));
const fetchDatasets = debounce((page) => {
props.setDatasetsPage(page);
props.fetchDatasets();
});
useEffect(() => {
fetchDatasets(1);
}, []);
const classValue = classnames({
'c-explore-datasets': true,
'-hidden': selected
});
return (
<div className={classValue}>
<div className="explore-datasets-header">
<div className="left-container">
<ExploreDatasetsSort />
<div className="tags-container">
{selectedTags.length > 0 &&
selectedTags.map(t => (
<button
key={t.id}
className="c-button -primary -compressed"
onClick={() => {
props.toggleFiltersSelected({ tag: t, tab: 'topics' });
fetchDatasets(1);
}}
>
<span
className="button-text"
title={t.label.toUpperCase()}
>
{t.label.toUpperCase()}
</span>
<Icon
name="icon-cross"
className="-tiny"
/>
</button>
))}
{search && (
<button
key="text-filter"
className="c-button -primary -compressed"
onClick={() => {
props.resetFiltersSort();
props.setFiltersSearch('');
fetchDatasets(1);
}}
>
<span
className="button-text"
title={`TEXT: ${search.toUpperCase()}`}
>
{`TEXT: ${search.toUpperCase()}`}
</span>
<Icon
name="icon-cross"
className="-tiny"
/>
</button>
)}
</div>
</div>
<div className="number-of-datasets">
{`${total} ${total === 1 ? 'DATASET' : 'DATASETS'}`}
</div>
</div>
{relatedDashboards.length > 0 &&
<div className="related-dashboards">
<div className="header">
<h4>Related dashboards</h4>
<Link to="dashboards">
<a className="header-button">
SEE ALL
</a>
</Link>
</div>
{relatedDashboards.map(dashboard => (
<Link to="dashboards_detail" params={{ slug: dashboard.slug }}>
<div
className="dashboard-button"
style={{
background: `linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.30)),url(${dashboard.backgroundURL})`,
'background-position': 'center',
'background-size': 'cover'
}}
onClick={() => logEvent('Explore Menu', 'Select Dashboard', dashboard.label)}
>
<div className="dashboard-title">
{dashboard.label}
</div>
</div>
</Link>
))}
</div>
}
{!list.length && !loading &&
<div className="request-data-container">
<div className="request-data-text">
Oops! We couldn't find data for your search...
</div>
<a
className="c-button -primary"
href="https://docs.google.com/forms/d/e/1FAIpQLSfXsPGQxM6p8KloU920t5Tfhx9FYFOq8-Rjml07UDH9EvsI1w/viewform"
target="_blank"
rel="noopener noreferrer"
>
Request data
</a>
</div>
}
<DatasetList
loading={loading}
numberOfPlaceholders={20}
list={list}
actions={
<MediaQuery
minDeviceWidth={breakpoints.medium}
values={{ deviceWidth: responsive.fakeWidth }}
>
<ExploreDatasetsActions />
</MediaQuery>
}
/>
{!!list.length && total > limit &&
<Paginator
options={{
page,
limit,
size: total
}}
onChange={(p) => {
// Scroll to the top of the list
if (window.scrollTo && document.querySelector('.sidebar-content').scrollTo) {
window.scrollTo(0, 0);
document.querySelector('.sidebar-content').scrollTo(0, 0);
}
fetchDatasets(p);
}}
/>
}
</div>
);
}
ExploreDatasetsComponent.propTypes = {
list: PropTypes.array,
page: PropTypes.number,
total: PropTypes.number,
limit: PropTypes.number,
options: PropTypes.object,
responsive: PropTypes.object,
selectedTags: PropTypes.array.isRequired,
search: PropTypes.string.isRequired,
// Actions
fetchDatasets: PropTypes.func.isRequired,
setDatasetsPage: PropTypes.func.isRequired,
toggleFiltersSelected: PropTypes.func.isRequired,
resetFiltersSort: PropTypes.func.isRequired,
setFiltersSearch: PropTypes.func.isRequired
};
export default ExploreDatasetsComponent;
| JavaScript | 0.000013 | @@ -5304,16 +5304,24 @@
//
+ -------
Scroll
@@ -5346,43 +5346,63 @@
list
-%0A if (window.scrollTo &&
+ -------------------%0A const sidebarContent =
doc
@@ -5432,32 +5432,56 @@
idebar-content')
+;%0A if (window
.scrollTo) %7B%0A
@@ -5530,52 +5530,99 @@
- document.querySelector('.
+%7D%0A if (sidebarContent && sidebarContent.scrollTo) %7B%0A
sidebar
--c
+C
ontent
-')
.scr
@@ -5643,24 +5643,88 @@
%7D
+%0A // ------------------------------------------------
%0A%0A
|
bcc037e48e9d1073f08c388110b3197613e0a885 | make class the abstract for use in the other light shadow classes | src/lights/LightShadow.js | src/lights/LightShadow.js | import { Matrix4 } from '../math/Matrix4.js';
import { Vector2 } from '../math/Vector2.js';
/**
* @author mrdoob / http://mrdoob.com/
*/
function LightShadow( camera ) {
this.camera = camera;
this.bias = 0;
this.radius = 1;
this.mapSize = new Vector2( 512, 512 );
this.map = null;
this.matrix = new Matrix4();
}
Object.assign( LightShadow.prototype, {
copy: function ( source ) {
this.camera = source.camera.clone();
this.bias = source.bias;
this.radius = source.radius;
this.mapSize.copy( source.mapSize );
return this;
},
clone: function () {
return new this.constructor().copy( this );
},
toJSON: function () {
var object = {};
if ( this.bias !== 0 ) object.bias = this.bias;
if ( this.radius !== 1 ) object.radius = this.radius;
if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
object.camera = this.camera.toJSON( false ).object;
delete object.camera.matrix;
return object;
}
} );
export { LightShadow };
| JavaScript | 0.000028 | @@ -84,16 +84,154 @@
or2.js';
+%0Aimport %7B Vector3 %7D from '../math/Vector3.js';%0Aimport %7B Vector4 %7D from '../math/Vector4.js';%0Aimport %7B Frustum %7D from '../math/Frustum.js';
%0A%0A/**%0A *
@@ -460,50 +460,1214 @@
);%0A%0A
-%7D%0A%0AObject.assign( LightShadow.prototype, %7B
+ this._frustum = new Frustum();%0A this._frameExtents = new Vector2( 1, 1 );%0A%0A this._viewportCount = 1;%0A%0A this._viewports = %5B%0A%0A new Vector4( 0, 0, 1, 1)%0A%0A %5D;%0A%0A%7D%0A%0AObject.assign( LightShadow.prototype, %7B%0A%0A _projScreenMatrix: new Matrix4(),%0A%0A _lightPositionWorld: new Vector3(),%0A%0A _lookTarget: new Vector3(),%0A%0A getViewportCount: function () %7B%0A%0A return this._viewportCount;%0A%0A %7D,%0A%0A getFrustum: function() %7B%0A%0A return this._frustum;%0A%0A %7D,%0A%0A updateMatrices: function ( light, viewCamera, viewportIndex ) %7B%0A%0A var shadowCamera = this.camera,%0A shadowMatrix = this.matrix,%0A projScreenMatrix = this._projScreenMatrix;%0A%0A projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );%0A%09%09this._frustum.setFromMatrix( projScreenMatrix );%0A%0A shadowMatrix.set(%0A%09%09%090.5, 0.0, 0.0, 0.5,%0A%09%09%090.0, 0.5, 0.0, 0.5,%0A%09%09%090.0, 0.0, 0.5, 0.5,%0A%09%09%090.0, 0.0, 0.0, 1.0%0A%09%09);%0A%0A%09%09shadowMatrix.multiply( shadowCamera.projectionMatrix );%0A%09%09shadowMatrix.multiply( shadowCamera.matrixWorldInverse );%0A%0A %7D,%0A%0A getViewport: function ( viewportIndex ) %7B%0A%0A return this._viewports%5B viewportIndex %5D;%0A%0A %7D,%0A%0A getFrameExtents: function () %7B%0A%0A return this._frameExtents;%0A%0A %7D,
%0A%0A%09c
|
bbe0b12a80cac7b335d269e453633adde9460b04 | support for item text promise (e.g. for angular-translate manual translation resolution via $translate('KEY')) | contextMenu.js | contextMenu.js | angular.module('ui.bootstrap.contextMenu', [])
.directive('contextMenu', ["$parse", function ($parse) {
var renderContextMenu = function ($scope, event, options, model) {
if (!$) { var $ = angular.element; }
$(event.currentTarget).addClass('context');
var $contextMenu = $('<div>');
$contextMenu.addClass('dropdown clearfix');
var $ul = $('<ul>');
$ul.addClass('dropdown-menu');
$ul.attr({ 'role': 'menu' });
$ul.css({
display: 'block',
position: 'absolute',
left: event.pageX + 'px',
top: event.pageY + 'px'
});
angular.forEach(options, function (item, i) {
var $li = $('<li>');
if (item === null) {
$li.addClass('divider');
} else {
var $a = $('<a>');
$a.attr({ tabindex: '-1', href: '#' });
var text = typeof item[0] == 'string' ? item[0] : item[0].call($scope, $scope, event, model);
$a.text(text);
$li.append($a);
var enabled = angular.isDefined(item[2]) ? item[2].call($scope, $scope, event, text, model) : true;
if (enabled) {
$li.on('click', function ($event) {
$event.preventDefault();
$scope.$apply(function () {
$(event.currentTarget).removeClass('context');
$contextMenu.remove();
item[1].call($scope, $scope, event, model);
});
});
} else {
$li.on('click', function ($event) {
$event.preventDefault();
});
$li.addClass('disabled');
}
}
$ul.append($li);
});
$contextMenu.append($ul);
var height = Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.body.clientHeight, document.documentElement.clientHeight
);
$contextMenu.css({
width: '100%',
height: height + 'px',
position: 'absolute',
top: 0,
left: 0,
zIndex: 9999
});
$(document).find('body').append($contextMenu);
$contextMenu.on("mousedown", function (e) {
if ($(e.target).hasClass('dropdown')) {
$(event.currentTarget).removeClass('context');
$contextMenu.remove();
}
}).on('contextmenu', function (event) {
$(event.currentTarget).removeClass('context');
event.preventDefault();
$contextMenu.remove();
});
};
return function ($scope, element, attrs) {
element.on('contextmenu', function (event) {
event.stopPropagation();
$scope.$apply(function () {
event.preventDefault();
var options = $scope.$eval(attrs.contextMenu);
var model = $scope.$eval(attrs.model);
if (options instanceof Array) {
if (options.length === 0) { return; }
renderContextMenu($scope, event, options, model);
} else {
throw '"' + attrs.contextMenu + '" not an array';
}
});
});
};
}]);
| JavaScript | 0 | @@ -77,16 +77,22 @@
$parse%22,
+ %22$q%22,
functio
@@ -100,16 +100,20 @@
($parse
+, $q
) %7B%0A
@@ -1045,19 +1045,95 @@
$
-a.text(text
+q.when(text).then(function(text) %7B%0A $a.text(text);%0A %7D
);%0A
|
ebfa3c04207bbe306def62e65c7629c9a8738029 | Declare jQuery in netsim.js for JSHint | apps/src/netsim/netsim.js | apps/src/netsim/netsim.js | /**
* Internet Simulator
*
* Copyright 2015 Code.org
* http://code.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Internet Simulator app for Code.org.
*/
/* jshint
funcscope: true,
newcap: true,
nonew: true,
shadow: false,
unused: true,
maxlen: 90,
maxparams: 3,
maxstatements: 200
*/
/* global -Blockly */
'use strict';
var page = require('./page.html');
var NetSimConnection = require('./NetSimConnection');
var DashboardUser = require('./DashboardUser');
var NetSimLobby = require('./NetSimLobby');
var NetSimRouterPanel = require('./NetSimRouterPanel');
var NetSimSendWidget = require('./NetSimSendWidget');
var NetSimLogWidget = require('./NetSimLogWidget');
var RunLoop = require('./RunLoop');
/**
* The top-level Internet Simulator controller.
* @param {StudioApp} studioApp The studioApp instance to build upon.
*/
var NetSim = function () {
this.skin = null;
this.level = null;
this.heading = 0;
/**
* Current user object which asynchronously grabs the current user's
* info from the dashboard API.
* @type {DashboardUser}
* @private
*/
this.currentUser_ = DashboardUser.getCurrentUser();
/**
* Manager for connection to shared shard of netsim app.
* @type {NetSimConnection}
* @private
*/
this.connection_ = null;
/**
* Tick and Render loop manager for the simulator
* @type {RunLoop}
* @private
*/
this.runLoop_ = new RunLoop();
};
module.exports = NetSim;
/**
*
*/
NetSim.prototype.injectStudioApp = function (studioApp) {
this.studioApp_ = studioApp;
};
/**
* Hook up input handlers to controls on the netsim page
* @private
*/
NetSim.prototype.attachHandlers_ = function () {
};
/**
* Called on page load.
* @param {Object} config Requires the following members:
* skin: ???
* level: ???
*/
NetSim.prototype.init = function(config) {
if (!this.studioApp_) {
throw new Error("NetSim requires a StudioApp");
}
this.skin = config.skin;
this.level = config.level;
config.html = page({
assetUrl: this.studioApp_.assetUrl,
data: {
visualization: '',
localeDirection: this.studioApp_.localeDirection(),
controls: require('./controls.html')({assetUrl: this.studioApp_.assetUrl})
},
hideRunButton: true
});
config.enableShowCode = false;
config.loadAudio = this.loadAudio_.bind(this);
// Override certain StudioApp methods - netsim does a lot of configuration
// itself, because of its nonstandard layout.
this.studioApp_.configureDom = this.configureDomOverride_.bind(this.studioApp_);
this.studioApp_.onResize = this.onResizeOverride_.bind(this.studioApp_);
this.studioApp_.init(config);
this.attachHandlers_();
// Create netsim lobby widget in page
this.currentUser_.whenReady(function () {
this.initWithUserName_(this.currentUser_);
}.bind(this));
// Begin the main simulation loop
this.runLoop_.begin();
};
/**
* Extracts query parameters from a full URL and returns them as a simple
* object.
* @returns {*}
*/
NetSim.prototype.getOverrideShardID = function () {
var parts = location.search.split('?');
if (parts.length === 1) {
return undefined;
}
var shardID;
parts[1].split('&').forEach(function (param) {
var sides = param.split('=');
if (sides.length > 1 && sides[0] === 's') {
shardID = sides[1];
}
});
return shardID;
};
/**
* Initialization that can happen once we have a user name.
* Could collapse this back into init if at some point we can guarantee that
* user name is available on load.
* @param {DashboardUser} user
* @private
*/
NetSim.prototype.initWithUserName_ = function (user) {
this.mainContainer_ = $('#netsim');
this.receivedMessageLog_ = NetSimLogWidget.createWithin(
document.getElementById('netsim_received'), 'Received Messages');
this.sentMessageLog_ = NetSimLogWidget.createWithin(
document.getElementById('netsim_sent'), 'Sent Messages');
this.connection_ = new NetSimConnection(this.sentMessageLog_,
this.receivedMessageLog_);
this.connection_.attachToRunLoop(this.runLoop_);
this.connection_.statusChanges.register(this, this.refresh_);
var lobbyContainer = document.getElementById('netsim_lobby_container');
this.lobbyControl_ = NetSimLobby.createWithin(lobbyContainer,
this.connection_, user, this.getOverrideShardID());
this.lobbyControl_.attachToRunLoop(this.runLoop_);
var routerPanelContainer = document.getElementById('netsim_tabpanel');
this.routerPanel_ = NetSimRouterPanel.createWithin(routerPanelContainer,
this.connection_);
this.routerPanel_.attachToRunLoop(this.runLoop_);
var sendWidgetContainer = document.getElementById('netsim_send');
this.sendWidget_ = NetSimSendWidget.createWithin(sendWidgetContainer,
this.connection_);
this.refresh_();
};
/**
* Respond to connection status changes show/hide the main content area.
* @private
*/
NetSim.prototype.refresh_ = function () {
if (this.connection_.isConnectedToRouter()) {
this.mainContainer_.show();
} else {
this.mainContainer_.hide();
}
};
/**
* Load audio assets for this app
* TODO (bbuchanan): Ought to pull this into an audio management module
* @private
*/
NetSim.prototype.loadAudio_ = function () {
};
/**
* Replaces StudioApp.configureDom.
* Should be bound against StudioApp instance.
* @param {Object} config Should at least contain
* containerId: ID of a parent DOM element for app content
* html: Content to put inside #containerId
* @private
*/
NetSim.prototype.configureDomOverride_ = function (config) {
var container = document.getElementById(config.containerId);
container.innerHTML = config.html;
};
/**
* Replaces StudioApp.onResize
* Should be bound against StudioApp instance.
* @private
*/
NetSim.prototype.onResizeOverride_ = function() {
var div = document.getElementById('appcontainer');
var divParent = div.parentNode;
var parentStyle = window.getComputedStyle(divParent);
var parentWidth = parseInt(parentStyle.width, 10);
div.style.top = divParent.offsetTop + 'px';
div.style.width = parentWidth + 'px';
};
| JavaScript | 0.000006 | @@ -855,16 +855,31 @@
ckly */%0A
+/* global $ */%0A
'use str
|
e9a4d3bcf82fa893a484d2a62a296304d1976d1a | fix navigation to the next question on answer submission | public/app/services/utils/rgiQuestionSetSrvc.js | public/app/services/utils/rgiQuestionSetSrvc.js | 'use strict';
angular.module('app').factory('rgiQuestionSetSrvc', function (rgiUtilsSrvc) {
var answers = [];
return {
isAnyQuestionRemaining: function(answer) {
return answer.question_order !== answers.length;
},
getNextQuestionId: function(answer) {
return String(rgiUtilsSrvc.zeroFill((answer.question_order + 1), 3));
},
setAnswers: function(answersData) {
answers = answersData;
}
};
});
| JavaScript | 0.988665 | @@ -70,16 +70,33 @@
nction (
+rgiQuestionSrvc,
rgiUtils
@@ -127,134 +127,1856 @@
= %5B%5D
-;%0A%0A return %7B%0A isAnyQuestionRemaining: function(answer) %7B%0A return answer.question_order !== answers.length
+, questions;%0A%0A rgiQuestionSrvc.query(%7Bassessment_ID: 'base'%7D, function (questionList) %7B%0A questions = questionList;%0A %7D);%0A%0A var getNextQuestion = function(answer) %7B%0A var linkedQuestion = getLinkedQuestion(getQuestionOption(answer));%0A return linkedQuestion === undefined ? getRootQuestions()%5B0%5D : linkedQuestion;%0A %7D;%0A%0A var getLinkedQuestion = function(option) %7B%0A var foundQuestion;%0A%0A questions.forEach(function(question) %7B%0A if(question.linkedOption === option._id) %7B%0A foundQuestion = question;%0A %7D%0A %7D);%0A%0A return foundQuestion;%0A %7D;%0A%0A var getQuestionOption = function(answer) %7B%0A var foundOption;%0A%0A questions.forEach(function(question) %7B%0A if(answer.root_question_ID === question._id) %7B%0A question.question_criteria.forEach(function(option) %7B%0A if(answer.researcher_score.text === option.text) %7B%0A foundOption = option;%0A %7D%0A %7D);%0A %7D%0A %7D);%0A%0A return foundOption;%0A %7D;%0A%0A var getRootQuestions = function() %7B%0A var rootQuestions = %5B%5D;%0A%0A questions.forEach(function(question) %7B%0A if((question.linkedOption === undefined) && !isQuestionAnswered(question)) %7B%0A rootQuestions.push(question);%0A %7D%0A %7D);%0A%0A return rootQuestions;%0A %7D;%0A%0A var isQuestionAnswered = function(question) %7B%0A var answered = false;%0A%0A answers.forEach(function(answer) %7B%0A if((answer.root_question_ID === question._id) && answer.researcher_score) %7B%0A answered = true;%0A %7D%0A %7D);%0A%0A return answered;%0A %7D;%0A%0A return %7B%0A isAnyQuestionRemaining: function(answer) %7B%0A return getNextQuestion(answer) !== undefined
;%0A
@@ -2079,22 +2079,39 @@
roFill((
+getNextQuestion(
answer
+)
.questio
@@ -2121,12 +2121,8 @@
rder
- + 1
), 3
|
9aea5f2019e8690b5524e2abfdfab1239879296b | create test seed data | server/config/seed.js | server/config/seed.js | /**
* Populate DB with sample data on server start
* to disable, edit config/environment/index.js, and set `seedDB: false`
*/
'use strict';
import Thing from '../api/thing/thing.model';
import User from '../api/user/user.model';
import Skill from '../api/skill/skill.model';
import Badge from '../api/badge/badge.model';
import Skilltree from '../api/skilltree/skilltree.model';
var multiplication1 = new Skill({
name: 'Multiplication by 0 or 1',
problemGenId: 0
});
var multiplication2 = new Skill({
name: 'Multiplication by 2',
problemGenId: 1
});
var multiplication3 = new Skill({
name: 'Multiplication by 3',
problemGenId: 2
});
var multiplication4 = new Skill({
name: 'Multiplication by 4',
problemGenId: 3
});
var division1 = new Skill({
name: 'Division by 0 or 1',
problemGenId: 4
});
var division2 = new Skill({
name: 'Division by 2',
problemGenId: 5
});
var division3 = new Skill({
name: 'Division by 3',
problemGenId: 6
});
var division4 = new Skill({
name: 'Division by 4',
problemGenId: 7
});
var hardAddition = new Skill({
name: 'Hard Addition',
info: 'Practice addition with problems within 1000',
problemGenId: 8
})
var rounding1 = new Skill({
name: 'Rounding to the nearest 10',
problemGenId: 9
});
var rounding2 = new Skill({
name: 'Rounding to the nearest 100',
problemGenId: 10
});
var rounding3 = new Skill({
name: 'Rounding to the nearest 10 or 100',
problemGenId: 11
});
Skill.find({}).removeAsync()
.then(function() {
multiplication1.saveAsync();
multiplication2.saveAsync();
multiplication3.saveAsync();
multiplication4.saveAsync();
division1.saveAsync();
division2.saveAsync();
division3.saveAsync();
division4.saveAsync();
hardAddition.saveAsync();
rounding1.saveAsync();
rounding2.saveAsync();
rounding3.saveAsync();
})
Badge.find({}).removeAsync()
.then(function() {
Badge.create({
name: 'WOO you passed a thing',
info: 'Congrats',
badgeDefId: 0,
image: 'add'
});
});
var rootSkill = new Skilltree({
name: 'Math',
skills: []
})
var additionSkill = new Skilltree({
name: 'Addition',
skills: [hardAddition._id]
})
additionSkill.parent = rootSkill;
var multiplicationSkill = new Skilltree({
name: 'Multiplication',
skills: [multiplication1._id, multiplication2._id, multiplication3._id, multiplication4._id]
})
multiplicationSkill.parent = rootSkill;
var divisionSkill = new Skilltree({
name: 'Division',
skills: [division1._id, division2._id, division3._id, division4._id]
})
divisionSkill.parent = rootSkill;
var roundingSkill = new Skilltree({
name: 'Rounding',
skills: [rounding1._id, rounding2._id, rounding3._id]
})
roundingSkill.parent = rootSkill;
Skilltree.find({}).removeAsync()
.then(function() {
rootSkill.saveAsync().then(function() {
additionSkill.saveAsync().then(function() {
multiplicationSkill.saveAsync().then(function() {
divisionSkill.saveAsync().then(function() {
roundingSkill.saveAsync()
})
})
})
})
})
User.find({}).removeAsync()
.then(function() {
User.createAsync({
provider: 'local',
name: 'Test User',
type: 'student',
email: 'test@example.com',
password: 'test',
studentData: {
skillRoot: rootSkill._id
}
}, {
provider: 'local',
role: 'admin',
name: 'Admin',
email: 'admin@example.com',
password: 'admin'
}, {
provider: 'local',
name: 'A Teacher',
type: 'teacher',
email: 'teacher@example.com',
password: 'test',
teacherData: {
classes: [{
name: 'Math'
}, {
name: 'Algebra'
}]
}
})
.then(function() {
console.log('finished populating users');
});
});
| JavaScript | 0.000002 | @@ -377,16 +377,1085 @@
odel';%0A%0A
+%0AUser.find(%7B%7D).removeAsync()%0A .then(function() %7B%0A var student1 = new User(%7B%0A provider: 'local',%0A name: 'Test User',%0A type: 'student',%0A email: 'test@example.com',%0A password: 'test',%0A studentData: %7B%0A points: 50%0A %7D%0A %7D)%0A%0A var student2 = new User(%7B%0A provider: 'local',%0A name: 'Test User 2',%0A type: 'student',%0A email: 'test2@example.com',%0A password: 'test',%0A studentData: %7B%0A points: 200%0A %7D%0A %7D)%0A%0A var teacher = new User(%7B%0A provider: 'local',%0A name: 'A Teacher',%0A type: 'teacher',%0A email: 'teacher@example.com',%0A password: 'test',%0A teacherData: %7B%0A classes: %5B%7B%0A name: 'Math'%0A students: %5Bstudent1._id, student2._id%5D%0A %7D, %7B%0A name: 'Algebra'%0A %7D%5D%0A %7D%0A %7D)%0A%0A student1.saveAsync();%0A student2.saveAsync();%0A teacher.saveAsync();%0A %7D);%0A%0A%0A%0A/*var simpleAddition = new Skill(%7B%0A name: 'Simple Addition',%0A info: 'Practice addition with problems within 10',%0A problemGenId: 0%0A %7D);*/%0A%0A
var mult
|
0e252f6682b6e23315e5961a1b22a54780d2dfc3 | Allow canary and beta tests to fail (#218) | config/ember-try.js | config/ember-try.js | 'use strict';
const getChannelURL = require('ember-source-channel-url');
module.exports = function() {
return Promise.all([
getChannelURL('release'),
getChannelURL('beta'),
getChannelURL('canary')
]).then((urls) => {
return {
useYarn: true,
scenarios: [
{
name: 'ember-lts-2.12',
npm: {
dependencies: {
'ember-data': '^2.12.0'
},
devDependencies: {
'ember-source': '^2.12.0'
}
}
},
{
name: 'ember-lts-2.16',
npm: {
dependencies: {
'ember-data': '^2.16.0'
},
devDependencies: {
'ember-source': '^2.16.0'
}
}
},
{
name: 'ember-release',
npm: {
dependencies: {
'ember-data': 'emberjs/data#release'
},
devDependencies: {
'ember-source': urls[0]
}
}
},
{
name: 'ember-beta',
npm: {
dependencies: {
'ember-data': 'emberjs/data#beta'
},
devDependencies: {
'ember-source': urls[1]
}
}
},
{
name: 'ember-canary',
npm: {
dependencies: {
'ember-data': 'emberjs/data#master'
},
devDependencies: {
'ember-source': urls[2]
}
}
}
]
}
});
};
| JavaScript | 0 | @@ -1275,32 +1275,63 @@
%7D%0A %7D
+,%0A allowedToFail: true
%0A %7D,%0A
@@ -1564,32 +1564,63 @@
%7D%0A %7D
+,%0A allowedToFail: true
%0A %7D%0A
|
c1ee019f670b283d21f990fa1d51b3ffce4147ad | fix typings test | tools/run-typings-test.js | tools/run-typings-test.js | /**
* This file uses the test project at test/typings-test to validate
* that AngularFire typings don't produce errors in user code.
*
* 1. Create a temp directory to copy the test project
* 2. Create a package.json based on test-project/package.sample.json,
* using versions from the project's root package.json.
* 3. NPM install inside the temporary project directory
* 4. Run TSC against the project's local tsconfig.json and local node_modules
* 5.
*/
const fs = require('fs');
const path = require('path');
const ncp = require('ncp');
const rimraf = require('rimraf');
const child_process = require('child_process');
const pathToTestSrcFolder = path.resolve(__dirname, '../test/typings-test/');
const binaryPath = path.resolve(__dirname, '../node_modules/.bin')
const rootPackage = require(path.resolve(__dirname, '../package.json'));
const startingCwd = process.cwd();
const pathToTestFolder = fs.mkdtempSync('/tmp/typings-test-');
process.chdir(pathToTestFolder)
ncp(pathToTestSrcFolder, pathToTestFolder, () => {
const samplePackage = require(`${pathToTestFolder}/package.sample.json`);
fs.writeFileSync(`${pathToTestFolder}/package.json`, JSON.stringify(samplePackage, null, 2)
.replace('{{ANGULARFIRE_VERSION}}', path.resolve(__dirname, '../dist/packages-dist'))
.replace('{{FIREBASE_VERSION}}', rootPackage.dependencies.firebase)
.replace('{{RXJS_VERSION}}', rootPackage.dependencies.rxjs)
.replace('{{ZONE_VERSION}}', rootPackage.devDependencies['zone.js'])
.replace('{{TYPESCRIPT_VERSION}}', rootPackage.devDependencies.typescript)
.replace(/\{\{ANGULAR_VERSION\}\}/g, rootPackage.dependencies['@angular/core']));
spawnIt('npm', ['install'])
.then(_ => spawnIt(`${pathToTestFolder}/node_modules/.bin/tsc`, ['--version']))
.then(_ => new Promise((res, rej) => {
child_process.exec(`${pathToTestFolder}/node_modules/.bin/tsc --diagnostics -p ${pathToTestFolder}/tsconfig.json`, (err, stdout, stderr) => {
console.log(stdout);
if (err) {
rej(1);
} else {
res();
}
});
}))
.catch(_ => {
// resolve with exit code 1
return Promise.resolve(1)
})
.then(cleanup)
.then(code => process.exit(code || 0));
})
function spawnIt(program, args) {
console.log('-----------------------------------');
console.log(program, (args && args.join(' ')) || '');
console.log('-----------------------------------');
return new Promise((res, rej) => {
child_process.spawn(program, args, {
cwd: pathToTestFolder,
stdio: 'inherit'
})
.on('close', (code) => {
if (code) return rej(code);
res();
})
});
}
function cleanup (val) {
rimraf.sync(pathToTestFolder);
return val;
}
| JavaScript | 0.005945 | @@ -1467,35 +1467,32 @@
, rootPackage.de
-vDe
pendencies%5B'zone
@@ -1938,24 +1938,29 @@
er%7D/tsconfig
+-test
.json%60, (err
|
0de7fde85c2ce9213513bb69e40b1ab27b0fbad9 | Add `useYarn` flag to `ember-try` configuration | config/ember-try.js | config/ember-try.js | /* eslint-env node */
module.exports = {
scenarios: [
{
name: 'ember-lts-2.8',
bower: {
dependencies: {
'ember': 'components/ember#lts-2-8'
},
resolutions: {
'ember': 'lts-2-8'
}
},
npm: {
devDependencies: {
'ember-source': null
}
}
},
{
name: 'ember-lts-2.12',
npm: {
devDependencies: {
'ember-source': '~2.12.0'
}
}
},
{
name: 'ember-release',
bower: {
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
npm: {
devDependencies: {
'ember-source': null
}
}
},
{
name: 'ember-beta',
bower: {
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
npm: {
devDependencies: {
'ember-source': null
}
}
},
{
name: 'ember-canary',
bower: {
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
},
npm: {
devDependencies: {
'ember-source': null
}
}
},
{
name: 'ember-default',
npm: {
devDependencies: {}
}
}
]
};
| JavaScript | 0 | @@ -34,16 +34,33 @@
rts = %7B%0A
+ useYarn: true,%0A
scenar
|
5b1773eb48aed9d0c615393eb7a41e5c92ad772c | Fix accumulateData | app/static/js/lib/cumulative.js | app/static/js/lib/cumulative.js | import {
filter,
fromPairs,
defaultTo,
head,
indexBy,
is,
keys,
last,
map,
prop,
range,
} from 'ramda'
export function accumulateData (data, column, series, extraYears = 0) {
let currentYear
let total = 0
// Check if request was canceled and thus column is undefined
if (!column) {
console.assert(column, 'Empty column for:', series, data)
return data
}
const dataYears = filter((row) => is(Number, row[column]), data.data)
const first = parseInt(head(keys(dataYears)))
const latest = parseInt(last(keys(dataYears)))
const years = range(first, latest + extraYears)
// console.debug('[AccumulateData] Range:', first, latest, column)
// TODO Write separate function that uses world production data until the estimation continues!
return indexBy(prop('Year'), map((year) => {
if (year <= latest) {
currentYear = defaultTo(0, parseFloat(data.data[year][column]))
} else {
currentYear = latest
}
total += currentYear
return fromPairs([
['Year', year],
[series, total],
])
}, years))
}
| JavaScript | 0.000004 | @@ -655,16 +655,20 @@
traYears
+ + 1
)%0A%0A /
@@ -1032,22 +1032,41 @@
tYear =
-latest
+data.data%5Blatest%5D%5Bcolumn%5D
%0A
|
8f4ce38963c66d0b436eb30d7aa7592a4194ddb1 | Remove unnecessary comment | src/sap.tnt/test/sap/tnt/demokit/sample/SideNavigation/V.controller.js | src/sap.tnt/test/sap/tnt/demokit/sample/SideNavigation/V.controller.js | sap.ui.define([
'jquery.sap.global',
'sap/ui/core/mvc/Controller',
'sap/m/Popover',
'sap/m/Button'
], function(jQuery, Controller, Popover, Button) {
"use strict";
var Controller = Controller.extend("sap.tnt.sample.SideNavigation.V", {
onInit: function () {
},
onCollapseExapandPress: function (event) {
var sideNavigation = this.getView().byId('sideNavigation');
var expanded = !sideNavigation.getExpanded();
sideNavigation.setExpanded(expanded);
//sideNavigation.setWidth(expanded? '20rem': '3rem');
}
});
return Controller;
});
| JavaScript | 0 | @@ -476,65 +476,8 @@
d);%0A
-%09%09%09//sideNavigation.setWidth(expanded? '20rem': '3rem');%0A
%09%09%7D%0A
|
7a57ebb6337c894fce2891c6349477c4e679f23d | Increase generated png size | server/lib/svg2png.js | server/lib/svg2png.js | import path from 'path';
import fs from 'fs';
import { getViewBoxDimensions } from './files';
const walkSync = function(dir) {
const isDirectory = dir => file => fs.statSync(path.join(dir, file)).isDirectory();
const filter = dir => file => file.match(/\.svg$/) || isDirectory(dir)(file);
return fs.readdirSync(dir).filter(filter(dir)).map(function(file) {
if (isDirectory(dir)(file)) {
console.log('mkdir', path.join(dir, file).replace('svg', 'png'));
walkSync(path.join(dir, file));
} else {
const svg2png = './node_modules/svg2png/bin/svg2png-cli.js';
const svg = path.join(dir, file);
const png = svg.replace(/svg/g, 'png');
const dim = getViewBoxDimensions(dir)(file);
console.log(`rm -rf ${png}`);
console.log(`${svg2png} ${svg} --output=${png} --width=${dim.width} --height=${dim.height}`);
}
});
};
console.log('mkdir public/png/');
walkSync('public/svg/');
| JavaScript | 0.000001 | @@ -826,16 +826,18 @@
im.width
+*4
%7D --heig
@@ -851,16 +851,18 @@
m.height
+*4
%7D%60);%0A
|
ea2b889f05f1e037226846b768d24b27a14a8bbb | Update server config for express 4 | app/templates/config/express.js | app/templates/config/express.js | var express = require('express'),
mongoStore = require('connect-mongo')(express),
config = require('./config');
module.exports = function(app) {
app.set('showStackError', true);
// No logger on test environment
if (process.env.NODE_ENV !== 'test') {
app.use(express.logger('dev'));
}
app.enable("jsonp callback");
app.configure(function() {
app.use(express.cookieParser());
app.use(express.methodOverride());
// express/mongo setup for
// storing session data
app.use(express.session({
secret: 'VENM',
store: new mongoStore({
url: config.db,
collection: 'sessions'
})
}));
// Continue to routing,
app.use(app.router);
});
// 500 Error
app.use(function(err, req, res, next) {
// If page not found continue to the
// 404 handling middleware
if (~err.message.indexOf('not found')) return next();
// log
console.error(err.stack);
// send response
res.status(500).json({
code: 500,
error: err.stack
});
});
// Send 404 error
app.use(function(req, res, next) {
// send response
res.status(404).json({
code: 404,
error: 'Not Found'
});
});
}
| JavaScript | 0 | @@ -27,16 +27,184 @@
ress'),%0A
+ morgan = require('morgan'),%0A session = require('express-session'),%0A cookieParser = require('cookie-parser'),%0A methodOverride = require('method-override'),%0A
mong
@@ -241,21 +241,22 @@
o')(
-express),%0A
+session);%0A%0Avar
con
@@ -454,22 +454,14 @@
use(
-express.logger
+morgan
('de
@@ -555,24 +555,16 @@
app.use(
-express.
cookiePa
@@ -588,24 +588,16 @@
app.use(
-express.
methodOv
@@ -626,16 +626,24 @@
express
+-session
/mongo s
@@ -704,16 +704,8 @@
use(
-express.
sess
|
dcc6f9326e115c1fe348956f96140d608958224b | Update user.js | server/models/user.js | server/models/user.js | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
crypto = require('crypto');
//mongoose.connect('mongodb://localhost/auth');
mongoose.connect('mongodb://ionic:ionicuser@dogen.mongohq.com:10095/app31139887');
/**
* Validations
*/
var validatePresenceOf = function(value) {
// If you are authenticating by any of the oauth strategies, don't validate.
return (this.provider && this.provider !== 'local') || (value && value.length);
};
var validateUniqueEmail = function(value, callback) {
var User = mongoose.model('User');
User.find({
$and: [{
email: value
}, {
_id: {
$ne: this._id
}
}]
}, function(err, user) {
callback(err || user.length === 0);
});
};
/**
* User Schema
*/
var UserSchema = new Schema({
name: {
type: String
},
email: {
type: String,
required: false,
unique: true,
match: [/\S+@\S+\.\S+/, 'Please enter a valid email'],
validate: [validateUniqueEmail, 'E-mail address is already in-use']
},
username: {
type: String,
unique: true,
required: true
},
roles: {
type: Array,
default: ['authenticated']
},
hashed_password: {
type: String,
validate: [validatePresenceOf, 'Password cannot be blank']
},
provider: {
type: String,
default: 'local'
},
salt: String,
resetPasswordToken: String,
resetPasswordExpires: Date,
facebook: {},
twitter: {},
github: {},
google: {},
linkedin: {}
});
/**
* Virtuals
*/
UserSchema.virtual('password').set(function(password) {
this._password = password;
this.salt = this.makeSalt();
this.hashed_password = this.hashPassword(password);
}).get(function() {
return this._password;
});
/**
* Pre-save hook
*/
UserSchema.pre('save', function(next) {
if (this.isNew && this.provider === 'local' && this.password && !this.password.length)
return next(new Error('Invalid password'));
next();
});
/**
* Methods
*/
UserSchema.methods = {
/**
* HasRole - check if the user has required role
*
* @param {String} plainText
* @return {Boolean}
* @api public
*/
hasRole: function(role) {
var roles = this.roles;
return roles.indexOf('admin') !== -1 || roles.indexOf(role) !== -1;
},
/**
* IsAdmin - check if the user is an administrator
*
* @return {Boolean}
* @api public
*/
isAdmin: function() {
return this.roles.indexOf('admin') !== -1;
},
/**
* Authenticate - check if the passwords are the same
*
* @param {String} plainText
* @return {Boolean}
* @api public
*/
authenticate: function(plainText) {
return this.hashPassword(plainText) === this.hashed_password;
},
/**
* Make salt
*
* @return {String}
* @api public
*/
makeSalt: function() {
return crypto.randomBytes(16).toString('base64');
},
/**
* Hash password
*
* @param {String} password
* @return {String}
* @api public
*/
hashPassword: function(password) {
if (!password || !this.salt) return '';
var salt = new Buffer(this.salt, 'base64');
return crypto.pbkdf2Sync(password, salt, 10000, 64).toString('base64');
},
// hasToken method
hasToken: function() {
return !!this.token.jwt;
},
/**
* getToken- check if the user has required token
*
* @param none
* @return {Boolean}
* @api public
*/
getToken: function() {
return this.token.jwt;
}
};
module.exports = mongoose.model('User', UserSchema);
| JavaScript | 0.000001 | @@ -139,18 +139,16 @@
pto');%0A%0A
-//
mongoose
@@ -182,24 +182,26 @@
st/auth');%0A%0A
+//
mongoose.con
|
7188738954c5b927a1ddd4406d6e2877b41cd480 | add imports | myuw/static/vue/tests/inst_summary.test.js | myuw/static/vue/tests/inst_summary.test.js | import axios from 'axios';
import dayjs from 'dayjs';
import {mount, createLocalVue} from '@vue/test-utils';
import BootstrapVue from 'bootstrap-vue';
import Vuex from 'vuex';
import InstructorCourseSummery from
'../components/home/inst_course_summary/summary.vue';
// import {statusOptions} from '../vuex/store/model_builder';
// import {expectAction} from './helper';
import inst_schedule from '../vuex/store/inst_schedule';
import mockBill2013Summer from
'./mock_data/inst_schedule/bill2013summer.json';
import mockBillpce2013Summer from
'./mock_data/inst_schedule/billpce2013summer.json';
import mockBillsea2013Spring from
'./mock_data/inst_schedule/billsea2013spring.json';
import mockNoCourse2013Summer from
'./mock_data/inst_schedule/2013summer.json';
const localVue = createLocalVue();
localVue.use(BootstrapVue);
jest.mock('axios');
describe('Instructor Schedule Summary', () => {
let store;
beforeEach(() => {
store = new Vuex.Store({
modules: {
'inst_schedule': inst_schedule,
},
state: {
user: {
netid:"billsea",
affiliations: {
instructor: true,
}
},
termData: {
year: 2013,
quarter: 'spring',
firstDay: "Apr 01 2013 00:00:00 GMT-0700",
},
nextTerm: {
year: 2013,
quarter: 'summer',
}
}
});
});
it('Basic Mount', async () => {
axios.get.mockImplementation((url) => {
const urlData = {
'/api/v1/instructor_schedule/current': mockBillsea2013Spring,
'/api/v1/instructor_schedule/2013,summer': mockNoCourse2013Summer,
};
return Promise.resolve({data: urlData[url]});
});
const wrapper = mount(InstructorCourseSummery, {store, localVue});
await new Promise((r) => setTimeout(r, 10));
expect(wrapper.vm.loaded).toBeTruthy();
expect(wrapper.find('h3').text()).toEqual(
'Spring 2013 Teaching Schedule');
});
it('Check fetch 2013,summer - success', () => {
axios.get.mockResolvedValue(
{data: mockNoCourse2013Summer, status: 200}
);
const getters = {
isReadyTagged: () => false,
isFetchingTagged: () => false,
};
return expectAction(
inst_schedule.actions.fetch, null, inst_schedule.state, getters, [
{type: 'setStatus', payload: statusOptions[1]},
{type: 'setValue', payload: mockNoCourse2013Summer},
{type: 'setStatus', payload: statusOptions[0]},
]);
});
it('Check status changes on fetch - failure', () => {
axios.get.mockResolvedValue(
Promise.reject({response: {status: 404}}));
const getters = {
isReadyTagged: () => false,
isFetchingTagged: () => false,
};
return expectAction(
inst_schedule.actions.fetch, null, inst_schedule.state, getters, [
{type: 'setStatus', payload: statusOptions[1]},
{type: 'setStatus', payload: statusOptions[2]},
]);
});
it ('Check postProcess - billsea 2013 spring', () => {
axios.get.mockResolvedValue(
{data: mockBillsea2013Spring, status: 200}
);
const getters = {
isReadyTagged: () => false,
isFetchingTagged: () => false,
};
return expectAction(
inst_schedule.actions.fetch, null, inst_schedule.state, getters, [
{type: 'setStatus', payload: statusOptions[1]},
{type: 'setValue', payload: mockBillsea2013Spring},
{type: 'setStatus', payload: statusOptions[0]},
]);
});
});
| JavaScript | 0.000001 | @@ -261,19 +261,16 @@
y.vue';%0A
-//
import %7B
@@ -324,11 +324,8 @@
r';%0A
-//
impo
@@ -820,16 +820,36 @@
rapVue);
+%0AlocalVue.use(Vuex);
%0A%0Ajest.m
|
86a1182bd6cd48dce5c2bb156846e8b4a0c070d3 | Convert Rect to stateless function | src/examples/GeometryShapes/Rect.js | src/examples/GeometryShapes/Rect.js | import React from 'react';
import PropTypes from 'react/lib/ReactPropTypes';
class Rect extends React.Component {
static propTypes = {
width: PropTypes.number.isRequired,
length: PropTypes.number.isRequired,
resourceId: PropTypes.string.isRequired,
};
render() {
const {
width,
length,
resourceId,
} = this.props;
return (<shape resourceId={resourceId}>
<moveTo
x={0}
y={0}
/>
<lineTo
x={0}
y={width}
/>
<lineTo
x={length}
y={width}
/>
<lineTo
x={length}
y={width}
/>
<lineTo
x={length}
y={0}
/>
<lineTo
x={0}
y={0}
/>
</shape>);
}
}
export default Rect;
| JavaScript | 0.999978 | @@ -74,34 +74,55 @@
s';%0A
-%0Aclass Rect extends
+import PureComponentMixin from 'react/lib/
React
-.
Comp
@@ -130,261 +130,337 @@
nent
- %7B%0A static propTypes = %7B%0A width: PropTypes.number.isRequired,%0A length: PropTypes.number.isRequired,%0A resourceId: PropTypes.string.isRequire
+WithPureRenderMixin';%0A%0Afunction Rect(props) %7B%0A const %7B%0A width,%0A length,%0A resourceI
d,%0A
+
-%7D;%0A%0A render() %7B%0A const %7B%0A width,%0A length,%0A resourceId,%0A %7D = this.props;%0A%0A
+ %7D = props;%0A%0A // console.log('wat');%0A //%0A // this.shouldComponentUpdate = function asdf()%7B%0A // console.log('should I update huh?');%0A //%0A // return PureComponentMixin.shouldComponentUpdate.apply(this, arguments);%0A // %7D;%0A%0A
re
@@ -501,18 +501,16 @@
d%7D%3E%0A
-
-
%3CmoveTo%0A
@@ -511,34 +511,30 @@
oveTo%0A
-
x=%7B0%7D%0A
-
y=%7B0%7D%0A
@@ -529,39 +529,35 @@
y=%7B0%7D%0A
-
/%3E%0A
-
%3ClineTo%0A
@@ -554,34 +554,30 @@
ineTo%0A
-
-
x=%7B0%7D%0A
-
y=%7Bwid
@@ -572,34 +572,32 @@
y=%7Bwidth%7D%0A
-
/%3E%0A %3Cli
@@ -587,34 +587,32 @@
%0A /%3E%0A
-
%3ClineTo%0A
x=%7Bl
@@ -591,34 +591,32 @@
/%3E%0A %3ClineTo%0A
-
x=%7Blength%7D
@@ -614,34 +614,32 @@
=%7Blength%7D%0A
-
-
y=%7Bwidth%7D%0A
@@ -628,39 +628,35 @@
y=%7Bwidth%7D%0A
-
/%3E%0A
-
%3ClineTo%0A
@@ -649,34 +649,32 @@
%3ClineTo%0A
-
x=%7Blength%7D%0A
@@ -678,31 +678,21 @@
-
y=%7B
-width
+0
%7D%0A
-
/%3E%0A
-
@@ -701,39 +701,30 @@
ineTo%0A
-
-
x=%7B
-length%7D%0A
+0%7D%0A
y=%7B0%7D%0A
@@ -731,84 +731,168 @@
-
/%3E%0A
- %3ClineTo%0A x=%7B0%7D%0A y=%7B0%7D%0A /%3E%0A %3C/shape%3E);%0A %7D
+%3C/shape%3E);%0A%7D%0A%0ARect.propTypes = %7B%0A width: PropTypes.number.isRequired,%0A length: PropTypes.number.isRequired,%0A resourceId: PropTypes.string.isRequired,
%0A%7D
+;
%0A%0Aex
|
02367b233110bda38d730036ddbf9436cb50c2a7 | Update labs.js | assets/js/labs.js | assets/js/labs.js | ;(function(win,doc,head,body){
if(!('addEventListener' in win)) return;
win.z = function(a){
var x=a.data.length,
b=0,
c=doc.getElementById("repos");
c.removeAttribute("hidden");
for(;x>b;b++){
var e=doc.createElement("div"),
f=a.data[b].homepage?a.data[b].homepage:a.data[b].html_url;
e.className=(b%6===0?'cell cell-sm-12 cell-md-4 cell-lg-3 repo block':(b%5===0?'cell cell-sm-12 cell-md-6 cell-lg-7 block repo':'cell cell-sm-12 cell-md-6 cell-lg-5 block repo'));
e.style.animationDelay=(win.Math.floor(win.Math.random()*500)+300)+'ms';
e.innerHTML='<a href="'+f+'" title="'+a.data[b].name+'"><h4>'+a.data[b].name+'</h4>'+'<small class="desc">'+a.data[b].description+'</small>'+'<small class="tags">'+a.data[b].language+'</small>'+'</a>';
c.appendChild(e);
}
};
win.addEventListener('load',handleLoad,false);
loadStylesheets(['https://amdouglas.com/assets/css/fonts.css','https://amdouglas.com/assets/css/labs.css']);
function loadStylesheets(urls){
for(var i = 0;i<urls.length;++i){
var css = doc.createElement('link');
css.rel = 'stylesheet';
css.href = urls[i];
head.appendChild(css);
}
}
function loadScripts(urls){
for(var i = 0;i<urls.length;++i){
var js = doc.createElement('script');
js.async = !0;
js.src = urls[i];
head.appendChild(js);
}
}
function handleLoad(){
win.removeEventListener('load',handleLoad,false);
loadScripts(['https://api.github.com/users/wnda/repos?callback=z','https://www.google-analytics.com/analytics.js']);
if('devicePixelRatio' in win && win.devicePixelRatio > 1 && wdth < 992){
appendOptionalMetaTags();
appendTouchIcons();
}
if('serviceWorker' in navigator){
navigator.serviceWorker.register('https://amdouglas.com/sw.js', {
scope: '/'
}).then(function(registration){
console.info("SW registered [" + registration.scope + "]");
}).catch(function(err){
console.warn("SW failed to register [" + err + "]");
});
}
win.GoogleAnalyticsObject = win.ga;
win.ga = win.ga || function(){
for(var p = 0; p < arguments.length; ++p){
(win.ga.q = win.ga.q || []).push(arguments[p]);
}
};
win.ga.l = 1 * new Date();
win.ga('create','UA-70873652-1','auto');
win.ga('send','pageview');
}
function appendTouchIcons(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://amdouglas.com/manifest.json', true);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
var data = JSON.parse(xhr.responseText);
for(var j=0;j<data.icons.length;++j){
if(data.icons[j].src.indexOf('apple') > -1){
var icon = doc.createElement('link');
icon.rel = 'apple-touch-icon-precomposed';
icon.href = data.icons[j].src;
icon.setAttribute('sizes', data.icons[j].sizes);
head.appendChild(icon);
}
}
}
}
};
xhr.send();
}
function appendOptionalMetaTags(){
var metatags = ['format-detection','apple-mobile-web-app-status-bar-style','apple-touch-fullscreen','apple-mobile-web-app-capable','mobile-web-app-capable','application-name','MobileOptimized','HandheldFriendly'];
var metacontents = ['telephone=no,email=no','black-translucent','yes','yes','yes','A. M. Douglas','width','true'];
var mtl = 8;
while(mtl--){
var metatag = doc.createElement('meta');
metatag.name = metatags[mtl];
metatag.content = metacontents[mtl];
head.appendChild(metatag);
}
}
})(window,window.document,window.document.head,window.document.body);
| JavaScript | 0.000001 | @@ -1708,40 +1708,8 @@
2)%7B%0A
- appendOptionalMetaTags();%0A
@@ -3146,590 +3146,8 @@
%7D%0A%0A
- function appendOptionalMetaTags()%7B%0A var metatags = %5B'format-detection','apple-mobile-web-app-status-bar-style','apple-touch-fullscreen','apple-mobile-web-app-capable','mobile-web-app-capable','application-name','MobileOptimized','HandheldFriendly'%5D;%0A var metacontents = %5B'telephone=no,email=no','black-translucent','yes','yes','yes','A. M. Douglas','width','true'%5D;%0A var mtl = 8;%0A while(mtl--)%7B%0A var metatag = doc.createElement('meta');%0A metatag.name = metatags%5Bmtl%5D;%0A metatag.content = metacontents%5Bmtl%5D;%0A head.appendChild(metatag);%0A %7D%0A %7D%0A %0A%0A
%7D)(w
|
39f1e24c5381fd9681720a8123cbf364ba60bcf4 | Include shiv instead of printshiv to support main. | grunt/modernizr.js | grunt/modernizr.js | // Generate Modernizr custom build from references in SCSS + JS assets
module.exports = function(grunt) {
grunt.config('modernizr', {
'devFile' : 'scripts/modernizr/modernizr.js',
'outputFile' : 'dist/scripts/modernizr/modernizr.js',
'extra' : {
'shiv' : false,
'printshiv' : true,
'load' : false,
'mq' : true,
'cssclasses' : true
},
'extensibility' : {
'addtest' : false,
'prefixed' : false,
'teststyles' : false,
'testprops' : false,
'testallprops' : false,
'hasevents' : false,
'prefixes' : false,
'domprefixes' : false
},
'uglify' : true,
'tests' : [],
// parseFiles = true: crawl all *.js, *.css, *.scss files;
// override by defining "files" array
'parseFiles' : true,
'files' : ['scss/**/*.scss',
'scripts/magnific-popup/dist/jquery.magnific-popup.js',
'scripts/magnific-popup/src/css/main.scss',
'scripts/jquery-cycle2/*.js',
'scripts/jquery-accessible-tabs/js/jquery.syncheight.js',
'scripts/jquery-accessible-tabs/js/jquery.tabs.js',
'scripts/gmaps/gmaps.js',
'scripts/*.js'],
'matchCommunityTests' : false,
'customTests' : [],
'excludeFiles' : ['Gruntfile.js', '*.json'],
});
grunt.loadNpmTasks('grunt-modernizr');
};
| JavaScript | 0 | @@ -285,28 +285,27 @@
'shiv' :
-fals
+tru
e,%0A
@@ -313,35 +313,36 @@
'printshiv' :
-tru
+fals
e,%0A '
|
ac6edee48b9c7c3c21d6e3c3879ecabed6e99721 | fix url | docusaurus/website/siteConfig.js | docusaurus/website/siteConfig.js | /**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// See https://docusaurus.io/docs/site-config for all the possible
// site configuration options.
const siteConfig = {
title: 'Create React App', // Title for your website.
tagline: 'Set up a modern web app by running one command.',
url: 'https://facebook.github.io', // Your website URL
baseUrl: '/', // Base URL for your project */
// For github.io type URLs, you would set the url and baseUrl like:
// url: 'https://facebook.github.io',
// baseUrl: '/test-site/',
// Used for publishing and more
projectName: 'create-react-app',
organizationName: 'facebook',
// For top-level user or org sites, the organization is still the same.
// e.g., for the https://JoelMarcey.github.io site, it would be set like...
// organizationName: 'JoelMarcey'
// For no header links in the top nav bar -> headerLinks: [],
headerLinks: [
{ doc: 'getting-started', label: 'Getting Started' },
{ href: 'https://reactjs.org/community/support.html', label: 'Help' },
{
href: 'https://www.github.com/facebook/create-react-app',
label: 'GitHub',
},
],
/* path to images for header/footer */
headerIcon: 'img/logo.svg',
footerIcon: 'img/logo.svg',
favicon: 'img/favicon/favicon.ico',
/* Colors for website */
colors: {
primaryColor: '#20232a',
secondaryColor: '#61dafb',
},
/* Custom fonts for website */
/*
fonts: {
myFont: [
"Times New Roman",
"Serif"
],
myOtherFont: [
"-apple-system",
"system-ui"
]
},
*/
// This copyright info is used in /core/Footer.js and blog RSS/Atom feeds.
copyright: `Copyright © ${new Date().getFullYear()} Facebook Inc.`,
highlight: {
// Highlight.js theme to use for syntax highlighting in code blocks.
theme: 'default',
},
// Add custom scripts here that would be placed in <script> tags.
scripts: ['https://buttons.github.io/buttons.js'],
// On page navigation for the current documentation page.
onPageNav: 'separate',
// No .html extensions for paths.
cleanUrl: true,
// Open Graph and Twitter card images.
ogImage: 'img/logo-og.png',
twitterImage: 'img/logo-og.png',
// You may provide arbitrary config keys to be used as needed by your
// template. For example, if you need your repo's URL...
repoUrl: 'https://github.com/facebook/create-react-app',
};
module.exports = siteConfig;
| JavaScript | 0.86565 | @@ -476,56 +476,8 @@
URL%0A
- baseUrl: '/', // Base URL for your project */%0A
//
@@ -542,21 +542,16 @@
l like:%0A
- //
url: '
@@ -579,21 +579,16 @@
ub.io',%0A
- //
baseUr
@@ -596,17 +596,24 @@
: '/
-test-site
+create-react-app
/',%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.