text
stringlengths 2
1.05M
|
|---|
import React from 'react';
import {Form, Input, Modal, Col, Row} from 'antd';
import Utils from '@/Common/Utils';
import moment from "moment";
const TextArea = Input.TextArea;
const FormItem = Form.Item;
const Util = new Utils();
class MessageModal {
//消息内容
MessageCoutent = Form.create()(props => {
const {
messageVisible,showMessage,form,messageRecord
} = props;
//取消
const cancelHandle = () => {
showMessage(false,{})
}
const formItemLayout = {labelCol: {span: 3}, wrapperCol: {span: 21}};
return (
<Modal
maskClosable={false}
title={`${messageRecord.title}`}
visible={messageVisible}
onCancel={cancelHandle}
width={400}
cancelText="取消"
destroyOnClose={true}
footer={false}
>
<Form>
<Row>
<Col><FormItem {...formItemLayout} label={'内容'} >{form.getFieldDecorator('content', {
initialValue: `${Util.isNotNull(messageRecord.content)?messageRecord.content:''}`
})(<TextArea style={{minHeight:100,maxHeight:100}} />)}</FormItem></Col>
</Row>
</Form>
</Modal>
);
})
}
export default MessageModal;
|
import React, { Component, Fragment } from 'react'
import { connect } from 'react-redux'
import axios from 'axios'
import PropTypes from 'prop-types'
import GridRow from '@govuk-react/grid-row'
import GridCol from '@govuk-react/grid-col'
import moment from 'moment'
import ReactRouterPropTypes from 'react-router-prop-types'
import { withRouter } from 'react-router'
import Statistic from '../Statistic/Statistic'
import Page from '../Components/Page'
import Period from '../Period/Period'
import { switchToIsoDateFormat, formatDateToLongHand } from '../stringUtils'
import { setPrisonLevelKeyworkerStats, setLoaded } from '../redux/actions'
import { RatioHeader, Ratio, NoDataMessage, PeriodText, SubHeader } from './KeyworkerDashboard.styles'
export class KeyworkerDashboard extends Component {
async componentDidMount() {
const { firstDay, lastDay } = this.getLastMonthsDates()
await this.loadStatsForPeriod(firstDay, lastDay)
}
async componentDidUpdate(prevProps) {
const { agencyId, fromDate, toDate } = this.props
if (agencyId !== prevProps.agencyId) {
await this.loadStatsForPeriod(fromDate, toDate)
}
}
getLastMonthsDates = () => {
const lastMonth = moment().subtract(1, 'months')
const firstDay = switchToIsoDateFormat(lastMonth.startOf('month'))
const lastDay = switchToIsoDateFormat(lastMonth.endOf('month'))
return { firstDay, lastDay }
}
getComparisonDates = (fromDate, toDate) => {
const fromDateMoment = moment(fromDate, 'YYYY-MM-DD')
const toDateMoment = moment(toDate, 'YYYY-MM-DD')
const diff = moment.duration(toDateMoment.diff(fromDateMoment)).asDays()
const comparisonFromDate = formatDateToLongHand(fromDateMoment.subtract(diff, 'days').format())
const comparisonToDate = formatDateToLongHand(toDateMoment.subtract(diff + 1, 'days').format())
const formattedChosenFromDate = formatDateToLongHand(fromDate)
const formattedChosenToDate = formatDateToLongHand(toDate)
return { comparisonFromDate, comparisonToDate, formattedChosenFromDate, formattedChosenToDate }
}
onSubmit = (values) => {
const { fromDate, toDate } = values
this.loadStatsForPeriod(switchToIsoDateFormat(fromDate), switchToIsoDateFormat(toDate))
}
async loadStatsForPeriod(fromDate, toDate) {
const { agencyId, handleError, dispatchLoaded, dispatchStats, migrated, history } = this.props
if (!migrated) {
history.push('/')
} else {
dispatchLoaded(false)
try {
const response = await axios.get('/api/keyworker-prison-stats', { params: { agencyId, fromDate, toDate } })
const { stats, prisonerToKeyWorkerRatio } = response.data
dispatchStats({ data: stats, prisonerToKeyWorkerRatio, fromDate, toDate })
} catch (error) {
handleError(error)
}
dispatchLoaded(true)
}
}
renderStatistic = (statistic) => (
<Fragment key={statistic.heading}>
<GridCol setWidth="one-quarter">
<Statistic {...statistic} />
</GridCol>
</Fragment>
)
renderData = () => {
const { data, fromDate, toDate } = this.props
const { comparisonFromDate, comparisonToDate, formattedChosenFromDate, formattedChosenToDate } =
(toDate && this.getComparisonDates(fromDate, toDate)) || {}
if (data.length > 0) {
return (
<>
<PeriodText data-qa="period-text">
Displaying statistics from {`${formattedChosenFromDate}`} to {`${formattedChosenToDate}`}. Comparing against
statistics from {`${comparisonFromDate}`} to {`${comparisonToDate}`}.
</PeriodText>
<GridRow>{data.slice(0, 4).map((statistic) => this.renderStatistic(statistic))}</GridRow>
{data.length > 4 && (
<>
<hr />
<GridRow>{data.slice(4, 8).map((statistic) => this.renderStatistic(statistic))}</GridRow>
<hr />
</>
)}
</>
)
}
return <NoDataMessage data-qa="no-data-message">There is no data for this period.</NoDataMessage>
}
render() {
const { prisonerToKeyWorkerRatio, fromDate, toDate, activeCaseLoad, sequenceFrequency, highComplexity } = this.props
return (
<Page title={`Key worker statistics for ${activeCaseLoad}`}>
{highComplexity && (
<SubHeader>These statistics do not include people with a high complexity of need level.</SubHeader>
)}
<SubHeader>
Prisoners in {activeCaseLoad} have a key worker session every {sequenceFrequency} week
{sequenceFrequency > 1 ? 's' : ''}.
</SubHeader>
<hr />
<GridRow>
<GridCol>
<Period fromDate={fromDate} toDate={toDate} onSubmit={this.onSubmit} />
</GridCol>
<GridCol setWidth="one-quarter">
<RatioHeader level={3} size="SMALL">
Prisoner to key worker ratio
</RatioHeader>
<Ratio data-qa="prisonerToKeyworkerRation-value">{`${prisonerToKeyWorkerRatio}:1`}</Ratio>
</GridCol>
</GridRow>
<hr />
{this.renderData()}
</Page>
)
}
}
KeyworkerDashboard.propTypes = {
agencyId: PropTypes.string.isRequired,
displayBack: PropTypes.func.isRequired,
handleError: PropTypes.func.isRequired,
history: ReactRouterPropTypes.history.isRequired,
migrated: PropTypes.bool.isRequired,
sequenceFrequency: PropTypes.number.isRequired,
fromDate: PropTypes.string.isRequired,
toDate: PropTypes.string.isRequired,
dispatchStats: PropTypes.func.isRequired,
dispatchLoaded: PropTypes.func.isRequired,
data: PropTypes.arrayOf(PropTypes.object).isRequired,
prisonerToKeyWorkerRatio: PropTypes.number.isRequired,
activeCaseLoad: PropTypes.string.isRequired,
highComplexity: PropTypes.bool.isRequired,
}
const mapDispatchToProps = (dispatch) => ({
dispatchStats: ({ data, fromDate, toDate, prisonerToKeyWorkerRatio }) =>
dispatch(setPrisonLevelKeyworkerStats({ data, fromDate, toDate, prisonerToKeyWorkerRatio })),
dispatchLoaded: (value) => dispatch(setLoaded(value)),
})
const mapStateToProps = (state) => ({
agencyId: state.app.user.activeCaseLoadId,
data: state.prisonLevelKeyWorkerStatsDashboard.data,
prisonerToKeyWorkerRatio: state.prisonLevelKeyWorkerStatsDashboard.prisonerToKeyWorkerRatio,
activeCaseLoad: state.app.user.caseLoadOptions.filter((caseLoad) => caseLoad.currentlyActive)[0].description,
migrated: state.keyworkerSettings.migrated,
sequenceFrequency: state.keyworkerSettings.sequenceFrequency,
fromDate: state.prisonLevelKeyWorkerStatsDashboard.fromDate,
toDate: state.prisonLevelKeyWorkerStatsDashboard.toDate,
highComplexity: state.keyworkerSettings.highComplexity,
})
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(KeyworkerDashboard))
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
const useStyles = makeStyles((theme) => ({
paper: {
padding: theme.spacing(2),
display: 'flex',
overflow: 'auto',
flexDirection: 'column',
},
header : {
fontSize: '20px',
paddingBottom: '3px',
color: '#828282',
},
section: {
padding: '10px'
}
}));
export default function TagDetails(props) {
const classes = useStyles();
return (
<Container>
<Grid container>
<Grid container className={classes.section}>
<Grid className={classes.header} item xs={12}>
{props.property.propertyAddress}
</Grid>
<Grid item xs={12} style={{color:'#828282'}}>
{props.property.propertyCity + ", " + props.property.propertyState + " " + props.property.propertyZip}
</Grid>
</Grid>
<Grid container className={classes.section}>
<Grid className={classes.header} item xs={12}>
TAG ID
</Grid>
<Grid item xs={12}>
{props.tag.id}
</Grid>
</Grid>
<Grid container className={classes.section}>
<Grid className={classes.header} item xs={12}>
UNIT DESCRIPTION
</Grid>
<Grid item xs={12}>
{props.tag.description}
</Grid>
</Grid>
<Grid container className={classes.section}>
<Grid className={classes.header} item xs={12}>
MODEL
</Grid>
<Grid item xs={12}>
{props.tag.unitModel}
</Grid>
</Grid>
<Grid container className={classes.section}>
<Grid className={classes.header} item xs={12}>
PURCHASE DATE
</Grid>
<Grid item xs={12}>
May 7, 2010
</Grid>
</Grid>
<Grid container className={classes.section}>
<Grid className={classes.header} item xs={12}>
WARRANTY EXPIRATION
</Grid>
<Grid item xs={12}>
May 7, 2015
</Grid>
</Grid>
<Grid container className={classes.section}>
<Grid className={classes.header} item xs={12}>
LAST SERVICE DATE
</Grid>
<Grid item xs={12}>
{props.tag.lastServiceDate}
</Grid>
</Grid>
</Grid>
</Container>
)
}
|
(function() {var implementors = {};
implementors["rust_info"] = [{text:"impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/marker/trait.Send.html\" title=\"trait core::marker::Send\">Send</a> for <a class=\"struct\" href=\"rust_info/types/struct.RustInfo.html\" title=\"struct rust_info::types::RustInfo\">RustInfo</a>",synthetic:true,types:["rust_info::types::RustInfo"]},{text:"impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/marker/trait.Send.html\" title=\"trait core::marker::Send\">Send</a> for <a class=\"enum\" href=\"rust_info/types/enum.RustChannel.html\" title=\"enum rust_info::types::RustChannel\">RustChannel</a>",synthetic:true,types:["rust_info::types::RustChannel"]},];
if (window.register_implementors) {
window.register_implementors(implementors);
} else {
window.pending_implementors = implementors;
}
})()
|
/*! vue-ydui v1.2.6 by YDCSS (c) 2018 Licensed MIT */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ydui=t():e.ydui=t()}(this,function(){return function(e){function t(i){if(r[i])return r[i].exports;var n=r[i]={exports:{},id:i,loaded:!1};return e[i].call(n.exports,n,n.exports,t),n.loaded=!0,n.exports}var r={};return t.m=e,t.c=r,t.p="/dist/",t(0)}({0:function(e,t,r){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.PreviewItem=t.PreviewHeader=t.Preview=void 0;var n=r(115),o=i(n),a=r(113),s=i(a),l=r(114),d=i(l);t.Preview=o.default,t.PreviewHeader=s.default,t.PreviewItem=d.default},1:function(e,t){e.exports=function(e,t,r,i){var n,o=e=e||{},a=typeof e.default;"object"!==a&&"function"!==a||(n=e,o=e.default);var s="function"==typeof o?o.options:o;if(t&&(s.render=t.render,s.staticRenderFns=t.staticRenderFns),r&&(s._scopeId=r),i){var l=s.computed||(s.computed={});Object.keys(i).forEach(function(e){var t=i[e];l[e]=function(){return t}})}return{esModule:n,exports:o,options:s}}},2:function(e,t){e.exports=function(){var e=[];return e.toString=function(){for(var e=[],t=0;t<this.length;t++){var r=this[t];r[2]?e.push("@media "+r[2]+"{"+r[1]+"}"):e.push(r[1])}return e.join("")},e.i=function(t,r){"string"==typeof t&&(t=[[null,t,""]]);for(var i={},n=0;n<this.length;n++){var o=this[n][0];"number"==typeof o&&(i[o]=!0)}for(n=0;n<t.length;n++){var a=t[n];"number"==typeof a[0]&&i[a[0]]||(r&&!a[2]?a[2]=r:r&&(a[2]="("+a[2]+") and ("+r+")"),e.push(a))}},e}},3:function(e,t,r){function i(e){for(var t=0;t<e.length;t++){var r=e[t],i=c[r.id];if(i){i.refs++;for(var n=0;n<i.parts.length;n++)i.parts[n](r.parts[n]);for(;n<r.parts.length;n++)i.parts.push(o(r.parts[n]));i.parts.length>r.parts.length&&(i.parts.length=r.parts.length)}else{for(var a=[],n=0;n<r.parts.length;n++)a.push(o(r.parts[n]));c[r.id]={id:r.id,refs:1,parts:a}}}}function n(){var e=document.createElement("style");return e.type="text/css",f.appendChild(e),e}function o(e){var t,r,i=document.querySelector('style[data-vue-ssr-id~="'+e.id+'"]');if(i){if(v)return h;i.parentNode.removeChild(i)}if(m){var o=u++;i=p||(p=n()),t=a.bind(null,i,o,!1),r=a.bind(null,i,o,!0)}else i=n(),t=s.bind(null,i),r=function(){i.parentNode.removeChild(i)};return t(e),function(i){if(i){if(i.css===e.css&&i.media===e.media&&i.sourceMap===e.sourceMap)return;t(e=i)}else r()}}function a(e,t,r,i){var n=r?"":i.css;if(e.styleSheet)e.styleSheet.cssText=g(t,n);else{var o=document.createTextNode(n),a=e.childNodes;a[t]&&e.removeChild(a[t]),a.length?e.insertBefore(o,a[t]):e.appendChild(o)}}function s(e,t){var r=t.css,i=t.media,n=t.sourceMap;if(i&&e.setAttribute("media",i),n&&(r+="\n/*# sourceURL="+n.sources[0]+" */",r+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(n))))+" */"),e.styleSheet)e.styleSheet.cssText=r;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(r))}}var l="undefined"!=typeof document,d=r(4),c={},f=l&&(document.head||document.getElementsByTagName("head")[0]),p=null,u=0,v=!1,h=function(){},m="undefined"!=typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());e.exports=function(e,t,r){v=r;var n=d(e,t);return i(n),function(t){for(var r=[],o=0;o<n.length;o++){var a=n[o],s=c[a.id];s.refs--,r.push(s)}t?(n=d(e,t),i(n)):n=[];for(var o=0;o<r.length;o++){var s=r[o];if(0===s.refs){for(var l=0;l<s.parts.length;l++)s.parts[l]();delete c[s.id]}}}};var g=function(){var e=[];return function(t,r){return e[t]=r,e.filter(Boolean).join("\n")}}()},4:function(e,t){e.exports=function(e,t){for(var r=[],i={},n=0;n<t.length;n++){var o=t[n],a=o[0],s=o[1],l=o[2],d=o[3],c={id:e+":"+n,css:s,media:l,sourceMap:d};i[a]?i[a].parts.push(c):r.push(i[a]={id:a,parts:[c]})}return r}},42:function(e,t,r){t=e.exports=r(2)(),t.push([e.id,'.yd-preview{background-color:#fff;position:relative;z-index:2}.yd-preview:before{top:-1px}.yd-preview:after,.yd-preview:before{content:"";position:absolute;z-index:0;left:0;width:100%;height:1px;background-image:-webkit-linear-gradient(bottom,#ececec 50%,transparent 0);background-image:linear-gradient(0deg,#ececec 50%,transparent 0)}.yd-preview:after{bottom:0}.yd-preview-header{height:1rem;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-pack:justify;-webkit-justify-content:space-between;-ms-flex-pack:justify;justify-content:space-between;-webkit-box-align:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center;margin-left:.24rem;padding-right:.24rem;position:relative;color:#999;font-size:.28rem;margin-bottom:.2rem}.yd-preview-header:after{height:1px;position:absolute;z-index:0;bottom:0;left:0;content:"";width:100%;background-image:-webkit-linear-gradient(bottom,#ececec 50%,transparent 0);background-image:linear-gradient(0deg,#ececec 50%,transparent 0)}.yd-preview-header>*{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1}.yd-preview-header>:first-child{margin-right:.2rem}.yd-preview-header>:last-child{text-align:right;color:#333;font-size:.32rem}.yd-preview-item{padding:0 .24rem;font-size:.27rem;color:#999;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;padding-bottom:.15rem}.yd-preview-item>*{display:block}.yd-preview-item>:first-child{min-width:1.1rem;text-align-last:justify;margin-right:.4rem;height:100%;text-align:right}.yd-preview-item>:last-child{word-break:normal;word-wrap:break-word;text-align:right;line-height:.45rem;-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1}.yd-preview-item:last-child{padding-bottom:.25rem}.yd-preview-footer{height:1rem;-ms-flex-align:center;font-size:.28rem;color:#999;margin-top:.1rem}.yd-preview-footer,.yd-preview-footer>*{position:relative;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.yd-preview-footer>*{-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1;height:inherit;-ms-flex-align:center;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center}.yd-preview-footer>:not(:first-child):after{content:"";position:absolute;z-index:0;top:0;left:0;width:1px;height:100%;background-image:-webkit-linear-gradient(right,#ececec 50%,transparent 0);background-image:linear-gradient(270deg,#ececec 50%,transparent 0)}.yd-preview-footer:before{content:"";position:absolute;z-index:0;top:-1px;left:0;width:100%;height:1px;background-image:-webkit-linear-gradient(bottom,#ececec 50%,transparent 0);background-image:linear-gradient(0deg,#ececec 50%,transparent 0)}',""])},113:function(e,t,r){var i=r(1)(r(293),r(173),null,null);e.exports=i.exports},114:function(e,t,r){var i=r(1)(r(294),r(180),null,null);e.exports=i.exports},115:function(e,t,r){r(220);var i=r(1)(r(295),r(151),null,null);e.exports=i.exports},151:function(e,t){e.exports={render:function(){var e=this,t=e.$createElement,r=e._self._c||t;return r("div",{staticClass:"yd-preview"},[e._t("default"),e._v(" "),e.buttons.length>0?r("div",{staticClass:"yd-preview-footer"},[e._l(e.buttons,function(t){return["object"==typeof t.link?[r("router-link",{style:{color:t.color},attrs:{to:t.link},nativeOn:{click:function(r){e.clickHander(t.click)}}},[e._v(e._s(t.text))])]:[r("a",{style:{color:t.color},attrs:{href:t.link?t.link:"javascript:;"},on:{click:function(r){e.clickHander(t.click)}}},[e._v(e._s(t.text))])]]})],2):e._e()],2)},staticRenderFns:[]}},173:function(e,t){e.exports={render:function(){var e=this,t=e.$createElement,r=e._self._c||t;return r("div",{staticClass:"yd-preview-header"},[e._t("left"),e._v(" "),e._t("right")],2)},staticRenderFns:[]}},180:function(e,t){e.exports={render:function(){var e=this,t=e.$createElement,r=e._self._c||t;return r("div",{staticClass:"yd-preview-item"},[e._t("left"),e._v(" "),e._t("right")],2)},staticRenderFns:[]}},220:function(e,t,r){var i=r(42);"string"==typeof i&&(i=[[e.id,i,""]]),i.locals&&(e.exports=i.locals);r(3)("3fc97482",i,!0)},293:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={name:"yd-preview-header"}},294:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={name:"yd-preview-item"}},295:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={name:"yd-preview",props:{buttons:[Array]},methods:{clickHander:function(e){"function"==typeof e&&e()}}}}})});
|
import difference from "./../src/difference.js";
import chai from "./../node_modules/chai/chai.js";
import { assert } from "chai";
describe('Difference function', function(){
it('difference([2,1],[2,3]) should be equal to 1',function(){
assert.equal(difference([2,1]))
})
})
|
// COPYRIGHT © 2021 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/3.37/esri/copyright.txt for details.
define(["esri/dijit/geoenrichment/utils/MaskUtil"],(function(e){var n={encodeXML:function(n){return e.maskWithUnicodeXML(String(n).replace(/ /g," "))}};return n}));
|
import { ToastAndroid } from 'react-native';
import {
LOADING_NOVEL,
GET_NOVEL,
GET_CHAPTERS,
FETCHING_NOVEL,
SET_NOVEL,
UPDATE_IN_LIBRARY,
CHAPTER_READ,
CHAPTER_DOWNLOADED,
CHAPTER_DELETED,
UPDATE_NOVEL,
SET_NOVEL_SETTINGS,
BOOKMARK_CHAPTER,
MARK_PREVIOUS_CHAPTERS_READ,
MARK_PREVIOUS_CHAPTERS_UNREAD,
} from './novel.types';
import { fetchNovel } from '../../services/Source/source';
import {
followNovel,
insertNovel,
getNovel,
} from '../../database/queries/NovelQueries';
import {
getChapters,
insertChapters,
markChapterRead,
downloadChapter,
deleteChapter,
markChapterUnread,
bookmarkChapter,
markPreviuschaptersRead,
markPreviousChaptersUnread,
getNextChapter,
} from '../../database/queries/ChapterQueries';
import { deleteUpdateFromDb } from '../../database/queries/UpdateQueries';
import {
SAVE_SCROLL_POSITION,
SET_CHAPTER_LIST_PREF,
SET_LAST_READ,
} from '../preferences/preference.types';
import { GET_LIBRARY_NOVELS } from '../library/library.types';
import { getLibrary } from '../../database/queries/LibraryQueries';
import { showToast } from '../../hooks/showToast';
import * as Notifications from 'expo-notifications';
Notifications.setNotificationHandler({
handleNotification: async () => {
return {
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: true,
};
},
});
import BackgroundService from 'react-native-background-actions';
import { SET_DOWNLOAD_QUEUE } from '../downloads/donwloads.types';
import { updateNovel } from '../../services/updates/LibraryUpdateQueries';
export const setNovel = novel => async dispatch => {
dispatch({ type: SET_NOVEL, payload: novel });
};
export const getNovelAction =
(followed, sourceId, novelUrl, novelId, sort, filter) => async dispatch => {
try {
dispatch({ type: LOADING_NOVEL });
if (followed === 1) {
/**
* If novel is followed directly get the chapters from db.
*/
const chapters = await getChapters(novelId, sort, filter);
dispatch({
type: GET_CHAPTERS,
payload: chapters,
});
} else {
dispatch({ type: FETCHING_NOVEL });
/**
* Check if novel is cached.
*/
let novel = await getNovel(sourceId, novelUrl);
if (novel) {
/**
* Get chapters from db.
*/
novel.chapters = await getChapters(novel.novelId, sort, filter);
dispatch({
type: GET_NOVEL,
payload: novel,
});
} else {
/**
* Fetch novel from source.
*/
const fetchedNovel = await fetchNovel(sourceId, novelUrl);
/**
* Insert novel in db.
*/
const fetchedNovelId = await insertNovel(fetchedNovel);
await insertChapters(fetchedNovelId, fetchedNovel.chapters);
/**
* Get novel from db.
*/
novel = await getNovel(sourceId, novelUrl);
novel.chapters = await getChapters(novel.novelId, sort, filter);
dispatch({
type: GET_NOVEL,
payload: novel,
});
}
}
} catch (error) {
showToast(error.message);
// dispatch({ type: NOVEL_ERROR });
}
};
export const sortAndFilterChapters =
(novelId, sort, filter) => async dispatch => {
dispatch({ type: FETCHING_NOVEL });
const chapters = await getChapters(novelId, sort, filter);
dispatch({
type: GET_CHAPTERS,
payload: chapters,
});
dispatch({
type: SET_CHAPTER_LIST_PREF,
payload: { novelId, sort, filter },
});
};
export const showChapterTitlesAction = (novelId, value) => async dispatch => {
dispatch({
type: SET_NOVEL_SETTINGS,
payload: { novelId, value: value },
});
};
export const followNovelAction = novel => async dispatch => {
await followNovel(novel.followed, novel.novelId);
if (!novel.followNovel) {
deleteUpdateFromDb(novel.novelId);
}
dispatch({
type: UPDATE_IN_LIBRARY,
payload: { novelUrl: novel.novelUrl, followed: !novel.followed },
});
const res = await getLibrary();
dispatch({
type: GET_LIBRARY_NOVELS,
payload: res,
});
showToast(!novel.followed ? 'Added to library' : 'Removed from library');
};
export const bookmarkChapterAction = chapters => async dispatch => {
chapters.map(chapter => {
bookmarkChapter(chapter.bookmark, chapter.chapterId);
dispatch({
type: BOOKMARK_CHAPTER,
payload: {
bookmark: chapter.bookmark,
chapterId: chapter.chapterId,
},
});
});
};
export const markChapterReadAction = (chapterId, novelId) => async dispatch => {
await markChapterRead(chapterId);
dispatch({
type: CHAPTER_READ,
payload: { chapterId },
});
const nextChapter = await getNextChapter(novelId, chapterId);
dispatch({
type: SET_LAST_READ,
payload: { novelId, chapterId: nextChapter.chapterId },
});
/**
* Reset progress on marked read
*/
dispatch({
type: SAVE_SCROLL_POSITION,
payload: {
position: 0,
percentage: 0,
chapterId,
novelId,
},
});
};
export const markPreviousChaptersReadAction =
(chapterId, novelId) => async dispatch => {
await markPreviuschaptersRead(chapterId, novelId);
dispatch({
type: MARK_PREVIOUS_CHAPTERS_READ,
payload: chapterId,
});
showToast('Marked previous chapters read');
};
export const markChaptersRead =
(chapters, novelId, sort, filter) => async dispatch => {
try {
chapters.map(chapter => markChapterRead(chapter.chapterId));
const chaps = await getChapters(novelId, sort, filter);
dispatch({
type: GET_CHAPTERS,
payload: chaps,
});
} catch (error) {
showToast(error.message);
}
};
export const markPreviousChaptersUnreadAction =
(chapterId, novelId) => async dispatch => {
await markPreviousChaptersUnread(chapterId, novelId);
dispatch({
type: MARK_PREVIOUS_CHAPTERS_UNREAD,
payload: chapterId,
});
};
export const markChapterUnreadAction =
(chapters, novelId) => async (dispatch, getState) => {
const { sort = 'ORDER BY chapterId ASC', filter = '' } =
getState().preferenceReducer.novelSettings[novelId];
chapters.map(chapter => markChapterUnread(chapter.chapterId));
const chaps = await getChapters(novelId, sort, filter);
dispatch({
type: GET_CHAPTERS,
payload: chaps,
});
};
export const downloadChapterAction =
(sourceId, novelUrl, chapterUrl, chapterName, chapterId) =>
async dispatch => {
// dispatch({
// type: CHAPTER_DOWNLOADING,
// payload: chapterId,
// });
dispatch({
type: SET_DOWNLOAD_QUEUE,
payload: [{ chapterId, chapterName }],
});
await downloadChapter(sourceId, novelUrl, chapterUrl, chapterId);
dispatch({
type: CHAPTER_DOWNLOADED,
payload: chapterId,
});
ToastAndroid.show(`Downloaded ${chapterName}`, ToastAndroid.SHORT);
};
export const downloadAllChaptersAction =
(sourceId, novelUrl, chaps) => async (dispatch, getState) => {
try {
const downloadQueue = getState().downloadsReducer.downloadQueue;
/**
* Filter downloaded chapters
*/
let chapters = chaps.filter(chapter => chapter.downloaded === 0);
/**
* Filter chapters already in download queue
*/
chapters = chapters.filter(
chapter =>
!downloadQueue.some(obj => obj.chapterId === chapter.chapterId),
);
chapters = chapters.map(chapter => ({
...chapter,
sourceId,
novelUrl,
}));
if (chapters.length > 0) {
dispatch({ type: SET_DOWNLOAD_QUEUE, payload: chapters });
const options = {
taskName: 'Library Update',
taskTitle: chapters[0].chapterName,
taskDesc: '0/' + chapters.length,
taskIcon: {
name: 'notification_icon',
type: 'drawable',
},
color: '#00adb5',
linkingURI: 'lnreader://downloads/redirect',
parameters: {
delay: 1000,
},
progressBar: {
max: chapters.length,
value: 0,
},
};
const sleep = time =>
new Promise(resolve => setTimeout(() => resolve(), time));
const veryIntensiveTask = async taskData => {
await new Promise(async resolve => {
for (
let i = 0;
BackgroundService.isRunning() && i < chapters.length;
i++
) {
if (BackgroundService.isRunning()) {
// dispatch({
// type: CHAPTER_DOWNLOADING,
// payload: chapters[i].chapterId,
// });
if (!chapters[i].downloaded) {
await downloadChapter(
sourceId,
novelUrl,
chapters[i].chapterUrl,
chapters[i].chapterId,
);
}
dispatch({
type: CHAPTER_DOWNLOADED,
payload: chapters[i].chapterId,
});
await BackgroundService.updateNotification({
taskTitle: chapters[i].chapterName,
taskDesc: i + 1 + '/' + chapters.length,
progressBar: {
max: chapters.length,
value: i + 1,
},
});
if (i + 1 === chapters.length) {
resolve();
Notifications.scheduleNotificationAsync({
content: {
title: 'Downloader',
body: 'Download completed',
},
trigger: null,
});
}
await sleep(taskData.delay);
}
}
});
};
await BackgroundService.start(veryIntensiveTask, options);
}
} catch (error) {
showToast(error.message);
}
};
export const deleteChapterAction =
(chapterId, chapterName) => async dispatch => {
await deleteChapter(chapterId);
dispatch({
type: CHAPTER_DELETED,
payload: chapterId,
});
showToast(`Deleted ${chapterName}`);
};
export const deleteAllChaptersAction = chapters => async dispatch => {
await chapters.map(chapter => {
deleteChapter(chapter.chapterId);
dispatch({
type: CHAPTER_DELETED,
payload: chapter.chapterId,
});
});
showToast('Chapters deleted');
};
export const updateNovelAction =
(sourceId, novelUrl, novelId, sort, filter) => async (dispatch, getState) => {
dispatch({ type: FETCHING_NOVEL });
const { downloadNewChapters = false, refreshNovelMetadata = false } =
getState().settingsReducer;
const options = {
downloadNewChapters,
refreshNovelMetadata,
};
await updateNovel(sourceId, novelUrl, novelId, options);
let novel = await getNovel(sourceId, novelUrl);
let chapters = await getChapters(novel.novelId, sort, filter);
dispatch({
type: UPDATE_NOVEL,
payload: { novel, chapters },
});
};
|
search_result['443']=["topic_000000000000012F.html","Import.GetClipBox Method",""];
|
const getters = {
isMobile: state => state.app.isMobile,
lang: state => state.app.lang,
theme: state => state.app.theme,
color: state => state.app.color,
token: state => state.user.token,
avatar: state => state.user.avatar,
nickname: state => state.user.name,
welcome: state => state.user.welcome,
roles: state => state.user.roles,
userInfo: state => state.user.info,
routers: state => state.permission.routers,
addRouters: state => state.permission.addRouters,
multiTab: state => state.app.multiTab,
visitedViews: state => state.tagsView.visitedViews,
cachedViews: state => state.tagsView.cachedViews
}
export default getters
|
class FilterCell{
constructor(value, x, y, filler){
this.text = value;
this.filler = filler;
this.col = color(255);
this.x = x;
this.y = y;
this.checked = false;
}
selected(){
this.checked = !this.checked;
}
show(opac){
if(this.checked){
this.col = color(12, 171, 235, opac);
}else{
this.col = color(255, opac);
}
push();
fill(this.col);
textSize(fontsize2);
text(this.text, this.x, this.y);
pop();
}
isOver(){
var w = textWidth(this.text);
var h = textAscent();
var x1 = this.x + w / 2;
var y1 = this.y + h / 2;
var x2 = this.x - w / 2;
var y2 = this.y - h / 2;
return (mouseX > x2 && mouseX < x1 && mouseY > y2 && mouseY < y1);
}
}
|
import React from 'react'
import PT from 'prop-types'
import { flatten } from 'flat'
import { removeValuesOfHiddenNodes, getWizardProgress } from '../../../helpers/wizardHelper'
import { getProductEstimate } from '../../../config/projectWizard'
import './HeaderWithProgress.scss'
const numberWithCommas = (n) => n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
function HeaderWithProgress({project, template, currentWizardStep}) {
const flatProject = flatten(removeValuesOfHiddenNodes(template, project), { safe: true })
const { priceEstimate } = getProductEstimate({scope: template}, flatProject)
const progress = currentWizardStep ? getWizardProgress(template, currentWizardStep) : 0
const currentStep = template.sections[(currentWizardStep || {}).sectionIndex || 0]
return (
<div styleName="HeaderWithProgress">
<div styleName="content">
<div styleName="title-estimate">
<h3>{currentStep.title}</h3>
<div>From ${numberWithCommas(priceEstimate)}</div>
</div>
<div styleName="progress-bar">
<div styleName="progress" style={{width: (progress*100)+'%'}} />
</div>
</div>
</div>
)
}
HeaderWithProgress.propTypes = {
project: PT.object.isRequired,
template: PT.object.isRequired,
currentWizardStep: PT.object,
}
export default HeaderWithProgress
|
const creteBookingDao = require('../dao/create-booking-dao');
const sendEmailBL = require('../bl/send-email-bl');
const PropertyRequiedError = require('../errors/property-required-error');
const createBooking = async (req, res, next) => {
try {
const { checkin, checkout, email, name, id_room } = req.body;
if (!checkin) {
throw new PropertyRequiedError('El parámetro checkin es requerido');
}
if (!checkout) {
throw new PropertyRequiedError('El parámetro checkout es requerido');
}
if (!email) {
throw new PropertyRequiedError('El parámetro email es requerido');
}
if (!name) {
throw new PropertyRequiedError('El parámetro name es requerido');
}
if (!id_room) {
throw new PropertyRequiedError('El parámetro id_room es requerido');
}
const bookingData = await creteBookingDao(req.body);
await sendEmailBL(bookingData);
res.send(bookingData);
} catch (error) {
next(error, req, res, next);
}
};
module.exports = createBooking;
|
/* jshint strict: false, unused: false */
var router = require('express').Router();
var tokenCheck = require('../auth/tokencheck.js');
var DbController = require('./databasecontroller.js');
// require token for all database operations
router.use(tokenCheck);
// foreign keys
router.route('/:database/fk/:refTable/:refColumn')
.get(DbController.getForeignValues);
// create and drop table
router.route('/:database/:table')
.delete(DbController.dropTable)
.post(DbController.createTable);
// database table
router.route('/:database/tables')
.get(DbController.getTables);
// subset of table
router.route('/:database/:table/:page')
.get(DbController.getRecords)
.put(DbController.updateRecord)
.post(DbController.addRecord);
// database performance
router.route('/performance')
.get(DbController.getPerformanceStats);
// database info
router.route('/info')
.get(DbController.getInfoStats);
// run query
router.route('/query')
.post(DbController.queryClientDB);
// *** return mysql databases
router.route('/db')
.get(DbController.getDatabases);
router.route('/connect')
.get(DbController.connect);
// create datase
router.route('/create')
.post(DbController.createDatabase);
// drop database
router.route('/delete')
.post(DbController.deleteDatabase)
module.exports = router;
|
import "../styles/main.scss";
import "babel-polyfill";
const modal = document.getElementById("myModal");
function promiseOfModal() {
return new Promise(function (resolve) {
window.setTimeout(function () {
resolve(modal)
}, (1000 * 60));
});
}
const runModal = async () => {
await promiseOfModal();
modal.style.display = "block";
console.log("You've been on the site for 60 seconds! Cool!");
};
runModal();
modal.addEventListener("click", (e) => {
switch (e.target.className) {
case "close":
case "modal":
modal.style.display = "none";
break;
}
})
//// continue button animation with alert to subscribe
const continueBtn = document.getElementById("continue");
function runAnimation() {
return new Promise((resolve) => {
continueBtn.addEventListener("animationend", () => {
continueBtn.classList.add("btn-info");
resolve(continueBtn);
});
});
}
async function runAlert() {
await runAnimation();
alert("Continue to subscribe!");
}
runAlert();
|
JSON.__proto__[1] = Uint8ClampedArray().buffer
f = (function() {
function g(c) {
Object.freeze(c).__proto__ = c
}
for each(b in []) {
try {
g(b)
} catch (e) {}
}
})
f()
f()
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View
} from 'react-native';
class dvdpila_remote extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('dvdpila_remote', () => dvdpila_remote);
|
import data from './data.json';
export default {
title: 'Components/Icons/SAP Icons',
parameters: {
description: `Icons are used to provide visual clarity, save screen space, and help guide users as they navigate an application. They are often used as visual elements within other components, although they can be used independently, given that they can be read by screen readers or have a tooltip for accessibility purposes. See [Project Confirguration](https://sap.github.io/fundamental-styles/?path=/docs/introduction-overview--page) for instructions on how to use the SAP icon font on your page.
##Usage
**Use the icon if:**
- You want to display an icon for illustrative purposes only, without interaction states, acting as a non-interactive icon/pictogram.
- You intend to pair the icon with another method of communication i.e. with text or a tooltip.
Note: If an icon needs to be selected or have any interaction states, it is recommended to use the transparent button style. See **Button** for more details on how to implement it.
`,
tags: ['development'],
components: ['button', 'button-split', 'icon', 'menu', 'popover', 'segmented-button']
}
};
export const sizes = () => `
<span class="sap-icon sap-icon--cart"></span>
<br />
<span class="sap-icon sap-icon--cart" style="font-size:5rem"></span>
<br />
<span class="sap-icon sap-icon--cart" style="font-size:10rem"></span>
`;
sizes.parameters = {
docs: {
iframeHeight: 250,
storyDescription: 'Icons don’t have predefined sizes because they align with the font size value. They are vector graphics, meaning they can be easily resized without compromising their appearance. And because icons are essentially a font, there are unlimited sizes.'
}
};
/**
* There are different semantic statuses that can be applied to the icon by adding a modifier class.
*
* | **Status** | **Modifier class** |
* | --------------: | :------------------------------- |
* | Default | `sap-icon--color-default` |
* | Contrast | `sap-icon--color-contrast` |
* | Non-interactive | `sap-icon--color-non-interactive`|
* | Tile | `sap-icon--color-tile` |
* | Marker | `sap-icon--color-marker` |
* | Critical | `sap-icon--color-critical` |
* | Negative | `sap-icon--color-negative` |
* | Neutral | `sap-icon--color-neutral` |
* | Positive | `sap-icon--color-positive` |
*/
export const colors = () => `
<span class="sap-icon sap-icon--cart" style="font-size:5rem" tabindex="0"></span>
<span class="sap-icon sap-icon--cart sap-icon--color-default" style="font-size:5rem"></span>
<span class="sap-icon sap-icon--cart sap-icon--color-contrast sap-icon--background-contrast" style="font-size:5rem"></span>
<span class="sap-icon sap-icon--cart sap-icon--color-non-interactive" style="font-size:5rem"></span>
<span class="sap-icon sap-icon--cart sap-icon--color-tile" style="font-size:5rem"></span>
<span class="sap-icon sap-icon--cart sap-icon--color-marker" style="font-size:5rem"></span>
<span class="sap-icon sap-icon--cart sap-icon--color-critical" style="font-size:5rem"></span>
<span class="sap-icon sap-icon--cart sap-icon--color-negative" style="font-size:5rem"></span>
<span class="sap-icon sap-icon--cart sap-icon--color-neutral" style="font-size:5rem"></span>
<span class="sap-icon sap-icon--cart sap-icon--color-positive" style="font-size:5rem"></span>
`;
export const availableIcons = () => {
const div = document.createElement('div');
div.className = 'fddocs-container';
div.innerHTML = data.icons.map((icon) => {
return (
'<div class="fddocs-container--icon">' +
`<span class="sap-icon sap-icon--${icon}" style="font-size:3rem"></span>` +
`<div>.sap-icon--${icon}</div>` +
'</div><br />'
);
}).join('');
return div.outerHTML;
};
availableIcons.parameters = {
docs: {
iframeHeight: 200,
storyDescription: 'There are several icons available. To display any one of these icons, add the `sap-icon--{icon-name}` modifier class identifying the icon style to the `sap-icon` class. For example, for a search icon, add `sap-icon sap-icon--search` with the desired font size value.'
},
skipRTLSnapshot: true
};
|
angular.module('job')
.factory('ThingService', ['$resource', 'cmsConfig', function ($resource, cmsConfig) {
/*eslint-disable */
// serverUrl
var ThingResource = $resource(cmsConfig.serverApi + '/thing/edit/:id', {}, {
edit: {method: 'POST', url: cmsConfig.serverApi + '/thing/edit/:id', headers: {'Content-Type': undefined}},
editList: {method: 'POST', url: cmsConfig.serverApi + '/thing/:id/list'},
editIsMainPage: {method: 'POST', url: cmsConfig.serverApi + '/thing/main'},
new: {method: 'POST', url: cmsConfig.serverApi + '/thing/new', headers: {'Content-Type': undefined}},
remove: {method: 'POST', url: cmsConfig.serverApi + '/thing/remove/:id', headers: {'Content-Type': undefined}},
removeIcon: {method: 'GET', url: cmsConfig.serverApi + '/thing/remove/icon/:id'}
});
/*eslint-enable */
function ThingService() {
}
ThingService.prototype.remove = function (thing, cb) {
var formData = new FormData();
if (thing.icon) {
formData.append('icon', thing.icon);
}
ThingResource.remove({id: thing._id}, formData, cb);
};
ThingService.prototype.removeIcon = function (id, cb) {
ThingResource.removeIcon({id: id}, cb);
};
ThingService.prototype.editList = function (options, cb) {
return ThingResource.editList({id: options._id}, {list: options.list}, function (res) {
return cb(res.error, res.data);
});
};
ThingService.prototype.editIsMainPage = function (options, cb) {
return ThingResource.editIsMainPage({}, {id: options._id, isPublic: options.isPublic}, function (res) {
return cb(res.error, res.data);
});
};
ThingService.prototype.validationForName = function (options, cb) {
if (options.name) {
var findThing = _.find(options.things, function (thing) {
return thing.thingName.toLowerCase() === options.name.toLowerCase();
});
if (!findThing) {
cb(true);
} else {
cb(false);
}
} else {
cb(false);
}
};
ThingService.prototype.save = function (options, cb) {
var formData = this.wrapDataToRequest(options);
if (options.editThing) {
ThingResource.edit({id: options.editThing._id}, formData, cb);
} else {
ThingResource.new(formData, cb);
}
};
ThingService.prototype.wrapDataToRequest = function (data) {
var formData = new FormData();
formData.append('thingName', data.name);
formData.append('plural', data.plural);
formData.append('rating', data.rating || 0);
formData.append('list', data.list);
if (data.icon) {
formData.append('icon', data.icon);
}
if (data.description) {
formData.append('thingDescription', data.description);
}
if (data.synonymous && data.synonymous.length) {
formData.append('synonymous', JSON.stringify(data.synonymous));
}
if (data.category && data.category.length) {
formData.append('thingCategory', JSON.stringify(data.category));
}
if (data.relatedThings && data.relatedThings.length) {
formData.append('relatedThings', JSON.stringify(data.relatedThings));
}
if (data.tags && data.tags.length) {
formData.append('tags', JSON.stringify(data.tags));
}
return formData;
};
return new ThingService();
}]);
|
/**
* Created by s.cosma on 29/07/2016.
*/
var webdriverio = require('webdriverio');
var webdrivercss = require('webdrivercss');
var browsers = ['internet explorer', 'chrome', 'firefox','MicrosoftEdge'];
browsers.forEach(function (element) {
var client = webdriverio.remote({
desiredCapabilities: {
browserName: element
}
});
webdrivercss.init(client, {
screenshotRoot: ['frontend-testing-comparative-',element].join(''),
api: 'http://localhost:8080/api/repositories/'
});
client
.init()
.url('http://localhost:3000')
.webdrivercss('login form', [{
name: 'title',
elem: 'h1'
}])
.sync()
.end();
});
|
import Phaser from 'phaser';
class Menu extends Phaser.State {
init() {
// set game config variable data from game cache
this.Config = this.game.cache.getJSON('config');
}
create() {
let startInstructions = 'Click to Start Game :\n\nUP arrow key for thrust.\n\nLEFT and RIGHT arrow keys to turn.\n\nSPACE key to fire.';
this.tf_start = this.game.add.text(this.game.world.centerX, this.game.world.centerY, startInstructions, this.Config.fontAssets.menuFontStyle);
this.tf_start.align = 'center';
this.tf_start.anchor.set(0.5);
this.game.input.onDown.addOnce(this.startGame, this);
}
startGame() {
this.game.state.start('Play');
}
}
export default Menu;
|
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
let engine;
let world;
var ball;
var ground;
var wall,rock;
function setup() {
createCanvas(400,400);
engine = Engine.create();
world = engine.world;
var ball_options = {
restitution: 0.95,
frictionAir:0.01
}
var rock_options={
restitution:0.85
}
var ground_options ={
isStatic: true
};
ground = Bodies.rectangle(200,390,400,20,ground_options);
World.add(world,ground);
ball = Bodies.circle(100,10,20,ball_options);
World.add(world,ball);
wall = Bodies.rectangle(300,200,200,20,ground_options);
World.add(world,wall);
rock = Bodies.circle(250,10,20,rock_options);
World.add(world,rock);
rectMode(CENTER);
ellipseMode(RADIUS);
}
function draw()
{
background(51);
Engine.update(engine);
ellipse(ball.position.x,ball.position.y,20);
rect(ground.position.x,ground.position.y,400,20);
ellipse(rock.position.x,rock.position.y,20);
rect(wall.position.x,wall.position.y,200,20);
}
|
import privateProps from '../privateProps.js'
import { warnAboutDepreation } from '../utils/utils.js';
function setButtonsDisabled (instance, buttons, disabled) {
const domCache = privateProps.domCache.get(instance)
buttons.forEach(button => {
domCache[button].disabled = disabled
})
}
function setInputDisabled (input, disabled) {
if (!input) {
return false
}
if (input.type === 'radio') {
const radiosContainer = input.parentNode.parentNode
const radios = radiosContainer.querySelectorAll('input')
for (let i = 0; i < radios.length; i++) {
radios[i].disabled = disabled
}
} else {
input.disabled = disabled
}
}
export function enableButtons () {
setButtonsDisabled(this, ['confirmButton', 'cancelButton'], false)
}
export function disableButtons () {
setButtonsDisabled(this, ['confirmButton', 'cancelButton'], true)
}
// @deprecated
export function enableConfirmButton () {
warnAboutDepreation('Swal.disableConfirmButton()', `Swal.getConfirmButton().removeAttribute('disabled')`)
setButtonsDisabled(this, ['confirmButton'], false)
}
// @deprecated
export function disableConfirmButton () {
warnAboutDepreation('Swal.enableConfirmButton()', `Swal.getConfirmButton().setAttribute('disabled', '')`)
setButtonsDisabled(this, ['confirmButton'], true)
}
export function enableInput () {
return setInputDisabled(this.getInput(), false)
}
export function disableInput () {
return setInputDisabled(this.getInput(), true)
}
|
import { deleteRiwayatSK } from "./deleteRiwayatSK";
import { editRiwayatSK } from "./editRiwayatSK";
import { getRiwayatSK } from "./getRiwayatSK";
import { getRiwayatSKById } from "./getRiwayatSKById";
import { insertRiwayatSK } from "./insertRiwayatSK";
export {
deleteRiwayatSK,
editRiwayatSK,
getRiwayatSK,
insertRiwayatSK,
getRiwayatSKById,
};
|
/**
* @fileoverview Enforce no naming of AMD modules
* @author Adam Davies
*/
'use strict';
// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------
const RuleTester = require('eslint').RuleTester;
const rule = require('../../lib/rules/no-amd-name');
const parserOptions = {
ecmaVersion: 2015,
sourceType: 'module'
};
// ------------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------------
const ruleTester = new RuleTester({ parserOptions });
ruleTester.run('no-amd-name', rule, {
valid: [
{
code: 'define([], function() {});'
},
{
code: 'define(["N/search"], function(search) {});'
},
{
code: 'define("moduleName");'
},
{
code: 'define("moduleName", ["N/search"]);'
}
],
invalid: [
{
code: 'define("moduleName", [], function() {});',
errors: [{ messageId: 'noModuleName' }],
output: 'define([], function() {});'
},
{
code: 'define("moduleName", ["N/search"], function(search) {});',
errors: [{ messageId: 'noModuleName' }],
output: 'define(["N/search"], function(search) {});'
}
]
});
|
/**
* @typedef {object} Phaser.GameObjects.RenderTexture.Types.RenderTextureConfig
* @since 3.2.0
*
* @property {number} [x=0] - The x coordinate of the RenderTextures position.
* @property {number} [y=0] - The y coordinate of the RenderTextures position.
* @property {number} [width=32] - The width of the RenderTexture.
* @property {number} [height=32] - The height of the RenderTexture.
* @property {string} [key] - The texture key to make the RenderTexture from.
* @property {string} [frame] - the frame to make the RenderTexture from.
*/
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M20 4h-3.17L15 2H9L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM9.88 4h4.24l1.83 2H20v12H4V6h4.05" /><path d="M15 11H9V8.5L5.5 12 9 15.5V13h6v2.5l3.5-3.5L15 8.5z" /></React.Fragment>
, 'SwitchCameraOutlined');
|
import { __spreadArrays } from "tslib";
import { merge as mergeStatic } from '../observable/merge';
export function merge() {
var observables = [];
for (var _i = 0; _i < arguments.length; _i++) {
observables[_i] = arguments[_i];
}
return function (source) { return source.lift.call(mergeStatic.apply(void 0, __spreadArrays([source], observables)), undefined); };
}
export function mergeWith() {
var otherSources = [];
for (var _i = 0; _i < arguments.length; _i++) {
otherSources[_i] = arguments[_i];
}
return merge.apply(void 0, otherSources);
}
//# sourceMappingURL=mergeWith.js.map
|
/*************************************************************
*
* MathJax/localization/ko/HTML-CSS.js
*
* Copyright (c) 2009-2019 The MathJax Consortium
*
* 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.
*
*/
MathJax.Localization.addTranslation("ko","HTML-CSS",{
version: "2.7.6",
isLoaded: true,
strings: {
LoadWebFont: "%1 \uC6F9\uD3F0\uD2B8\uB97C \uBD88\uB7EC\uC624\uACE0 \uC788\uC2B5\uB2C8\uB2E4...",
CantLoadWebFont: "%1 \uC6F9\uD3F0\uD2B8\uB97C \uBD88\uB7EC\uC62C \uC218 \uC5C6\uC2B5\uB2C8\uB2E4",
FirefoxCantLoadWebFont: "\uD30C\uC774\uC5B4\uD3ED\uC2A4\uB294 \uC6D0\uACA9 \uD638\uC2A4\uD2B8\uB85C\uBD80\uD130 \uC6F9 \uD3F0\uD2B8\uB97C \uBD88\uB7EC\uC62C \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.",
CantFindFontUsing: "%1\uB97C \uC0AC\uC6A9\uD55C \uC720\uD6A8\uD55C \uD3F0\uD2B8\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.",
WebFontsNotAvailable: "\uC6F9 \uD3F0\uD2B8 \uC0AC\uC6A9\uC774 \uBD88\uAC00\uD569\uB2C8\uB2E4. \uC774\uBBF8\uC9C0 \uD3F0\uD2B8\uB97C \uB300\uC2E0 \uC0AC\uC6A9\uD569\uB2C8\uB2E4."
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/ko/HTML-CSS.js");
|
import isEmpty from 'lodash/isEmpty';
import initialState from './initialState';
import types from '../actions/actionTypes';
export default (state = initialState, action = {}) => {
switch (action.type) {
case types.SET_CURRENT_USER:
return {
isAuthenticated: !isEmpty(action.user),
user: action.user
};
default: return state;
}
};
|
import Vue from 'vue';
import App from '@front/views/App'; // Корневой компонент
import store from '@front/store/index.js'; // store нужен для хранения состояния приложения
import router from '@front/router/index.js'; // конфгурация маршрутизатора
import axios from 'axios'; // необходимо для использования ajax запросов
import VueAxios from 'vue-axios';
import * as filters from '@front/filters';
Vue.use(VueAxios, axios);
Vue.config.productionTip = false;
Object.keys(filters).forEach(key => {
Vue.filter(key, filters[key]);
});
Vue.prototype.$filters = Vue.options.filters;
// инициализация Vue
new Vue({
el: '#app', // элемент в DOM для инициализации
router,
store,
render: h => h(App), // компонент, используемый в качестве корневого
});
|
jQuery(function(e){var t;"function"==typeof e.fn.owlCarousel&&(t={rtl:!!wenTravelOptions.rtl,autoHeight:!0,margin:40,items:5,nav:!1,dots:!1,autoplay:!0,autoplayTimeout:4e3,loop:!0,responsive:{0:{items:1},640:{items:2},1024:{items:4},1120:{items:5}},navText:[wenTravelOptions.iconNavPrev,wenTravelOptions.iconNavNext]},e(".wen-travel-logo-slider-content-wrapper").owlCarousel(t))});
|
/* JS #7 */
if (!this.BOOTGETJSTEST) {
this.BOOTGETJSTEST = { scriptCounter: 0 };
}
this.BOOTGETJSTEST.js7 = true;
this.BOOTGETJSTEST.currentScript = 7;
this.BOOTGETJSTEST.scriptCounter += 1;
if (this.console) {
this.console.log("Executed js7.js.");
}
|
import render from "./render";
// rudimentary state management
const state = [{}];
export const getState = () => {
return state[state.length - 1];
};
export const setState = (nextState) => {
const currentState = state[state.length - 1];
state.push({
...currentState,
...nextState,
})
render(getState().targetId, getState().Layout);
};
|
////@ts-check
//I HAVE TO REVIEW THE Inheritance and the prototype chain
const typedef = require('./typedef')
const WOQLQuery = require('./query/woqlBuilder')
/**
* @license Apache Version 2
* @module WOQL
* @constructor WOQL
* @description The WOQL object is a wrapper around the WOQLQuery object
* Syntactic sugar to allow writing WOQL.triple()... instead of new WOQLQuery().triple()
* Every function matches one of the public api functions of the woql query object
*/
let WOQL = {}
/**
* WOQL primitives are WOQL.js functions which directly map onto words in
* the underlying JSON-LD language. All other WOQL.js functions are compound functions
* which translate into multiple WOQL primitives, or are helper functions which reduce
* the need to write verbose JSON-LD directly.
*/
/**
* WOQL Literals, Prefixes & IRI Constant
*/
/*
* We expose all the real woql predicates via the WOQL object,
* for ease of typing all return a WOQL query object
*/
/**
* Query running against any specific commit Id
* @param {string} refPath - path to specific reference Id or commit Id
* @param {WOQLQuery} subquery - subquery for the specific commit point
* @returns {WOQLQuery}
* @example
* WOQL.using("userName/dbName/local/commit|branch/commitID").triple("v:A", "v:B", "v:C")
*/
WOQL.using = function(refPath, subquery) {
return new WOQLQuery().using(refPath, subquery)
}
/**
* Adds a text comment to a query - can also be used to wrap any part of a query to turn it off
* @param {string} comment - text comment
* @param {WOQLQuery} subquery - query that is "commented out"
* @returns {WOQLQuery}
*/
WOQL.comment = function(comment, subquery) {
return new WOQLQuery().comment(comment, subquery)
}
/**
* @example WOQL.select("v:a",triple("v:a","v:b","v:c"))
* Filters the query so that only the variables included in [V1...Vn] are returned in the bindings
* @param {...string} varNames - only these variables are returned
* @returns {WOQLQuery}
*/
WOQL.select = function(...varNames) {
return new WOQLQuery().select(...varNames)
}
/**
* Filter the query to return only results that are distinct in the given variables
* @param {...string} varNames - these variables are guaranteed to be unique as a tuple
* @returns {WOQLQuery}
*/
WOQL.distinct = function(...varNames) {
return new WOQLQuery().distinct(...varNames)
}
/**
* Logical conjunction of the contained queries - all queries must match or the entire clause fails
* @param {...WOQLQuery} subqueries - A list of one or more woql queries to execute as a conjunction
* @returns {WOQLQuery} - A WOQLQuery object containing the conjunction of queries
* @example
* //find triples that are of type scm:Journey, and have
* //a start_station v:Start, and that start_station is labeled
* //v:Start_Label
*
* WOQL.and(
* WOQL.triple("v:Journey", "type", "scm:Journey"),
* WOQL.triple("v:Journey", "start_station", "v:Start"),
* WOQL.triple("v:Start", "label", "v:Start_Label"))
*
*/
WOQL.and = function(...subqueries) {
return new WOQLQuery().and(...subqueries)
}
/**
* Read a node identified by an IRI as a JSON-LD document
* @param {string} IRI - The document id or a variable
* @param {string} output - variable name
* @param {object} formatObj
* @return {object} WOQLQuery
*/
WOQL.read_object = function(IRI, output, formatObj) {
return new WOQLQuery().read_object(IRI, output, formatObj)
}
/**
* Creates a logical OR of the arguments
* @param {...WOQLQuery} subqueries - A list of one or more woql queries to execute as alternatives
* @returns {WOQLQuery} - A WOQLQuery object containing the logical Or of the subqueries
* @example
* or(
* triple("v:Subject", 'label', "A"),
* triple("v:Subject", "label", "a")
* )
*/
WOQL.or = function(...subqueries) {
return new WOQLQuery().or(...subqueries)
}
/**
* Specifies the database URL that will be the default database for the enclosed query
* @param {typedef.GraphRef} graphRef- A valid graph resource identifier string
* @param {WOQLQuery} [query] - The query
* @returns {WOQLQuery} A WOQLQuery object containing the from expression
*/
WOQL.from = function(graphRef, query) {
return new WOQLQuery().from(graphRef, query)
}
/**
* Specifies the graph resource to write the contained query into
* @param {typedef.GraphRef} graphRef- A valid graph resource identifier string
* @param {WOQLQuery} subquery - The query which will be written into the graph
* @returns {WOQLQuery} A WOQLQuery which will be written into the graph in question
* @example
* //Subq is an argument or a chained query
* using("admin/minecraft").into("instance/main").add_triple("a", "type", "scm:X")
* //writes a single tripe (doc:a, rdf:type, scm:X) into the main instance graph
*
*/
WOQL.into = function(graphRef, subquery) {
return new WOQLQuery().into(graphRef, subquery)
}
/**
* Creates a triple pattern matching rule for the triple [S, P, O] (Subject, Predicate, Object)
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string} object - The IRI of a node or a variable, or a literal
* @returns {WOQLQuery}
*/
WOQL.triple = function(subject, predicate, object) {
return new WOQLQuery().triple(subject, predicate, object)
}
/**
* Creates a triple pattern matching rule for the triple [S, P, O] (Subject, Predicate, Object) added in the current layer
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string} object - The IRI of a node or a variable, or a literal
* @returns {WOQLQuery}
*/
WOQL.added_triple = function(subject, predicate, object) {
return new WOQLQuery().added_triple(subject, predicate, object)
}
/**
* Creates a triple pattern matching rule for the triple [S, P, O] (Subject, Predicate, Object) added in the current commit
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string} object - The IRI of a node or a variable, or a literal
* @returns {WOQLQuery}
*/
WOQL.removed_triple = function(subject, predicate, object) {
return new WOQLQuery().removed_triple(subject, predicate, object)
}
/**
* Creates a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph)
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string} object - The IRI of a node or a variable, or a literal
* @param {typedef.GraphRef} graphRef - A valid graph resource identifier string
* @returns {WOQLQuery}
*/
WOQL.quad = function(subject, predicate, object, graphRef) {
return new WOQLQuery().quad(subject, predicate, object, graphRef)
}
/**
* Creates a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph) removed from the current commit
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string} object - The IRI of a node or a variable, or a literal
* @param {typedef.GraphRef} graphRef- A valid graph resource identifier string
* @returns {WOQLQuery}
*/
WOQL.added_quad = function(subject, predicate, object, graphRef) {
return new WOQLQuery().added_quad(subject, predicate, object, graphRef)
}
/**
* Creates a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph) removed from the current commit
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string} object - The IRI of a node or a variable, or a literal
* @param {typedef.GraphRef} graphRef- A valid graph resource identifier string
* @returns {WOQLQuery}
*/
WOQL.removed_quad = function(subject, predicate, object, graphRef) {
return new WOQLQuery().removed_quad(subject, predicate, object, graphRef)
}
/**
* Returns true if ClassA subsumes ClassB, according to the current DB schema
* @param {string} classA - ClassA
* @param {string} classB - ClassB
* @returns {boolean} WOQLQuery
*/
WOQL.sub = function(classA, classB) {
return new WOQLQuery().sub(classA, classB)
}
WOQL.subsumption = WOQL.sub
/**
* Matches if a is equal to b
* @param {string} varName - literal, variable or id
* @param {string} varValue - literal, variable or id
* @returns {WOQLQuery}
*
*
*/
WOQL.eq = function(varName, varValue) {
return new WOQLQuery().eq(varName, varValue)
}
WOQL.equals = WOQL.eq
/**
* Substring
* @param {string} string - String or variable
* @param {number} before - integer or variable (characters from start to begin)
* @param {number} [length] - integer or variable (length of substring)
* @param {number} [after] - integer or variable (number of characters after substring)
* @param {string} [substring] - String or variable
* @returns {WOQLQuery}
*/
WOQL.substr = function(string, before, length, after, substring) {
return new WOQLQuery().substr(string, before, length, after, substring)
}
WOQL.substring = WOQL.substr
/**
* Retrieves the exernal resource defined by QueryResource and copies values from it into variables defined in AsVars
* @param {WOQLQuery} asvars - an array of AsVar variable mappings (see as for format below)
* @param {WOQLQuery} queryResource - an external resource (remote, file, post) to query
* @returns {WOQLQuery} A WOQLQuery which contains the get expression
* @example
* let [a, b] = vars("a", "b")
* get(as("a", a).as("b", b)).remote("http://my.url.com/x.csv")
* //copies the values from column headed "a" into a variable a and from column
* //"b" into a variable b from remote CSV
*/
WOQL.get = function(asvars, queryResource) {
return new WOQLQuery().get(asvars, queryResource)
}
/**
* @put Outputs the results of a query to a file
* @param {WOQLQuery} varsToExp - an array of AsVar variable mappings (see as for format below)
* @param {WOQLQuery} query - The query which will be executed to produce the results
* @param {string} fileResource - an file resource local to the server
* @returns {WOQLQuery} A WOQLQuery which contains the put expression
* @example
* let [s, p, o] = vars("Subject", "Predicate", "Object")
* WOQL.put(WOQL.as("s", s).as("p", p).as("o", o), WOQL.all())
* .file({file:"/app/local_files/dump.csv"})
*/
WOQL.put = function(varsToExp, query, fileResource) {
return new WOQLQuery().put(varsToExp, query, fileResource)
}
/**
* Imports the value identified by Source to a Target variable
* @param {string | number} source - Source
* @param {string} target - Target
* @param {string} [type] - type to cast value to string|number etc...
* @returns {WOQLQuery}
* @example
* WOQL.as("first var", "v:First_Var",{} "string").as("second var", "v:Second_Var")
* WOQL.as(["first var", "v:First_Var", "string"], ["second var", "v:Second_Var"])
*/
WOQL.as = function(source, target, type) {
return new WOQLQuery().as(source, target, type)
}
/**
* Identifies a remote resource by URL and specifies the format of the resource through the options
* @param {object} remoteObj - The URL at which the remote resource can be accessed
* @param {typedef.DataFormatObj} [formatObj] - The format of the resource data {}
* @returns {WOQLQuery} A WOQLQuery which contains the remote resource identifier
* @example
* remote({url:"http://url.of.resource"}, {type: "csv"})
*/
//
WOQL.remote = function(remoteObj, formatObj) {
return new WOQLQuery().remote(remoteObj, formatObj)
}
/**
* Identifies a file resource as a path on the server and specifies the format through the options
* @param {object} url - The Path on the server at which the file resource can be accessed
* @param {typedef.DataFormatObj} [formatObj] - imput options
* @returns {WOQLQuery} A WOQLQuery which contains the file resource identifier
* @example
* file("/path/to/file", {type: 'turtle'} )
*/
WOQL.file = function(url, formatObj) {
return new WOQLQuery().file(url, formatObj)
}
/**
* Identifies a resource as a local path on the client, to be sent to the server through a
* HTTP POST request, with the format defined through the options
* @param {string} url - The Path on the server at which the file resource can be accessed
* @param {typedef.DataFormatObj} [formatObj] - imput options, optional
* @returns {WOQLQuery} A WOQLQuery which contains the Post resource identifier
* @example
* post("/.../.../", {type:'csv'})
*/
WOQL.post = function(url, formatObj) {
return new WOQLQuery().post(url, formatObj)
}
/**
* Deletes a single triple from the default graph of the database
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string} object - The IRI of a node or a variable, or a literal
* @returns {WOQLQuery} - A WOQLQuery which contains the Triple Deletion statement
* @example
* delete_triple("john", "age", 42)
*/
WOQL.delete_triple = function(subject, predicate, object) {
return new WOQLQuery().delete_triple(subject, predicate, object)
}
/**
* Deletes a single triple from the graph [Subject, Predicate, Object, Graph]
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string} object - The IRI of a node or a variable, or a literal
* @param {typedef.GraphRef} graphRef - A valid graph resource identifier string
* @returns {WOQLQuery} - A WOQLQuery which contains the Delete Quad Statement
* @example remove the class Person from the schema/main graph
* WOQL.delete_quad("Person", "type", "owl:Class", "schema/main")
*/
WOQL.delete_quad = function(subject, predicate, object, graphRef) {
return new WOQLQuery().delete_quad(subject, predicate, object, graphRef)
}
/**
* Adds triples according to the the pattern [subject,predicate,object]
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string} object - The IRI of a node or a variable, or a literal
* @returns {object} WOQLQuery
*/
WOQL.add_triple = function(subject, predicate, object) {
return new WOQLQuery().add_triple(subject, predicate, object)
}
/**
* Adds quads according to the pattern [S,P,O,G]
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string} object - The IRI of a node or a variable, or a literal
* @param {typedef.GraphRef} graphRef- A valid graph resource identifier string
* @returns {object} WOQLQuery
*/
WOQL.add_quad = function(subject, predicate, object, graphRef) {
return new WOQLQuery().add_quad(subject, predicate, object, graphRef)
}
/**
*
* When the subquery is met, the update query is executed
* @param {WOQLQuery} subquery - the condition query
* @param {WOQLQuery} [updateQuery]
* @returns {WOQLQuery} - A WOQLQuery which contains the when expression
* @example
* when(true()).triple("a", "b", "c")
*/
//Functions which take a query as an argument advance the cursor to make the chaining of queries fall into the corrent place in the encompassing json.
/*WOQL.when = function(subquery, updateQuery) {
return new WOQLQuery().when(subquery, updateQuery)
}*/
/**
*
* Remove whitespace from both sides of a string:
* @param {string} inputStr - A string or variable containing the untrimmed version of the string
* @param {string} resultVarName - A string or variable containing the trimmed version of the string
* @returns {WOQLQuery} A WOQLQuery which contains the Trim pattern matching expression
* @example
* trim("hello ","v:trimmed")
* //trimmed contains "hello"
*/
WOQL.trim = function(inputStr, resultVarName) {
return new WOQLQuery().trim(inputStr, resultVarName)
}
/**
*
* Evaluates the passed arithmetic expression and generates or matches the result value
* @param {object| WOQLQuery | string} arithExp - A WOQL query containing a valid WOQL Arithmetic Expression, which is evaluated by the function
* @param {string | number} resultVarName - Either a variable, in which the result of the expression will be stored, or a numeric literal which will be used as a test of result of the evaluated expression
* @returns {WOQLQuery} A WOQLQuery which contains the Arithmetic function
* @example
* evaluate(plus(2, minus(3, 1)), "v:result")
*/
WOQL.evaluate = function(arithExp, resultVarName) {
return new WOQLQuery().eval(arithExp, resultVarName)
}
/**
* Evaluates the passed arithmetic expression and generates or matches the result value
* @param {object| WOQLQuery | string} arithExp - query or JSON-LD representing the query
* @param {string} resultVarName - output variable
* @returns {WOQLQuery} WOQLQuery
*/
WOQL.eval = WOQL.evaluate
/**
*
* Adds the numbers together
* @param {...(string |number)} args - a variable or numeric containing the values to add
* @returns {WOQLQuery} A WOQLQuery which contains the addition expression
* @example
* evaluate(plus(2, plus(3, 1)), "v:result")
*/
WOQL.plus = function(...args) {
return new WOQLQuery().plus(...args)
}
/**
*
* Subtracts Numbers N1..Nn
* @param {...(string |number)} args - variable or numeric containing the value that will be subtracted from
* @returns {WOQLQuery} A WOQLQuery which contains the subtraction expression
* @example
* evaluate(minus(2.1, plus(0.2, 1)), "v:result")
*/
WOQL.minus = function(...args) {
return new WOQLQuery().minus(...args)
}
/**
*
* Multiplies numbers N1...Nn together
* @param {...(string |number)} args - a variable or numeric containing the value
* @returns {WOQLQuery} A WOQLQuery which contains the multiplication expression
* @example
* evaluate(times(10, minus(2.1, plus(0.2, 1))), "v:result")
* //result contains 9.000000000000002y
*/
WOQL.times = function(...args) {
return new WOQLQuery().times(...args)
}
/**
*
* Divides numbers N1...Nn by each other left, to right precedence
* @param {...(string |number)} args - numbers to tbe divided
* @returns {WOQLQuery} A WOQLQuery which contains the division expression
* evaluate(divide(times(10, minus(2.1, plus(0.2, 1))), 10), "v:result")
* //result contains 0.9000000000000001
*/
WOQL.divide = function(...args) {
return new WOQLQuery().divide(...args)
}
/**
*
* Division - integer division - args are divided left to right
* @param {...(string |number)} args - numbers for division
* @returns {WOQLQuery} A WOQLQuery which contains the division expression
* @example
* let [result] = vars("result")
* evaluate(div(10, 3), result)
* //result contains 3
*/
WOQL.div = function(...args) {
return new WOQLQuery().div(...args)
}
/*
* @param {integer or double} a - base number
* @param {integer or double} b - power of
* @returns {object} WOQLQuery*/
/**
*
* Exponent - raises varNum01 to the power of varNum02
* @param {string | number} varNum - a variable or numeric containing the number to be raised to the power of the second number
* @param {number} expNum - a variable or numeric containing the exponent
* @returns {WOQLQuery} A WOQLQuery which contains the exponent expression
* @example
* evaluate(exp(3, 2), "v:result")
* //result contains 9
*/
WOQL.exp = function(varNum, expNum) {
return new WOQLQuery().exp(varNum, expNum)
}
/**
*
* Generates the nearest lower integer to the passed number
* @param {string | number} varNum - Variable or numeric containing the number to be floored
* @returns {WOQLQuery} A WOQLQuery which contains the floor expression
* @example
* let [result] = vars("result")
* evaluate(divide(floor(times(10, minus(2.1, plus(0.2, 1)))), 10), result)
* //result contains 0.9 - floating point error removed
*/
WOQL.floor = function(varNum) {
return new WOQLQuery().floor(varNum)
}
/**
*
* Tests whether a given instance IRI has type Class, according to the current state of the DB
* @param {string} instanceIRI - A string IRI or a variable that identify the class instance
* @param {string} classId - A Class IRI or a variable
* @returns {WOQLQuery} A WOQLQuery object containing the type test
* @example
* let [subject] = vars("subject")
* isa(subject, "Person")
*/
WOQL.isa = function(instanceIRI, classId) {
return new WOQLQuery().isa(instanceIRI, classId)
}
/**
*
* Generates a string Leverstein distance measure between stringA and stringB
* @param {string} stringA - string literal or variable representing a string to be compared
* @param {string} stringB - string literal or variable representing the other string to be compared
* @param {number | string} distance - variable representing the distance between the variables
* @returns {WOQLQuery} A WOQLQuery which contains the Like pattern matching expression
* @example
* let [dist] = vars('dist')
* like("hello", "hallo", dist)
* //dist contains 0.7265420560747664
*/
WOQL.like = function(stringA, stringB, distance) {
return new WOQLQuery().like(stringA, stringB, distance)
}
/**
*
* Compares the value of v1 against v2 and returns true if v1 is less than v2
* @param {string | number} varNum01 - a variable or numeric containing the number to be compared
* @param {string | number} varNum02 - a variable or numeric containing the second comporator
* @returns {WOQLQuery} A WOQLQuery which contains the comparison expression
* @example
* less(1, 1.1).eq("v:result", literal(true, "boolean"))
* //result contains true
*/
WOQL.less = function(varNum01, varNum02) {
return new WOQLQuery().less(varNum01, varNum02)
}
/**
*
* Compares the value of v1 against v2 and returns true if v1 is greater than v2
* @param {string | number} varNum01 - a variable or numeric containing the number to be compared
* @param {string | number} varNum02 - a variable or numeric containing the second comporator
* @returns {WOQLQuery} A WOQLQuery which contains the comparison expression
* @example
* greater(1.2, 1.1).eq("v:result", literal(true, "boolean"))
* //result contains true
*/
WOQL.greater = function(varNum01, varNum02) {
return new WOQLQuery().greater(varNum01, varNum02)
}
/**
*
* Specifies that the Subquery is optional - if it does not match the query will not fail
* @param {WOQLQuery} [subquery] - A subquery which will be optionally matched
* @returns {WOQLQuery} A WOQLQuery object containing the optional sub Query
* @example
* let [subject] = vars("subject")
* opt(triple(subject, 'label', "A"))
* //Subq is an argument or a chained query
* opt().triple(subject, 'label', "A")
*/
WOQL.opt = function(subquery) {
return new WOQLQuery().opt(subquery)
}
WOQL.optional = WOQL.opt
/**
*
* Generate a new IRI from the prefix and a hash of the variables which will be unique for any given combination of variables
* @param {string} prefix - A prefix for the IRI - typically formed of the doc prefix and the classtype of the entity (“doc:Person”)
* @param {array | string} inputVarList - An array of variables and / or strings from which the unique hash will be generated
* @param {string} resultVarName - Variable in which the unique ID is stored
* @returns {WOQLQuery} A WOQLQuery object containing the unique ID generating function
* @example
* unique("doc:Person", ["John", "Smith"], "v:newid")
*/
WOQL.unique = function(prefix, inputVarList, resultVarName) {
return new WOQLQuery().unique(prefix, inputVarList, resultVarName)
}
/**
*
* Generate a new IRI from the prefix and concatention of the variables
* @param {string} prefix - A prefix for the IRI - typically formed of the doc prefix and the classtype of the entity (“doc:Person”)
* @param {array | string} inputVarList - An array of variables and / or strings from which the unique hash will be generated
* @param {string} resultVarName - Variable in which the unique ID is stored
* @returns {WOQLQuery} A WOQLQuery object containing the ID generating function
* @example
* let [newid] = vars("newid")
* idgen("doc:Person", ["John", "Smith"], newid)
*/
WOQL.idgen = function(prefix, inputVarList, resultVarName) {
return new WOQLQuery().idgen(prefix, inputVarList, resultVarName)
}
WOQL.idgenerator = WOQL.idgen
/**
*
* Changes a string to upper-case
* @param {string} inputVarName - string or variable representing the uncapitalized string
* @param {string} resultVarName - variable that stores the capitalized string output
* @returns {WOQLQuery} A WOQLQuery which contains the Upper case pattern matching expression
* @example
* upper("aBCe", "v:allcaps")
* //upper contains "ABCE"
*/
WOQL.upper = function(inputVarName, resultVarName) {
return new WOQLQuery().upper(inputVarName, resultVarName)
}
/**
*
* Changes a string to lower-case
* @param {string} inputVarName - string or variable representing the non-lowercased string
* @param {string} resultVarName - variable that stores the lowercased string output
* @returns {WOQLQuery} A WOQLQuery which contains the Lower case pattern matching expression
* @example
* let [lower] = var("l")
* lower("aBCe", lower)
* //lower contains "abce"
*/
WOQL.lower = function(inputVarName, resultVarName) {
return new WOQLQuery().lower(inputVarName, resultVarName)
}
/**
*
* Pads out the string input to be exactly len long by appending the pad character pad to form output
* @param {string} inputVarName - The input string or variable in unpadded state
* @param {string} pad - The characters to use to pad the string or a variable representing them
* @param {number | string} len - The variable or integer value representing the length of the output string
* @param {string} resultVarName - stores output
* @returns {WOQLQuery} A WOQLQuery which contains the Pad pattern matching expression
* @example
* let [fixed] = vars("fixed length")
* pad("joe", " ", 8, fixed)
* //fixed contains "joe "
*/
WOQL.pad = function(inputVarName, pad, len, resultVarName) {
return new WOQLQuery().pad(inputVarName, pad, len, resultVarName)
}
/**
* Splits a string (Input) into a list strings (Output) by removing separator
* @param {string} inputVarName - A string or variable representing the unsplit string
* @param {string} separator - A string or variable containing a sequence of charatcters to use as a separator
* @param {string} resultVarName - variable that stores output list
* @returns {WOQLQuery} A WOQLQuery which contains the Split pattern matching expression
* @example
* split("joe has a hat", " ", "v:words")
*/
WOQL.split = function(inputVarName, separator, resultVarName) {
return new WOQLQuery().split(inputVarName, separator, resultVarName)
}
/**
* Matches if List includes Element
* @param {string | object} element - Either a variable, IRI or any simple datatype
* @param {string} list - List ([string, literal] or string*) Either a variable representing a list or a list of variables or literals
* @returns {WOQLQuery} A WOQLQuery which contains the List inclusion pattern matching expression
* @example
* let [name] = vars("name")
* member("name", ["john", "joe", "frank"])
*/
WOQL.member = function(element, list) {
return new WOQLQuery().member(element, list)
}
/**
*
* takes a variable number of string arguments and concatenates them into a single string
* @param {array | string} varList - a variable representing a list or a list of variables or strings - variables can be embedded in the string if they do not contain spaces
* @param {string} resultVarName - A variable or string containing the output string
* @returns {WOQLQuery} A WOQLQuery which contains the Concatenation pattern matching expression
* @example
* concat(["v:first_name", " ", "v:last_name"], "v:full_name")
* WOQL.concat(["first_name", " ", "last_name"], "full_name")
* //both versions work
*/
WOQL.concat = function(varList, resultVarName) {
return new WOQLQuery().concat(varList, resultVarName)
}
/**
*
* Joins a list variable together (Input) into a string variable (Output) by glueing the strings together with Glue
* @param {string | array} varList - a variable representing a list or a list of strings and / or variables
* @param {string} glue - A variable (v:glue) or (glue) string representing the characters to put in between the joined strings in input
* @param {string} resultVarName - A variable or string containing the output string
* @returns {WOQLQuery} A WOQLQuery which contains the Join pattern matching expression
* @example
* join(["joe", "has", "a", "hat", " ", "v:sentence")
*/
WOQL.join = function(varList, glue, resultVarName) {
return new WOQLQuery().join(varList, glue, resultVarName)
}
/**
* computes the sum of the List of values passed. In contrast to other arithmetic functions, sum self-evaluates - it does not have to be passed to evaluate()
* @param {WOQLQuery} subquery - a subquery or ([string or numeric]) - a list variable, or a list of variables or numeric literals
* @param {number} total - the variable name with the sum result of the values in List
* @returns {WOQLQuery} - A WOQLQuery which contains the Sum expression
* @example
* sum([2, 3, 4, 5], "v:total")
*/
WOQL.sum = function(subquery, total) {
return new WOQLQuery().sum(subquery, total)
}
/**
*
* Specifies an offset position in the results to start listing results from
* @param {number | string} start - A variable that refers to an interger or an integer literal
* @param {WOQLQuery} [subquery] - WOQL Query object, you can pass a subquery as an argument or a chained query
* @returns {WOQLQuery} A WOQLQuery whose results will be returned starting from the specified offset
* @example
* let [a, b, c] = vars("a", "b", "c")
* start(100).triple(a, b, c)
*/
WOQL.start = function(start, subquery) {
return new WOQLQuery().start(start, subquery)
}
/**
*
* Specifies a maximum number of results that will be returned from the subquery
* @param {number | string} limit - A variable that refers to an non-negative integer or a non-negative integer
* @param {WOQLQuery} [subquery] - A subquery whose results will be limited
* @returns {WOQLQuery} A WOQLQuery whose results will be returned starting from the specified offset
* @example
* let [a, b, c] = vars("a", "b", "c")
* limit(100).triple(a, b, c)
* //subquery is an argument or a chained query
* limit(100,triple(a, b, c))
*/
WOQL.limit = function(limit, subquery) {
return new WOQLQuery().limit(limit, subquery)
}
/**
*
* Matches the regular expression defined in Patern against the Test string, to produce the matched patterns in Matches
* @param {string} pattern - string or variable using normal PCRE regular expression syntax with the exception that special characters have to be escaped twice (to enable transport in JSONLD)
* @param {string} inputVarName - string or variable containing the string to be tested for patterns with the regex
* @param {string | array | object} resultVarList - variable representing the list of matches or a list of strings or variables
* @returns {WOQLQuery} A WOQLQuery which contains the Regular Expression pattern matching expression
* @example
* WOQL.re("h(.).*", "hello", ["v:All", "v:Sub"])
* //e contains 'e', llo contains 'llo'
* //p is a regex pattern (.*) using normal regular expression syntax, the only unusual thing is that special characters have to be escaped twice, s is the string to be matched and m is a list of matches:
*/
WOQL.re = function(pattern, inputVarName, resultVarList) {
return new WOQLQuery().re(pattern, inputVarName, resultVarList)
}
WOQL.regexp = WOQL.re
/**
*
* Calculates the length of the list in va and stores it in vb
* @param {string | array} inputVarList - Either a variable representing a list or a list of variables or literals
* @param {string} resultVarName - A variable in which the length of the list is stored or the length of the list as a non-negative integer
* @returns {WOQLQuery} A WOQLQuery which contains the Length pattern matching expression
* @example
* let [count] = vars("count")
* length(["john", "joe", "frank"], count)
*/
WOQL.length = function(inputVarList, resultVarName) {
return new WOQLQuery().length(inputVarList, resultVarName)
}
/**
*
* Logical negation of the contained subquery - if the subquery matches, the query will fail to match
* @param {string | WOQLQuery} [subquery] - A subquery which will be negated
* @returns {WOQLQuery} A WOQLQuery object containing the negated sub Query
* @example
* let [subject, label] = vars("subject", "label")
* not().triple(subject, 'label', label)
*/
WOQL.not = function(subquery) {
return new WOQLQuery().not(subquery)
}
/**
* Results in one solution of the subqueries
* @param {string| WOQLQuery } [subquery] - WOQL Query objects
* @returns {WOQLQuery} A WOQLQuery object containing the once sub Query
*/
WOQL.once = function(subquery) {
return new WOQLQuery().once(subquery)
}
/**
* Runs the query without backtracking on side-effects
* @param {string| WOQLQuery } [subquery] - WOQL Query objects
* @returns {WOQLQuery} A WOQLQuery object containing the immediately sub Query
*/
WOQL.immediately = function(subquery) {
return new WOQLQuery().immediately(subquery)
}
/**
* Creates a count of the results of the query
* @param {string | number} countVarName - variable or integer count
* @param {WOQLQuery} [subquery]
* @returns {WOQLQuery} A WOQLQuery object containing the count sub Query
* @example
* WOQL.count("v:count").triple("v:Person","type","scm:Person")
*/
WOQL.count = function(countVarName, subquery) {
return new WOQLQuery().count(countVarName, subquery)
}
/**
*
* Casts the value of Input to a new value of type Type and stores the result in CastVar
* @param {string | number | object} varName - Either a single variable or a literal of any basic type
* @param {string} varType - Either a variable or a basic datatype (xsd / xdd)
* @param {string} resultVarName - save the return variable
* @returns {WOQLQuery} A WOQLQuery which contains the casting expression
* @example
* cast("22/3/98", "xsd:dateTime", "v:time")
*/
WOQL.typecast = function(varName, varType, resultVarName) {
return new WOQLQuery().typecast(varName, varType, resultVarName)
}
WOQL.cast = WOQL.typecast
/**
* Orders the results of the contained subquery by a precedence list of variables
* @param {...string} varNames - A sequence of variables, by which to order the results, each optionally followed by either “asc” or “desc” to represent order
* @returns {WOQLQuery} A WOQLQuery which contains the ordering expression
* @example
* WOQL.order_by("v:A", "v:B asc", "v:C desc").triple("v:A", "v:B", "v:C");
*/
WOQL.order_by = function(...varNames) {
return new WOQLQuery().order_by(...varNames)
}
/**
*
* Groups the results of the contained subquery on the basis of identical values for Groupvars, extracts the patterns defined in PatternVars and stores the results in GroupedVar
* @param {array | string} varList - Either a single variable or an array of variables
* @param {array | string} patternVars - Either a single variable or an array of variables
* @param {string} resultVarName - output variable name
* @param {WOQLQuery} [subquery] - The query whose results will be grouped
* @returns {WOQLQuery} A WOQLQuery which contains the grouping expression
* @example
* //subquery is an argument or a chained query
* let [age, last_name, first_name, age_group, person] = vars("age", "last name", "first name", "age group", "person")
* group_by(age, [last_name, first_name], age_group)
* .triple(person, "first_name", first_name)
* .triple(person, "last_name", last_name)
* .triple(person, "age", age)
*/
WOQL.group_by = function(varList, patternVars, resultVarName, subquery) {
return new WOQLQuery().group_by(varList, patternVars, resultVarName, subquery)
}
/**
*
* A function that always matches, always returns true
* @returns {WOQLQuery} A WOQLQuery object containing the true value that will match any pattern
* @example
* when(true()).triple("a", "b", "c")
*/
WOQL.true = function() {
return new WOQLQuery().true()
}
/**
*
* Performs a path regular expression match on the graph
* @param {string} subject - An IRI or variable that refers to an IRI representing the subject, i.e. the starting point of the path
* @param {string} pattern -(string) - A path regular expression describing a pattern through multiple edges of the graph
* Path regular expressions consist of a sequence of predicates and / or a set of alternatives, with quantification operators
* The characters that are interpreted specially are the following:
* | representing alternative choices
* , - representing a sequence of predcitates
* + - Representing a quantification of 1 or more of the preceding pattern in a sequence
* {min, max} - Representing at least min examples and at most max examples of the preceding pattern
* - Representing any predicate
* () - Parentheses, interpreted in the normal way to group clauses
* @param {string} object - An IRI or variable that refers to an IRI representing the object, i.e. ending point of the path
* @param {string} resultVarName - A variable in which the actual paths traversed will be stored
* @returns {WOQLQuery} - A WOQLQuery which contains the path regular expression matching expression
* @example
* let [person, grand_uncle, lineage] = vars("person", "grand uncle", "lineage")
* path(person, ((father|mother) {2,2}), brother), grand_uncle, lineage)
*/
WOQL.path = function(subject, pattern, object, resultVarName) {
return new WOQLQuery().path(subject, pattern, object, resultVarName)
}
/**
*
* Calculates the size in bytes of the contents of the resource identified in ResourceID
* @param {string} resourceId - A valid resource identifier string (can refer to any graph / branch / commit / db)
* @param {string} resultVarName - The variable name
* @example
* size("admin/minecraft/local/branch/main/instance/main", "v:varSize")
* //returns the number of bytes in the main instance graph on the main branch
*/
WOQL.size = function(resourceId, resultVarName) {
return new WOQLQuery().size(resourceId, resultVarName)
}
/**
*
* Calculates the number of triples of the contents of the resource identified in ResourceID
* @param {string} resourceId - A valid resource identifier string (can refer to any graph / branch / commit / db)
* @param {string | number} tripleCount - An integer literal with the size in bytes or a variable containing that integer
* @returns {WOQLQuery} A WOQLQuery which contains the size expression
* @example
* triple_count("admin/minecraft/local/_commits", "v:count")
* //returns the number of bytes in the local commit graph
*/
WOQL.triple_count = function(resourceId, tripleCount) {
return new WOQLQuery().triple_count(resourceId, tripleCount)
}
/**
*
* Returns true if 'elementId' is of type 'elementType', according to the current DB schema
* @param {string} elementId - the id of a schema graph element
* @param {string} elementType - the element type
* @returns {WOQLQuery} A WOQLQuery object containing the type_of pattern matching rule
*
*/
WOQL.type_of = function(elementId, elementType) {
return new WOQLQuery().type_of(elementId, elementType)
}
/**
*
* Generates a query that by default matches all triples in a graph identified by "graph" or in all the current terminusDB's graph
* @param {string | boolean} [graph] - false or the resource identifier of a graph possible value are schema/{main - myschema - *} | instance/{main - myschema - *} | inference/{main - myschema - *}
* @param {string} [subject] - The IRI of a triple’s subject or a variable, default value "v:Subject"
* @param {string} [predicate] - The IRI of a property or a variable, default value "v:Predicate"
* @param {string} [object] - The IRI of a node or a variable, or a literal, default value "v:Object"
* @returns {WOQLQuery} A WOQLQuery which contains the pattern matching expression
* @example
* star("schema/main")
* //will return every triple in schema/main graph
*/
WOQL.star = function(graph, subject, predicate, object) {
return new WOQLQuery().star(graph, subject, predicate, object)
}
/**
*
* Generates a query that by default matches all triples in a graph - identical to star() except for order of arguments
* @param {string} [subject] - The IRI of a triple’s subject or a variable
* @param {string} [predicate] - The IRI of a property or a variable
* @param {string} [object] - The IRI of a node or a variable, or a literal
* @param {typedef.GraphRef} [graphRef] - the resource identifier of a graph possible value are schema/{main - myschema - *} | instance/{main - myschema - *} | inference/{main - myschema - *}
* @returns {WOQLQuery} - A WOQLQuery which contains the pattern matching expression
* all("mydoc")
* //will return every triple in the instance/main graph that has "doc:mydoc" as its subject
*/
WOQL.all = function(subject, predicate, object, graphRef) {
return new WOQLQuery().all(subject, predicate, object, graphRef)
}
/**
*
* Specifies the identity of a node that can then be used in subsequent builder functions. Note that node() requires subsequent chained functions to complete the triples / quads that it produces - by itself it only generates the subject.
* @param {string} nodeid - The IRI of a node or a variable containing an IRI which will be the subject of the builder functions
* @param {typedef.FuntionType} [chainType] - Optional type of builder function to build (default is triple)
* @returns {WOQLQuery} - A WOQLQuery which contains the partial Node pattern matching expression
* @example
* node("mydoc").label("my label")
* //equivalent to triple("mydoc", "label", "my label")
*/
WOQL.node = function(nodeid, chainType) {
return new WOQLQuery().node(nodeid, chainType)
}
//These ones are special ones for dealing with the schema only...
/**
* Inserts a single triple into the database declaring the Node to have type Type, optionally into the specified graph
* @param {string} classId - IRI string or variable containing the IRI of the node to be inserted
* @param {string} classType - IRI string or variable containing the IRI of the type of the node (class/document name)
* @param {typedef.GraphRef} [graphRef] - Optional Graph resource identifier
* @returns {WOQLQuery} A WOQLQuery which contains the insert expression
* @example
* insert("mydoc", "MyType")
* //equivalent to add_triple("mydoc", "type", "MyType")
*/
WOQL.insert = function(classId, classType, graphRef) {
return new WOQLQuery().insert(classId, classType, graphRef)
}
/**
* Sets the graph resource ID that will be used for subsequent chained function calls
* @param {typedef.GraphRef} [graphRef] Resource String identifying the graph which will be used for subsequent chained schema calls
* @returns {WOQLQuery} A WOQLQuery which contains the partial Graph pattern matching expression
* @example
* WOQL.graph("schema")
* //equivalent to add_quad("MyClass", "label", "My Class Label", "schema/main")
*/
WOQL.graph = function(graphRef) {
return new WOQLQuery().graph(graphRef)
}
//to be review
/**
* Deletes all triples in the passed graph (defaults to instance/main)
* @param {typedef.GraphRef} [graphRef] - Resource String identifying the graph from which all triples will be removed
* @returns {WOQLQuery} - A WOQLQuery which contains the deletion expression
* @example
* nuke("schema/main")
* //will delete everything from the schema/main graph
*/
WOQL.nuke = function(graphRef) {
return new WOQLQuery().nuke(graphRef)
}
/**
* Generates an empty WOQLQuery object
* @returns {WOQLQuery}
* @example
* let q = query()
* //then q.triple(1, 1) ...
*/
WOQL.query = function() {
return new WOQLQuery()
}
/**
* Generates a WOQLQuery object from the passed WOQL JSON - if an argument is passed, the query object is created from it, if none is passed, the current state is returned as a JSON-LD
* @param {object} [JSON_LD] - JSON-LD woql document encoding a query
* @returns {WOQLQuery | object} either a JSON-LD or a WOQLQuery object
*
* json version of query for passing to api
*/
WOQL.json = function(JSON_LD) {
return new WOQLQuery().json(JSON_LD)
}
/**
* get the predefined library query [WOQLLibrary](/api/woqlLibrary.js?id=WOQLLibrary)
* @returns {WOQLQuery} WOQLQuery object
* @example
* //get commits older than the specified commit id
* const query = WOQL.lib().previousCommits('m8vpxewh2aovfauebfkbzwmj4qwr5lb')
*
* //return the commits of a specific branch starting from the head
* //you can add the limit (how many results to return.) and the start point
* //if a timestamp is given, gets the commits before the specified timestamp
* //WOQL.lib().commits(branch='main',limit=0,start=0,timestamp=0)
*
* const query = WOQL.lib().commits('main',10,2,1630683082.9278786)
*
* //return the branches list with the timestamp and commits id
* const query = WOQL.lib().branches()
*/
WOQL.lib = function() {
return new WOQLQuery().lib()
}
/**
* Generates explicitly a JSON-LD string literal from the input
* @param {string | boolean | number} val - any primitive literal type
* @returns {object} - A JSON-LD string literal
* @example
* string(1)
* //returns { "@type": "xsd:string", "@value": "1" }
*/
WOQL.string = function(val) {
return new WOQLQuery().string(val)
}
WOQL.read_object = function(IRI, output, formatObj) {
return new WOQLQuery().read_object(IRI, output, formatObj)
}
/**
* Generates explicitly a JSON-LD string literal from the input
* @param {string} val - any literal type
* @param {string} type - an xsd or xdd type
* @returns {object} - A JSON-LD literal
* @example
* literal(1, "nonNegativeInteger")
* //returns { "@type": "xsd:nonNegativeInteger", "@value": 1 }
*/
WOQL.literal = function(val, type) {
return new WOQLQuery().literal(val, type)
}
/**
* Explicitly sets a value to be an IRI - avoiding automatic type marshalling
* @param {string} val string which will be treated as an IRI
* @returns {object} - A JSON-LD IRI value
*/
WOQL.iri = function(val) {
return new WOQLQuery().iri(val)
}
/**
* Generates javascript variables for use as WOQL variables within a query
* @param {...string} varNames
* @returns {array} an array of javascript variables which can be dereferenced using the array destructuring operation
* @example
* const [a, b, c] = WOQL.vars("a", "b", "c")
* //a, b, c are javascript variables which can be used as WOQL variables in subsequent queries
*/
WOQL.vars = function(...varNames) {
return varNames.map(item => 'v:' + item)
}
/**
* Gets/Sets woqlClient
* @param {WOQLClient}
* @returns {WOQLClient}
*/
WOQL.client = function(client) {
if (client) this._client = client
return this._client
}
/**
*
* query module
* allow you to use WOQL words as top level functions
* @param {*} auto_eval
*/
WOQL.emerge = function(auto_eval) {
let unemerged = ['emerge', 'true', 'eval']
function _emerge_str(k) {
let str = `function ${k}(...args){
return WOQL.${k}(...args)
}`
return str
}
let funcs = []
for (var k in this) {
if (typeof this[k] == 'function') {
if (unemerged.indexOf(k) == -1) {
funcs.push(_emerge_str(k))
}
}
}
let str = funcs.join(';\n')
if (auto_eval) eval(str)
return str
}
/**
* Update a pattern matching rule for the triple (Subject, Predicate, oldObjValue) with the new one (Subject, Predicate, newObjValue)
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string} newObjValue - The value to update or a literal
* @param {string} oldObjValue - The old value of the object
* @returns {WOQLQuery} A WOQLQuery which contains the a Update Triple Statement
*/
WOQL.update_triple = function(subject, predicate, newObjValue, oldObjValue) {
return new WOQLQuery().update_triple(subject, predicate, newObjValue, oldObjValue)
}
/**
* Update a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph)
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string} newObject - The value to update or a literal
* @param {typedef.GraphRef} graphRef - A valid graph resource identifier string
* @returns {WOQLQuery} A WOQLQuery which contains the a Update Quad Statement
*/
WOQL.update_quad = function(subject, predicate, newObject, graphRef) {
return new WOQLQuery().update_quad(subject, predicate, newObject, graphRef)
}
/**
* Creates a pattern matching rule for a quad [Subject, Predicate, Object, Graph] or for a triple [Subject, Predicate, Object]
* add extra information about the type of the value object
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string | number | boolean} objValue - an specific value
* @param {typedef.GraphRef} [graphRef] - specify a graph type, default is instance schema|instance
* @returns {WOQLQuery} A WOQLQuery which contains the a quad or a triple Statement
*/
WOQL.value = function(subject, predicate, objValue, graphRef) {
return new WOQLQuery().value(subject, predicate, objValue, graphRef)
}
/**
* Creates a pattern matching rule for a quad [Subject, Predicate, Object, Graph] or for a triple [Subject, Predicate, Object]
* @param {string} subject - The IRI of a triple’s subject or a variable
* @param {string} predicate - The IRI of a property or a variable
* @param {string} object - The IRI of a node or a variable, or a literal
* @param {typedef.GraphRef} [graphRef] - specify a graph type, default is instance schema|instance
* @returns {WOQLQuery} A WOQLQuery which contains the a quad or a triple Statement
*/
WOQL.link = function(subject, predicate, object, graphRef) {
return new WOQLQuery().link(subject, predicate, object, graphRef)
}
module.exports = WOQL
|
var getMonthName=function(t){var e=[];return e[0]="JAN",e[1]="FEB",e[2]="MAR",e[3]="APR",e[4]="MAY",e[5]="JUN",e[6]="JUL",e[7]="AUG",e[8]="SEP",e[9]="OCT",e[10]="NOV",e[11]="DEC",e[t]},getDate=function(t){var e=new Date(t),r=e.getDate(),n=e.getMonth()+1,o=e.getFullYear();return r<10&&(r="0"+r),n<10&&(n="0"+n),e=o+"-"+n+"-"+r},handleVisitorsAreaChart=function(){var t=function(t){var e=new Date;return e=e.setDate(e.getDate()-t)},e=[{key:"Unique Visitors",color:COLOR_AQUA,values:[[t(77),13],[t(76),13],[t(75),6],[t(73),6],[t(72),6],[t(71),5],[t(70),5],[t(69),5],[t(68),6],[t(67),7],[t(66),6],[t(65),9],[t(64),9],[t(63),8],[t(62),10],[t(61),10],[t(60),10],[t(59),10],[t(58),9],[t(57),9],[t(56),10],[t(55),9],[t(54),9],[t(53),8],[t(52),8],[t(51),8],[t(50),8],[t(49),8],[t(48),7],[t(47),7],[t(46),6],[t(45),6],[t(44),6],[t(43),6],[t(42),5],[t(41),5],[t(40),4],[t(39),4],[t(38),5],[t(37),5],[t(36),5],[t(35),7],[t(34),7],[t(33),7],[t(32),10],[t(31),9],[t(30),9],[t(29),10],[t(28),11],[t(27),11],[t(26),8],[t(25),8],[t(24),7],[t(23),8],[t(22),9],[t(21),8],[t(20),9],[t(19),10],[t(18),9],[t(17),10],[t(16),16],[t(15),17],[t(14),16],[t(13),17],[t(12),16],[t(11),15],[t(10),14],[t(9),24],[t(8),18],[t(7),15],[t(6),14],[t(5),16],[t(4),16],[t(3),17],[t(2),7],[t(1),7],[t(0),7]]},{key:"Page Views",color:COLOR_BLUE,values:[[t(77),14],[t(76),13],[t(75),15],[t(73),14],[t(72),13],[t(71),15],[t(70),16],[t(69),16],[t(68),14],[t(67),14],[t(66),13],[t(65),12],[t(64),13],[t(63),13],[t(62),15],[t(61),16],[t(60),16],[t(59),17],[t(58),17],[t(57),18],[t(56),15],[t(55),15],[t(54),15],[t(53),19],[t(52),19],[t(51),18],[t(50),18],[t(49),17],[t(48),16],[t(47),18],[t(46),18],[t(45),18],[t(44),16],[t(43),14],[t(42),14],[t(41),13],[t(40),14],[t(39),13],[t(38),10],[t(37),9],[t(36),10],[t(35),11],[t(34),11],[t(33),11],[t(32),10],[t(31),9],[t(30),10],[t(29),13],[t(28),14],[t(27),14],[t(26),13],[t(25),12],[t(24),11],[t(23),13],[t(22),13],[t(21),13],[t(20),13],[t(19),14],[t(18),13],[t(17),13],[t(16),19],[t(15),21],[t(14),22],[t(13),25],[t(12),24],[t(11),24],[t(10),22],[t(9),16],[t(8),15],[t(7),12],[t(6),12],[t(5),15],[t(4),15],[t(3),15],[t(2),18],[t(2),18],[t(0),17]]}];nv.addGraph(function(){var t=nv.models.stackedAreaChart().useInteractiveGuideline(!0).x(function(t){return t[0]}).y(function(t){return t[1]}).pointSize(.5).margin({left:35,right:25,top:20,bottom:20}).controlLabels({stacked:"Stacked"}).showControls(!1).duration(300);return t.xAxis.tickFormat(function(t){var e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return t=new Date(t),t=e[t.getMonth()]+" "+t.getDate()}),t.yAxis.tickFormat(d3.format(",.0f")),d3.select("#visitors-line-chart").append("svg").datum(e).transition().duration(1e3).call(t).each("start",function(){setTimeout(function(){d3.selectAll("#visitors-line-chart *").each(function(){this.__transition__&&(this.__transition__.duration=1)})},0)}),nv.utils.windowResize(t.update),t})},handleVisitorsDonutChart=function(){var t=[{label:"Return Visitors",value:784466,color:COLOR_BLUE},{label:"New Visitors",value:416747,color:COLOR_GREEN}],e=[{inner:.65,outer:.93},{inner:.6,outer:1}];nv.addGraph(function(){var r=nv.models.pieChart().x(function(t){return t.label}).y(function(t){return t.value}).margin({left:10,right:10,top:10,bottom:10}).showLegend(!1).donut(!0).growOnHover(!1).arcsRadius(e).donutRatio(.5);return r.labelFormat(d3.format(",.0f")),d3.select("#visitors-donut-chart").append("svg").datum(t).transition().duration(3e3).call(r),r})},handleVisitorsVectorMap=function(){0!==$("#visitors-map").length&&$("#visitors-map").vectorMap({map:"world_merc_en",scaleColors:[COLOR_BLACK_LIGHTER,COLOR_BLACK],container:$("#visitors-map"),normalizeFunction:"linear",hoverOpacity:.5,hoverColor:!1,zoomOnScroll:!1,markerStyle:{initial:{fill:COLOR_BLACK,stroke:"transparent",r:3}},regions:[{attribute:"fill"}],regionStyle:{initial:{fill:COLOR_BLACK_LIGHTER,"fill-opacity":1,stroke:"none","stroke-width":.4,"stroke-opacity":1},hover:{"fill-opacity":.8},selected:{fill:"yellow"}},series:{regions:[{values:{IN:COLOR_BLUE,US:COLOR_GREEN,MN:COLOR_GREY_DARKER}}]},focusOn:{x:.5,y:.5,scale:1},backgroundColor:"transparent"})},handleScheduleCalendar=function(){var t=["January","February","March","April","May","June","July","August","September","October","November","December"],e=["S","M","T","W","T","F","S"],r=new Date,n=r.getMonth()+1,o=r.getFullYear(),a=[["2/"+n+"/"+o,"Popover Title","#",COLOR_GREEN,"Some contents here"],["5/"+n+"/"+o,"Tooltip with link","http://www.seantheme.com/",COLOR_BLACK],["18/"+n+"/"+o,"Popover with HTML Content","#",COLOR_BLACK,'Some contents here <div class="text-right"><a href="http://www.google.com">view more >>></a></div>'],["28/"+n+"/"+o,"Color Admin V1.3 Launched","http://www.seantheme.com/color-admin-v1.3",COLOR_BLACK]],i=$("#schedule-calendar");$(i).calendar({months:t,days:e,events:a,popover_options:{placement:"top",html:!0}}),$(i).find("td.event").each(function(){var t=$(this).css("background-color");$(this).removeAttr("style"),$(this).find("a").css("background-color",t)}),$(i).find(".icon-arrow-left, .icon-arrow-right").parent().on("click",function(){$(i).find("td.event").each(function(){var t=$(this).css("background-color");$(this).removeAttr("style"),$(this).find("a").css("background-color",t)})})},DashboardV2=function(){"use strict";return{init:function(){handleVisitorsDonutChart(),handleVisitorsVectorMap()}}}();
|
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { createStructuredSelector } from 'reselect';
import { Spin, Alert } from 'antd';
import Progress from 'fetcher/Progress';
import Message from 'fetcher/Message';
import * as tokenUtils from 'utils/token';
import GlobalStyle from '../../global-styles';
import Wrapper from './Wrapper';
import Public from '../Public';
import Private from '../Private';
import {
useInjectReducerSaga,
checkToken,
selectors as checkTokenSelectors,
} from './checkToken';
export function App({
loading,
fetched,
errorMsg,
isTokenValid,
dispatchCheckToken,
}) {
useInjectReducerSaga();
useEffect(() => {
if (tokenUtils.get()) {
dispatchCheckToken();
}
}, []);
useEffect(() => {
if (fetched && !isTokenValid) {
tokenUtils.remove();
}
}, [fetched]);
if (errorMsg) {
return <Alert message={errorMsg} type="error" />;
}
let content = '';
if (loading) {
content = <Spin size="large" />;
} else if (isTokenValid) {
content = <Private />;
} else if (!tokenUtils.get() || (fetched && !isTokenValid)) {
content = <Public />;
}
return (
<Wrapper>
<GlobalStyle />
<Progress />
<Message />
{content}
</Wrapper>
);
}
App.propTypes = {
loading: PropTypes.bool,
isTokenValid: PropTypes.bool,
fetched: PropTypes.bool,
errorMsg: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
dispatchCheckToken: PropTypes.func,
};
const mapStateToProps = createStructuredSelector({
errorMsg: checkTokenSelectors.makeSelectErrorMsg(),
loading: checkTokenSelectors.makeSelectLoading(),
fetched: checkTokenSelectors.makeSelectFetched(),
isTokenValid: checkTokenSelectors.makeSelectIsValid(),
});
function mapDispatchToProps(dispatch) {
return {
dispatchCheckToken: () => dispatch(checkToken()),
};
}
const withConnect = connect(
mapStateToProps,
mapDispatchToProps,
);
export default compose(withConnect)(App);
|
var fs = require('fs');
var j;
var list;
var use;
var toS = function(str) {
//return str;
return '";\n' + str + '\nstr += "';
};
var patterns = [
// use
/{use\s'([^']*)'}\n/g, function(str, path) {
// Переводим строку в массив
path = path.split('/');
// Получаем имя файла
var file = String(path.pop());
// Получаем тип файла
var type = String(file.split('.').pop());
// Use не соответствует формату
if (!type || file == type) {
return str;
}
// Добавляем в use новый тип файла
if (!(type in use)) {
use[type] = [];
}
// Добавляем в use новый файл
use[type].push([path.join('/'), file]);
// Возвращаем пустую строку, тем самым удаляем {use} из кода
return '';
},
// use:type
/{use:([^']+)\s'([^']*)'}\n/g, function(str, type, tag) {
// Тип файла не найден
if (!(type in use)) {
return str;
}
// Создаем список подключаемых файлов
var tags = [];
// Проходим по списку подключаемых файлов
for (var i = 0; i < use[type].length; i++) {
tags[i] = tag
// Подставляем путь к файлу
.replace(/{path}/, use[type][i][0] + '' + (use[type][i][0] == '' ? '' : '/'))
// Подставляем имя файла
.replace(/{file}/, use[type][i][1])
// Подставляем полный путь к файлу (путь + имя)
.replace(/{src}/, use[type][i][0] + '' + (use[type][i][0] == '' ? '' : '/') + '' + use[type][i][1]) + '\n';
}
// Переводим массив в строку
return tags.join('');
},
// for
/{for\s([a-zA-Z_$]{1}[a-zA-Z_$0-9]*)}/g, function(str, obj) {
list[obj] = (obj in list ? list[obj] : j++);
return toS('for (i[' + list[obj] + '] = 0; i[' + list[obj] + '] < vars.' + obj + '.length; i[' + list[obj] + ']++) {');
},
// end for
/{\/for}/g, toS('}'),
// if
/{if\s([a-zA-Z_$]{1}[^}]*)}/g, toS('if (vars.$1) {'),
// else
/{else}/g, toS('} else {'),
// end if
/{\/if}/g, toS('}'),
// var
/{([a-zA-Z_$]{1}[a-zA-Z_$0-9]*)}/g, '" + vars.$1 + "'
];
fs.readFile('1.html', function(err, str) {
j = 0;
list = {};
use = {};
//var text = JSON.stringify(str.toString());
var text = str.toString();
for (var i = 0; i < patterns.length; i+=2) {
text = text.replace(patterns[i], patterns[i + 1]);
}
// for
for (var obj in list) {
text = text.replace(
new RegExp("{" + obj + "\.([a-zA-Z_$]{1}[a-zA-Z_$0-9]*)}","g"),
'" + vars.' + obj + '[i[' + list[obj] + ']].$1 + "'
);
}
var func = '';
func += 'function(vars) {\n';
func += 'var i=[];\n';
func += 'var str = ' + text + ';\n';
func += 'return str;\n';
func += '};\n';
console.log(func);
});
|
/*
* Duplicate Safari Window in Google Chrome
*
* Opens a new Chrome window containing the same tabs that are open in
* the frontmost Safari window (excluding Safari-specific tabs like
* Bookmarks, Favorites, History, and Top Sites).
*
* Last updated 2018-10-18.
*
* Copyright 2018 Lawrence Andrew Velázquez
* SPDX-License-Identifier: MIT
*/
'use strict';
// Ideally these would be const, but global const/let declarations
// interact poorly with OSA persistence.
var Chrome = Application('com.google.Chrome');
var Safari = Application('com.apple.Safari');
/*
* Given a reference to a Safari window, returns an array containing the
* URIs of the window's tabs. The URIs are ordered by tab position, from
* left to right. Safari-specific URIs (e.g., "history://") are
* included. The URI "about:blank" is returned for blank tabs.
*/
function getSafariURIs(window) {
// Request tab information in bulk and store it in proxy objects to
// minimize the number of Apple events sent.
const tabs = window.tabs().map(ref => ({ref}));
window.tabs.name().forEach((name, idx) => { tabs[idx].name = name; });
window.tabs.url().forEach((uri, idx) => { tabs[idx].uri = uri; });
// There are at least two situations in which Safari returns null
// for a tab's URI:
// - The tab has not been loaded. When a window is restored,
// Safari loads the front tab but defers loading the other tabs
// until the user activates them. However, unloaded tabs do have
// their correct names, which are the titles of their websites.
// - The tab is empty. Safari allows users to open new tabs with
// no content at all. These tabs have the name "Untitled".
// I'm not aware of a foolproof method for distinguishing between
// these. This function assumes that a tab with a null URI and the
// name "Untitled" is empty and would break on an unloaded tab for
// a silly website named "Untitled".
let nullTabs = tabs.filter(({uri}) => !uri);
if (nullTabs.length) {
// Force unloaded tabs to load by activating each one.
const initTab = window.currentTab();
nullTabs.forEach(({ref}) => { window.currentTab = ref; });
window.currentTab = initTab;
// Tabs don't load instantaneously, so wait for Safari to load
// them in parallel. It would be cleaner to use a "whose" clause
// to count remaining null-URI tabs, but that doesn't work.
while (nullTabs.some(({name}) => name !== 'Untitled')) {
delay(1);
window.tabs.url().forEach((uri, idx) => { tabs[idx].uri = uri; });
nullTabs = nullTabs.filter(({uri}) => !uri);
}
// Any remaining null-URI tabs should have the name "Untitled".
// Assume these are empty tabs and set an appropriate URI in
// their proxy objects.
nullTabs.forEach(tab => { tab.uri = 'about:blank'; });
}
// Tabs that failed to load report a Safari-specific error URI. The
// original URI can be extracted from the text of the error page.
// Tested with Safari 12.0 on macOS 10.13.
tabs.filter(({uri}) =>
uri === 'file:///Applications/Safari.app/Contents/Resources/' ||
uri === 'safari-resource:/ErrorPage.html'
).forEach(tab => {
const match = /Safari can’t open the page “(.+?)”/u.exec(tab.ref.text());
if (match) {
tab.uri = match[1];
} else {
window.currentTab = tab;
// If there were a way to bring only the relevant window to
// the front instead of activating the entire application,
// that would be nice.
throwAlert({
message: 'Could not obtain URI of current tab.',
as: 'critical',
givingUpAfter: 60
});
}
});
return tabs.map(tab => tab.uri);
}
/*
* Given a URI, returns whether it is recognized to be special to
* Safari.
*/
function isSafariSpecialURI(uri) {
return uri === 'bookmarks://' ||
uri === 'favorites://' ||
uri === 'file:///Applications/Safari.app/Contents/Resources/' ||
uri === 'history://' ||
uri.startsWith('safari-resource:') ||
uri === 'topsites://';
}
/*
* Given an array of URIs, creates a new Chrome window with a tab for each.
*/
function makeNewChromeWindowWithURIs(uris) {
let window = Chrome.Window().make();
if (uris.length) {
// Re-use the initial tab, create the rest.
window.tabs[0].url = uris[0];
uris.slice(1).forEach(u => { window.tabs.push(Chrome.Tab({url: u})); });
}
return window;
}
/*
* Given an object containing named parameters for displayAlert(),
* displays an alert and throws an exception.
*/
function throwAlert(alertParameters) {
// Should Safari display the alert instead of the script runner?
const runner = Application.currentApplication();
runner.includeStandardAdditions = true
runner.displayAlert('Duplicate Window in Chrome', alertParameters);
throw new Error(alertParameters.message);
}
function run() {
const visibleSafariWindows = Safari.windows.whose({visible: true})();
if (!visibleSafariWindows.length) {
throwAlert({
message: "There are no visible Safari windows to duplicate.",
as: "critical",
givingUpAfter: 60
});
}
let uris = getSafariURIs(visibleSafariWindows[0]);
let currentTabIdx = visibleSafariWindows[0].currentTab.index();
// Safari-specific tabs to the left of the active tab will be
// omitted. Adjust the index to account for this.
currentTabIdx -=
uris.slice(0, currentTabIdx - 1).filter(isSafariSpecialURI).length;
uris = uris.filter(uri => !isSafariSpecialURI(uri));
if (!uris.length) {
throwAlert({
message: "Could not duplicate because all tabs are Safari-only.",
as: "critical",
givingUpAfter: 60
});
}
// If there were a way to bring only the relevant window to
// the front instead of activating the entire application,
// that would be nice.
makeNewChromeWindowWithURIs(uris).activeTabIndex = currentTabIdx;
}
|
module.exports = {
siteMetadata: {
title: `Gatsby Default Starter`,
description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
author: `@emmzytech`,
},
pathPrefix: "/Construct-Site",
plugins: [
`gatsby-plugin-react-helmet`,
`gatsby-plugin-image`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
`gatsby-plugin-gatsby-cloud`,
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
|
import { parseUrl } from './parser';
export function modelToViewUrlAttributeConverter( registry, options, domain ) {
return dispatcher => {
dispatcher.on( 'attribute:url:preview', converter );
};
function converter( evt, data, conversionApi ) {
if ( !conversionApi.consumable.consume( data.item, evt.name ) ) {
return;
}
const url = data.attributeNewValue;
const information = parseUrl( domain, url );
const viewWriter = conversionApi.writer;
const figure = conversionApi.mapper.toViewElement( data.item );
viewWriter.remove( viewWriter.createRangeIn( figure ) );
const linkViewElement = registry.getLinkViewElement( viewWriter, url, options, information );
viewWriter.insert( viewWriter.createPositionAt( figure, 0 ), linkViewElement );
}
}
|
/*globals describe it expect */
import UriRecognizer from '../src/uri-recognizer'
describe('uri-recognizer', () => {
it('default', () => {
const recognizer = new UriRecognizer()
const handler = function () {}
recognizer.add('localhost/products/:id', handler)
recognizer.add('localhost/products/1', handler)
recognizer.add('localhost/:collection/:id', handler)
recognizer.add('localhost/*path', handler)
recognizer.add('*', handler)
const result = recognizer.recognize('localhost/products/1')
expect(result.length).toEqual(5)
})
it('regex', () => {
const recognizer = new UriRecognizer()
const handler = function () {}
recognizer.add(/^localhost\/odata.svc\/Products\((\d+)\)$/, handler)
const result = recognizer.recognize('localhost/odata.svc/Products(100)')
expect(result.length).toEqual(1)
expect(result[0].params.groups.length).toEqual(1)
})
})
|
import Taro from "@tarojs/taro";
import { tokenValidate } from "@actions/api";
/**
* 特殊转跳,用于检测token并跳转,token不存在时转跳login界面
* @param {callback} iteratee 当TOKEN验证正确时发起回调
* @return {callback} itreratee(token,arguments)
*/
let reLaunch = iteratee => {
const token = Taro.getStorageSync("token");
if (!!token) {
tokenValidate(token).then(res => {
if (res.data.status == 0) {
return iteratee(token, arguments);
} else {
Taro.navigateTo({
url: "/packageA/login/login"
});
}
});
} else {
Taro.navigateTo({
url: "/packageA/login/login"
});
}
};
export { reLaunch };
|
const initialState = {
fetched: false,
fetching: false,
data: [
{
id: 0,
name: "Osiągnięcie #1",
img: "/badges/1.png",
},
{
id: 1,
name: "Rozwiąż 5 zadań",
img: "/badges/2.png",
},
{
id: 2,
name: "Osiągnięcie #3",
img: "/badges/3.png",
},
{
id: 3,
name: "Osiągnięcie #4",
img: "/badges/3.png",
},
{
id: 4,
name: "Osiągnięcie #5",
img: "/badges/4.png",
},
{
id: 5,
name: "Osiągnięcie #6",
img: "/badges/5.png",
},
{
id: 6,
name: "Osiągnięcie #7",
img: "/badges/6.png",
},
],
};
export default function reducer(state = initialState, action) {
// const newState = Object.assign({}, state, {
// data: state.data.slice(),
// });
return state;
}
|
class ListapizzasController {
constructor($log, menuService, LoginService, $uibModal, $http, $state) {
this._log = $log;
this.showList = true;
this._menuService = menuService;
this._loginService = LoginService;
this.$uibModal = $uibModal;
this._http = $http;
this._state = $state;
}
buyPizza = (pizza) => {
console.log("I am buying this pizza "+pizza);
if (!this.ifAdm()) {
this.abrirModal(pizza);
}
}
abrirModal = (pizza) => {
this._pizza = pizza;
var modalInstance = this.$uibModal.open({
animation: true,
component: 'comprarPizza',
resolve: {
pizzaEscolhida: () => {
return this._pizza;
}
}
});
modalInstance.result // Promesa de retorno do resultado do modal
.then( (pedido) => this.concluirCompra(pedido) )
.catch ( () => this._log.info('comprar-pizza dismissed at: ' + new Date()));
}
concluirCompra = (pedido) => {
console.log(pedido); // Adiciona a nossa lista de compras. Componente carrinho de compras
// terá um serviço que carregará essa lista e aqui injetariamos tal serviço e adicionariamos
// à lista.
this._http.post('/api/carrinho', pedido).then((response)=>{ console.log("Api carrinho:"+response);
this._state.go('carrinho');
});
showAlert('Sua compra foi adicionada ao carrinho', 'success', 9000);
}
showAlert = function (message, type, tempo) {
this.alertMsg = { text: message, type: type, tempo: tempo };
}
RemoverPizza = (pizza) => {
this.remove({$event: pizza});
}
EditarPizza = (pizza) => {
this._log.info(pizza);
this.showList = false;
this.pizza = pizza;
this.novoNome = pizza.nome;
this.novaDescricao = pizza.descricao;
this.novaImg_src = pizza.imagem;
this.novoTipo = pizza.tipo;
this.novoPreco = pizza.preco;
}
AtualizarPizza = () => {
if (this.novoNome == null) {this.novoNome = this.pizza.nome;}
if (this.novaDescricao == null) {this.novaDescricao = this.pizza.descricao;}
if (this.novaImg_src == null) {this.novaImg_src = this.pizza.imagem;}
if (this.novoTipo == null) {this.novoTipo = this.pizza.tipo;}
if (this.novoPreco == null) {this.novoPreco = this.pizza.preco;}
var novaPizza = {
nome: this.novoNome,
descricao: this.novaDescricao,
tipo: this.novoTipo,
imagem: this.novaImg_src,
preco: this.novoPreco,
id: this.pizza.id
}
this.pizza = null; // No reason to keep in memory
this.showList = true;
this.save({$event: novaPizza});
}
UpdateList = () => {
let promisse = this._menuService
.getListPromisse();
promisse.then((response)=>{ console.log(response);
this.listaCardapio = response.data;
}
);
}
ifAdm = () => { // Em vez de repitir esse codigo, devia injetar o serviço login no serviço
// menu e criar esse método no mesmo, quando precisar dele basta invoca-lo
// chamando a função do serviço menu. (Farei isso qndo tiver tempo sobrando)
if (this._loginService.logginType == "adm"){
return true;
} else {
return false
}
}
$onChanges (changedObjs) {
if (changedObjs.update) {
this.UpdateList();
}
}
}
ListapizzasController.$inject = ['$log','menuService', 'LoginService', '$uibModal', '$http','$state'];
export default ListapizzasController;
|
const path = require('path');
const {buildExternal, packer} = require('lerna-packer');
const apps = {
demo: {
root: path.resolve(__dirname, 'packages', 'demo'),
template: path.resolve(__dirname, 'packages', 'demo/public/index.html'),
publicPath: path.resolve(__dirname, 'packages', 'demo/public'),// dev-server
port: 4200,
main: path.resolve(__dirname, 'packages', 'demo/src/index.js'),
dist: path.resolve(__dirname, 'dist', 'demo'),
servedPath: '/',// todo: make package.json homepage dependent,
vendors: ['react-error-boundary', 'immutable', '@material-ui/core', '@material-ui/icons'],
},
docs: {
root: path.resolve(__dirname, 'packages', 'docs'),
template: path.resolve(__dirname, 'packages', 'docs/public/index.html'),
publicPath: path.resolve(__dirname, 'packages', 'docs/public'),// dev-server
port: 4201,
main: path.resolve(__dirname, 'packages', 'docs/src/index.js'),
dist: path.resolve(__dirname, 'dist', 'docs'),
servedPath: '/',
vendors: ['react-error-boundary', 'immutable', '@material-ui/core', '@material-ui/icons'],
copy: [{from: path.resolve(__dirname, 'schema'), to: path.resolve(__dirname, 'dist', 'docs', 'schema')}],
},
};
const packages = {
// the keys are the commonjs names that is applied to externals
// this is the same as `@babel/plugin-transform-modules-commonjs` applies
uiSchema: {
name: '@ui-schema/ui-schema',
root: path.resolve(__dirname, 'packages', 'ui-schema'),
entry: path.resolve(__dirname, 'packages', 'ui-schema/src/'),
externals: {
react: buildExternal('react'),
immutable: buildExternal('immutable'),
'react-dom': buildExternal('react-dom'),
},
},
uiSchemaPro: {
name: '@ui-schema/pro',
root: path.resolve(__dirname, 'packages', 'ui-schema-pro'),
entry: path.resolve(__dirname, 'packages', 'ui-schema-pro/src/'),
externals: {
react: buildExternal('react'),
immutable: buildExternal('immutable'),
'react-dom': buildExternal('react-dom'),
'@ui-schema/ui-schema': buildExternal('@ui-schema/ui-schema'),
},
},
dsMaterial: {
// noClean: true,
name: '@ui-schema/ds-material',
root: path.resolve(__dirname, 'packages', 'ds-material'),
entry: path.resolve(__dirname, 'packages', 'ds-material/src/'),
externals: {
'@ui-schema/ui-schema': buildExternal('@ui-schema/ui-schema'),
'@material-ui/core': buildExternal('@material-ui/core'),
'@material-ui/icons': buildExternal('@material-ui/icons'),
react: buildExternal('react'),
'react-dom': buildExternal('react-dom'),
},
},
dsBootstrap: {
name: '@ui-schema/ds-bootstrap',
root: path.resolve(__dirname, 'packages', 'ds-bootstrap'),
entry: path.resolve(__dirname, 'packages', 'ds-bootstrap/src/'),
externals: {
'@ui-schema/ui-schema': buildExternal('@ui-schema/ui-schema'),
react: buildExternal('react'),
'react-dom': buildExternal('react-dom'),
},
},
materialPickers: {
name: '@ui-schema/material-pickers',
root: path.resolve(__dirname, 'packages', 'material-pickers'),
entry: path.resolve(__dirname, 'packages', 'material-pickers/src/'),
externals: {
'@ui-schema/ui-schema': buildExternal('@ui-schema/ui-schema'),
'@ui-schema/ds-material': buildExternal('@ui-schema/ds-material'),
'@material-ui/core': buildExternal('@material-ui/core'),
'@material-ui/icons': buildExternal('@material-ui/icons'),
react: buildExternal('react'),
'react-dom': buildExternal('react-dom'),
},
},
materialRichtext: {
name: '@ui-schema/material-richtext',
root: path.resolve(__dirname, 'packages', 'material-richtext'),
entry: path.resolve(__dirname, 'packages', 'material-richtext/src/'),
externals: {
'@ui-schema/ui-schema': buildExternal('@ui-schema/ui-schema'),
'@ui-schema/ds-material': buildExternal('@ui-schema/ds-material'),
'@material-ui/core': buildExternal('@material-ui/core'),
'@material-ui/icons': buildExternal('@material-ui/icons'),
react: buildExternal('react'),
'react-dom': buildExternal('react-dom'),
draftJs: buildExternal('draft-js'),
draftJsPluginsEditor: buildExternal('draft-js-plugins-editor'),
},
},
materialCode: {
name: '@ui-schema/material-code',
root: path.resolve(__dirname, 'packages', 'material-code'),
entry: path.resolve(__dirname, 'packages', 'material-code/src/'),
externals: {
'@ui-schema/ui-schema': buildExternal('@ui-schema/ui-schema'),
'@ui-schema/ds-material': buildExternal('@ui-schema/ds-material'),
'@material-ui/core': buildExternal('@material-ui/core'),
'@material-ui/icons': buildExternal('@material-ui/icons'),
react: buildExternal('react'),
'react-dom': buildExternal('react-dom'),
reactCodemirror2: buildExternal('react-codemirror2'),
codemirror: buildExternal('codemirror'),
},
},
materialColor: {
name: '@ui-schema/material-color',
root: path.resolve(__dirname, 'packages', 'material-color'),
entry: path.resolve(__dirname, 'packages', 'material-color/src/'),
externals: {
'@ui-schema/ui-schema': buildExternal('@ui-schema/ui-schema'),
'@ui-schema/ds-material': buildExternal('@ui-schema/ds-material'),
'@material-ui/core': buildExternal('@material-ui/core'),
'@material-ui/icons': buildExternal('@material-ui/icons'),
react: buildExternal('react'),
'react-dom': buildExternal('react-dom'),
materialUiColorPicker: buildExternal('material-ui-color-picker'),
},
},
materialEditorJs: {
name: '@ui-schema/material-editorjs',
root: path.resolve(__dirname, 'packages', 'material-editorjs'),
entry: path.resolve(__dirname, 'packages', 'material-editorjs/src/'),
externals: {
'@ui-schema/ui-schema': buildExternal('@ui-schema/ui-schema'),
'@ui-schema/ds-material': buildExternal('@ui-schema/ds-material'),
'@material-ui/core': buildExternal('@material-ui/core'),
'@material-ui/icons': buildExternal('@material-ui/icons'),
react: buildExternal('react'),
'react-dom': buildExternal('react-dom'),
'react-editor-js': buildExternal('react-editor-js'),
'@editorjs/editorjs': buildExternal('@editorjs/editorjs'),
'@editorjs/paragraph': buildExternal('@editorjs/paragraph'),
},
},
materialDnd: {
name: '@ui-schema/material-dnd',
root: path.resolve(__dirname, 'packages', 'material-dnd'),
entry: path.resolve(__dirname, 'packages', 'material-dnd/src/'),
externals: {
'@ui-schema/ui-schema': buildExternal('@ui-schema/ui-schema'),
'@ui-schema/ds-material': buildExternal('@ui-schema/ds-material'),
'@material-ui/core': buildExternal('@material-ui/core'),
'@material-ui/icons': buildExternal('@material-ui/icons'),
react: buildExternal('react'),
'react-dom': buildExternal('react-dom'),
'react-beautiful-dnd': buildExternal('react-beautiful-dnd'),
},
},
};
packer(apps, packages, __dirname);
|
import * as Yup from "yup";
import { Formik } from "formik";
import { useTranslation } from "react-i18next";
import React, { memo } from "react";
import DataModal from "./DataModal";
// import DatabaseContext from "contexts/database/database.provider";
import FormikControl from "containers/FormikContainer/FormikControl";
import ModalEvents from "../constants/ModalEvents";
import { TypedMutation } from "core/mutations";
import { TypedQuery } from "core/queries";
// import Switch from "@material-ui/core/Switch";
import { CREATE_ADDRESS, UPDATE_ADDRESS } from "graphql/mutations";
import { COUNTRIES_QUERY } from "graphql/queries";
import { showNotification } from "helpers";
import { withRouter } from "react-router-dom";
import { useAlert } from "react-alert";
export const TypedCreateAddressMutation = TypedMutation(CREATE_ADDRESS);
export const TypedUpdateAddressMutation = TypedMutation(UPDATE_ADDRESS);
export const TypedCountriesQuery = TypedQuery(COUNTRIES_QUERY);
const initialValues = {
firstName: "",
lastName: "",
companyName: "",
streetAddress1: "",
streetAddress2: "",
city: "",
postalCode: "",
country: "KE",
phone: "",
isDefaultAddress: true,
};
const AddressModal = () => {
const { t } = useTranslation();
const alert = useAlert();
// const { createResume, updateResume } = useContext(DatabaseContext);
const schema = Yup.object().shape({
firstName: Yup.string()
.min(3, t("shared.forms.validation.min", { number: 3 }))
.required(t("shared.forms.validation.required")),
lastName: Yup.string()
.min(3, t("shared.forms.validation.min", { number: 3 }))
.required(t("shared.forms.validation.required")),
companyName: Yup.string()
.min(3, t("shared.forms.validation.min", { number: 3 }))
.required(t("shared.forms.validation.required")),
streetAddress1: Yup.string()
.min(10, t("shared.forms.validation.min", { number: 10 }))
.required(t("shared.forms.validation.required")),
streetAddress2: Yup.string()
.min(10, t("shared.forms.validation.min", { number: 10 }))
.required(t("shared.forms.validation.required")),
city: Yup.string()
.min(3, t("shared.forms.validation.min", { number: 3 }))
.required(t("shared.forms.validation.required")),
phone: Yup.string()
.min(12, t("shared.forms.validation.min", { number: 3 }))
.required(t("shared.forms.validation.required")),
});
// if (!imgPreview) {
// setInitialValues({ name: "", preview: img });
// }
return (
<Formik
validateOnBlur
initialValues={initialValues}
validationSchema={schema}
enableReinitialize
>
{(formik) => (
<TypedCreateAddressMutation
onCompleted={(data, errors) =>
showNotification(
data.accountAddressCreate,
errors,
alert,
"accountErrors",
"Address Created",
formik.setErrors,
)
}
>
{(addressCreate) => {
return (
<TypedUpdateAddressMutation
onCompleted={(data, errors) =>
showNotification(
data.accountAddressUpdate,
errors,
alert,
"accountErrors",
"Address Updated",
formik.setErrors,
)
}
>
{(addressUpdate) => {
return (
<DataModal
title={{
create: "Create Address",
edit: "Edit Address",
}}
onEdit={addressUpdate}
onCreate={addressCreate}
event={ModalEvents.CREATE_ADDRESS_MODAL}
>
<div className="dashboard-list-box-content">
<div className="form grid grid-cols-2 gap-6">
<FormikControl
control="input"
type="text"
label="First Name"
placeholder="Jane"
name="firstName"
/>
<FormikControl
control="input"
type="text"
label="Last Name"
placeholder="Doe"
name="lastName"
/>
</div>
<div className="form grid grid-cols-2 gap-6">
<FormikControl
control="input"
type="text"
label="Street Address 1"
placeholder="Street Address 1"
name="streetAddress1"
/>
<FormikControl
control="input"
type="text"
label="Street Address 2"
placeholder="Street Address 2"
name="streetAddress2"
/>
</div>
<div className="form grid grid-cols-2 gap-6">
<FormikControl
control="input"
type="text"
label="Company Name"
placeholder="e.g. Safaricom PLC"
name="companyName"
/>
<FormikControl
control="phone"
type="phone"
label="Phone Number"
placeholder="e.g. +254 722-123123"
name="phone"
/>
</div>
<div className="form grid grid-cols-2 gap-6">
<FormikControl
control="input"
type="text"
label="City"
placeholder="Nairobi"
name="city"
/>
<FormikControl
control="input"
type="text"
label="Postal Code"
placeholder="00200"
name="postalCode"
/>
</div>
</div>
</DataModal>
);
}}
</TypedUpdateAddressMutation>
);
}}
</TypedCreateAddressMutation>
)}
</Formik>
);
};
export default memo(withRouter(AddressModal));
|
define(function(require) {
require('plugins/es5-array');
var Config = require('config');
var Core = require('core/core');
var Filter = require('core/filter/filter');
var Cache = require('core/cache.dictionary');
var Mustache = require('plugins/mustache.min');
/**
* 数据字典过滤器
*/
var FilterDictionary = Filter.extend(function() {
var filter = this;
/**
* 缓存数据
*/
this.cache = {};
// @override
this.convert = function(name, value) {
if (Cache.getMap(name)) {
var format = Cache.getMap(name)[value];
return format === undefined ? value : format;
}
return value;
}
/**
* 添加过滤字典
*
* 必须确保先预加载,因为表格渲染时格式化数据只能同步进行
*/
this.add = function(names) {
if (!names) return Promise.resolve();
if (!$.isArray(names)) {
names = [names];
}
// 过滤已经加载的字典项
names = names.filter(function(name) {
return !Cache.get(name);
});
return Promise.all(
names
// 修改字典名称变为URL
.map(function(name) {
return Mustache.render(Config.URL.Dictionary, {
code: name
});
})
// 发起请求加载
.map(Core.getJSON)
)
// 缓存 (请求顺序不一定一致,但是items结果顺序由Promise保证和names一致)
.then(function(items) {
names.forEach(function(name, index) {
Cache.save(name, items[index]);
});
})
['catch'](function(result) {
console.error(result);
});
}
});
// 由于要保存缓存数据,数据字典过滤器实例单例化
return new FilterDictionary();
});
|
var searchData=
[
['uart_2ec_838',['uart.c',['../uart_8c.html',1,'']]],
['uart_2eh_839',['uart.h',['../uart_8h.html',1,'']]]
];
|
// Arguments passed into this controller can be accessed via the `$.args` object directly or:
var args = $.args;
Alloy.Collections.instance("NodesTilmeldte");
Alloy.Collections.instance("NodesTilmeldte").fetch();
function transform(model) {
//convert the model to a JSON object
var nodeObject = model.toJSON();
var output = {
"title" : nodeObject.title,
"id" : nodeObject.nid,
"cid" : model.cid,
"dato": nodeObject.dato,
"author": nodeObject.author_realname,
"author_image": nodeObject.author_image,
"address": nodeObject.adresse
};
var dato = moment(output.dato);
output.dato = dato.format("DD.MM.YY");
return output;
}
var buttonSwiped = 0;
function showDelete() {
if(buttonSwiped == 0) {
$.deletebtn.animate({
right:0,
duration:250
});
buttonSwiped++;
} else {
$.deletebtn.animate({
right:"-30%",
duration:250
});
buttonSwiped--;
}
}
$.table.addEventListener('click', function(_event) {
//get the correct approach
//
// The properties synch adapter that is provided by appcelerator does not set the model.id so get
// will never work. See the appcelerator documentation on Backbone Sync Adapters
var model = Alloy.Collections.Nodes.getByCid(_event.rowData.modelId);
Alloy.Globals.id = _event.rowData.nodeId;
var url = "http://drupal.casper-storm.dk/node/" + Alloy.Globals.id + "?_format=json";
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
var response = JSON.parse(this.responseText);
response = {"title": response.title[0].value,
"dato": response.field_dato[0].value,
"kategori": response.field_kategori[0].value,
"adresse": response.field_adresse[0].value,
"person": response.field_person_behov[0].value,
"beskrivelse": response.field_beskrivelse_af_opgave[0].value,
"author_realname": response.field_user_realname[0].value,
"author_image": response.field_user_image[0].value };
//alert(response);
//create the controller and pass the model to it
var detailController = Alloy.createController("opgavedetaljer", {
data : response
}).getView();
//get view returns to root view when no view ID is provided
detailController.open();
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug(e.error);
alert('error' + e.error);
},
timeout : 5000 // in milliseconds
});
// Prepare the connection.
client.open("GET", url);
// Send the request.
client.send();
});
|
// register NC SP83
var sp = gmaps.ags.Util.registerSR(2264, 'PROJCS["NAD_1983_StatePlane_North_Carolina_FIPS_3200_Feet",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["False_Easting",2000000.002616666],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",-79.0],PARAMETER["Standard_Parallel_1",34.33333333333334],PARAMETER["Standard_Parallel_2",36.16666666666666],PARAMETER["Latitude_Of_Origin",33.75],UNIT["Foot_US",0.3048006096012192]]');
function init() {
var url = 'http://maps.ci.charlotte.nc.us/ArcGIS/rest/services/GET/BaseMap/MapServer';
var svc = new gmaps.ags.MapService(url);
google.maps.event.addListenerOnce(svc, 'load', function() {
try {
var tileLayer = new gmaps.ags.TileLayer(svc);
var agsType = new gmaps.ags.MapType([tileLayer], {
name: 'StatePlane'
});
var bnds = svc.getInitialBounds();
var myOptions = {
zoom: 12,
center: bnds.getCenter(),
mapTypeId: 'stateplane',
mapTypeControlOptions: {
mapTypeIds: ['stateplane', google.maps.MapTypeId.ROADMAP]
}
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map.mapTypes.set('stateplane', agsType);
google.maps.event.addListener(map, 'mousemove', function(e) {
window.status = sp.forward([e.latLng.lng(), e.latLng.lat()]).join(',');
})
} catch (e) {
alert(e);
}
});
}
window.onload = init;
|
Date.prototype.getDayOfWeek = function() {
var days = [
"Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag"
];
return days[this.getDay()];
};
Date.prototype.getMonthString = function() {
var months = [
"Januar",
"Februar",
"März",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
];
return months[this.getMonth()];
};
Date.prototype.getFullMinutes = function () {
return ('0' + this.getMinutes()).slice(-2);
};
Date.prototype.getFullHours = function () {
return ('0' + this.getHours()).slice(-2);
};
var Clock = function(greeter) {
this.greeter = greeter;
this.time = $('#time');
this.date = $('#date');
setInterval(this.update.bind(this), 1000);
};
Clock.prototype.update = function() {
var date = new Date();
var time = date.getFullHours() + ':' + date.getFullMinutes();
var dateString = date.getDayOfWeek() + ", " + date.getDate() + ". " + date.getMonthString() + " " + date.getFullYear();
this.time.html(time);
this.date.html(dateString);
};
|
import React from 'react';
import './App.css';
import ProductListContainer from './Containers/ProductListContainer/ProductListContainer';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import ProductDetailsContainer from './Containers/ProductDetailsContainer/ProductDetailsContainer';
import ShoppingCartContainer from './Containers/ShoppingCartContainer/ShoppingCartContainer';
import SignInContainer from './Containers/SignInContainer/SignInContainer';
import RegisterContainer from './Containers/RegisterContainer/RegisterContainer';
function App() {
return (
<Router>
<Switch>
<Route exact path='/' component={ProductListContainer}></Route>
<Route exact path='/cart' component={ShoppingCartContainer}></Route>
<Route exact path='/sign-in' component={SignInContainer}></Route>
<Route exact path='/register' component={RegisterContainer}></Route>
<Route exact path='/:id' component={ProductDetailsContainer}></Route>
</Switch>
</Router>
);
}
export default App;
|
(function () {
'use strict';
angular
.module('flairbiApp')
.factory('JhiMetricsService', JhiMetricsService);
JhiMetricsService.$inject = ['$rootScope', '$http'];
function JhiMetricsService($rootScope, $http) {
var service = {
getMetrics: getMetrics,
threadDump: threadDump
};
return service;
function getMetrics() {
return $http.get('management/metrics').then(function (response) {
return response.data;
});
}
function threadDump() {
return $http.get('management/dump').then(function (response) {
return response.data;
});
}
}
})();
|
import controller from './models.controller';
import template from './models.html';
export default {
bindings: {
addModel: '<',
namespaces: '<',
deleteModel: '<',
generateToken: '<',
updateModel: '<',
namespaceId: '<',
models: '<',
projectId: '<',
project: '<',
},
template,
controller,
};
|
"use strict";
var aName = 'lisi';
var dAge = 18;
dAge = 18.13;
dAge = 17;
var isSingleDog = true;
isSingleDog = false;
var undef = undefined;
var nul = null;
//5.数组
//let arrJS = [1,'a',true,[],{}]
var arrHero = ['test1', 'test2'];
var arrHeroAge = [18, 21];
//7元组
var tup1 = ['test1', 18, true];
console.log(tup1[0]);
console.log(tup1.length);
//8 枚举
var Gender;
(function (Gender) {
Gender[Gender["Boy"] = 1] = "Boy";
Gender[Gender["Girl"] = 2] = "Girl";
Gender[Gender["Unknown"] = 3] = "Unknown";
})(Gender || (Gender = {}));
console.log(Gender.Boy);
console.log(Gender.Girl);
|
const {Usuario} = require('../models');
const Sequelize = require('sequelize');
const Op = Sequelize.Op
const IndexController = {
async index(req,res){
let {page = 1} = req.query
let {count:total, rows:users} = await Usuario.findAndCountAll({
limit:5,
offset:(page - 1)* 5
});
let totalPagina = Math.round(total/5)
return res.render('usuarios',{users,totalPagina})
},
async findById(req,res){
let {id} = req.params;
let user = await Usuario.findOne({
where:{
id_usuario:id
}
});
return res.render('viewUsuario',{user})
},
create(req,res){
return res.render('cadastroUsuario')
},
async store (req,res){
const {nome, email, senha} = req.body;
console.log(nome,email,senha)
const resultado = await Usuario.create({
nome,
email,
senha
});
// log usado apenas pra testes
console.log(resultado)
return res.redirect('/')
},
//atualizando usuario = update--------------------------------------
// mostrando a tela de edição
async edit(req,res){
const {id} = req.params
const usuario = await Usuario.findByPk(id);
return res.render('editarUsuario',{usuario})
},
async update(req,res){
const {id} = req.params
const {nome, email, senha} = req.body
const resultado = await Usuario.update({
nome,
email,
senha
},
{
where:{
id_usuario:id
}
})
console.log(resultado)
return res.redirect('/')
},
//deletando
async destroy(req,res){
const {id} = req.params
const resultado = await Usuario.destroy({
where:{
id_usuario: id
}
})
console.log(resultado)
return res.redirect('/')
}
}
module.exports = IndexController;
|
var CMsg=function()
{
}
CMsg.E=function(_msg)
{
alert(_msg);
}
|
// ==================
// MediaRecorder.js
/**
* Implementation of https://dvcs.w3.org/hg/dap/raw-file/default/media-stream-capture/MediaRecorder.html
* The MediaRecorder accepts a mediaStream as input source passed from UA. When recorder starts,
* a MediaEncoder will be created and accept the mediaStream as input source.
* Encoder will get the raw data by track data changes, encode it by selected MIME Type, then store the encoded in EncodedBufferCache object.
* The encoded data will be extracted on every timeslice passed from Start function call or by RequestData function.
* Thread model:
* When the recorder starts, it creates a "Media Encoder" thread to read data from MediaEncoder object and store buffer in EncodedBufferCache object.
* Also extract the encoded data and create blobs on every timeslice passed from start function or RequestData function called by UA.
*/
function MediaRecorderWrapper(mediaStream) {
var self = this;
/**
* This method records MediaStream.
* @method
* @memberof MediaStreamRecorder
* @example
* recorder.start(5000);
*/
this.start = function(timeSlice, __disableLogs) {
this.timeSlice = timeSlice || 5000;
if (!self.mimeType) {
self.mimeType = 'video/webm';
}
if (self.mimeType.indexOf('audio') !== -1) {
if (mediaStream.getVideoTracks().length && mediaStream.getAudioTracks().length) {
var stream;
if (!!navigator.mozGetUserMedia) {
stream = new MediaStream();
stream.addTrack(mediaStream.getAudioTracks()[0]);
} else {
// webkitMediaStream
stream = new MediaStream(mediaStream.getAudioTracks());
}
mediaStream = stream;
}
}
if (self.mimeType.indexOf('audio') !== -1) {
self.mimeType = IsChrome ? 'audio/webm' : 'audio/ogg';
}
self.dontFireOnDataAvailableEvent = false;
var recorderHints = {
mimeType: self.mimeType
};
if (!self.disableLogs && !__disableLogs) {
console.log('Passing following params over MediaRecorder API.', recorderHints);
}
if (mediaRecorder) {
// mandatory to make sure Firefox doesn't fails to record streams 3-4 times without reloading the page.
mediaRecorder = null;
}
if (IsChrome && !isMediaRecorderCompatible()) {
// to support video-only recording on stable
recorderHints = 'video/vp8';
}
// http://dxr.mozilla.org/mozilla-central/source/content/media/MediaRecorder.cpp
// https://wiki.mozilla.org/Gecko:MediaRecorder
// https://dvcs.w3.org/hg/dap/raw-file/default/media-stream-capture/MediaRecorder.html
// starting a recording session; which will initiate "Reading Thread"
// "Reading Thread" are used to prevent main-thread blocking scenarios
try {
mediaRecorder = new MediaRecorder(mediaStream, recorderHints);
} catch (e) {
// if someone passed NON_supported mimeType
// or if Firefox on Android
mediaRecorder = new MediaRecorder(mediaStream);
}
if ('canRecordMimeType' in mediaRecorder && mediaRecorder.canRecordMimeType(self.mimeType) === false) {
if (!self.disableLogs) {
console.warn('MediaRecorder API seems unable to record mimeType:', self.mimeType);
}
}
// i.e. stop recording when <video> is paused by the user; and auto restart recording
// when video is resumed. E.g. yourStream.getVideoTracks()[0].muted = true; // it will auto-stop recording.
if (self.ignoreMutedMedia === true) {
mediaRecorder.ignoreMutedMedia = true;
}
var firedOnDataAvailableOnce = false;
// Dispatching OnDataAvailable Handler
mediaRecorder.ondataavailable = function(e) {
// how to fix FF-corrupt-webm issues?
// should we leave this? e.data.size < 26800
if (!e.data || !e.data.size || e.data.size < 26800 || firedOnDataAvailableOnce) {
return;
}
firedOnDataAvailableOnce = true;
var blob = self.getNativeBlob ? e.data : new Blob([e.data], {
type: self.mimeType || 'video/webm'
});
self.ondataavailable(blob);
// self.dontFireOnDataAvailableEvent = true;
if (!!mediaRecorder && mediaRecorder.state === 'recording') {
mediaRecorder.stop();
}
mediaRecorder = null;
if (self.dontFireOnDataAvailableEvent) {
return;
}
// record next interval
self.start(timeSlice, '__disableLogs');
};
mediaRecorder.onerror = function(error) {
if (!self.disableLogs) {
if (error.name === 'InvalidState') {
console.error('The MediaRecorder is not in a state in which the proposed operation is allowed to be executed.');
} else if (error.name === 'OutOfMemory') {
console.error('The UA has exhaused the available memory. User agents SHOULD provide as much additional information as possible in the message attribute.');
} else if (error.name === 'IllegalStreamModification') {
console.error('A modification to the stream has occurred that makes it impossible to continue recording. An example would be the addition of a Track while recording is occurring. User agents SHOULD provide as much additional information as possible in the message attribute.');
} else if (error.name === 'OtherRecordingError') {
console.error('Used for an fatal error other than those listed above. User agents SHOULD provide as much additional information as possible in the message attribute.');
} else if (error.name === 'GenericError') {
console.error('The UA cannot provide the codec or recording option that has been requested.', error);
} else {
console.error('MediaRecorder Error', error);
}
}
// When the stream is "ended" set recording to 'inactive'
// and stop gathering data. Callers should not rely on
// exactness of the timeSlice value, especially
// if the timeSlice value is small. Callers should
// consider timeSlice as a minimum value
if (!!mediaRecorder && mediaRecorder.state !== 'inactive' && mediaRecorder.state !== 'stopped') {
mediaRecorder.stop();
}
};
// void start(optional long mTimeSlice)
// The interval of passing encoded data from EncodedBufferCache to onDataAvailable
// handler. "mTimeSlice < 0" means Session object does not push encoded data to
// onDataAvailable, instead, it passive wait the client side pull encoded data
// by calling requestData API.
try {
mediaRecorder.start(3.6e+6);
} catch (e) {
mediaRecorder = null;
}
setTimeout(function() {
if (!mediaRecorder) {
return;
}
if (mediaRecorder.state === 'recording') {
// "stop" method auto invokes "requestData"!
mediaRecorder.requestData();
// mediaRecorder.stop();
}
}, timeSlice);
// Start recording. If timeSlice has been provided, mediaRecorder will
// raise a dataavailable event containing the Blob of collected data on every timeSlice milliseconds.
// If timeSlice isn't provided, UA should call the RequestData to obtain the Blob data, also set the mTimeSlice to zero.
};
/**
* This method stops recording MediaStream.
* @param {function} callback - Callback function, that is used to pass recorded blob back to the callee.
* @method
* @memberof MediaStreamRecorder
* @example
* recorder.stop(function(blob) {
* video.src = URL.createObjectURL(blob);
* });
*/
this.stop = function(callback) {
if (!mediaRecorder) {
return;
}
// mediaRecorder.state === 'recording' means that media recorder is associated with "session"
// mediaRecorder.state === 'stopped' means that media recorder is detached from the "session" ... in this case; "session" will also be deleted.
if (mediaRecorder.state === 'recording') {
// "stop" method auto invokes "requestData"!
mediaRecorder.requestData();
setTimeout(function() {
self.dontFireOnDataAvailableEvent = true;
if (!!mediaRecorder && mediaRecorder.state === 'recording') {
mediaRecorder.stop();
}
mediaRecorder = null;
self.onstop();
}, 2000);
}
};
/**
* This method pauses the recording process.
* @method
* @memberof MediaStreamRecorder
* @example
* recorder.pause();
*/
this.pause = function() {
if (!mediaRecorder) {
return;
}
if (mediaRecorder.state === 'recording') {
mediaRecorder.pause();
}
this.dontFireOnDataAvailableEvent = true;
};
/**
* The recorded blobs are passed over this event.
* @event
* @memberof MediaStreamRecorder
* @example
* recorder.ondataavailable = function(data) {};
*/
this.ondataavailable = function(blob) {
console.log('recorded-blob', blob);
};
/**
* This method resumes the recording process.
* @method
* @memberof MediaStreamRecorder
* @example
* recorder.resume();
*/
this.resume = function() {
if (this.dontFireOnDataAvailableEvent) {
this.dontFireOnDataAvailableEvent = false;
var disableLogs = self.disableLogs;
self.disableLogs = true;
this.start(this.timeslice || 5000);
self.disableLogs = disableLogs;
return;
}
if (!mediaRecorder) {
return;
}
if (mediaRecorder.state === 'paused') {
mediaRecorder.resume();
}
};
/**
* This method resets currently recorded data.
* @method
* @memberof MediaStreamRecorder
* @example
* recorder.clearRecordedData();
*/
this.clearRecordedData = function() {
if (!mediaRecorder) {
return;
}
this.pause();
this.dontFireOnDataAvailableEvent = true;
this.stop();
};
this.onstop = function() {};
// Reference to "MediaRecorder" object
var mediaRecorder;
function isMediaStreamActive() {
if ('active' in mediaStream) {
if (!mediaStream.active) {
return false;
}
} else if ('ended' in mediaStream) { // old hack
if (mediaStream.ended) {
return false;
}
}
return true;
}
// this method checks if media stream is stopped
// or any track is ended.
(function looper() {
if (!mediaRecorder) {
return;
}
if (isMediaStreamActive() === false) {
self.stop();
return;
}
setTimeout(looper, 1000); // check every second
})();
}
if (typeof MediaStreamRecorder !== 'undefined') {
MediaStreamRecorder.MediaRecorderWrapper = MediaRecorderWrapper;
}
|
/* Copyright 2012 Mozilla Foundation
*
* 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.
*/
/* globals PDFJS, PDFBug, FirefoxCom, Stats, ProgressBar,
DownloadManager, getFileName, getPDFFileNameFromURL,
PDFHistory, Preferences, SidebarView, ViewHistory, Stats,
PDFThumbnailViewer, URL, noContextMenuHandler, SecondaryToolbar,
PasswordPrompt, PDFPresentationMode, PDFDocumentProperties, HandTool,
Promise, PDFLinkService, PDFOutlineView, PDFAttachmentView,
OverlayManager, PDFFindController, PDFFindBar, PDFViewer,
PDFRenderingQueue, PresentationModeState, parseQueryString,
RenderingStates, UNKNOWN_SCALE, DEFAULT_SCALE_VALUE,
IGNORE_CURRENT_POSITION_ON_ZOOM: true */
'use strict';
var DEFAULT_URL = '../data/MAKE-IT_D1.3.pdf';
var DEFAULT_SCALE_DELTA = 1.1;
var MIN_SCALE = 0.25;
var MAX_SCALE = 10.0;
var SCALE_SELECT_CONTAINER_PADDING = 8;
var SCALE_SELECT_PADDING = 22;
var PAGE_NUMBER_LOADING_INDICATOR = 'visiblePageIsLoading';
var DISABLE_AUTO_FETCH_LOADING_BAR_TIMEOUT = 5000;
function configure(PDFJS) {
PDFJS.imageResourcesPath = '../v0.2/bower_components/pdfjs-dist/web/images/';
PDFJS.workerSrc = '../v0.2/bower_components/pdfjs-dist/build/pdf.worker.js';
PDFJS.cMapUrl = '../v0.2bower_components/pdfjs-dist/cmaps/';
PDFJS.cMapPacked = true;
}
var mozL10n = document.mozL10n || document.webL10n;
var CSS_UNITS = 96.0 / 72.0;
var DEFAULT_SCALE_VALUE = 'auto';
var DEFAULT_SCALE = 1.0;
var UNKNOWN_SCALE = 0;
var MAX_AUTO_SCALE = 1.25;
var SCROLLBAR_PADDING = 40;
var VERTICAL_PADDING = 5;
function getFileName(url) {
var anchor = url.indexOf('#');
var query = url.indexOf('?');
var end = Math.min(
anchor > 0 ? anchor : url.length,
query > 0 ? query : url.length);
return url.substring(url.lastIndexOf('/', end) + 1, end);
}
/**
* Returns scale factor for the canvas. It makes sense for the HiDPI displays.
* @return {Object} The object with horizontal (sx) and vertical (sy)
scales. The scaled property is set to false if scaling is
not required, true otherwise.
*/
function getOutputScale(ctx) {
var devicePixelRatio = window.devicePixelRatio || 1;
var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio || 1;
var pixelRatio = devicePixelRatio / backingStoreRatio;
return {
sx: pixelRatio,
sy: pixelRatio,
scaled: pixelRatio !== 1
};
}
/**
* Scrolls specified element into view of its parent.
* @param {Object} element - The element to be visible.
* @param {Object} spot - An object with optional top and left properties,
* specifying the offset from the top left edge.
* @param {boolean} skipOverflowHiddenElements - Ignore elements that have
* the CSS rule `overflow: hidden;` set. The default is false.
*/
function scrollIntoView(element, spot, skipOverflowHiddenElements) {
// Assuming offsetParent is available (it's not available when viewer is in
// hidden iframe or object). We have to scroll: if the offsetParent is not set
// producing the error. See also animationStartedClosure.
var parent = element.offsetParent;
if (!parent) {
console.error('offsetParent is not set -- cannot scroll');
return;
}
var checkOverflow = skipOverflowHiddenElements || false;
var offsetY = element.offsetTop + element.clientTop;
var offsetX = element.offsetLeft + element.clientLeft;
while (parent.clientHeight === parent.scrollHeight ||
(checkOverflow && getComputedStyle(parent).overflow === 'hidden')) {
if (parent.dataset._scaleY) {
offsetY /= parent.dataset._scaleY;
offsetX /= parent.dataset._scaleX;
}
offsetY += parent.offsetTop;
offsetX += parent.offsetLeft;
parent = parent.offsetParent;
if (!parent) {
return; // no need to scroll
}
}
if (spot) {
if (spot.top !== undefined) {
offsetY += spot.top;
}
if (spot.left !== undefined) {
offsetX += spot.left;
parent.scrollLeft = offsetX;
}
}
parent.scrollTop = offsetY;
}
/**
* Helper function to start monitoring the scroll event and converting them into
* PDF.js friendly one: with scroll debounce and scroll direction.
*/
function watchScroll(viewAreaElement, callback) {
var debounceScroll = function debounceScroll(evt) {
if (rAF) {
return;
}
// schedule an invocation of scroll for next animation frame.
rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
rAF = null;
var currentY = viewAreaElement.scrollTop;
var lastY = state.lastY;
if (currentY !== lastY) {
state.down = currentY > lastY;
}
state.lastY = currentY;
callback(state);
});
};
var state = {
down: true,
lastY: viewAreaElement.scrollTop,
_eventHandler: debounceScroll
};
var rAF = null;
viewAreaElement.addEventListener('scroll', debounceScroll, true);
return state;
}
/**
* Helper function to parse query string (e.g. ?param1=value&parm2=...).
*/
function parseQueryString(query) {
var parts = query.split('&');
var params = {};
for (var i = 0, ii = parts.length; i < ii; ++i) {
var param = parts[i].split('=');
var key = param[0].toLowerCase();
var value = param.length > 1 ? param[1] : null;
params[decodeURIComponent(key)] = decodeURIComponent(value);
}
return params;
}
/**
* Use binary search to find the index of the first item in a given array which
* passes a given condition. The items are expected to be sorted in the sense
* that if the condition is true for one item in the array, then it is also true
* for all following items.
*
* @returns {Number} Index of the first array element to pass the test,
* or |items.length| if no such element exists.
*/
function binarySearchFirstItem(items, condition) {
var minIndex = 0;
var maxIndex = items.length - 1;
if (items.length === 0 || !condition(items[maxIndex])) {
return items.length;
}
if (condition(items[minIndex])) {
return minIndex;
}
while (minIndex < maxIndex) {
var currentIndex = (minIndex + maxIndex) >> 1;
var currentItem = items[currentIndex];
if (condition(currentItem)) {
maxIndex = currentIndex;
} else {
minIndex = currentIndex + 1;
}
}
return minIndex; /* === maxIndex */
}
/**
* Approximates float number as a fraction using Farey sequence (max order
* of 8).
* @param {number} x - Positive float number.
* @returns {Array} Estimated fraction: the first array item is a numerator,
* the second one is a denominator.
*/
function approximateFraction(x) {
// Fast paths for int numbers or their inversions.
if (Math.floor(x) === x) {
return [x, 1];
}
var xinv = 1 / x;
var limit = 8;
if (xinv > limit) {
return [1, limit];
} else if (Math.floor(xinv) === xinv) {
return [1, xinv];
}
var x_ = x > 1 ? xinv : x;
// a/b and c/d are neighbours in Farey sequence.
var a = 0, b = 1, c = 1, d = 1;
// Limiting search to order 8.
while (true) {
// Generating next term in sequence (order of q).
var p = a + c, q = b + d;
if (q > limit) {
break;
}
if (x_ <= p / q) {
c = p; d = q;
} else {
a = p; b = q;
}
}
// Select closest of the neighbours to x.
if (x_ - a / b < c / d - x_) {
return x_ === x ? [a, b] : [b, a];
} else {
return x_ === x ? [c, d] : [d, c];
}
}
function roundToDivide(x, div) {
var r = x % div;
return r === 0 ? x : Math.round(x - r + div);
}
/**
* Generic helper to find out what elements are visible within a scroll pane.
*/
function getVisibleElements(scrollEl, views, sortByVisibility) {
var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
function isElementBottomBelowViewTop(view) {
var element = view.div;
var elementBottom =
element.offsetTop + element.clientTop + element.clientHeight;
return elementBottom > top;
}
var visible = [], view, element;
var currentHeight, viewHeight, hiddenHeight, percentHeight;
var currentWidth, viewWidth;
var firstVisibleElementInd = (views.length === 0) ? 0 :
binarySearchFirstItem(views, isElementBottomBelowViewTop);
for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
view = views[i];
element = view.div;
currentHeight = element.offsetTop + element.clientTop;
viewHeight = element.clientHeight;
if (currentHeight > bottom) {
break;
}
currentWidth = element.offsetLeft + element.clientLeft;
viewWidth = element.clientWidth;
if (currentWidth + viewWidth < left || currentWidth > right) {
continue;
}
hiddenHeight = Math.max(0, top - currentHeight) +
Math.max(0, currentHeight + viewHeight - bottom);
percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;
visible.push({
id: view.id,
x: currentWidth,
y: currentHeight,
view: view,
percent: percentHeight
});
}
var first = visible[0];
var last = visible[visible.length - 1];
if (sortByVisibility) {
visible.sort(function(a, b) {
var pc = a.percent - b.percent;
if (Math.abs(pc) > 0.001) {
return -pc;
}
return a.id - b.id; // ensure stability
});
}
return {first: first, last: last, views: visible};
}
/**
* Event handler to suppress context menu.
*/
function noContextMenuHandler(e) {
e.preventDefault();
}
/**
* Returns the filename or guessed filename from the url (see issue 3455).
* url {String} The original PDF location.
* @return {String} Guessed PDF file name.
*/
function getPDFFileNameFromURL(url) {
var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
// SCHEME HOST 1.PATH 2.QUERY 3.REF
// Pattern to get last matching NAME.pdf
var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
var splitURI = reURI.exec(url);
var suggestedFilename = reFilename.exec(splitURI[1]) ||
reFilename.exec(splitURI[2]) ||
reFilename.exec(splitURI[3]);
if (suggestedFilename) {
suggestedFilename = suggestedFilename[0];
if (suggestedFilename.indexOf('%') !== -1) {
// URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
try {
suggestedFilename =
reFilename.exec(decodeURIComponent(suggestedFilename))[0];
} catch(e) { // Possible (extremely rare) errors:
// URIError "Malformed URI", e.g. for "%AA.pdf"
// TypeError "null has no properties", e.g. for "%2F.pdf"
}
}
}
return suggestedFilename || 'document.pdf';
}
var ProgressBar = (function ProgressBarClosure() {
function clamp(v, min, max) {
return Math.min(Math.max(v, min), max);
}
function ProgressBar(id, opts) {
this.visible = true;
// Fetch the sub-elements for later.
this.div = document.querySelector(id + ' .progress');
// Get the loading bar element, so it can be resized to fit the viewer.
this.bar = this.div.parentNode;
// Get options, with sensible defaults.
this.height = opts.height || 100;
this.width = opts.width || 100;
this.units = opts.units || '%';
// Initialize heights.
this.div.style.height = this.height + this.units;
this.percent = 0;
}
ProgressBar.prototype = {
updateBar: function ProgressBar_updateBar() {
if (this._indeterminate) {
this.div.classList.add('indeterminate');
this.div.style.width = this.width + this.units;
return;
}
this.div.classList.remove('indeterminate');
var progressSize = this.width * this._percent / 100;
this.div.style.width = progressSize + this.units;
},
get percent() {
return this._percent;
},
set percent(val) {
this._indeterminate = isNaN(val);
this._percent = clamp(val, 0, 100);
this.updateBar();
},
setWidth: function ProgressBar_setWidth(viewer) {
if (viewer) {
var container = viewer.parentNode;
var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
if (scrollbarWidth > 0) {
this.bar.setAttribute('style', 'width: calc(100% - ' +
scrollbarWidth + 'px);');
}
}
},
hide: function ProgressBar_hide() {
if (!this.visible) {
return;
}
this.visible = false;
this.bar.classList.add('hidden');
document.body.classList.remove('loadingInProgress');
},
show: function ProgressBar_show() {
if (this.visible) {
return;
}
this.visible = true;
document.body.classList.add('loadingInProgress');
this.bar.classList.remove('hidden');
}
};
return ProgressBar;
})();
var DEFAULT_PREFERENCES = {
showPreviousViewOnLoad: true,
defaultZoomValue: '',
sidebarViewOnLoad: 0,
enableHandToolOnLoad: false,
enableWebGL: false,
pdfBugEnabled: false,
disableRange: false,
disableStream: false,
disableAutoFetch: false,
disableFontFace: false,
disableTextLayer: false,
useOnlyCssZoom: false,
externalLinkTarget: 0,
};
var SidebarView = {
NONE: 0,
THUMBS: 1,
OUTLINE: 2,
ATTACHMENTS: 3
};
/**
* Preferences - Utility for storing persistent settings.
* Used for settings that should be applied to all opened documents,
* or every time the viewer is loaded.
*/
var Preferences = {
prefs: Object.create(DEFAULT_PREFERENCES),
isInitializedPromiseResolved: false,
initializedPromise: null,
/**
* Initialize and fetch the current preference values from storage.
* @return {Promise} A promise that is resolved when the preferences
* have been initialized.
*/
initialize: function preferencesInitialize() {
return this.initializedPromise =
this._readFromStorage(DEFAULT_PREFERENCES).then(function(prefObj) {
this.isInitializedPromiseResolved = true;
if (prefObj) {
this.prefs = prefObj;
}
}.bind(this));
},
/**
* Stub function for writing preferences to storage.
* NOTE: This should be overridden by a build-specific function defined below.
* @param {Object} prefObj The preferences that should be written to storage.
* @return {Promise} A promise that is resolved when the preference values
* have been written.
*/
_writeToStorage: function preferences_writeToStorage(prefObj) {
return Promise.resolve();
},
/**
* Stub function for reading preferences from storage.
* NOTE: This should be overridden by a build-specific function defined below.
* @param {Object} prefObj The preferences that should be read from storage.
* @return {Promise} A promise that is resolved with an {Object} containing
* the preferences that have been read.
*/
_readFromStorage: function preferences_readFromStorage(prefObj) {
return Promise.resolve();
},
/**
* Reset the preferences to their default values and update storage.
* @return {Promise} A promise that is resolved when the preference values
* have been reset.
*/
reset: function preferencesReset() {
return this.initializedPromise.then(function() {
this.prefs = Object.create(DEFAULT_PREFERENCES);
return this._writeToStorage(DEFAULT_PREFERENCES);
}.bind(this));
},
/**
* Replace the current preference values with the ones from storage.
* @return {Promise} A promise that is resolved when the preference values
* have been updated.
*/
reload: function preferencesReload() {
return this.initializedPromise.then(function () {
this._readFromStorage(DEFAULT_PREFERENCES).then(function(prefObj) {
if (prefObj) {
this.prefs = prefObj;
}
}.bind(this));
}.bind(this));
},
/**
* Set the value of a preference.
* @param {string} name The name of the preference that should be changed.
* @param {boolean|number|string} value The new value of the preference.
* @return {Promise} A promise that is resolved when the value has been set,
* provided that the preference exists and the types match.
*/
set: function preferencesSet(name, value) {
return this.initializedPromise.then(function () {
if (DEFAULT_PREFERENCES[name] === undefined) {
throw new Error('preferencesSet: \'' + name + '\' is undefined.');
} else if (value === undefined) {
throw new Error('preferencesSet: no value is specified.');
}
var valueType = typeof value;
var defaultType = typeof DEFAULT_PREFERENCES[name];
if (valueType !== defaultType) {
if (valueType === 'number' && defaultType === 'string') {
value = value.toString();
} else {
throw new Error('Preferences_set: \'' + value + '\' is a \"' +
valueType + '\", expected \"' + defaultType + '\".');
}
} else {
if (valueType === 'number' && (value | 0) !== value) {
throw new Error('Preferences_set: \'' + value +
'\' must be an \"integer\".');
}
}
this.prefs[name] = value;
return this._writeToStorage(this.prefs);
}.bind(this));
},
/**
* Get the value of a preference.
* @param {string} name The name of the preference whose value is requested.
* @return {Promise} A promise that is resolved with a {boolean|number|string}
* containing the value of the preference.
*/
get: function preferencesGet(name) {
return this.initializedPromise.then(function () {
var defaultValue = DEFAULT_PREFERENCES[name];
if (defaultValue === undefined) {
throw new Error('preferencesGet: \'' + name + '\' is undefined.');
} else {
var prefValue = this.prefs[name];
if (prefValue !== undefined) {
return prefValue;
}
}
return defaultValue;
}.bind(this));
}
};
Preferences._writeToStorage = function (prefObj) {
return new Promise(function (resolve) {
localStorage.setItem('pdfjs.preferences', JSON.stringify(prefObj));
resolve();
});
};
Preferences._readFromStorage = function (prefObj) {
return new Promise(function (resolve) {
var readPrefs = JSON.parse(localStorage.getItem('pdfjs.preferences'));
resolve(readPrefs);
});
};
(function mozPrintCallbackPolyfillClosure() {
if ('mozPrintCallback' in document.createElement('canvas')) {
return;
}
// Cause positive result on feature-detection:
HTMLCanvasElement.prototype.mozPrintCallback = undefined;
var canvases; // During print task: non-live NodeList of <canvas> elements
var index; // Index of <canvas> element that is being processed
var print = window.print;
window.print = function print() {
if (canvases) {
console.warn('Ignored window.print() because of a pending print job.');
return;
}
try {
dispatchEvent('beforeprint');
} finally {
canvases = document.querySelectorAll('canvas');
index = -1;
next();
}
};
function dispatchEvent(eventType) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent(eventType, false, false, 'custom');
window.dispatchEvent(event);
}
function next() {
if (!canvases) {
return; // Print task cancelled by user (state reset in abort())
}
renderProgress();
if (++index < canvases.length) {
var canvas = canvases[index];
if (typeof canvas.mozPrintCallback === 'function') {
canvas.mozPrintCallback({
context: canvas.getContext('2d'),
abort: abort,
done: next
});
} else {
next();
}
} else {
renderProgress();
print.call(window);
setTimeout(abort, 20); // Tidy-up
}
}
function abort() {
if (canvases) {
canvases = null;
renderProgress();
dispatchEvent('afterprint');
}
}
function renderProgress() {
var progressContainer = document.getElementById('mozPrintCallback-shim');
if (canvases && canvases.length) {
var progress = Math.round(100 * index / canvases.length);
var progressBar = progressContainer.querySelector('progress');
var progressPerc = progressContainer.querySelector('.relative-progress');
progressBar.value = progress;
progressPerc.textContent = progress + '%';
progressContainer.removeAttribute('hidden');
progressContainer.onclick = abort;
} else {
progressContainer.setAttribute('hidden', '');
}
}
var hasAttachEvent = !!document.attachEvent;
window.addEventListener('keydown', function(event) {
// Intercept Cmd/Ctrl + P in all browsers.
// Also intercept Cmd/Ctrl + Shift + P in Chrome and Opera
if (event.keyCode === 80/*P*/ && (event.ctrlKey || event.metaKey) &&
!event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
window.print();
if (hasAttachEvent) {
// Only attachEvent can cancel Ctrl + P dialog in IE <=10
// attachEvent is gone in IE11, so the dialog will re-appear in IE11.
return;
}
event.preventDefault();
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
event.stopPropagation();
}
return;
}
if (event.keyCode === 27 && canvases) { // Esc
abort();
}
}, true);
if (hasAttachEvent) {
document.attachEvent('onkeydown', function(event) {
event = event || window.event;
if (event.keyCode === 80/*P*/ && event.ctrlKey) {
event.keyCode = 0;
return false;
}
});
}
if ('onbeforeprint' in window) {
// Do not propagate before/afterprint events when they are not triggered
// from within this polyfill. (FF/IE).
var stopPropagationIfNeeded = function(event) {
if (event.detail !== 'custom' && event.stopImmediatePropagation) {
event.stopImmediatePropagation();
}
};
window.addEventListener('beforeprint', stopPropagationIfNeeded, false);
window.addEventListener('afterprint', stopPropagationIfNeeded, false);
}
})();
var DownloadManager = (function DownloadManagerClosure() {
function download(blobUrl, filename) {
var a = document.createElement('a');
if (a.click) {
// Use a.click() if available. Otherwise, Chrome might show
// "Unsafe JavaScript attempt to initiate a navigation change
// for frame with URL" and not open the PDF at all.
// Supported by (not mentioned = untested):
// - Firefox 6 - 19 (4- does not support a.click, 5 ignores a.click)
// - Chrome 19 - 26 (18- does not support a.click)
// - Opera 9 - 12.15
// - Internet Explorer 6 - 10
// - Safari 6 (5.1- does not support a.click)
a.href = blobUrl;
a.target = '_parent';
// Use a.download if available. This increases the likelihood that
// the file is downloaded instead of opened by another PDF plugin.
if ('download' in a) {
a.download = filename;
}
// <a> must be in the document for IE and recent Firefox versions.
// (otherwise .click() is ignored)
(document.body || document.documentElement).appendChild(a);
a.click();
a.parentNode.removeChild(a);
} else {
if (window.top === window &&
blobUrl.split('#')[0] === window.location.href.split('#')[0]) {
// If _parent == self, then opening an identical URL with different
// location hash will only cause a navigation, not a download.
var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&';
blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&');
}
window.open(blobUrl, '_parent');
}
}
function DownloadManager() {}
DownloadManager.prototype = {
downloadUrl: function DownloadManager_downloadUrl(url, filename) {
if (!PDFJS.isValidUrl(url, true)) {
return; // restricted/invalid URL
}
download(url + '#pdfjs.action=download', filename);
},
downloadData: function DownloadManager_downloadData(data, filename,
contentType) {
if (navigator.msSaveBlob) { // IE10 and above
return navigator.msSaveBlob(new Blob([data], { type: contentType }),
filename);
}
var blobUrl = PDFJS.createObjectURL(data, contentType);
download(blobUrl, filename);
},
download: function DownloadManager_download(blob, url, filename) {
if (!URL) {
// URL.createObjectURL is not supported
this.downloadUrl(url, filename);
return;
}
if (navigator.msSaveBlob) {
// IE10 / IE11
if (!navigator.msSaveBlob(blob, filename)) {
this.downloadUrl(url, filename);
}
return;
}
var blobUrl = URL.createObjectURL(blob);
download(blobUrl, filename);
}
};
return DownloadManager;
})();
var DEFAULT_VIEW_HISTORY_CACHE_SIZE = 20;
/**
* View History - This is a utility for saving various view parameters for
* recently opened files.
*
* The way that the view parameters are stored depends on how PDF.js is built,
* for 'node make <flag>' the following cases exist:
* - FIREFOX or MOZCENTRAL - uses sessionStorage.
* - GENERIC or CHROME - uses localStorage, if it is available.
*/
var ViewHistory = (function ViewHistoryClosure() {
function ViewHistory(fingerprint, cacheSize) {
this.fingerprint = fingerprint;
this.cacheSize = cacheSize || DEFAULT_VIEW_HISTORY_CACHE_SIZE;
this.isInitializedPromiseResolved = false;
this.initializedPromise =
this._readFromStorage().then(function (databaseStr) {
this.isInitializedPromiseResolved = true;
var database = JSON.parse(databaseStr || '{}');
if (!('files' in database)) {
database.files = [];
}
if (database.files.length >= this.cacheSize) {
database.files.shift();
}
var index;
for (var i = 0, length = database.files.length; i < length; i++) {
var branch = database.files[i];
if (branch.fingerprint === this.fingerprint) {
index = i;
break;
}
}
if (typeof index !== 'number') {
index = database.files.push({fingerprint: this.fingerprint}) - 1;
}
this.file = database.files[index];
this.database = database;
}.bind(this));
}
ViewHistory.prototype = {
_writeToStorage: function ViewHistory_writeToStorage() {
return new Promise(function (resolve) {
var databaseStr = JSON.stringify(this.database);
localStorage.setItem('database', databaseStr);
resolve();
}.bind(this));
},
_readFromStorage: function ViewHistory_readFromStorage() {
return new Promise(function (resolve) {
resolve(localStorage.getItem('database'));
});
},
set: function ViewHistory_set(name, val) {
if (!this.isInitializedPromiseResolved) {
return;
}
this.file[name] = val;
return this._writeToStorage();
},
setMultiple: function ViewHistory_setMultiple(properties) {
if (!this.isInitializedPromiseResolved) {
return;
}
for (var name in properties) {
this.file[name] = properties[name];
}
return this._writeToStorage();
},
get: function ViewHistory_get(name, defaultValue) {
if (!this.isInitializedPromiseResolved) {
return defaultValue;
}
return this.file[name] || defaultValue;
}
};
return ViewHistory;
})();
/**
* Creates a "search bar" given a set of DOM elements that act as controls
* for searching or for setting search preferences in the UI. This object
* also sets up the appropriate events for the controls. Actual searching
* is done by PDFFindController.
*/
var PDFFindBar = (function PDFFindBarClosure() {
function PDFFindBar(options) {
this.opened = false;
this.bar = options.bar || null;
this.toggleButton = options.toggleButton || null;
this.findField = options.findField || null;
this.highlightAll = options.highlightAllCheckbox || null;
this.caseSensitive = options.caseSensitiveCheckbox || null;
this.findMsg = options.findMsg || null;
this.findResultsCount = options.findResultsCount || null;
this.findStatusIcon = options.findStatusIcon || null;
this.findPreviousButton = options.findPreviousButton || null;
this.findNextButton = options.findNextButton || null;
this.findController = options.findController || null;
if (this.findController === null) {
throw new Error('PDFFindBar cannot be used without a ' +
'PDFFindController instance.');
}
// Add event listeners to the DOM elements.
var self = this;
this.toggleButton.addEventListener('click', function() {
self.toggle();
});
this.findField.addEventListener('input', function() {
self.dispatchEvent('');
});
this.bar.addEventListener('keydown', function(evt) {
switch (evt.keyCode) {
case 13: // Enter
if (evt.target === self.findField) {
self.dispatchEvent('again', evt.shiftKey);
}
break;
case 27: // Escape
self.close();
break;
}
});
this.findPreviousButton.addEventListener('click', function() {
self.dispatchEvent('again', true);
});
this.findNextButton.addEventListener('click', function() {
self.dispatchEvent('again', false);
});
this.highlightAll.addEventListener('click', function() {
self.dispatchEvent('highlightallchange');
});
this.caseSensitive.addEventListener('click', function() {
self.dispatchEvent('casesensitivitychange');
});
}
PDFFindBar.prototype = {
dispatchEvent: function PDFFindBar_dispatchEvent(type, findPrev) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('find' + type, true, true, {
query: this.findField.value,
caseSensitive: this.caseSensitive.checked,
highlightAll: this.highlightAll.checked,
findPrevious: findPrev
});
return window.dispatchEvent(event);
},
updateUIState:
function PDFFindBar_updateUIState(state, previous, matchCount) {
var notFound = false;
var findMsg = '';
var status = '';
switch (state) {
case FindStates.FIND_FOUND:
break;
case FindStates.FIND_PENDING:
status = 'pending';
break;
case FindStates.FIND_NOTFOUND:
findMsg = mozL10n.get('find_not_found', null, 'Phrase not found');
notFound = true;
break;
case FindStates.FIND_WRAPPED:
if (previous) {
findMsg = mozL10n.get('find_reached_top', null,
'Reached top of document, continued from bottom');
} else {
findMsg = mozL10n.get('find_reached_bottom', null,
'Reached end of document, continued from top');
}
break;
}
if (notFound) {
this.findField.classList.add('notFound');
} else {
this.findField.classList.remove('notFound');
}
this.findField.setAttribute('data-status', status);
this.findMsg.textContent = findMsg;
this.updateResultsCount(matchCount);
},
updateResultsCount: function(matchCount) {
if (!this.findResultsCount) {
return; // no UI control is provided
}
// If there are no matches, hide the counter
if (!matchCount) {
this.findResultsCount.classList.add('hidden');
return;
}
// Create the match counter
this.findResultsCount.textContent = matchCount.toLocaleString();
// Show the counter
this.findResultsCount.classList.remove('hidden');
},
open: function PDFFindBar_open() {
if (!this.opened) {
this.opened = true;
this.toggleButton.classList.add('toggled');
this.bar.classList.remove('hidden');
}
this.findField.select();
this.findField.focus();
},
close: function PDFFindBar_close() {
if (!this.opened) {
return;
}
this.opened = false;
this.toggleButton.classList.remove('toggled');
this.bar.classList.add('hidden');
this.findController.active = false;
},
toggle: function PDFFindBar_toggle() {
if (this.opened) {
this.close();
} else {
this.open();
}
}
};
return PDFFindBar;
})();
var FindStates = {
FIND_FOUND: 0,
FIND_NOTFOUND: 1,
FIND_WRAPPED: 2,
FIND_PENDING: 3
};
var FIND_SCROLL_OFFSET_TOP = -50;
var FIND_SCROLL_OFFSET_LEFT = -400;
/**
* Provides "search" or "find" functionality for the PDF.
* This object actually performs the search for a given string.
*/
var PDFFindController = (function PDFFindControllerClosure() {
function PDFFindController(options) {
this.startedTextExtraction = false;
this.extractTextPromises = [];
this.pendingFindMatches = Object.create(null);
this.active = false; // If active, find results will be highlighted.
this.pageContents = []; // Stores the text for each page.
this.pageMatches = [];
this.matchCount = 0;
this.selected = { // Currently selected match.
pageIdx: -1,
matchIdx: -1
};
this.offset = { // Where the find algorithm currently is in the document.
pageIdx: null,
matchIdx: null
};
this.pagesToSearch = null;
this.resumePageIdx = null;
this.state = null;
this.dirtyMatch = false;
this.findTimeout = null;
this.pdfViewer = options.pdfViewer || null;
this.integratedFind = options.integratedFind || false;
this.charactersToNormalize = {
'\u2018': '\'', // Left single quotation mark
'\u2019': '\'', // Right single quotation mark
'\u201A': '\'', // Single low-9 quotation mark
'\u201B': '\'', // Single high-reversed-9 quotation mark
'\u201C': '"', // Left double quotation mark
'\u201D': '"', // Right double quotation mark
'\u201E': '"', // Double low-9 quotation mark
'\u201F': '"', // Double high-reversed-9 quotation mark
'\u00BC': '1/4', // Vulgar fraction one quarter
'\u00BD': '1/2', // Vulgar fraction one half
'\u00BE': '3/4', // Vulgar fraction three quarters
};
this.findBar = options.findBar || null;
// Compile the regular expression for text normalization once
var replace = Object.keys(this.charactersToNormalize).join('');
this.normalizationRegex = new RegExp('[' + replace + ']', 'g');
var events = [
'find',
'findagain',
'findhighlightallchange',
'findcasesensitivitychange'
];
this.firstPagePromise = new Promise(function (resolve) {
this.resolveFirstPage = resolve;
}.bind(this));
this.handleEvent = this.handleEvent.bind(this);
for (var i = 0, len = events.length; i < len; i++) {
window.addEventListener(events[i], this.handleEvent);
}
}
PDFFindController.prototype = {
setFindBar: function PDFFindController_setFindBar(findBar) {
this.findBar = findBar;
},
reset: function PDFFindController_reset() {
this.startedTextExtraction = false;
this.extractTextPromises = [];
this.active = false;
},
normalize: function PDFFindController_normalize(text) {
var self = this;
return text.replace(this.normalizationRegex, function (ch) {
return self.charactersToNormalize[ch];
});
},
calcFindMatch: function PDFFindController_calcFindMatch(pageIndex) {
var pageContent = this.normalize(this.pageContents[pageIndex]);
var query = this.normalize(this.state.query);
var caseSensitive = this.state.caseSensitive;
var queryLen = query.length;
if (queryLen === 0) {
// Do nothing: the matches should be wiped out already.
return;
}
if (!caseSensitive) {
pageContent = pageContent.toLowerCase();
query = query.toLowerCase();
}
var matches = [];
var matchIdx = -queryLen;
while (true) {
matchIdx = pageContent.indexOf(query, matchIdx + queryLen);
if (matchIdx === -1) {
break;
}
matches.push(matchIdx);
}
this.pageMatches[pageIndex] = matches;
this.updatePage(pageIndex);
if (this.resumePageIdx === pageIndex) {
this.resumePageIdx = null;
this.nextPageMatch();
}
// Update the matches count
if (matches.length > 0) {
this.matchCount += matches.length;
this.updateUIResultsCount();
}
},
extractText: function PDFFindController_extractText() {
if (this.startedTextExtraction) {
return;
}
this.startedTextExtraction = true;
this.pageContents = [];
var extractTextPromisesResolves = [];
var numPages = this.pdfViewer.pagesCount;
for (var i = 0; i < numPages; i++) {
this.extractTextPromises.push(new Promise(function (resolve) {
extractTextPromisesResolves.push(resolve);
}));
}
var self = this;
function extractPageText(pageIndex) {
self.pdfViewer.getPageTextContent(pageIndex).then(
function textContentResolved(textContent) {
var textItems = textContent.items;
var str = [];
for (var i = 0, len = textItems.length; i < len; i++) {
str.push(textItems[i].str);
}
// Store the pageContent as a string.
self.pageContents.push(str.join(''));
extractTextPromisesResolves[pageIndex](pageIndex);
if ((pageIndex + 1) < self.pdfViewer.pagesCount) {
extractPageText(pageIndex + 1);
}
}
);
}
extractPageText(0);
},
handleEvent: function PDFFindController_handleEvent(e) {
if (this.state === null || e.type !== 'findagain') {
this.dirtyMatch = true;
}
this.state = e.detail;
this.updateUIState(FindStates.FIND_PENDING);
this.firstPagePromise.then(function() {
this.extractText();
clearTimeout(this.findTimeout);
if (e.type === 'find') {
// Only trigger the find action after 250ms of silence.
this.findTimeout = setTimeout(this.nextMatch.bind(this), 250);
} else {
this.nextMatch();
}
}.bind(this));
},
updatePage: function PDFFindController_updatePage(index) {
if (this.selected.pageIdx === index) {
// If the page is selected, scroll the page into view, which triggers
// rendering the page, which adds the textLayer. Once the textLayer is
// build, it will scroll onto the selected match.
this.pdfViewer.scrollPageIntoView(index + 1);
}
var page = this.pdfViewer.getPageView(index);
if (page.textLayer) {
page.textLayer.updateMatches();
}
},
nextMatch: function PDFFindController_nextMatch() {
var previous = this.state.findPrevious;
var currentPageIndex = this.pdfViewer.currentPageNumber - 1;
var numPages = this.pdfViewer.pagesCount;
this.active = true;
if (this.dirtyMatch) {
// Need to recalculate the matches, reset everything.
this.dirtyMatch = false;
this.selected.pageIdx = this.selected.matchIdx = -1;
this.offset.pageIdx = currentPageIndex;
this.offset.matchIdx = null;
this.hadMatch = false;
this.resumePageIdx = null;
this.pageMatches = [];
this.matchCount = 0;
var self = this;
for (var i = 0; i < numPages; i++) {
// Wipe out any previous highlighted matches.
this.updatePage(i);
// As soon as the text is extracted start finding the matches.
if (!(i in this.pendingFindMatches)) {
this.pendingFindMatches[i] = true;
this.extractTextPromises[i].then(function(pageIdx) {
delete self.pendingFindMatches[pageIdx];
self.calcFindMatch(pageIdx);
});
}
}
}
// If there's no query there's no point in searching.
if (this.state.query === '') {
this.updateUIState(FindStates.FIND_FOUND);
return;
}
// If we're waiting on a page, we return since we can't do anything else.
if (this.resumePageIdx) {
return;
}
var offset = this.offset;
// Keep track of how many pages we should maximally iterate through.
this.pagesToSearch = numPages;
// If there's already a matchIdx that means we are iterating through a
// page's matches.
if (offset.matchIdx !== null) {
var numPageMatches = this.pageMatches[offset.pageIdx].length;
if ((!previous && offset.matchIdx + 1 < numPageMatches) ||
(previous && offset.matchIdx > 0)) {
// The simple case; we just have advance the matchIdx to select
// the next match on the page.
this.hadMatch = true;
offset.matchIdx = (previous ? offset.matchIdx - 1 :
offset.matchIdx + 1);
this.updateMatch(true);
return;
}
// We went beyond the current page's matches, so we advance to
// the next page.
this.advanceOffsetPage(previous);
}
// Start searching through the page.
this.nextPageMatch();
},
matchesReady: function PDFFindController_matchesReady(matches) {
var offset = this.offset;
var numMatches = matches.length;
var previous = this.state.findPrevious;
if (numMatches) {
// There were matches for the page, so initialize the matchIdx.
this.hadMatch = true;
offset.matchIdx = (previous ? numMatches - 1 : 0);
this.updateMatch(true);
return true;
} else {
// No matches, so attempt to search the next page.
this.advanceOffsetPage(previous);
if (offset.wrapped) {
offset.matchIdx = null;
if (this.pagesToSearch < 0) {
// No point in wrapping again, there were no matches.
this.updateMatch(false);
// while matches were not found, searching for a page
// with matches should nevertheless halt.
return true;
}
}
// Matches were not found (and searching is not done).
return false;
}
},
/**
* The method is called back from the text layer when match presentation
* is updated.
* @param {number} pageIndex - page index.
* @param {number} index - match index.
* @param {Array} elements - text layer div elements array.
* @param {number} beginIdx - start index of the div array for the match.
* @param {number} endIdx - end index of the div array for the match.
*/
updateMatchPosition: function PDFFindController_updateMatchPosition(
pageIndex, index, elements, beginIdx, endIdx) {
if (this.selected.matchIdx === index &&
this.selected.pageIdx === pageIndex) {
var spot = {
top: FIND_SCROLL_OFFSET_TOP,
left: FIND_SCROLL_OFFSET_LEFT
};
scrollIntoView(elements[beginIdx], spot,
/* skipOverflowHiddenElements = */ true);
}
},
nextPageMatch: function PDFFindController_nextPageMatch() {
if (this.resumePageIdx !== null) {
console.error('There can only be one pending page.');
}
do {
var pageIdx = this.offset.pageIdx;
var matches = this.pageMatches[pageIdx];
if (!matches) {
// The matches don't exist yet for processing by "matchesReady",
// so set a resume point for when they do exist.
this.resumePageIdx = pageIdx;
break;
}
} while (!this.matchesReady(matches));
},
advanceOffsetPage: function PDFFindController_advanceOffsetPage(previous) {
var offset = this.offset;
var numPages = this.extractTextPromises.length;
offset.pageIdx = (previous ? offset.pageIdx - 1 : offset.pageIdx + 1);
offset.matchIdx = null;
this.pagesToSearch--;
if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
offset.pageIdx = (previous ? numPages - 1 : 0);
offset.wrapped = true;
}
},
updateMatch: function PDFFindController_updateMatch(found) {
var state = FindStates.FIND_NOTFOUND;
var wrapped = this.offset.wrapped;
this.offset.wrapped = false;
if (found) {
var previousPage = this.selected.pageIdx;
this.selected.pageIdx = this.offset.pageIdx;
this.selected.matchIdx = this.offset.matchIdx;
state = (wrapped ? FindStates.FIND_WRAPPED : FindStates.FIND_FOUND);
// Update the currently selected page to wipe out any selected matches.
if (previousPage !== -1 && previousPage !== this.selected.pageIdx) {
this.updatePage(previousPage);
}
}
this.updateUIState(state, this.state.findPrevious);
if (this.selected.pageIdx !== -1) {
this.updatePage(this.selected.pageIdx);
}
},
updateUIResultsCount:
function PDFFindController_updateUIResultsCount() {
if (this.findBar === null) {
throw new Error('PDFFindController is not initialized with a ' +
'PDFFindBar instance.');
}
this.findBar.updateResultsCount(this.matchCount);
},
updateUIState: function PDFFindController_updateUIState(state, previous) {
if (this.integratedFind) {
FirefoxCom.request('updateFindControlState',
{ result: state, findPrevious: previous });
return;
}
if (this.findBar === null) {
throw new Error('PDFFindController is not initialized with a ' +
'PDFFindBar instance.');
}
this.findBar.updateUIState(state, previous, this.matchCount);
}
};
return PDFFindController;
})();
/**
* Performs navigation functions inside PDF, such as opening specified page,
* or destination.
* @class
* @implements {IPDFLinkService}
*/
var PDFLinkService = (function () {
/**
* @constructs PDFLinkService
*/
function PDFLinkService() {
this.baseUrl = null;
this.pdfDocument = null;
this.pdfViewer = null;
this.pdfHistory = null;
this._pagesRefCache = null;
}
PDFLinkService.prototype = {
setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
this.baseUrl = baseUrl;
this.pdfDocument = pdfDocument;
this._pagesRefCache = Object.create(null);
},
setViewer: function PDFLinkService_setViewer(pdfViewer) {
this.pdfViewer = pdfViewer;
},
setHistory: function PDFLinkService_setHistory(pdfHistory) {
this.pdfHistory = pdfHistory;
},
/**
* @returns {number}
*/
get pagesCount() {
return this.pdfDocument.numPages;
},
/**
* @returns {number}
*/
get page() {
return this.pdfViewer.currentPageNumber;
},
/**
* @param {number} value
*/
set page(value) {
this.pdfViewer.currentPageNumber = value;
},
/**
* @param dest - The PDF destination object.
*/
navigateTo: function PDFLinkService_navigateTo(dest) {
var destString = '';
var self = this;
var goToDestination = function(destRef) {
// dest array looks like that: <page-ref> </XYZ|FitXXX> <args..>
var pageNumber = destRef instanceof Object ?
self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
(destRef + 1);
if (pageNumber) {
if (pageNumber > self.pagesCount) {
pageNumber = self.pagesCount;
}
self.pdfViewer.scrollPageIntoView(pageNumber, dest);
if (self.pdfHistory) {
// Update the browsing history.
self.pdfHistory.push({
dest: dest,
hash: destString,
page: pageNumber
});
}
} else {
self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
var pageNum = pageIndex + 1;
var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
self._pagesRefCache[cacheKey] = pageNum;
goToDestination(destRef);
});
}
};
var destinationPromise;
if (typeof dest === 'string') {
destString = dest;
destinationPromise = this.pdfDocument.getDestination(dest);
} else {
destinationPromise = Promise.resolve(dest);
}
destinationPromise.then(function(destination) {
dest = destination;
if (!(destination instanceof Array)) {
return; // invalid destination
}
goToDestination(destination[0]);
});
},
/**
* @param dest - The PDF destination object.
* @returns {string} The hyperlink to the PDF object.
*/
getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
if (typeof dest === 'string') {
return this.getAnchorUrl('#' + escape(dest));
}
if (dest instanceof Array) {
var destRef = dest[0]; // see navigateTo method for dest format
var pageNumber = destRef instanceof Object ?
this._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
(destRef + 1);
if (pageNumber) {
var pdfOpenParams = this.getAnchorUrl('#page=' + pageNumber);
var destKind = dest[1];
if (typeof destKind === 'object' && 'name' in destKind &&
destKind.name === 'XYZ') {
var scale = (dest[4] || this.pdfViewer.currentScaleValue);
var scaleNumber = parseFloat(scale);
if (scaleNumber) {
scale = scaleNumber * 100;
}
pdfOpenParams += '&zoom=' + scale;
if (dest[2] || dest[3]) {
pdfOpenParams += ',' + (dest[2] || 0) + ',' + (dest[3] || 0);
}
}
return pdfOpenParams;
}
}
return this.getAnchorUrl('');
},
/**
* Prefix the full url on anchor links to make sure that links are resolved
* relative to the current URL instead of the one defined in <base href>.
* @param {String} anchor The anchor hash, including the #.
* @returns {string} The hyperlink to the PDF object.
*/
getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
return (this.baseUrl || '') + anchor;
},
/**
* @param {string} hash
*/
setHash: function PDFLinkService_setHash(hash) {
if (hash.indexOf('=') >= 0) {
var params = parseQueryString(hash);
// borrowing syntax from "Parameters for Opening PDF Files"
if ('nameddest' in params) {
if (this.pdfHistory) {
this.pdfHistory.updateNextHashParam(params.nameddest);
}
this.navigateTo(params.nameddest);
return;
}
var pageNumber, dest;
if ('page' in params) {
pageNumber = (params.page | 0) || 1;
}
if ('zoom' in params) {
// Build the destination array.
var zoomArgs = params.zoom.split(','); // scale,left,top
var zoomArg = zoomArgs[0];
var zoomArgNumber = parseFloat(zoomArg);
if (zoomArg.indexOf('Fit') === -1) {
// If the zoomArg is a number, it has to get divided by 100. If it's
// a string, it should stay as it is.
dest = [null, { name: 'XYZ' },
zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
(zoomArgNumber ? zoomArgNumber / 100 : zoomArg)];
} else {
if (zoomArg === 'Fit' || zoomArg === 'FitB') {
dest = [null, { name: zoomArg }];
} else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') ||
(zoomArg === 'FitV' || zoomArg === 'FitBV')) {
dest = [null, { name: zoomArg },
zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null];
} else if (zoomArg === 'FitR') {
if (zoomArgs.length !== 5) {
console.error('PDFLinkService_setHash: ' +
'Not enough parameters for \'FitR\'.');
} else {
dest = [null, { name: zoomArg },
(zoomArgs[1] | 0), (zoomArgs[2] | 0),
(zoomArgs[3] | 0), (zoomArgs[4] | 0)];
}
} else {
console.error('PDFLinkService_setHash: \'' + zoomArg +
'\' is not a valid zoom value.');
}
}
}
if (dest) {
this.pdfViewer.scrollPageIntoView(pageNumber || this.page, dest);
} else if (pageNumber) {
this.page = pageNumber; // simple page
}
if ('pagemode' in params) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagemode', true, true, {
mode: params.pagemode,
});
this.pdfViewer.container.dispatchEvent(event);
}
} else if (/^\d+$/.test(hash)) { // page number
this.page = hash;
} else { // named destination
if (this.pdfHistory) {
this.pdfHistory.updateNextHashParam(unescape(hash));
}
this.navigateTo(unescape(hash));
}
},
/**
* @param {string} action
*/
executeNamedAction: function PDFLinkService_executeNamedAction(action) {
// See PDF reference, table 8.45 - Named action
switch (action) {
case 'GoBack':
if (this.pdfHistory) {
this.pdfHistory.back();
}
break;
case 'GoForward':
if (this.pdfHistory) {
this.pdfHistory.forward();
}
break;
case 'NextPage':
this.page++;
break;
case 'PrevPage':
this.page--;
break;
case 'LastPage':
this.page = this.pagesCount;
break;
case 'FirstPage':
this.page = 1;
break;
default:
break; // No action according to spec
}
var event = document.createEvent('CustomEvent');
event.initCustomEvent('namedaction', true, true, {
action: action
});
this.pdfViewer.container.dispatchEvent(event);
},
/**
* @param {number} pageNum - page number.
* @param {Object} pageRef - reference to the page.
*/
cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
this._pagesRefCache[refStr] = pageNum;
}
};
return PDFLinkService;
})();
var PDFHistory = (function () {
function PDFHistory(options) {
this.linkService = options.linkService;
this.initialized = false;
this.initialDestination = null;
this.initialBookmark = null;
}
PDFHistory.prototype = {
/**
* @param {string} fingerprint
* @param {IPDFLinkService} linkService
*/
initialize: function pdfHistoryInitialize(fingerprint) {
this.initialized = true;
this.reInitialized = false;
this.allowHashChange = true;
this.historyUnlocked = true;
this.isViewerInPresentationMode = false;
this.previousHash = window.location.hash.substring(1);
this.currentBookmark = '';
this.currentPage = 0;
this.updatePreviousBookmark = false;
this.previousBookmark = '';
this.previousPage = 0;
this.nextHashParam = '';
this.fingerprint = fingerprint;
this.currentUid = this.uid = 0;
this.current = {};
var state = window.history.state;
if (this._isStateObjectDefined(state)) {
// This corresponds to navigating back to the document
// from another page in the browser history.
if (state.target.dest) {
this.initialDestination = state.target.dest;
} else {
this.initialBookmark = state.target.hash;
}
this.currentUid = state.uid;
this.uid = state.uid + 1;
this.current = state.target;
} else {
// This corresponds to the loading of a new document.
if (state && state.fingerprint &&
this.fingerprint !== state.fingerprint) {
// Reinitialize the browsing history when a new document
// is opened in the web viewer.
this.reInitialized = true;
}
this._pushOrReplaceState({fingerprint: this.fingerprint}, true);
}
var self = this;
window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
if (!self.historyUnlocked) {
return;
}
if (evt.state) {
// Move back/forward in the history.
self._goTo(evt.state);
return;
}
// If the state is not set, then the user tried to navigate to a
// different hash by manually editing the URL and pressing Enter, or by
// clicking on an in-page link (e.g. the "current view" link).
// Save the current view state to the browser history.
// Note: In Firefox, history.null could also be null after an in-page
// navigation to the same URL, and without dispatching the popstate
// event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881
if (self.uid === 0) {
// Replace the previous state if it was not explicitly set.
var previousParams = (self.previousHash && self.currentBookmark &&
self.previousHash !== self.currentBookmark) ?
{hash: self.currentBookmark, page: self.currentPage} :
{page: 1};
replacePreviousHistoryState(previousParams, function() {
updateHistoryWithCurrentHash();
});
} else {
updateHistoryWithCurrentHash();
}
}, false);
function updateHistoryWithCurrentHash() {
self.previousHash = window.location.hash.slice(1);
self._pushToHistory({hash: self.previousHash}, false, true);
self._updatePreviousBookmark();
}
function replacePreviousHistoryState(params, callback) {
// To modify the previous history entry, the following happens:
// 1. history.back()
// 2. _pushToHistory, which calls history.replaceState( ... )
// 3. history.forward()
// Because a navigation via the history API does not immediately update
// the history state, the popstate event is used for synchronization.
self.historyUnlocked = false;
// Suppress the hashchange event to avoid side effects caused by
// navigating back and forward.
self.allowHashChange = false;
window.addEventListener('popstate', rewriteHistoryAfterBack);
history.back();
function rewriteHistoryAfterBack() {
window.removeEventListener('popstate', rewriteHistoryAfterBack);
window.addEventListener('popstate', rewriteHistoryAfterForward);
self._pushToHistory(params, false, true);
history.forward();
}
function rewriteHistoryAfterForward() {
window.removeEventListener('popstate', rewriteHistoryAfterForward);
self.allowHashChange = true;
self.historyUnlocked = true;
callback();
}
}
function pdfHistoryBeforeUnload() {
var previousParams = self._getPreviousParams(null, true);
if (previousParams) {
var replacePrevious = (!self.current.dest &&
self.current.hash !== self.previousHash);
self._pushToHistory(previousParams, false, replacePrevious);
self._updatePreviousBookmark();
}
// Remove the event listener when navigating away from the document,
// since 'beforeunload' prevents Firefox from caching the document.
window.removeEventListener('beforeunload', pdfHistoryBeforeUnload,
false);
}
window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
// If the entire viewer (including the PDF file) is cached in
// the browser, we need to reattach the 'beforeunload' event listener
// since the 'DOMContentLoaded' event is not fired on 'pageshow'.
window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
}, false);
window.addEventListener('presentationmodechanged', function(e) {
self.isViewerInPresentationMode = !!e.detail.active;
});
},
clearHistoryState: function pdfHistory_clearHistoryState() {
this._pushOrReplaceState(null, true);
},
_isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
return (state && state.uid >= 0 &&
state.fingerprint && this.fingerprint === state.fingerprint &&
state.target && state.target.hash) ? true : false;
},
_pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,
replace) {
if (replace) {
window.history.replaceState(stateObj, '', document.URL);
} else {
window.history.pushState(stateObj, '', document.URL);
}
},
get isHashChangeUnlocked() {
if (!this.initialized) {
return true;
}
return this.allowHashChange;
},
_updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
if (this.updatePreviousBookmark &&
this.currentBookmark && this.currentPage) {
this.previousBookmark = this.currentBookmark;
this.previousPage = this.currentPage;
this.updatePreviousBookmark = false;
}
},
updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
pageNum) {
if (this.initialized) {
this.currentBookmark = bookmark.substring(1);
this.currentPage = pageNum | 0;
this._updatePreviousBookmark();
}
},
updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
if (this.initialized) {
this.nextHashParam = param;
}
},
push: function pdfHistoryPush(params, isInitialBookmark) {
if (!(this.initialized && this.historyUnlocked)) {
return;
}
if (params.dest && !params.hash) {
params.hash = (this.current.hash && this.current.dest &&
this.current.dest === params.dest) ?
this.current.hash :
this.linkService.getDestinationHash(params.dest).split('#')[1];
}
if (params.page) {
params.page |= 0;
}
if (isInitialBookmark) {
var target = window.history.state.target;
if (!target) {
// Invoked when the user specifies an initial bookmark,
// thus setting initialBookmark, when the document is loaded.
this._pushToHistory(params, false);
this.previousHash = window.location.hash.substring(1);
}
this.updatePreviousBookmark = this.nextHashParam ? false : true;
if (target) {
// If the current document is reloaded,
// avoid creating duplicate entries in the history.
this._updatePreviousBookmark();
}
return;
}
if (this.nextHashParam) {
if (this.nextHashParam === params.hash) {
this.nextHashParam = null;
this.updatePreviousBookmark = true;
return;
} else {
this.nextHashParam = null;
}
}
if (params.hash) {
if (this.current.hash) {
if (this.current.hash !== params.hash) {
this._pushToHistory(params, true);
} else {
if (!this.current.page && params.page) {
this._pushToHistory(params, false, true);
}
this.updatePreviousBookmark = true;
}
} else {
this._pushToHistory(params, true);
}
} else if (this.current.page && params.page &&
this.current.page !== params.page) {
this._pushToHistory(params, true);
}
},
_getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
beforeUnload) {
if (!(this.currentBookmark && this.currentPage)) {
return null;
} else if (this.updatePreviousBookmark) {
this.updatePreviousBookmark = false;
}
if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
// Prevent the history from getting stuck in the current state,
// effectively preventing the user from going back/forward in
// the history.
//
// This happens if the current position in the document didn't change
// when the history was previously updated. The reasons for this are
// either:
// 1. The current zoom value is such that the document does not need to,
// or cannot, be scrolled to display the destination.
// 2. The previous destination is broken, and doesn't actally point to a
// position within the document.
// (This is either due to a bad PDF generator, or the user making a
// mistake when entering a destination in the hash parameters.)
return null;
}
if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
if (this.previousBookmark === this.currentBookmark) {
return null;
}
} else if (this.current.page || onlyCheckPage) {
if (this.previousPage === this.currentPage) {
return null;
}
} else {
return null;
}
var params = {hash: this.currentBookmark, page: this.currentPage};
if (this.isViewerInPresentationMode) {
params.hash = null;
}
return params;
},
_stateObj: function pdfHistory_stateObj(params) {
return {fingerprint: this.fingerprint, uid: this.uid, target: params};
},
_pushToHistory: function pdfHistory_pushToHistory(params,
addPrevious, overwrite) {
if (!this.initialized) {
return;
}
if (!params.hash && params.page) {
params.hash = ('page=' + params.page);
}
if (addPrevious && !overwrite) {
var previousParams = this._getPreviousParams();
if (previousParams) {
var replacePrevious = (!this.current.dest &&
this.current.hash !== this.previousHash);
this._pushToHistory(previousParams, false, replacePrevious);
}
}
this._pushOrReplaceState(this._stateObj(params),
(overwrite || this.uid === 0));
this.currentUid = this.uid++;
this.current = params;
this.updatePreviousBookmark = true;
},
_goTo: function pdfHistory_goTo(state) {
if (!(this.initialized && this.historyUnlocked &&
this._isStateObjectDefined(state))) {
return;
}
if (!this.reInitialized && state.uid < this.currentUid) {
var previousParams = this._getPreviousParams(true);
if (previousParams) {
this._pushToHistory(this.current, false);
this._pushToHistory(previousParams, false);
this.currentUid = state.uid;
window.history.back();
return;
}
}
this.historyUnlocked = false;
if (state.target.dest) {
this.linkService.navigateTo(state.target.dest);
} else {
this.linkService.setHash(state.target.hash);
}
this.currentUid = state.uid;
if (state.uid > this.uid) {
this.uid = state.uid;
}
this.current = state.target;
this.updatePreviousBookmark = true;
var currentHash = window.location.hash.substring(1);
if (this.previousHash !== currentHash) {
this.allowHashChange = false;
}
this.previousHash = currentHash;
this.historyUnlocked = true;
},
back: function pdfHistoryBack() {
this.go(-1);
},
forward: function pdfHistoryForward() {
this.go(1);
},
go: function pdfHistoryGo(direction) {
if (this.initialized && this.historyUnlocked) {
var state = window.history.state;
if (direction === -1 && state && state.uid > 0) {
window.history.back();
} else if (direction === 1 && state && state.uid < (this.uid - 1)) {
window.history.forward();
}
}
}
};
return PDFHistory;
})();
var SecondaryToolbar = {
opened: false,
previousContainerHeight: null,
newContainerHeight: null,
initialize: function secondaryToolbarInitialize(options) {
this.toolbar = options.toolbar;
this.buttonContainer = this.toolbar.firstElementChild;
// Define the toolbar buttons.
this.toggleButton = options.toggleButton;
this.presentationModeButton = options.presentationModeButton;
this.openFile = options.openFile;
this.print = options.print;
this.download = options.download;
this.viewBookmark = options.viewBookmark;
this.firstPage = options.firstPage;
this.lastPage = options.lastPage;
this.pageRotateCw = options.pageRotateCw;
this.pageRotateCcw = options.pageRotateCcw;
this.documentPropertiesButton = options.documentPropertiesButton;
// Attach the event listeners.
var elements = [
// Button to toggle the visibility of the secondary toolbar:
{ element: this.toggleButton, handler: this.toggle },
// All items within the secondary toolbar
// (except for toggleHandTool, hand_tool.js is responsible for it):
{ element: this.presentationModeButton,
handler: this.presentationModeClick },
{ element: this.openFile, handler: this.openFileClick },
{ element: this.print, handler: this.printClick },
{ element: this.download, handler: this.downloadClick },
{ element: this.viewBookmark, handler: this.viewBookmarkClick },
{ element: this.firstPage, handler: this.firstPageClick },
{ element: this.lastPage, handler: this.lastPageClick },
{ element: this.pageRotateCw, handler: this.pageRotateCwClick },
{ element: this.pageRotateCcw, handler: this.pageRotateCcwClick },
{ element: this.documentPropertiesButton,
handler: this.documentPropertiesClick }
];
for (var item in elements) {
var element = elements[item].element;
if (element) {
element.addEventListener('click', elements[item].handler.bind(this));
}
}
},
// Event handling functions.
presentationModeClick: function secondaryToolbarPresentationModeClick(evt) {
PDFViewerApplication.requestPresentationMode();
this.close();
},
openFileClick: function secondaryToolbarOpenFileClick(evt) {
document.getElementById('fileInput').click();
this.close();
},
printClick: function secondaryToolbarPrintClick(evt) {
window.print();
this.close();
},
downloadClick: function secondaryToolbarDownloadClick(evt) {
PDFViewerApplication.download();
this.close();
},
viewBookmarkClick: function secondaryToolbarViewBookmarkClick(evt) {
this.close();
},
firstPageClick: function secondaryToolbarFirstPageClick(evt) {
PDFViewerApplication.page = 1;
this.close();
},
lastPageClick: function secondaryToolbarLastPageClick(evt) {
if (PDFViewerApplication.pdfDocument) {
PDFViewerApplication.page = PDFViewerApplication.pagesCount;
}
this.close();
},
pageRotateCwClick: function secondaryToolbarPageRotateCwClick(evt) {
PDFViewerApplication.rotatePages(90);
},
pageRotateCcwClick: function secondaryToolbarPageRotateCcwClick(evt) {
PDFViewerApplication.rotatePages(-90);
},
documentPropertiesClick: function secondaryToolbarDocumentPropsClick(evt) {
PDFViewerApplication.pdfDocumentProperties.open();
this.close();
},
// Misc. functions for interacting with the toolbar.
setMaxHeight: function secondaryToolbarSetMaxHeight(container) {
if (!container || !this.buttonContainer) {
return;
}
this.newContainerHeight = container.clientHeight;
if (this.previousContainerHeight === this.newContainerHeight) {
return;
}
this.buttonContainer.setAttribute('style',
'max-height: ' + (this.newContainerHeight - SCROLLBAR_PADDING) + 'px;');
this.previousContainerHeight = this.newContainerHeight;
},
open: function secondaryToolbarOpen() {
if (this.opened) {
return;
}
this.opened = true;
this.toggleButton.classList.add('toggled');
this.toolbar.classList.remove('hidden');
},
close: function secondaryToolbarClose(target) {
if (!this.opened) {
return;
} else if (target && !this.toolbar.contains(target)) {
return;
}
this.opened = false;
this.toolbar.classList.add('hidden');
this.toggleButton.classList.remove('toggled');
},
toggle: function secondaryToolbarToggle() {
if (this.opened) {
this.close();
} else {
this.open();
}
}
};
var DELAY_BEFORE_RESETTING_SWITCH_IN_PROGRESS = 1500; // in ms
var DELAY_BEFORE_HIDING_CONTROLS = 3000; // in ms
var ACTIVE_SELECTOR = 'pdfPresentationMode';
var CONTROLS_SELECTOR = 'pdfPresentationModeControls';
/**
* @typedef {Object} PDFPresentationModeOptions
* @property {HTMLDivElement} container - The container for the viewer element.
* @property {HTMLDivElement} viewer - (optional) The viewer element.
* @property {PDFViewer} pdfViewer - The document viewer.
* @property {PDFThumbnailViewer} pdfThumbnailViewer - (optional) The thumbnail
* viewer.
* @property {Array} contextMenuItems - (optional) The menuitems that are added
* to the context menu in Presentation Mode.
*/
/**
* @class
*/
var PDFPresentationMode = (function PDFPresentationModeClosure() {
/**
* @constructs PDFPresentationMode
* @param {PDFPresentationModeOptions} options
*/
function PDFPresentationMode(options) {
this.container = options.container;
this.viewer = options.viewer || options.container.firstElementChild;
this.pdfViewer = options.pdfViewer;
this.pdfThumbnailViewer = options.pdfThumbnailViewer || null;
var contextMenuItems = options.contextMenuItems || null;
this.active = false;
this.args = null;
this.contextMenuOpen = false;
this.mouseScrollTimeStamp = 0;
this.mouseScrollDelta = 0;
if (contextMenuItems) {
for (var i = 0, ii = contextMenuItems.length; i < ii; i++) {
var item = contextMenuItems[i];
item.element.addEventListener('click', function (handler) {
this.contextMenuOpen = false;
handler();
}.bind(this, item.handler));
}
}
}
PDFPresentationMode.prototype = {
/**
* Request the browser to enter fullscreen mode.
* @returns {boolean} Indicating if the request was successful.
*/
request: function PDFPresentationMode_request() {
if (this.switchInProgress || this.active ||
!this.viewer.hasChildNodes()) {
return false;
}
this._addFullscreenChangeListeners();
this._setSwitchInProgress();
this._notifyStateChange();
if (this.container.requestFullscreen) {
this.container.requestFullscreen();
} else if (this.container.mozRequestFullScreen) {
this.container.mozRequestFullScreen();
} else if (this.container.webkitRequestFullscreen) {
this.container.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
} else if (this.container.msRequestFullscreen) {
this.container.msRequestFullscreen();
} else {
return false;
}
this.args = {
page: this.pdfViewer.currentPageNumber,
previousScale: this.pdfViewer.currentScaleValue,
};
return true;
},
/**
* Switches page when the user scrolls (using a scroll wheel or a touchpad)
* with large enough motion, to prevent accidental page switches.
* @param {number} delta - The delta value from the mouse event.
*/
mouseScroll: function PDFPresentationMode_mouseScroll(delta) {
if (!this.active) {
return;
}
var MOUSE_SCROLL_COOLDOWN_TIME = 50;
var PAGE_SWITCH_THRESHOLD = 120;
var PageSwitchDirection = {
UP: -1,
DOWN: 1
};
var currentTime = (new Date()).getTime();
var storedTime = this.mouseScrollTimeStamp;
// If we've already switched page, avoid accidentally switching again.
if (currentTime > storedTime &&
currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) {
return;
}
// If the scroll direction changed, reset the accumulated scroll delta.
if ((this.mouseScrollDelta > 0 && delta < 0) ||
(this.mouseScrollDelta < 0 && delta > 0)) {
this._resetMouseScrollState();
}
this.mouseScrollDelta += delta;
if (Math.abs(this.mouseScrollDelta) >= PAGE_SWITCH_THRESHOLD) {
var pageSwitchDirection = (this.mouseScrollDelta > 0) ?
PageSwitchDirection.UP : PageSwitchDirection.DOWN;
var page = this.pdfViewer.currentPageNumber;
this._resetMouseScrollState();
// If we're at the first/last page, we don't need to do anything.
if ((page === 1 && pageSwitchDirection === PageSwitchDirection.UP) ||
(page === this.pdfViewer.pagesCount &&
pageSwitchDirection === PageSwitchDirection.DOWN)) {
return;
}
this.pdfViewer.currentPageNumber = (page + pageSwitchDirection);
this.mouseScrollTimeStamp = currentTime;
}
},
get isFullscreen() {
return !!(document.fullscreenElement ||
document.mozFullScreen ||
document.webkitIsFullScreen ||
document.msFullscreenElement);
},
/**
* @private
*/
_notifyStateChange: function PDFPresentationMode_notifyStateChange() {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('presentationmodechanged', true, true, {
active: this.active,
switchInProgress: !!this.switchInProgress
});
window.dispatchEvent(event);
},
/**
* Used to initialize a timeout when requesting Presentation Mode,
* i.e. when the browser is requested to enter fullscreen mode.
* This timeout is used to prevent the current page from being scrolled
* partially, or completely, out of view when entering Presentation Mode.
* NOTE: This issue seems limited to certain zoom levels (e.g. page-width).
* @private
*/
_setSwitchInProgress: function PDFPresentationMode_setSwitchInProgress() {
if (this.switchInProgress) {
clearTimeout(this.switchInProgress);
}
this.switchInProgress = setTimeout(function switchInProgressTimeout() {
this._removeFullscreenChangeListeners();
delete this.switchInProgress;
this._notifyStateChange();
}.bind(this), DELAY_BEFORE_RESETTING_SWITCH_IN_PROGRESS);
},
/**
* @private
*/
_resetSwitchInProgress:
function PDFPresentationMode_resetSwitchInProgress() {
if (this.switchInProgress) {
clearTimeout(this.switchInProgress);
delete this.switchInProgress;
}
},
/**
* @private
*/
_enter: function PDFPresentationMode_enter() {
this.active = true;
this._resetSwitchInProgress();
this._notifyStateChange();
this.container.classList.add(ACTIVE_SELECTOR);
// Ensure that the correct page is scrolled into view when entering
// Presentation Mode, by waiting until fullscreen mode in enabled.
setTimeout(function enterPresentationModeTimeout() {
this.pdfViewer.currentPageNumber = this.args.page;
this.pdfViewer.currentScaleValue = 'page-fit';
}.bind(this), 0);
this._addWindowListeners();
this._showControls();
this.contextMenuOpen = false;
this.container.setAttribute('contextmenu', 'viewerContextMenu');
// Text selection is disabled in Presentation Mode, thus it's not possible
// for the user to deselect text that is selected (e.g. with "Select all")
// when entering Presentation Mode, hence we remove any active selection.
window.getSelection().removeAllRanges();
},
/**
* @private
*/
_exit: function PDFPresentationMode_exit() {
var page = this.pdfViewer.currentPageNumber;
this.container.classList.remove(ACTIVE_SELECTOR);
// Ensure that the correct page is scrolled into view when exiting
// Presentation Mode, by waiting until fullscreen mode is disabled.
setTimeout(function exitPresentationModeTimeout() {
this.active = false;
this._removeFullscreenChangeListeners();
this._notifyStateChange();
this.pdfViewer.currentScaleValue = this.args.previousScale;
this.pdfViewer.currentPageNumber = page;
this.args = null;
}.bind(this), 0);
this._removeWindowListeners();
this._hideControls();
this._resetMouseScrollState();
this.container.removeAttribute('contextmenu');
this.contextMenuOpen = false;
if (this.pdfThumbnailViewer) {
this.pdfThumbnailViewer.ensureThumbnailVisible(page);
}
},
/**
* @private
*/
_mouseDown: function PDFPresentationMode_mouseDown(evt) {
if (this.contextMenuOpen) {
this.contextMenuOpen = false;
evt.preventDefault();
return;
}
if (evt.button === 0) {
// Enable clicking of links in presentation mode. Please note:
// Only links pointing to destinations in the current PDF document work.
var isInternalLink = (evt.target.href &&
evt.target.classList.contains('internalLink'));
if (!isInternalLink) {
// Unless an internal link was clicked, advance one page.
evt.preventDefault();
this.pdfViewer.currentPageNumber += (evt.shiftKey ? -1 : 1);
}
}
},
/**
* @private
*/
_contextMenu: function PDFPresentationMode_contextMenu() {
this.contextMenuOpen = true;
},
/**
* @private
*/
_showControls: function PDFPresentationMode_showControls() {
if (this.controlsTimeout) {
clearTimeout(this.controlsTimeout);
} else {
this.container.classList.add(CONTROLS_SELECTOR);
}
this.controlsTimeout = setTimeout(function showControlsTimeout() {
this.container.classList.remove(CONTROLS_SELECTOR);
delete this.controlsTimeout;
}.bind(this), DELAY_BEFORE_HIDING_CONTROLS);
},
/**
* @private
*/
_hideControls: function PDFPresentationMode_hideControls() {
if (!this.controlsTimeout) {
return;
}
clearTimeout(this.controlsTimeout);
this.container.classList.remove(CONTROLS_SELECTOR);
delete this.controlsTimeout;
},
/**
* Resets the properties used for tracking mouse scrolling events.
* @private
*/
_resetMouseScrollState:
function PDFPresentationMode_resetMouseScrollState() {
this.mouseScrollTimeStamp = 0;
this.mouseScrollDelta = 0;
},
/**
* @private
*/
_addWindowListeners: function PDFPresentationMode_addWindowListeners() {
this.showControlsBind = this._showControls.bind(this);
this.mouseDownBind = this._mouseDown.bind(this);
this.resetMouseScrollStateBind = this._resetMouseScrollState.bind(this);
this.contextMenuBind = this._contextMenu.bind(this);
window.addEventListener('mousemove', this.showControlsBind);
window.addEventListener('mousedown', this.mouseDownBind);
window.addEventListener('keydown', this.resetMouseScrollStateBind);
window.addEventListener('contextmenu', this.contextMenuBind);
},
/**
* @private
*/
_removeWindowListeners:
function PDFPresentationMode_removeWindowListeners() {
window.removeEventListener('mousemove', this.showControlsBind);
window.removeEventListener('mousedown', this.mouseDownBind);
window.removeEventListener('keydown', this.resetMouseScrollStateBind);
window.removeEventListener('contextmenu', this.contextMenuBind);
delete this.showControlsBind;
delete this.mouseDownBind;
delete this.resetMouseScrollStateBind;
delete this.contextMenuBind;
},
/**
* @private
*/
_fullscreenChange: function PDFPresentationMode_fullscreenChange() {
if (this.isFullscreen) {
this._enter();
} else {
this._exit();
}
},
/**
* @private
*/
_addFullscreenChangeListeners:
function PDFPresentationMode_addFullscreenChangeListeners() {
this.fullscreenChangeBind = this._fullscreenChange.bind(this);
window.addEventListener('fullscreenchange', this.fullscreenChangeBind);
window.addEventListener('mozfullscreenchange', this.fullscreenChangeBind);
window.addEventListener('webkitfullscreenchange',
this.fullscreenChangeBind);
window.addEventListener('MSFullscreenChange', this.fullscreenChangeBind);
},
/**
* @private
*/
_removeFullscreenChangeListeners:
function PDFPresentationMode_removeFullscreenChangeListeners() {
window.removeEventListener('fullscreenchange', this.fullscreenChangeBind);
window.removeEventListener('mozfullscreenchange',
this.fullscreenChangeBind);
window.removeEventListener('webkitfullscreenchange',
this.fullscreenChangeBind);
window.removeEventListener('MSFullscreenChange',
this.fullscreenChangeBind);
delete this.fullscreenChangeBind;
}
};
return PDFPresentationMode;
})();
var GrabToPan = (function GrabToPanClosure() {
/**
* Construct a GrabToPan instance for a given HTML element.
* @param options.element {Element}
* @param options.ignoreTarget {function} optional. See `ignoreTarget(node)`
* @param options.onActiveChanged {function(boolean)} optional. Called
* when grab-to-pan is (de)activated. The first argument is a boolean that
* shows whether grab-to-pan is activated.
*/
function GrabToPan(options) {
this.element = options.element;
this.document = options.element.ownerDocument;
if (typeof options.ignoreTarget === 'function') {
this.ignoreTarget = options.ignoreTarget;
}
this.onActiveChanged = options.onActiveChanged;
// Bind the contexts to ensure that `this` always points to
// the GrabToPan instance.
this.activate = this.activate.bind(this);
this.deactivate = this.deactivate.bind(this);
this.toggle = this.toggle.bind(this);
this._onmousedown = this._onmousedown.bind(this);
this._onmousemove = this._onmousemove.bind(this);
this._endPan = this._endPan.bind(this);
// This overlay will be inserted in the document when the mouse moves during
// a grab operation, to ensure that the cursor has the desired appearance.
var overlay = this.overlay = document.createElement('div');
overlay.className = 'grab-to-pan-grabbing';
}
GrabToPan.prototype = {
/**
* Class name of element which can be grabbed
*/
CSS_CLASS_GRAB: 'grab-to-pan-grab',
/**
* Bind a mousedown event to the element to enable grab-detection.
*/
activate: function GrabToPan_activate() {
if (!this.active) {
this.active = true;
this.element.addEventListener('mousedown', this._onmousedown, true);
this.element.classList.add(this.CSS_CLASS_GRAB);
if (this.onActiveChanged) {
this.onActiveChanged(true);
}
}
},
/**
* Removes all events. Any pending pan session is immediately stopped.
*/
deactivate: function GrabToPan_deactivate() {
if (this.active) {
this.active = false;
this.element.removeEventListener('mousedown', this._onmousedown, true);
this._endPan();
this.element.classList.remove(this.CSS_CLASS_GRAB);
if (this.onActiveChanged) {
this.onActiveChanged(false);
}
}
},
toggle: function GrabToPan_toggle() {
if (this.active) {
this.deactivate();
} else {
this.activate();
}
},
/**
* Whether to not pan if the target element is clicked.
* Override this method to change the default behaviour.
*
* @param node {Element} The target of the event
* @return {boolean} Whether to not react to the click event.
*/
ignoreTarget: function GrabToPan_ignoreTarget(node) {
// Use matchesSelector to check whether the clicked element
// is (a child of) an input element / link
return node[matchesSelector](
'a[href], a[href] *, input, textarea, button, button *, select, option'
);
},
/**
* @private
*/
_onmousedown: function GrabToPan__onmousedown(event) {
if (event.button !== 0 || this.ignoreTarget(event.target)) {
return;
}
if (event.originalTarget) {
try {
/* jshint expr:true */
event.originalTarget.tagName;
} catch (e) {
// Mozilla-specific: element is a scrollbar (XUL element)
return;
}
}
this.scrollLeftStart = this.element.scrollLeft;
this.scrollTopStart = this.element.scrollTop;
this.clientXStart = event.clientX;
this.clientYStart = event.clientY;
this.document.addEventListener('mousemove', this._onmousemove, true);
this.document.addEventListener('mouseup', this._endPan, true);
// When a scroll event occurs before a mousemove, assume that the user
// dragged a scrollbar (necessary for Opera Presto, Safari and IE)
// (not needed for Chrome/Firefox)
this.element.addEventListener('scroll', this._endPan, true);
event.preventDefault();
event.stopPropagation();
this.document.documentElement.classList.add(this.CSS_CLASS_GRABBING);
var focusedElement = document.activeElement;
if (focusedElement && !focusedElement.contains(event.target)) {
focusedElement.blur();
}
},
/**
* @private
*/
_onmousemove: function GrabToPan__onmousemove(event) {
this.element.removeEventListener('scroll', this._endPan, true);
if (isLeftMouseReleased(event)) {
this._endPan();
return;
}
var xDiff = event.clientX - this.clientXStart;
var yDiff = event.clientY - this.clientYStart;
this.element.scrollTop = this.scrollTopStart - yDiff;
this.element.scrollLeft = this.scrollLeftStart - xDiff;
if (!this.overlay.parentNode) {
document.body.appendChild(this.overlay);
}
},
/**
* @private
*/
_endPan: function GrabToPan__endPan() {
this.element.removeEventListener('scroll', this._endPan, true);
this.document.removeEventListener('mousemove', this._onmousemove, true);
this.document.removeEventListener('mouseup', this._endPan, true);
if (this.overlay.parentNode) {
this.overlay.parentNode.removeChild(this.overlay);
}
}
};
// Get the correct (vendor-prefixed) name of the matches method.
var matchesSelector;
['webkitM', 'mozM', 'msM', 'oM', 'm'].some(function(prefix) {
var name = prefix + 'atches';
if (name in document.documentElement) {
matchesSelector = name;
}
name += 'Selector';
if (name in document.documentElement) {
matchesSelector = name;
}
return matchesSelector; // If found, then truthy, and [].some() ends.
});
// Browser sniffing because it's impossible to feature-detect
// whether event.which for onmousemove is reliable
var isNotIEorIsIE10plus = !document.documentMode || document.documentMode > 9;
var chrome = window.chrome;
var isChrome15OrOpera15plus = chrome && (chrome.webstore || chrome.app);
// ^ Chrome 15+ ^ Opera 15+
var isSafari6plus = /Apple/.test(navigator.vendor) &&
/Version\/([6-9]\d*|[1-5]\d+)/.test(navigator.userAgent);
/**
* Whether the left mouse is not pressed.
* @param event {MouseEvent}
* @return {boolean} True if the left mouse button is not pressed.
* False if unsure or if the left mouse button is pressed.
*/
function isLeftMouseReleased(event) {
if ('buttons' in event && isNotIEorIsIE10plus) {
// http://www.w3.org/TR/DOM-Level-3-Events/#events-MouseEvent-buttons
// Firefox 15+
// Internet Explorer 10+
return !(event.buttons | 1);
}
if (isChrome15OrOpera15plus || isSafari6plus) {
// Chrome 14+
// Opera 15+
// Safari 6.0+
return event.which === 0;
}
}
return GrabToPan;
})();
var HandTool = {
initialize: function handToolInitialize(options) {
var toggleHandTool = options.toggleHandTool;
this.handTool = new GrabToPan({
element: options.container,
onActiveChanged: function(isActive) {
if (!toggleHandTool) {
return;
}
if (isActive) {
toggleHandTool.title =
mozL10n.get('hand_tool_disable.title', null, 'Disable hand tool');
toggleHandTool.firstElementChild.textContent =
mozL10n.get('hand_tool_disable_label', null, 'Disable hand tool');
} else {
toggleHandTool.title =
mozL10n.get('hand_tool_enable.title', null, 'Enable hand tool');
toggleHandTool.firstElementChild.textContent =
mozL10n.get('hand_tool_enable_label', null, 'Enable hand tool');
}
}
});
if (toggleHandTool) {
toggleHandTool.addEventListener('click', this.toggle.bind(this), false);
window.addEventListener('localized', function (evt) {
Preferences.get('enableHandToolOnLoad').then(function resolved(value) {
if (value) {
this.handTool.activate();
}
}.bind(this), function rejected(reason) {});
}.bind(this));
window.addEventListener('presentationmodechanged', function (evt) {
if (evt.detail.switchInProgress) {
return;
}
if (evt.detail.active) {
this.enterPresentationMode();
} else {
this.exitPresentationMode();
}
}.bind(this));
}
},
toggle: function handToolToggle() {
this.handTool.toggle();
SecondaryToolbar.close();
},
enterPresentationMode: function handToolEnterPresentationMode() {
if (this.handTool.active) {
this.wasActive = true;
this.handTool.deactivate();
}
},
exitPresentationMode: function handToolExitPresentationMode() {
if (this.wasActive) {
this.wasActive = null;
this.handTool.activate();
}
}
};
var OverlayManager = {
overlays: {},
active: null,
/**
* @param {string} name The name of the overlay that is registered. This must
* be equal to the ID of the overlay's DOM element.
* @param {function} callerCloseMethod (optional) The method that, if present,
* will call OverlayManager.close from the Object
* registering the overlay. Access to this method is
* necessary in order to run cleanup code when e.g.
* the overlay is force closed. The default is null.
* @param {boolean} canForceClose (optional) Indicates if opening the overlay
* will close an active overlay. The default is false.
* @returns {Promise} A promise that is resolved when the overlay has been
* registered.
*/
register: function overlayManagerRegister(name,
callerCloseMethod, canForceClose) {
return new Promise(function (resolve) {
var element, container;
if (!name || !(element = document.getElementById(name)) ||
!(container = element.parentNode)) {
throw new Error('Not enough parameters.');
} else if (this.overlays[name]) {
throw new Error('The overlay is already registered.');
}
this.overlays[name] = { element: element,
container: container,
callerCloseMethod: (callerCloseMethod || null),
canForceClose: (canForceClose || false) };
resolve();
}.bind(this));
},
/**
* @param {string} name The name of the overlay that is unregistered.
* @returns {Promise} A promise that is resolved when the overlay has been
* unregistered.
*/
unregister: function overlayManagerUnregister(name) {
return new Promise(function (resolve) {
if (!this.overlays[name]) {
throw new Error('The overlay does not exist.');
} else if (this.active === name) {
throw new Error('The overlay cannot be removed while it is active.');
}
delete this.overlays[name];
resolve();
}.bind(this));
},
/**
* @param {string} name The name of the overlay that should be opened.
* @returns {Promise} A promise that is resolved when the overlay has been
* opened.
*/
open: function overlayManagerOpen(name) {
return new Promise(function (resolve) {
if (!this.overlays[name]) {
throw new Error('The overlay does not exist.');
} else if (this.active) {
if (this.overlays[name].canForceClose) {
this._closeThroughCaller();
} else if (this.active === name) {
throw new Error('The overlay is already active.');
} else {
throw new Error('Another overlay is currently active.');
}
}
this.active = name;
this.overlays[this.active].element.classList.remove('hidden');
this.overlays[this.active].container.classList.remove('hidden');
window.addEventListener('keydown', this._keyDown);
resolve();
}.bind(this));
},
/**
* @param {string} name The name of the overlay that should be closed.
* @returns {Promise} A promise that is resolved when the overlay has been
* closed.
*/
close: function overlayManagerClose(name) {
return new Promise(function (resolve) {
if (!this.overlays[name]) {
throw new Error('The overlay does not exist.');
} else if (!this.active) {
throw new Error('The overlay is currently not active.');
} else if (this.active !== name) {
throw new Error('Another overlay is currently active.');
}
this.overlays[this.active].container.classList.add('hidden');
this.overlays[this.active].element.classList.add('hidden');
this.active = null;
window.removeEventListener('keydown', this._keyDown);
resolve();
}.bind(this));
},
/**
* @private
*/
_keyDown: function overlayManager_keyDown(evt) {
var self = OverlayManager;
if (self.active && evt.keyCode === 27) { // Esc key.
self._closeThroughCaller();
evt.preventDefault();
}
},
/**
* @private
*/
_closeThroughCaller: function overlayManager_closeThroughCaller() {
if (this.overlays[this.active].callerCloseMethod) {
this.overlays[this.active].callerCloseMethod();
}
if (this.active) {
this.close(this.active);
}
}
};
var PasswordPrompt = {
overlayName: null,
updatePassword: null,
reason: null,
passwordField: null,
passwordText: null,
passwordSubmit: null,
passwordCancel: null,
initialize: function secondaryToolbarInitialize(options) {
this.overlayName = options.overlayName;
this.passwordField = options.passwordField;
this.passwordText = options.passwordText;
this.passwordSubmit = options.passwordSubmit;
this.passwordCancel = options.passwordCancel;
// Attach the event listeners.
this.passwordSubmit.addEventListener('click',
this.verifyPassword.bind(this));
this.passwordCancel.addEventListener('click', this.close.bind(this));
this.passwordField.addEventListener('keydown', function (e) {
if (e.keyCode === 13) { // Enter key
this.verifyPassword();
}
}.bind(this));
OverlayManager.register(this.overlayName, this.close.bind(this), true);
},
open: function passwordPromptOpen() {
OverlayManager.open(this.overlayName).then(function () {
this.passwordField.type = 'password';
this.passwordField.focus();
var promptString = mozL10n.get('password_label', null,
'Enter the password to open this PDF file.');
if (this.reason === PDFJS.PasswordResponses.INCORRECT_PASSWORD) {
promptString = mozL10n.get('password_invalid', null,
'Invalid password. Please try again.');
}
this.passwordText.textContent = promptString;
}.bind(this));
},
close: function passwordPromptClose() {
OverlayManager.close(this.overlayName).then(function () {
this.passwordField.value = '';
this.passwordField.type = '';
}.bind(this));
},
verifyPassword: function passwordPromptVerifyPassword() {
var password = this.passwordField.value;
if (password && password.length > 0) {
this.close();
return this.updatePassword(password);
}
}
};
/**
* @typedef {Object} PDFDocumentPropertiesOptions
* @property {string} overlayName - Name/identifier for the overlay.
* @property {Object} fields - Names and elements of the overlay's fields.
* @property {HTMLButtonElement} closeButton - Button for closing the overlay.
*/
/**
* @class
*/
var PDFDocumentProperties = (function PDFDocumentPropertiesClosure() {
/**
* @constructs PDFDocumentProperties
* @param {PDFDocumentPropertiesOptions} options
*/
function PDFDocumentProperties(options) {
this.fields = options.fields;
this.overlayName = options.overlayName;
this.rawFileSize = 0;
this.url = null;
this.pdfDocument = null;
// Bind the event listener for the Close button.
if (options.closeButton) {
options.closeButton.addEventListener('click', this.close.bind(this));
}
this.dataAvailablePromise = new Promise(function (resolve) {
this.resolveDataAvailable = resolve;
}.bind(this));
OverlayManager.register(this.overlayName, this.close.bind(this));
}
PDFDocumentProperties.prototype = {
/**
* Open the document properties overlay.
*/
open: function PDFDocumentProperties_open() {
Promise.all([OverlayManager.open(this.overlayName),
this.dataAvailablePromise]).then(function () {
this._getProperties();
}.bind(this));
},
/**
* Close the document properties overlay.
*/
close: function PDFDocumentProperties_close() {
OverlayManager.close(this.overlayName);
},
/**
* Set the file size of the PDF document. This method is used to
* update the file size in the document properties overlay once it
* is known so we do not have to wait until the entire file is loaded.
*
* @param {number} fileSize - The file size of the PDF document.
*/
setFileSize: function PDFDocumentProperties_setFileSize(fileSize) {
if (fileSize > 0) {
this.rawFileSize = fileSize;
}
},
/**
* Set a reference to the PDF document and the URL in order
* to populate the overlay fields with the document properties.
* Note that the overlay will contain no information if this method
* is not called.
*
* @param {Object} pdfDocument - A reference to the PDF document.
* @param {string} url - The URL of the document.
*/
setDocumentAndUrl:
function PDFDocumentProperties_setDocumentAndUrl(pdfDocument, url) {
this.pdfDocument = pdfDocument;
this.url = url;
this.resolveDataAvailable();
},
/**
* @private
*/
_getProperties: function PDFDocumentProperties_getProperties() {
if (!OverlayManager.active) {
// If the dialog was closed before dataAvailablePromise was resolved,
// don't bother updating the properties.
return;
}
// Get the file size (if it hasn't already been set).
this.pdfDocument.getDownloadInfo().then(function(data) {
if (data.length === this.rawFileSize) {
return;
}
this.setFileSize(data.length);
this._updateUI(this.fields['fileSize'], this._parseFileSize());
}.bind(this));
// Get the document properties.
this.pdfDocument.getMetadata().then(function(data) {
var content = {
'fileName': getPDFFileNameFromURL(this.url),
'fileSize': this._parseFileSize(),
'title': data.info.Title,
'author': data.info.Author,
'subject': data.info.Subject,
'keywords': data.info.Keywords,
'creationDate': this._parseDate(data.info.CreationDate),
'modificationDate': this._parseDate(data.info.ModDate),
'creator': data.info.Creator,
'producer': data.info.Producer,
'version': data.info.PDFFormatVersion,
'pageCount': this.pdfDocument.numPages
};
// Show the properties in the dialog.
for (var identifier in content) {
this._updateUI(this.fields[identifier], content[identifier]);
}
}.bind(this));
},
/**
* @private
*/
_updateUI: function PDFDocumentProperties_updateUI(field, content) {
if (field && content !== undefined && content !== '') {
field.textContent = content;
}
},
/**
* @private
*/
_parseFileSize: function PDFDocumentProperties_parseFileSize() {
var fileSize = this.rawFileSize, kb = fileSize / 1024;
if (!kb) {
return;
} else if (kb < 1024) {
return mozL10n.get('document_properties_kb', {
size_kb: (+kb.toPrecision(3)).toLocaleString(),
size_b: fileSize.toLocaleString()
}, '{{size_kb}} KB ({{size_b}} bytes)');
} else {
return mozL10n.get('document_properties_mb', {
size_mb: (+(kb / 1024).toPrecision(3)).toLocaleString(),
size_b: fileSize.toLocaleString()
}, '{{size_mb}} MB ({{size_b}} bytes)');
}
},
/**
* @private
*/
_parseDate: function PDFDocumentProperties_parseDate(inputDate) {
// This is implemented according to the PDF specification, but note that
// Adobe Reader doesn't handle changing the date to universal time
// and doesn't use the user's time zone (they're effectively ignoring
// the HH' and mm' parts of the date string).
var dateToParse = inputDate;
if (dateToParse === undefined) {
return '';
}
// Remove the D: prefix if it is available.
if (dateToParse.substring(0,2) === 'D:') {
dateToParse = dateToParse.substring(2);
}
// Get all elements from the PDF date string.
// JavaScript's Date object expects the month to be between
// 0 and 11 instead of 1 and 12, so we're correcting for this.
var year = parseInt(dateToParse.substring(0,4), 10);
var month = parseInt(dateToParse.substring(4,6), 10) - 1;
var day = parseInt(dateToParse.substring(6,8), 10);
var hours = parseInt(dateToParse.substring(8,10), 10);
var minutes = parseInt(dateToParse.substring(10,12), 10);
var seconds = parseInt(dateToParse.substring(12,14), 10);
var utRel = dateToParse.substring(14,15);
var offsetHours = parseInt(dateToParse.substring(15,17), 10);
var offsetMinutes = parseInt(dateToParse.substring(18,20), 10);
// As per spec, utRel = 'Z' means equal to universal time.
// The other cases ('-' and '+') have to be handled here.
if (utRel === '-') {
hours += offsetHours;
minutes += offsetMinutes;
} else if (utRel === '+') {
hours -= offsetHours;
minutes -= offsetMinutes;
}
// Return the new date format from the user's locale.
var date = new Date(Date.UTC(year, month, day, hours, minutes, seconds));
var dateString = date.toLocaleDateString();
var timeString = date.toLocaleTimeString();
return mozL10n.get('document_properties_date_string',
{date: dateString, time: timeString},
'{{date}}, {{time}}');
}
};
return PDFDocumentProperties;
})();
var PresentationModeState = {
UNKNOWN: 0,
NORMAL: 1,
CHANGING: 2,
FULLSCREEN: 3,
};
var IGNORE_CURRENT_POSITION_ON_ZOOM = false;
var DEFAULT_CACHE_SIZE = 10;
var CLEANUP_TIMEOUT = 30000;
var RenderingStates = {
INITIAL: 0,
RUNNING: 1,
PAUSED: 2,
FINISHED: 3
};
/**
* Controls rendering of the views for pages and thumbnails.
* @class
*/
var PDFRenderingQueue = (function PDFRenderingQueueClosure() {
/**
* @constructs
*/
function PDFRenderingQueue() {
this.pdfViewer = null;
this.pdfThumbnailViewer = null;
this.onIdle = null;
this.highestPriorityPage = null;
this.idleTimeout = null;
this.printing = false;
this.isThumbnailViewEnabled = false;
}
PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ {
/**
* @param {PDFViewer} pdfViewer
*/
setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
this.pdfViewer = pdfViewer;
},
/**
* @param {PDFThumbnailViewer} pdfThumbnailViewer
*/
setThumbnailViewer:
function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
this.pdfThumbnailViewer = pdfThumbnailViewer;
},
/**
* @param {IRenderableView} view
* @returns {boolean}
*/
isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
return this.highestPriorityPage === view.renderingId;
},
renderHighestPriority: function
PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
if (this.idleTimeout) {
clearTimeout(this.idleTimeout);
this.idleTimeout = null;
}
// Pages have a higher priority than thumbnails, so check them first.
if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
return;
}
// No pages needed rendering so check thumbnails.
if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
if (this.pdfThumbnailViewer.forceRendering()) {
return;
}
}
if (this.printing) {
// If printing is currently ongoing do not reschedule cleanup.
return;
}
if (this.onIdle) {
this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
}
},
getHighestPriority: function
PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
// The state has changed figure out which page has the highest priority to
// render next (if any).
// Priority:
// 1 visible pages
// 2 if last scrolled down page after the visible pages
// 2 if last scrolled up page before the visible pages
var visibleViews = visible.views;
var numVisible = visibleViews.length;
if (numVisible === 0) {
return false;
}
for (var i = 0; i < numVisible; ++i) {
var view = visibleViews[i].view;
if (!this.isViewFinished(view)) {
return view;
}
}
// All the visible views have rendered, try to render next/previous pages.
if (scrolledDown) {
var nextPageIndex = visible.last.id;
// ID's start at 1 so no need to add 1.
if (views[nextPageIndex] &&
!this.isViewFinished(views[nextPageIndex])) {
return views[nextPageIndex];
}
} else {
var previousPageIndex = visible.first.id - 2;
if (views[previousPageIndex] &&
!this.isViewFinished(views[previousPageIndex])) {
return views[previousPageIndex];
}
}
// Everything that needs to be rendered has been.
return null;
},
/**
* @param {IRenderableView} view
* @returns {boolean}
*/
isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
return view.renderingState === RenderingStates.FINISHED;
},
/**
* Render a page or thumbnail view. This calls the appropriate function
* based on the views state. If the view is already rendered it will return
* false.
* @param {IRenderableView} view
*/
renderView: function PDFRenderingQueue_renderView(view) {
var state = view.renderingState;
switch (state) {
case RenderingStates.FINISHED:
return false;
case RenderingStates.PAUSED:
this.highestPriorityPage = view.renderingId;
view.resume();
break;
case RenderingStates.RUNNING:
this.highestPriorityPage = view.renderingId;
break;
case RenderingStates.INITIAL:
this.highestPriorityPage = view.renderingId;
var continueRendering = function () {
this.renderHighestPriority();
}.bind(this);
view.draw().then(continueRendering, continueRendering);
break;
}
return true;
},
};
return PDFRenderingQueue;
})();
var TEXT_LAYER_RENDER_DELAY = 200; // ms
/**
* @typedef {Object} PDFPageViewOptions
* @property {HTMLDivElement} container - The viewer element.
* @property {number} id - The page unique ID (normally its number).
* @property {number} scale - The page scale display.
* @property {PageViewport} defaultViewport - The page viewport.
* @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
* @property {IPDFTextLayerFactory} textLayerFactory
* @property {IPDFAnnotationLayerFactory} annotationLayerFactory
*/
/**
* @class
* @implements {IRenderableView}
*/
var PDFPageView = (function PDFPageViewClosure() {
/**
* @constructs PDFPageView
* @param {PDFPageViewOptions} options
*/
function PDFPageView(options) {
var container = options.container;
var id = options.id;
var scale = options.scale;
var defaultViewport = options.defaultViewport;
var renderingQueue = options.renderingQueue;
var textLayerFactory = options.textLayerFactory;
var annotationLayerFactory = options.annotationLayerFactory;
this.id = id;
this.renderingId = 'page' + id;
this.rotation = 0;
this.scale = scale || DEFAULT_SCALE;
this.viewport = defaultViewport;
this.pdfPageRotate = defaultViewport.rotation;
this.hasRestrictedScaling = false;
this.renderingQueue = renderingQueue;
this.textLayerFactory = textLayerFactory;
this.annotationLayerFactory = annotationLayerFactory;
this.renderingState = RenderingStates.INITIAL;
this.resume = null;
this.onBeforeDraw = null;
this.onAfterDraw = null;
this.textLayer = null;
this.zoomLayer = null;
this.annotationLayer = null;
var div = document.createElement('div');
div.id = 'pageContainer' + this.id;
div.className = 'page';
div.style.width = Math.floor(this.viewport.width) + 'px';
div.style.height = Math.floor(this.viewport.height) + 'px';
div.setAttribute('data-page-number', this.id);
this.div = div;
container.appendChild(div);
}
PDFPageView.prototype = {
setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
this.pdfPage = pdfPage;
this.pdfPageRotate = pdfPage.rotate;
var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS,
totalRotation);
this.stats = pdfPage.stats;
this.reset();
},
destroy: function PDFPageView_destroy() {
this.zoomLayer = null;
this.reset();
if (this.pdfPage) {
this.pdfPage.cleanup();
}
},
reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) {
if (this.renderTask) {
this.renderTask.cancel();
}
this.resume = null;
this.renderingState = RenderingStates.INITIAL;
var div = this.div;
div.style.width = Math.floor(this.viewport.width) + 'px';
div.style.height = Math.floor(this.viewport.height) + 'px';
var childNodes = div.childNodes;
var currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null;
var currentAnnotationNode = (keepAnnotations && this.annotationLayer &&
this.annotationLayer.div) || null;
for (var i = childNodes.length - 1; i >= 0; i--) {
var node = childNodes[i];
if (currentZoomLayerNode === node || currentAnnotationNode === node) {
continue;
}
div.removeChild(node);
}
div.removeAttribute('data-loaded');
if (currentAnnotationNode) {
// Hide annotationLayer until all elements are resized
// so they are not displayed on the already-resized page
this.annotationLayer.hide();
} else {
this.annotationLayer = null;
}
if (this.canvas && !currentZoomLayerNode) {
// Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption.
this.canvas.width = 0;
this.canvas.height = 0;
delete this.canvas;
}
this.loadingIconDiv = document.createElement('div');
this.loadingIconDiv.className = 'loadingIcon';
div.appendChild(this.loadingIconDiv);
},
update: function PDFPageView_update(scale, rotation) {
this.scale = scale || this.scale;
if (typeof rotation !== 'undefined') {
this.rotation = rotation;
}
var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = this.viewport.clone({
scale: this.scale * CSS_UNITS,
rotation: totalRotation
});
var isScalingRestricted = false;
if (this.canvas && PDFJS.maxCanvasPixels > 0) {
var outputScale = this.outputScale;
var pixelsInViewport = this.viewport.width * this.viewport.height;
var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
PDFJS.maxCanvasPixels) {
isScalingRestricted = true;
}
}
if (this.canvas) {
if (PDFJS.useOnlyCssZoom ||
(this.hasRestrictedScaling && isScalingRestricted)) {
this.cssTransform(this.canvas, true);
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagerendered', true, true, {
pageNumber: this.id,
cssTransform: true,
});
this.div.dispatchEvent(event);
return;
}
if (!this.zoomLayer) {
this.zoomLayer = this.canvas.parentNode;
this.zoomLayer.style.position = 'absolute';
}
}
if (this.zoomLayer) {
this.cssTransform(this.zoomLayer.firstChild);
}
this.reset(/* keepZoomLayer = */ true, /* keepAnnotations = */ true);
},
/**
* Called when moved in the parent's container.
*/
updatePosition: function PDFPageView_updatePosition() {
if (this.textLayer) {
this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
}
},
cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) {
var CustomStyle = PDFJS.CustomStyle;
// Scale canvas, canvas wrapper, and page container.
var width = this.viewport.width;
var height = this.viewport.height;
var div = this.div;
canvas.style.width = canvas.parentNode.style.width = div.style.width =
Math.floor(width) + 'px';
canvas.style.height = canvas.parentNode.style.height = div.style.height =
Math.floor(height) + 'px';
// The canvas may have been originally rotated, rotate relative to that.
var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
var absRotation = Math.abs(relativeRotation);
var scaleX = 1, scaleY = 1;
if (absRotation === 90 || absRotation === 270) {
// Scale x and y because of the rotation.
scaleX = height / width;
scaleY = width / height;
}
var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
'scale(' + scaleX + ',' + scaleY + ')';
CustomStyle.setProp('transform', canvas, cssTransform);
if (this.textLayer) {
// Rotating the text layer is more complicated since the divs inside the
// the text layer are rotated.
// TODO: This could probably be simplified by drawing the text layer in
// one orientation then rotating overall.
var textLayerViewport = this.textLayer.viewport;
var textRelativeRotation = this.viewport.rotation -
textLayerViewport.rotation;
var textAbsRotation = Math.abs(textRelativeRotation);
var scale = width / textLayerViewport.width;
if (textAbsRotation === 90 || textAbsRotation === 270) {
scale = width / textLayerViewport.height;
}
var textLayerDiv = this.textLayer.textLayerDiv;
var transX, transY;
switch (textAbsRotation) {
case 0:
transX = transY = 0;
break;
case 90:
transX = 0;
transY = '-' + textLayerDiv.style.height;
break;
case 180:
transX = '-' + textLayerDiv.style.width;
transY = '-' + textLayerDiv.style.height;
break;
case 270:
transX = '-' + textLayerDiv.style.width;
transY = 0;
break;
default:
console.error('Bad rotation value.');
break;
}
CustomStyle.setProp('transform', textLayerDiv,
'rotate(' + textAbsRotation + 'deg) ' +
'scale(' + scale + ', ' + scale + ') ' +
'translate(' + transX + ', ' + transY + ')');
CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
}
if (redrawAnnotations && this.annotationLayer) {
this.annotationLayer.render(this.viewport, 'display');
}
},
get width() {
return this.viewport.width;
},
get height() {
return this.viewport.height;
},
getPagePoint: function PDFPageView_getPagePoint(x, y) {
return this.viewport.convertToPdfPoint(x, y);
},
draw: function PDFPageView_draw() {
if (this.renderingState !== RenderingStates.INITIAL) {
console.error('Must be in new state before drawing');
}
this.renderingState = RenderingStates.RUNNING;
var pdfPage = this.pdfPage;
var viewport = this.viewport;
var div = this.div;
// Wrap the canvas so if it has a css transform for highdpi the overflow
// will be hidden in FF.
var canvasWrapper = document.createElement('div');
canvasWrapper.style.width = div.style.width;
canvasWrapper.style.height = div.style.height;
canvasWrapper.classList.add('canvasWrapper');
var canvas = document.createElement('canvas');
canvas.id = 'page' + this.id;
// Keep the canvas hidden until the first draw callback, or until drawing
// is complete when `!this.renderingQueue`, to prevent black flickering.
canvas.setAttribute('hidden', 'hidden');
var isCanvasHidden = true;
canvasWrapper.appendChild(canvas);
if (this.annotationLayer && this.annotationLayer.div) {
// annotationLayer needs to stay on top
div.insertBefore(canvasWrapper, this.annotationLayer.div);
} else {
div.appendChild(canvasWrapper);
}
this.canvas = canvas;
canvas.mozOpaque = true;
var ctx = canvas.getContext('2d', {alpha: false});
var outputScale = getOutputScale(ctx);
this.outputScale = outputScale;
if (PDFJS.useOnlyCssZoom) {
var actualSizeViewport = viewport.clone({scale: CSS_UNITS});
// Use a scale that will make the canvas be the original intended size
// of the page.
outputScale.sx *= actualSizeViewport.width / viewport.width;
outputScale.sy *= actualSizeViewport.height / viewport.height;
outputScale.scaled = true;
}
if (PDFJS.maxCanvasPixels > 0) {
var pixelsInViewport = viewport.width * viewport.height;
var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
outputScale.sx = maxScale;
outputScale.sy = maxScale;
outputScale.scaled = true;
this.hasRestrictedScaling = true;
} else {
this.hasRestrictedScaling = false;
}
}
var sfx = approximateFraction(outputScale.sx);
var sfy = approximateFraction(outputScale.sy);
canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]);
canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]);
canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px';
canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px';
// Add the viewport so it's known what it was originally drawn with.
canvas._viewport = viewport;
var textLayerDiv = null;
var textLayer = null;
if (this.textLayerFactory) {
textLayerDiv = document.createElement('div');
textLayerDiv.className = 'textLayer';
textLayerDiv.style.width = canvasWrapper.style.width;
textLayerDiv.style.height = canvasWrapper.style.height;
if (this.annotationLayer && this.annotationLayer.div) {
// annotationLayer needs to stay on top
div.insertBefore(textLayerDiv, this.annotationLayer.div);
} else {
div.appendChild(textLayerDiv);
}
textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv,
this.id - 1,
this.viewport);
}
this.textLayer = textLayer;
var resolveRenderPromise, rejectRenderPromise;
var promise = new Promise(function (resolve, reject) {
resolveRenderPromise = resolve;
rejectRenderPromise = reject;
});
// Rendering area
var self = this;
function pageViewDrawCallback(error) {
// The renderTask may have been replaced by a new one, so only remove
// the reference to the renderTask if it matches the one that is
// triggering this callback.
if (renderTask === self.renderTask) {
self.renderTask = null;
}
if (error === 'cancelled') {
rejectRenderPromise(error);
return;
}
self.renderingState = RenderingStates.FINISHED;
if (isCanvasHidden) {
self.canvas.removeAttribute('hidden');
isCanvasHidden = false;
}
if (self.loadingIconDiv) {
div.removeChild(self.loadingIconDiv);
delete self.loadingIconDiv;
}
if (self.zoomLayer) {
// Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption.
var zoomLayerCanvas = self.zoomLayer.firstChild;
zoomLayerCanvas.width = 0;
zoomLayerCanvas.height = 0;
div.removeChild(self.zoomLayer);
self.zoomLayer = null;
}
self.error = error;
self.stats = pdfPage.stats;
if (self.onAfterDraw) {
self.onAfterDraw();
}
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagerendered', true, true, {
pageNumber: self.id,
cssTransform: false,
});
div.dispatchEvent(event);
// This custom event is deprecated, and will be removed in the future,
// please use the |pagerendered| event instead.
var deprecatedEvent = document.createEvent('CustomEvent');
deprecatedEvent.initCustomEvent('pagerender', true, true, {
pageNumber: pdfPage.pageNumber
});
div.dispatchEvent(deprecatedEvent);
if (!error) {
resolveRenderPromise(undefined);
} else {
rejectRenderPromise(error);
}
}
var renderContinueCallback = null;
if (this.renderingQueue) {
renderContinueCallback = function renderContinueCallback(cont) {
if (!self.renderingQueue.isHighestPriority(self)) {
self.renderingState = RenderingStates.PAUSED;
self.resume = function resumeCallback() {
self.renderingState = RenderingStates.RUNNING;
cont();
};
return;
}
if (isCanvasHidden) {
self.canvas.removeAttribute('hidden');
isCanvasHidden = false;
}
cont();
};
}
var transform = !outputScale.scaled ? null :
[outputScale.sx, 0, 0, outputScale.sy, 0, 0];
var renderContext = {
canvasContext: ctx,
transform: transform,
viewport: this.viewport,
// intent: 'default', // === 'display'
};
var renderTask = this.renderTask = this.pdfPage.render(renderContext);
renderTask.onContinue = renderContinueCallback;
this.renderTask.promise.then(
function pdfPageRenderCallback() {
pageViewDrawCallback(null);
if (textLayer) {
self.pdfPage.getTextContent({ normalizeWhitespace: true }).then(
function textContentResolved(textContent) {
textLayer.setTextContent(textContent);
textLayer.render(TEXT_LAYER_RENDER_DELAY);
}
);
}
},
function pdfPageRenderError(error) {
pageViewDrawCallback(error);
}
);
if (this.annotationLayerFactory) {
if (!this.annotationLayer) {
this.annotationLayer = this.annotationLayerFactory.
createAnnotationLayerBuilder(div, this.pdfPage);
}
this.annotationLayer.render(this.viewport, 'display');
}
div.setAttribute('data-loaded', true);
if (self.onBeforeDraw) {
self.onBeforeDraw();
}
return promise;
},
beforePrint: function PDFPageView_beforePrint() {
var CustomStyle = PDFJS.CustomStyle;
var pdfPage = this.pdfPage;
var viewport = pdfPage.getViewport(1);
// Use the same hack we use for high dpi displays for printing to get
// better output until bug 811002 is fixed in FF.
var PRINT_OUTPUT_SCALE = 2;
var canvas = document.createElement('canvas');
// The logical size of the canvas.
canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;
canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;
// The rendered size of the canvas, relative to the size of canvasWrapper.
canvas.style.width = (PRINT_OUTPUT_SCALE * 100) + '%';
canvas.style.height = (PRINT_OUTPUT_SCALE * 100) + '%';
var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' +
(1 / PRINT_OUTPUT_SCALE) + ')';
CustomStyle.setProp('transform' , canvas, cssScale);
CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');
var printContainer = document.getElementById('printContainer');
var canvasWrapper = document.createElement('div');
canvasWrapper.style.width = viewport.width + 'pt';
canvasWrapper.style.height = viewport.height + 'pt';
canvasWrapper.appendChild(canvas);
printContainer.appendChild(canvasWrapper);
canvas.mozPrintCallback = function(obj) {
var ctx = obj.context;
ctx.save();
ctx.fillStyle = 'rgb(255, 255, 255)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.restore();
// Used by the mozCurrentTransform polyfill in src/display/canvas.js.
ctx._transformMatrix =
[PRINT_OUTPUT_SCALE, 0, 0, PRINT_OUTPUT_SCALE, 0, 0];
ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE);
var renderContext = {
canvasContext: ctx,
viewport: viewport,
intent: 'print'
};
pdfPage.render(renderContext).promise.then(function() {
// Tell the printEngine that rendering this canvas/page has finished.
obj.done();
}, function(error) {
console.error(error);
// Tell the printEngine that rendering this canvas/page has failed.
// This will make the print proces stop.
if ('abort' in obj) {
obj.abort();
} else {
obj.done();
}
});
};
},
};
return PDFPageView;
})();
/**
* @typedef {Object} TextLayerBuilderOptions
* @property {HTMLDivElement} textLayerDiv - The text layer container.
* @property {number} pageIndex - The page index.
* @property {PageViewport} viewport - The viewport of the text layer.
* @property {PDFFindController} findController
*/
/**
* TextLayerBuilder provides text-selection functionality for the PDF.
* It does this by creating overlay divs over the PDF text. These divs
* contain text that matches the PDF text they are overlaying. This object
* also provides a way to highlight text that is being searched for.
* @class
*/
var TextLayerBuilder = (function TextLayerBuilderClosure() {
function TextLayerBuilder(options) {
this.textLayerDiv = options.textLayerDiv;
this.renderingDone = false;
this.divContentDone = false;
this.pageIdx = options.pageIndex;
this.pageNumber = this.pageIdx + 1;
this.matches = [];
this.viewport = options.viewport;
this.textDivs = [];
this.findController = options.findController || null;
this.textLayerRenderTask = null;
this._bindMouse();
}
TextLayerBuilder.prototype = {
_finishRendering: function TextLayerBuilder_finishRendering() {
this.renderingDone = true;
var endOfContent = document.createElement('div');
endOfContent.className = 'endOfContent';
this.textLayerDiv.appendChild(endOfContent);
var event = document.createEvent('CustomEvent');
event.initCustomEvent('textlayerrendered', true, true, {
pageNumber: this.pageNumber
});
this.textLayerDiv.dispatchEvent(event);
},
/**
* Renders the text layer.
* @param {number} timeout (optional) if specified, the rendering waits
* for specified amount of ms.
*/
render: function TextLayerBuilder_render(timeout) {
if (!this.divContentDone || this.renderingDone) {
return;
}
if (this.textLayerRenderTask) {
this.textLayerRenderTask.cancel();
this.textLayerRenderTask = null;
}
this.textDivs = [];
var textLayerFrag = document.createDocumentFragment();
this.textLayerRenderTask = PDFJS.renderTextLayer({
textContent: this.textContent,
container: textLayerFrag,
viewport: this.viewport,
textDivs: this.textDivs,
timeout: timeout
});
this.textLayerRenderTask.promise.then(function () {
this.textLayerDiv.appendChild(textLayerFrag);
this._finishRendering();
this.updateMatches();
}.bind(this), function (reason) {
// canceled or failed to render text layer -- skipping errors
});
},
setTextContent: function TextLayerBuilder_setTextContent(textContent) {
if (this.textLayerRenderTask) {
this.textLayerRenderTask.cancel();
this.textLayerRenderTask = null;
}
this.textContent = textContent;
this.divContentDone = true;
},
convertMatches: function TextLayerBuilder_convertMatches(matches) {
var i = 0;
var iIndex = 0;
var bidiTexts = this.textContent.items;
var end = bidiTexts.length - 1;
var queryLen = (this.findController === null ?
0 : this.findController.state.query.length);
var ret = [];
for (var m = 0, len = matches.length; m < len; m++) {
// Calculate the start position.
var matchIdx = matches[m];
// Loop over the divIdxs.
while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
iIndex += bidiTexts[i].str.length;
i++;
}
if (i === bidiTexts.length) {
console.error('Could not find a matching mapping');
}
var match = {
begin: {
divIdx: i,
offset: matchIdx - iIndex
}
};
// Calculate the end position.
matchIdx += queryLen;
// Somewhat the same array as above, but use > instead of >= to get
// the end position right.
while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
iIndex += bidiTexts[i].str.length;
i++;
}
match.end = {
divIdx: i,
offset: matchIdx - iIndex
};
ret.push(match);
}
return ret;
},
renderMatches: function TextLayerBuilder_renderMatches(matches) {
// Early exit if there is nothing to render.
if (matches.length === 0) {
return;
}
var bidiTexts = this.textContent.items;
var textDivs = this.textDivs;
var prevEnd = null;
var pageIdx = this.pageIdx;
var isSelectedPage = (this.findController === null ?
false : (pageIdx === this.findController.selected.pageIdx));
var selectedMatchIdx = (this.findController === null ?
-1 : this.findController.selected.matchIdx);
var highlightAll = (this.findController === null ?
false : this.findController.state.highlightAll);
var infinity = {
divIdx: -1,
offset: undefined
};
function beginText(begin, className) {
var divIdx = begin.divIdx;
textDivs[divIdx].textContent = '';
appendTextToDiv(divIdx, 0, begin.offset, className);
}
function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
var div = textDivs[divIdx];
var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
var node = document.createTextNode(content);
if (className) {
var span = document.createElement('span');
span.className = className;
span.appendChild(node);
div.appendChild(span);
return;
}
div.appendChild(node);
}
var i0 = selectedMatchIdx, i1 = i0 + 1;
if (highlightAll) {
i0 = 0;
i1 = matches.length;
} else if (!isSelectedPage) {
// Not highlighting all and this isn't the selected page, so do nothing.
return;
}
for (var i = i0; i < i1; i++) {
var match = matches[i];
var begin = match.begin;
var end = match.end;
var isSelected = (isSelectedPage && i === selectedMatchIdx);
var highlightSuffix = (isSelected ? ' selected' : '');
if (this.findController) {
this.findController.updateMatchPosition(pageIdx, i, textDivs,
begin.divIdx, end.divIdx);
}
// Match inside new div.
if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
// If there was a previous div, then add the text at the end.
if (prevEnd !== null) {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
}
// Clear the divs and set the content until the starting point.
beginText(begin);
} else {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
}
if (begin.divIdx === end.divIdx) {
appendTextToDiv(begin.divIdx, begin.offset, end.offset,
'highlight' + highlightSuffix);
} else {
appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
'highlight begin' + highlightSuffix);
for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
textDivs[n0].className = 'highlight middle' + highlightSuffix;
}
beginText(end, 'highlight end' + highlightSuffix);
}
prevEnd = end;
}
if (prevEnd) {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
}
},
updateMatches: function TextLayerBuilder_updateMatches() {
// Only show matches when all rendering is done.
if (!this.renderingDone) {
return;
}
// Clear all matches.
var matches = this.matches;
var textDivs = this.textDivs;
var bidiTexts = this.textContent.items;
var clearedUntilDivIdx = -1;
// Clear all current matches.
for (var i = 0, len = matches.length; i < len; i++) {
var match = matches[i];
var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
for (var n = begin, end = match.end.divIdx; n <= end; n++) {
var div = textDivs[n];
div.textContent = bidiTexts[n].str;
div.className = '';
}
clearedUntilDivIdx = match.end.divIdx + 1;
}
if (this.findController === null || !this.findController.active) {
return;
}
// Convert the matches on the page controller into the match format
// used for the textLayer.
this.matches = this.convertMatches(this.findController === null ?
[] : (this.findController.pageMatches[this.pageIdx] || []));
this.renderMatches(this.matches);
},
/**
* Fixes text selection: adds additional div where mouse was clicked.
* This reduces flickering of the content if mouse slowly dragged down/up.
* @private
*/
_bindMouse: function TextLayerBuilder_bindMouse() {
var div = this.textLayerDiv;
div.addEventListener('mousedown', function (e) {
var end = div.querySelector('.endOfContent');
if (!end) {
return;
}
// On non-Firefox browsers, the selection will feel better if the height
// of the endOfContent div will be adjusted to start at mouse click
// location -- this will avoid flickering when selections moves up.
// However it does not work when selection started on empty space.
var adjustTop = e.target !== div;
adjustTop = adjustTop && window.getComputedStyle(end).
getPropertyValue('-moz-user-select') !== 'none';
if (adjustTop) {
var divBounds = div.getBoundingClientRect();
var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
end.style.top = (r * 100).toFixed(2) + '%';
}
end.classList.add('active');
});
div.addEventListener('mouseup', function (e) {
var end = div.querySelector('.endOfContent');
if (!end) {
return;
}
end.style.top = '';
end.classList.remove('active');
});
},
};
return TextLayerBuilder;
})();
/**
* @constructor
* @implements IPDFTextLayerFactory
*/
function DefaultTextLayerFactory() {}
DefaultTextLayerFactory.prototype = {
/**
* @param {HTMLDivElement} textLayerDiv
* @param {number} pageIndex
* @param {PageViewport} viewport
* @returns {TextLayerBuilder}
*/
createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
return new TextLayerBuilder({
textLayerDiv: textLayerDiv,
pageIndex: pageIndex,
viewport: viewport
});
}
};
/**
* @typedef {Object} AnnotationLayerBuilderOptions
* @property {HTMLDivElement} pageDiv
* @property {PDFPage} pdfPage
* @property {IPDFLinkService} linkService
*/
/**
* @class
*/
var AnnotationLayerBuilder = (function AnnotationLayerBuilderClosure() {
/**
* @param {AnnotationLayerBuilderOptions} options
* @constructs AnnotationLayerBuilder
*/
function AnnotationLayerBuilder(options) {
this.pageDiv = options.pageDiv;
this.pdfPage = options.pdfPage;
this.linkService = options.linkService;
this.div = null;
}
AnnotationLayerBuilder.prototype =
/** @lends AnnotationLayerBuilder.prototype */ {
/**
* @param {PageViewport} viewport
* @param {string} intent (default value is 'display')
*/
render: function AnnotationLayerBuilder_render(viewport, intent) {
var self = this;
var parameters = {
intent: (intent === undefined ? 'display' : intent),
};
this.pdfPage.getAnnotations(parameters).then(function (annotations) {
viewport = viewport.clone({ dontFlip: true });
parameters = {
viewport: viewport,
div: self.div,
annotations: annotations,
page: self.pdfPage,
linkService: self.linkService
};
if (self.div) {
// If an annotationLayer already exists, refresh its children's
// transformation matrices.
PDFJS.AnnotationLayer.update(parameters);
} else {
// Create an annotation layer div and render the annotations
// if there is at least one annotation.
if (annotations.length === 0) {
return;
}
self.div = document.createElement('div');
self.div.className = 'annotationLayer';
self.pageDiv.appendChild(self.div);
parameters.div = self.div;
PDFJS.AnnotationLayer.render(parameters);
if (typeof mozL10n !== 'undefined') {
mozL10n.translate(self.div);
}
}
});
},
hide: function AnnotationLayerBuilder_hide() {
if (!this.div) {
return;
}
this.div.setAttribute('hidden', 'true');
}
};
return AnnotationLayerBuilder;
})();
/**
* @constructor
* @implements IPDFAnnotationLayerFactory
*/
function DefaultAnnotationLayerFactory() {}
DefaultAnnotationLayerFactory.prototype = {
/**
* @param {HTMLDivElement} pageDiv
* @param {PDFPage} pdfPage
* @returns {AnnotationLayerBuilder}
*/
createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
return new AnnotationLayerBuilder({
pageDiv: pageDiv,
pdfPage: pdfPage,
linkService: new SimpleLinkService(),
});
}
};
/**
* @typedef {Object} PDFViewerOptions
* @property {HTMLDivElement} container - The container for the viewer element.
* @property {HTMLDivElement} viewer - (optional) The viewer element.
* @property {IPDFLinkService} linkService - The navigation/linking service.
* @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
* queue object.
* @property {boolean} removePageBorders - (optional) Removes the border shadow
* around the pages. The default is false.
*/
/**
* Simple viewer control to display PDF content/pages.
* @class
* @implements {IRenderableView}
*/
var PDFViewer = (function pdfViewer() {
function PDFPageViewBuffer(size) {
var data = [];
this.push = function cachePush(view) {
var i = data.indexOf(view);
if (i >= 0) {
data.splice(i, 1);
}
data.push(view);
if (data.length > size) {
data.shift().destroy();
}
};
this.resize = function (newSize) {
size = newSize;
while (data.length > size) {
data.shift().destroy();
}
};
}
function isSameScale(oldScale, newScale) {
if (newScale === oldScale) {
return true;
}
if (Math.abs(newScale - oldScale) < 1e-15) {
// Prevent unnecessary re-rendering of all pages when the scale
// changes only because of limited numerical precision.
return true;
}
return false;
}
/**
* @constructs PDFViewer
* @param {PDFViewerOptions} options
*/
function PDFViewer(options) {
this.container = options.container;
this.viewer = options.viewer || options.container.firstElementChild;
this.linkService = options.linkService || new SimpleLinkService();
this.removePageBorders = options.removePageBorders || false;
this.defaultRenderingQueue = !options.renderingQueue;
if (this.defaultRenderingQueue) {
// Custom rendering queue is not specified, using default one
this.renderingQueue = new PDFRenderingQueue();
this.renderingQueue.setViewer(this);
} else {
this.renderingQueue = options.renderingQueue;
}
this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
this.updateInProgress = false;
this.presentationModeState = PresentationModeState.UNKNOWN;
this._resetView();
if (this.removePageBorders) {
this.viewer.classList.add('removePageBorders');
}
}
PDFViewer.prototype = /** @lends PDFViewer.prototype */{
get pagesCount() {
return this._pages.length;
},
getPageView: function (index) {
return this._pages[index];
},
get currentPageNumber() {
return this._currentPageNumber;
},
set currentPageNumber(val) {
if (!this.pdfDocument) {
this._currentPageNumber = val;
return;
}
var event = document.createEvent('UIEvents');
event.initUIEvent('pagechange', true, true, window, 0);
event.updateInProgress = this.updateInProgress;
if (!(0 < val && val <= this.pagesCount)) {
event.pageNumber = this._currentPageNumber;
event.previousPageNumber = val;
this.container.dispatchEvent(event);
return;
}
event.previousPageNumber = this._currentPageNumber;
this._currentPageNumber = val;
event.pageNumber = val;
this.container.dispatchEvent(event);
// Check if the caller is `PDFViewer_update`, to avoid breaking scrolling.
if (this.updateInProgress) {
return;
}
this.scrollPageIntoView(val);
},
/**
* @returns {number}
*/
get currentScale() {
return this._currentScale !== UNKNOWN_SCALE ? this._currentScale :
DEFAULT_SCALE;
},
/**
* @param {number} val - Scale of the pages in percents.
*/
set currentScale(val) {
if (isNaN(val)) {
throw new Error('Invalid numeric scale');
}
if (!this.pdfDocument) {
this._currentScale = val;
this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
return;
}
this._setScale(val, false);
},
/**
* @returns {string}
*/
get currentScaleValue() {
return this._currentScaleValue;
},
/**
* @param val - The scale of the pages (in percent or predefined value).
*/
set currentScaleValue(val) {
if (!this.pdfDocument) {
this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
this._currentScaleValue = val;
return;
}
this._setScale(val, false);
},
/**
* @returns {number}
*/
get pagesRotation() {
return this._pagesRotation;
},
/**
* @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
*/
set pagesRotation(rotation) {
this._pagesRotation = rotation;
for (var i = 0, l = this._pages.length; i < l; i++) {
var pageView = this._pages[i];
pageView.update(pageView.scale, rotation);
}
this._setScale(this._currentScaleValue, true);
if (this.defaultRenderingQueue) {
this.update();
}
},
/**
* @param pdfDocument {PDFDocument}
*/
setDocument: function (pdfDocument) {
if (this.pdfDocument) {
this._resetView();
}
this.pdfDocument = pdfDocument;
if (!pdfDocument) {
return;
}
var pagesCount = pdfDocument.numPages;
var self = this;
var resolvePagesPromise;
var pagesPromise = new Promise(function (resolve) {
resolvePagesPromise = resolve;
});
this.pagesPromise = pagesPromise;
pagesPromise.then(function () {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagesloaded', true, true, {
pagesCount: pagesCount
});
self.container.dispatchEvent(event);
});
var isOnePageRenderedResolved = false;
var resolveOnePageRendered = null;
var onePageRendered = new Promise(function (resolve) {
resolveOnePageRendered = resolve;
});
this.onePageRendered = onePageRendered;
var bindOnAfterAndBeforeDraw = function (pageView) {
pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
// Add the page to the buffer at the start of drawing. That way it can
// be evicted from the buffer and destroyed even if we pause its
// rendering.
self._buffer.push(this);
};
// when page is painted, using the image as thumbnail base
pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
if (!isOnePageRenderedResolved) {
isOnePageRenderedResolved = true;
resolveOnePageRendered();
}
};
};
var firstPagePromise = pdfDocument.getPage(1);
this.firstPagePromise = firstPagePromise;
// Fetch a single page so we can get a viewport that will be the default
// viewport for all pages
return firstPagePromise.then(function(pdfPage) {
var scale = this.currentScale;
var viewport = pdfPage.getViewport(scale * CSS_UNITS);
for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
var textLayerFactory = null;
if (!PDFJS.disableTextLayer) {
textLayerFactory = this;
}
var pageView = new PDFPageView({
container: this.viewer,
id: pageNum,
scale: scale,
defaultViewport: viewport.clone(),
renderingQueue: this.renderingQueue,
textLayerFactory: textLayerFactory,
annotationLayerFactory: this
});
bindOnAfterAndBeforeDraw(pageView);
this._pages.push(pageView);
}
var linkService = this.linkService;
// Fetch all the pages since the viewport is needed before printing
// starts to create the correct size canvas. Wait until one page is
// rendered so we don't tie up too many resources early on.
onePageRendered.then(function () {
if (!PDFJS.disableAutoFetch) {
var getPagesLeft = pagesCount;
for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
var pageView = self._pages[pageNum - 1];
if (!pageView.pdfPage) {
pageView.setPdfPage(pdfPage);
}
linkService.cachePageRef(pageNum, pdfPage.ref);
getPagesLeft--;
if (!getPagesLeft) {
resolvePagesPromise();
}
}.bind(null, pageNum));
}
} else {
// XXX: Printing is semi-broken with auto fetch disabled.
resolvePagesPromise();
}
});
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagesinit', true, true, null);
self.container.dispatchEvent(event);
if (this.defaultRenderingQueue) {
this.update();
}
if (this.findController) {
this.findController.resolveFirstPage();
}
}.bind(this));
},
_resetView: function () {
this._pages = [];
this._currentPageNumber = 1;
this._currentScale = UNKNOWN_SCALE;
this._currentScaleValue = null;
this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
this._location = null;
this._pagesRotation = 0;
this._pagesRequests = [];
var container = this.viewer;
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
},
_scrollUpdate: function PDFViewer_scrollUpdate() {
if (this.pagesCount === 0) {
return;
}
this.update();
for (var i = 0, ii = this._pages.length; i < ii; i++) {
this._pages[i].updatePosition();
}
},
_setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(
newScale, newValue, preset) {
var event = document.createEvent('UIEvents');
event.initUIEvent('scalechange', true, true, window, 0);
event.scale = newScale;
if (preset) {
event.presetValue = newValue;
}
this.container.dispatchEvent(event);
},
_setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
newScale, newValue, noScroll, preset) {
this._currentScaleValue = newValue;
if (isSameScale(this._currentScale, newScale)) {
if (preset) {
this._setScaleDispatchEvent(newScale, newValue, true);
}
return;
}
for (var i = 0, ii = this._pages.length; i < ii; i++) {
this._pages[i].update(newScale);
}
this._currentScale = newScale;
if (!noScroll) {
var page = this._currentPageNumber, dest;
if (this._location && !IGNORE_CURRENT_POSITION_ON_ZOOM &&
!(this.isInPresentationMode || this.isChangingPresentationMode)) {
page = this._location.pageNumber;
dest = [null, { name: 'XYZ' }, this._location.left,
this._location.top, null];
}
this.scrollPageIntoView(page, dest);
}
this._setScaleDispatchEvent(newScale, newValue, preset);
if (this.defaultRenderingQueue) {
this.update();
}
},
_setScale: function pdfViewer_setScale(value, noScroll) {
var scale = parseFloat(value);
if (scale > 0) {
this._setScaleUpdatePages(scale, value, noScroll, false);
} else {
var currentPage = this._pages[this._currentPageNumber - 1];
if (!currentPage) {
return;
}
var hPadding = (this.isInPresentationMode || this.removePageBorders) ?
0 : SCROLLBAR_PADDING;
var vPadding = (this.isInPresentationMode || this.removePageBorders) ?
0 : VERTICAL_PADDING;
var pageWidthScale = (this.container.clientWidth - hPadding) /
currentPage.width * currentPage.scale;
var pageHeightScale = (this.container.clientHeight - vPadding) /
currentPage.height * currentPage.scale;
switch (value) {
case 'page-actual':
scale = 1;
break;
case 'page-width':
scale = pageWidthScale;
break;
case 'page-height':
scale = pageHeightScale;
break;
case 'page-fit':
scale = Math.min(pageWidthScale, pageHeightScale);
break;
case 'auto':
var isLandscape = (currentPage.width > currentPage.height);
// For pages in landscape mode, fit the page height to the viewer
// *unless* the page would thus become too wide to fit horizontally.
var horizontalScale = isLandscape ?
Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
break;
default:
console.error('pdfViewSetScale: \'' + value +
'\' is an unknown zoom value.');
return;
}
this._setScaleUpdatePages(scale, value, noScroll, true);
}
},
/**
* Scrolls page into view.
* @param {number} pageNumber
* @param {Array} dest - (optional) original PDF destination array:
* <page-ref> </XYZ|FitXXX> <args..>
*/
scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber,
dest) {
if (!this.pdfDocument) {
return;
}
var pageView = this._pages[pageNumber - 1];
if (this.isInPresentationMode) {
if (this._currentPageNumber !== pageView.id) {
// Avoid breaking getVisiblePages in presentation mode.
this.currentPageNumber = pageView.id;
return;
}
dest = null;
// Fixes the case when PDF has different page sizes.
this._setScale(this._currentScaleValue, true);
}
if (!dest) {
scrollIntoView(pageView.div);
return;
}
var x = 0, y = 0;
var width = 0, height = 0, widthScale, heightScale;
var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
pageView.scale / CSS_UNITS;
var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
pageView.scale / CSS_UNITS;
var scale = 0;
switch (dest[1].name) {
case 'XYZ':
x = dest[2];
y = dest[3];
scale = dest[4];
// If x and/or y coordinates are not supplied, default to
// _top_ left of the page (not the obvious bottom left,
// since aligning the bottom of the intended page with the
// top of the window is rarely helpful).
x = x !== null ? x : 0;
y = y !== null ? y : pageHeight;
break;
case 'Fit':
case 'FitB':
scale = 'page-fit';
break;
case 'FitH':
case 'FitBH':
y = dest[2];
scale = 'page-width';
// According to the PDF spec, section 12.3.2.2, a `null` value in the
// parameter should maintain the position relative to the new page.
if (y === null && this._location) {
x = this._location.left;
y = this._location.top;
}
break;
case 'FitV':
case 'FitBV':
x = dest[2];
width = pageWidth;
height = pageHeight;
scale = 'page-height';
break;
case 'FitR':
x = dest[2];
y = dest[3];
width = dest[4] - x;
height = dest[5] - y;
var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
widthScale = (this.container.clientWidth - hPadding) /
width / CSS_UNITS;
heightScale = (this.container.clientHeight - vPadding) /
height / CSS_UNITS;
scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
break;
default:
return;
}
if (scale && scale !== this._currentScale) {
this.currentScaleValue = scale;
} else if (this._currentScale === UNKNOWN_SCALE) {
this.currentScaleValue = DEFAULT_SCALE_VALUE;
}
if (scale === 'page-fit' && !dest[4]) {
scrollIntoView(pageView.div);
return;
}
var boundingRect = [
pageView.viewport.convertToViewportPoint(x, y),
pageView.viewport.convertToViewportPoint(x + width, y + height)
];
var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
scrollIntoView(pageView.div, { left: left, top: top });
},
_updateLocation: function (firstPage) {
var currentScale = this._currentScale;
var currentScaleValue = this._currentScaleValue;
var normalizedScaleValue =
parseFloat(currentScaleValue) === currentScale ?
Math.round(currentScale * 10000) / 100 : currentScaleValue;
var pageNumber = firstPage.id;
var pdfOpenParams = '#page=' + pageNumber;
pdfOpenParams += '&zoom=' + normalizedScaleValue;
var currentPageView = this._pages[pageNumber - 1];
var container = this.container;
var topLeft = currentPageView.getPagePoint(
(container.scrollLeft - firstPage.x),
(container.scrollTop - firstPage.y));
var intLeft = Math.round(topLeft[0]);
var intTop = Math.round(topLeft[1]);
pdfOpenParams += ',' + intLeft + ',' + intTop;
this._location = {
pageNumber: pageNumber,
scale: normalizedScaleValue,
top: intTop,
left: intLeft,
pdfOpenParams: pdfOpenParams
};
},
update: function PDFViewer_update() {
var visible = this._getVisiblePages();
var visiblePages = visible.views;
if (visiblePages.length === 0) {
return;
}
this.updateInProgress = true;
var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
2 * visiblePages.length + 1);
this._buffer.resize(suggestedCacheSize);
this.renderingQueue.renderHighestPriority(visible);
var currentId = this._currentPageNumber;
var firstPage = visible.first;
for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
i < ii; ++i) {
var page = visiblePages[i];
if (page.percent < 100) {
break;
}
if (page.id === currentId) {
stillFullyVisible = true;
break;
}
}
if (!stillFullyVisible) {
currentId = visiblePages[0].id;
}
if (!this.isInPresentationMode) {
this.currentPageNumber = currentId;
}
this._updateLocation(firstPage);
this.updateInProgress = false;
var event = document.createEvent('UIEvents');
event.initUIEvent('updateviewarea', true, true, window, 0);
event.location = this._location;
this.container.dispatchEvent(event);
},
containsElement: function (element) {
return this.container.contains(element);
},
focus: function () {
this.container.focus();
},
get isInPresentationMode() {
return this.presentationModeState === PresentationModeState.FULLSCREEN;
},
get isChangingPresentationMode() {
return this.presentationModeState === PresentationModeState.CHANGING;
},
get isHorizontalScrollbarEnabled() {
return (this.isInPresentationMode ?
false : (this.container.scrollWidth > this.container.clientWidth));
},
_getVisiblePages: function () {
if (!this.isInPresentationMode) {
return getVisibleElements(this.container, this._pages, true);
} else {
// The algorithm in getVisibleElements doesn't work in all browsers and
// configurations when presentation mode is active.
var visible = [];
var currentPage = this._pages[this._currentPageNumber - 1];
visible.push({ id: currentPage.id, view: currentPage });
return { first: currentPage, last: currentPage, views: visible };
}
},
cleanup: function () {
for (var i = 0, ii = this._pages.length; i < ii; i++) {
if (this._pages[i] &&
this._pages[i].renderingState !== RenderingStates.FINISHED) {
this._pages[i].reset();
}
}
},
/**
* @param {PDFPageView} pageView
* @returns {PDFPage}
* @private
*/
_ensurePdfPageLoaded: function (pageView) {
if (pageView.pdfPage) {
return Promise.resolve(pageView.pdfPage);
}
var pageNumber = pageView.id;
if (this._pagesRequests[pageNumber]) {
return this._pagesRequests[pageNumber];
}
var promise = this.pdfDocument.getPage(pageNumber).then(
function (pdfPage) {
pageView.setPdfPage(pdfPage);
this._pagesRequests[pageNumber] = null;
return pdfPage;
}.bind(this));
this._pagesRequests[pageNumber] = promise;
return promise;
},
forceRendering: function (currentlyVisiblePages) {
var visiblePages = currentlyVisiblePages || this._getVisiblePages();
var pageView = this.renderingQueue.getHighestPriority(visiblePages,
this._pages,
this.scroll.down);
if (pageView) {
this._ensurePdfPageLoaded(pageView).then(function () {
this.renderingQueue.renderView(pageView);
}.bind(this));
return true;
}
return false;
},
getPageTextContent: function (pageIndex) {
return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
return page.getTextContent({ normalizeWhitespace: true });
});
},
/**
* @param {HTMLDivElement} textLayerDiv
* @param {number} pageIndex
* @param {PageViewport} viewport
* @returns {TextLayerBuilder}
*/
createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
return new TextLayerBuilder({
textLayerDiv: textLayerDiv,
pageIndex: pageIndex,
viewport: viewport,
findController: this.isInPresentationMode ? null : this.findController
});
},
/**
* @param {HTMLDivElement} pageDiv
* @param {PDFPage} pdfPage
* @returns {AnnotationLayerBuilder}
*/
createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
return new AnnotationLayerBuilder({
pageDiv: pageDiv,
pdfPage: pdfPage,
linkService: this.linkService
});
},
setFindController: function (findController) {
this.findController = findController;
},
};
return PDFViewer;
})();
var SimpleLinkService = (function SimpleLinkServiceClosure() {
function SimpleLinkService() {}
SimpleLinkService.prototype = {
/**
* @returns {number}
*/
get page() {
return 0;
},
/**
* @param {number} value
*/
set page(value) {},
/**
* @param dest - The PDF destination object.
*/
navigateTo: function (dest) {},
/**
* @param dest - The PDF destination object.
* @returns {string} The hyperlink to the PDF object.
*/
getDestinationHash: function (dest) {
return '#';
},
/**
* @param hash - The PDF parameters/hash.
* @returns {string} The hyperlink to the PDF object.
*/
getAnchorUrl: function (hash) {
return '#';
},
/**
* @param {string} hash
*/
setHash: function (hash) {},
/**
* @param {string} action
*/
executeNamedAction: function (action) {},
/**
* @param {number} pageNum - page number.
* @param {Object} pageRef - reference to the page.
*/
cachePageRef: function (pageNum, pageRef) {}
};
return SimpleLinkService;
})();
var THUMBNAIL_SCROLL_MARGIN = -19;
var THUMBNAIL_WIDTH = 98; // px
var THUMBNAIL_CANVAS_BORDER_WIDTH = 1; // px
/**
* @typedef {Object} PDFThumbnailViewOptions
* @property {HTMLDivElement} container - The viewer element.
* @property {number} id - The thumbnail's unique ID (normally its number).
* @property {PageViewport} defaultViewport - The page viewport.
* @property {IPDFLinkService} linkService - The navigation/linking service.
* @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
*/
/**
* @class
* @implements {IRenderableView}
*/
var PDFThumbnailView = (function PDFThumbnailViewClosure() {
function getTempCanvas(width, height) {
var tempCanvas = PDFThumbnailView.tempImageCache;
if (!tempCanvas) {
tempCanvas = document.createElement('canvas');
PDFThumbnailView.tempImageCache = tempCanvas;
}
tempCanvas.width = width;
tempCanvas.height = height;
// Since this is a temporary canvas, we need to fill the canvas with a white
// background ourselves. |_getPageDrawContext| uses CSS rules for this.
tempCanvas.mozOpaque = true;
var ctx = tempCanvas.getContext('2d', {alpha: false});
ctx.save();
ctx.fillStyle = 'rgb(255, 255, 255)';
ctx.fillRect(0, 0, width, height);
ctx.restore();
return tempCanvas;
}
/**
* @constructs PDFThumbnailView
* @param {PDFThumbnailViewOptions} options
*/
function PDFThumbnailView(options) {
var container = options.container;
var id = options.id;
var defaultViewport = options.defaultViewport;
var linkService = options.linkService;
var renderingQueue = options.renderingQueue;
this.id = id;
this.renderingId = 'thumbnail' + id;
this.pdfPage = null;
this.rotation = 0;
this.viewport = defaultViewport;
this.pdfPageRotate = defaultViewport.rotation;
this.linkService = linkService;
this.renderingQueue = renderingQueue;
this.hasImage = false;
this.resume = null;
this.renderingState = RenderingStates.INITIAL;
this.pageWidth = this.viewport.width;
this.pageHeight = this.viewport.height;
this.pageRatio = this.pageWidth / this.pageHeight;
this.canvasWidth = THUMBNAIL_WIDTH;
this.canvasHeight = (this.canvasWidth / this.pageRatio) | 0;
this.scale = this.canvasWidth / this.pageWidth;
var anchor = document.createElement('a');
anchor.href = linkService.getAnchorUrl('#page=' + id);
anchor.title = mozL10n.get('thumb_page_title', {page: id}, 'Page {{page}}');
anchor.onclick = function stopNavigation() {
linkService.page = id;
return false;
};
var div = document.createElement('div');
div.id = 'thumbnailContainer' + id;
div.className = 'thumbnail';
this.div = div;
if (id === 1) {
// Highlight the thumbnail of the first page when no page number is
// specified (or exists in cache) when the document is loaded.
div.classList.add('selected');
}
var ring = document.createElement('div');
ring.className = 'thumbnailSelectionRing';
var borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH;
ring.style.width = this.canvasWidth + borderAdjustment + 'px';
ring.style.height = this.canvasHeight + borderAdjustment + 'px';
this.ring = ring;
div.appendChild(ring);
anchor.appendChild(div);
container.appendChild(anchor);
}
PDFThumbnailView.prototype = {
setPdfPage: function PDFThumbnailView_setPdfPage(pdfPage) {
this.pdfPage = pdfPage;
this.pdfPageRotate = pdfPage.rotate;
var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = pdfPage.getViewport(1, totalRotation);
this.reset();
},
reset: function PDFThumbnailView_reset() {
if (this.renderTask) {
this.renderTask.cancel();
}
this.hasImage = false;
this.resume = null;
this.renderingState = RenderingStates.INITIAL;
this.pageWidth = this.viewport.width;
this.pageHeight = this.viewport.height;
this.pageRatio = this.pageWidth / this.pageHeight;
this.canvasHeight = (this.canvasWidth / this.pageRatio) | 0;
this.scale = (this.canvasWidth / this.pageWidth);
this.div.removeAttribute('data-loaded');
var ring = this.ring;
var childNodes = ring.childNodes;
for (var i = childNodes.length - 1; i >= 0; i--) {
ring.removeChild(childNodes[i]);
}
var borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH;
ring.style.width = this.canvasWidth + borderAdjustment + 'px';
ring.style.height = this.canvasHeight + borderAdjustment + 'px';
if (this.canvas) {
// Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption.
this.canvas.width = 0;
this.canvas.height = 0;
delete this.canvas;
}
if (this.image) {
this.image.removeAttribute('src');
delete this.image;
}
},
update: function PDFThumbnailView_update(rotation) {
if (typeof rotation !== 'undefined') {
this.rotation = rotation;
}
var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = this.viewport.clone({
scale: 1,
rotation: totalRotation
});
this.reset();
},
/**
* @private
*/
_getPageDrawContext:
function PDFThumbnailView_getPageDrawContext(noCtxScale) {
var canvas = document.createElement('canvas');
this.canvas = canvas;
canvas.mozOpaque = true;
var ctx = canvas.getContext('2d', {alpha: false});
var outputScale = getOutputScale(ctx);
canvas.width = (this.canvasWidth * outputScale.sx) | 0;
canvas.height = (this.canvasHeight * outputScale.sy) | 0;
canvas.style.width = this.canvasWidth + 'px';
canvas.style.height = this.canvasHeight + 'px';
if (!noCtxScale && outputScale.scaled) {
ctx.scale(outputScale.sx, outputScale.sy);
}
var image = document.createElement('img');
this.image = image;
image.id = this.renderingId;
image.className = 'thumbnailImage';
image.setAttribute('aria-label', mozL10n.get('thumb_page_canvas',
{ page: this.id }, 'Thumbnail of Page {{page}}'));
image.style.width = canvas.style.width;
image.style.height = canvas.style.height;
return ctx;
},
/**
* @private
*/
_convertCanvasToImage: function PDFThumbnailView_convertCanvasToImage() {
if (!this.canvas) {
return;
}
this.image.src = this.canvas.toDataURL();
this.div.setAttribute('data-loaded', true);
this.ring.appendChild(this.image);
// Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption.
this.canvas.width = 0;
this.canvas.height = 0;
delete this.canvas;
},
draw: function PDFThumbnailView_draw() {
if (this.renderingState !== RenderingStates.INITIAL) {
console.error('Must be in new state before drawing');
}
if (this.hasImage) {
return Promise.resolve(undefined);
}
this.hasImage = true;
this.renderingState = RenderingStates.RUNNING;
var resolveRenderPromise, rejectRenderPromise;
var promise = new Promise(function (resolve, reject) {
resolveRenderPromise = resolve;
rejectRenderPromise = reject;
});
var self = this;
function thumbnailDrawCallback(error) {
// The renderTask may have been replaced by a new one, so only remove
// the reference to the renderTask if it matches the one that is
// triggering this callback.
if (renderTask === self.renderTask) {
self.renderTask = null;
}
if (error === 'cancelled') {
rejectRenderPromise(error);
return;
}
self.renderingState = RenderingStates.FINISHED;
self._convertCanvasToImage();
if (!error) {
resolveRenderPromise(undefined);
} else {
rejectRenderPromise(error);
}
}
var ctx = this._getPageDrawContext();
var drawViewport = this.viewport.clone({ scale: this.scale });
var renderContinueCallback = function renderContinueCallback(cont) {
if (!self.renderingQueue.isHighestPriority(self)) {
self.renderingState = RenderingStates.PAUSED;
self.resume = function resumeCallback() {
self.renderingState = RenderingStates.RUNNING;
cont();
};
return;
}
cont();
};
var renderContext = {
canvasContext: ctx,
viewport: drawViewport
};
var renderTask = this.renderTask = this.pdfPage.render(renderContext);
renderTask.onContinue = renderContinueCallback;
renderTask.promise.then(
function pdfPageRenderCallback() {
thumbnailDrawCallback(null);
},
function pdfPageRenderError(error) {
thumbnailDrawCallback(error);
}
);
return promise;
},
setImage: function PDFThumbnailView_setImage(pageView) {
var img = pageView.canvas;
if (this.hasImage || !img) {
return;
}
if (!this.pdfPage) {
this.setPdfPage(pageView.pdfPage);
}
this.hasImage = true;
this.renderingState = RenderingStates.FINISHED;
var ctx = this._getPageDrawContext(true);
var canvas = ctx.canvas;
if (img.width <= 2 * canvas.width) {
ctx.drawImage(img, 0, 0, img.width, img.height,
0, 0, canvas.width, canvas.height);
this._convertCanvasToImage();
return;
}
// drawImage does an awful job of rescaling the image, doing it gradually.
var MAX_NUM_SCALING_STEPS = 3;
var reducedWidth = canvas.width << MAX_NUM_SCALING_STEPS;
var reducedHeight = canvas.height << MAX_NUM_SCALING_STEPS;
var reducedImage = getTempCanvas(reducedWidth, reducedHeight);
var reducedImageCtx = reducedImage.getContext('2d');
while (reducedWidth > img.width || reducedHeight > img.height) {
reducedWidth >>= 1;
reducedHeight >>= 1;
}
reducedImageCtx.drawImage(img, 0, 0, img.width, img.height,
0, 0, reducedWidth, reducedHeight);
while (reducedWidth > 2 * canvas.width) {
reducedImageCtx.drawImage(reducedImage,
0, 0, reducedWidth, reducedHeight,
0, 0, reducedWidth >> 1, reducedHeight >> 1);
reducedWidth >>= 1;
reducedHeight >>= 1;
}
ctx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight,
0, 0, canvas.width, canvas.height);
this._convertCanvasToImage();
}
};
return PDFThumbnailView;
})();
PDFThumbnailView.tempImageCache = null;
/**
* @typedef {Object} PDFThumbnailViewerOptions
* @property {HTMLDivElement} container - The container for the thumbnail
* elements.
* @property {IPDFLinkService} linkService - The navigation/linking service.
* @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
*/
/**
* Simple viewer control to display thumbnails for pages.
* @class
* @implements {IRenderableView}
*/
var PDFThumbnailViewer = (function PDFThumbnailViewerClosure() {
/**
* @constructs PDFThumbnailViewer
* @param {PDFThumbnailViewerOptions} options
*/
function PDFThumbnailViewer(options) {
this.container = options.container;
this.renderingQueue = options.renderingQueue;
this.linkService = options.linkService;
this.scroll = watchScroll(this.container, this._scrollUpdated.bind(this));
this._resetView();
}
PDFThumbnailViewer.prototype = {
/**
* @private
*/
_scrollUpdated: function PDFThumbnailViewer_scrollUpdated() {
this.renderingQueue.renderHighestPriority();
},
getThumbnail: function PDFThumbnailViewer_getThumbnail(index) {
return this.thumbnails[index];
},
/**
* @private
*/
_getVisibleThumbs: function PDFThumbnailViewer_getVisibleThumbs() {
return getVisibleElements(this.container, this.thumbnails);
},
scrollThumbnailIntoView:
function PDFThumbnailViewer_scrollThumbnailIntoView(page) {
var selected = document.querySelector('.thumbnail.selected');
if (selected) {
selected.classList.remove('selected');
}
var thumbnail = document.getElementById('thumbnailContainer' + page);
if (thumbnail) {
thumbnail.classList.add('selected');
}
var visibleThumbs = this._getVisibleThumbs();
var numVisibleThumbs = visibleThumbs.views.length;
// If the thumbnail isn't currently visible, scroll it into view.
if (numVisibleThumbs > 0) {
var first = visibleThumbs.first.id;
// Account for only one thumbnail being visible.
var last = (numVisibleThumbs > 1 ? visibleThumbs.last.id : first);
if (page <= first || page >= last) {
scrollIntoView(thumbnail, { top: THUMBNAIL_SCROLL_MARGIN });
}
}
},
get pagesRotation() {
return this._pagesRotation;
},
set pagesRotation(rotation) {
this._pagesRotation = rotation;
for (var i = 0, l = this.thumbnails.length; i < l; i++) {
var thumb = this.thumbnails[i];
thumb.update(rotation);
}
},
cleanup: function PDFThumbnailViewer_cleanup() {
var tempCanvas = PDFThumbnailView.tempImageCache;
if (tempCanvas) {
// Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption.
tempCanvas.width = 0;
tempCanvas.height = 0;
}
PDFThumbnailView.tempImageCache = null;
},
/**
* @private
*/
_resetView: function PDFThumbnailViewer_resetView() {
this.thumbnails = [];
this._pagesRotation = 0;
this._pagesRequests = [];
},
setDocument: function PDFThumbnailViewer_setDocument(pdfDocument) {
if (this.pdfDocument) {
// cleanup of the elements and views
var thumbsView = this.container;
while (thumbsView.hasChildNodes()) {
thumbsView.removeChild(thumbsView.lastChild);
}
this._resetView();
}
this.pdfDocument = pdfDocument;
if (!pdfDocument) {
return Promise.resolve();
}
return pdfDocument.getPage(1).then(function (firstPage) {
var pagesCount = pdfDocument.numPages;
var viewport = firstPage.getViewport(1.0);
for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
var thumbnail = new PDFThumbnailView({
container: this.container,
id: pageNum,
defaultViewport: viewport.clone(),
linkService: this.linkService,
renderingQueue: this.renderingQueue
});
this.thumbnails.push(thumbnail);
}
}.bind(this));
},
/**
* @param {PDFPageView} pageView
* @returns {PDFPage}
* @private
*/
_ensurePdfPageLoaded:
function PDFThumbnailViewer_ensurePdfPageLoaded(thumbView) {
if (thumbView.pdfPage) {
return Promise.resolve(thumbView.pdfPage);
}
var pageNumber = thumbView.id;
if (this._pagesRequests[pageNumber]) {
return this._pagesRequests[pageNumber];
}
var promise = this.pdfDocument.getPage(pageNumber).then(
function (pdfPage) {
thumbView.setPdfPage(pdfPage);
this._pagesRequests[pageNumber] = null;
return pdfPage;
}.bind(this));
this._pagesRequests[pageNumber] = promise;
return promise;
},
ensureThumbnailVisible:
function PDFThumbnailViewer_ensureThumbnailVisible(page) {
// Ensure that the thumbnail of the current page is visible
// when switching from another view.
scrollIntoView(document.getElementById('thumbnailContainer' + page));
},
forceRendering: function () {
var visibleThumbs = this._getVisibleThumbs();
var thumbView = this.renderingQueue.getHighestPriority(visibleThumbs,
this.thumbnails,
this.scroll.down);
if (thumbView) {
this._ensurePdfPageLoaded(thumbView).then(function () {
this.renderingQueue.renderView(thumbView);
}.bind(this));
return true;
}
return false;
}
};
return PDFThumbnailViewer;
})();
/**
* @typedef {Object} PDFOutlineViewOptions
* @property {HTMLDivElement} container - The viewer element.
* @property {Array} outline - An array of outline objects.
* @property {IPDFLinkService} linkService - The navigation/linking service.
*/
/**
* @class
*/
var PDFOutlineView = (function PDFOutlineViewClosure() {
/**
* @constructs PDFOutlineView
* @param {PDFOutlineViewOptions} options
*/
function PDFOutlineView(options) {
this.container = options.container;
this.outline = options.outline;
this.linkService = options.linkService;
this.lastToggleIsShow = true;
}
PDFOutlineView.prototype = {
reset: function PDFOutlineView_reset() {
var container = this.container;
while (container.firstChild) {
container.removeChild(container.firstChild);
}
this.lastToggleIsShow = true;
},
/**
* @private
*/
_dispatchEvent: function PDFOutlineView_dispatchEvent(outlineCount) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('outlineloaded', true, true, {
outlineCount: outlineCount
});
this.container.dispatchEvent(event);
},
/**
* @private
*/
_bindLink: function PDFOutlineView_bindLink(element, item) {
if (item.url) {
PDFJS.addLinkAttributes(element, { url: item.url });
return;
}
var linkService = this.linkService;
element.href = linkService.getDestinationHash(item.dest);
element.onclick = function goToDestination(e) {
linkService.navigateTo(item.dest);
return false;
};
},
/**
* Prepend a button before an outline item which allows the user to toggle
* the visibility of all outline items at that level.
*
* @private
*/
_addToggleButton: function PDFOutlineView_addToggleButton(div) {
var toggler = document.createElement('div');
toggler.className = 'outlineItemToggler';
toggler.onclick = function(event) {
event.stopPropagation();
toggler.classList.toggle('outlineItemsHidden');
if (event.shiftKey) {
var shouldShowAll = !toggler.classList.contains('outlineItemsHidden');
this._toggleOutlineItem(div, shouldShowAll);
}
}.bind(this);
div.insertBefore(toggler, div.firstChild);
},
/**
* Toggle the visibility of the subtree of an outline item.
*
* @param {Element} root - the root of the outline (sub)tree.
* @param {boolean} state - whether to show the outline (sub)tree. If false,
* the outline subtree rooted at |root| will be collapsed.
*
* @private
*/
_toggleOutlineItem: function PDFOutlineView_toggleOutlineItem(root, show) {
this.lastToggleIsShow = show;
var togglers = root.querySelectorAll('.outlineItemToggler');
for (var i = 0, ii = togglers.length; i < ii; ++i) {
togglers[i].classList[show ? 'remove' : 'add']('outlineItemsHidden');
}
},
/**
* Collapse or expand all subtrees of the outline.
*/
toggleOutlineTree: function PDFOutlineView_toggleOutlineTree() {
this._toggleOutlineItem(this.container, !this.lastToggleIsShow);
},
render: function PDFOutlineView_render() {
var outline = this.outline;
var outlineCount = 0;
this.reset();
if (!outline) {
this._dispatchEvent(outlineCount);
return;
}
var fragment = document.createDocumentFragment();
var queue = [{ parent: fragment, items: this.outline }];
var hasAnyNesting = false;
while (queue.length > 0) {
var levelData = queue.shift();
for (var i = 0, len = levelData.items.length; i < len; i++) {
var item = levelData.items[i];
var div = document.createElement('div');
div.className = 'outlineItem';
var element = document.createElement('a');
this._bindLink(element, item);
element.textContent = PDFJS.removeNullCharacters(item.title);
div.appendChild(element);
if (item.items.length > 0) {
hasAnyNesting = true;
this._addToggleButton(div);
var itemsDiv = document.createElement('div');
itemsDiv.className = 'outlineItems';
div.appendChild(itemsDiv);
queue.push({ parent: itemsDiv, items: item.items });
}
levelData.parent.appendChild(div);
outlineCount++;
}
}
if (hasAnyNesting) {
this.container.classList.add('outlineWithDeepNesting');
}
this.container.appendChild(fragment);
this._dispatchEvent(outlineCount);
}
};
return PDFOutlineView;
})();
/**
* @typedef {Object} PDFAttachmentViewOptions
* @property {HTMLDivElement} container - The viewer element.
* @property {Array} attachments - An array of attachment objects.
* @property {DownloadManager} downloadManager - The download manager.
*/
/**
* @class
*/
var PDFAttachmentView = (function PDFAttachmentViewClosure() {
/**
* @constructs PDFAttachmentView
* @param {PDFAttachmentViewOptions} options
*/
function PDFAttachmentView(options) {
this.container = options.container;
this.attachments = options.attachments;
this.downloadManager = options.downloadManager;
}
PDFAttachmentView.prototype = {
reset: function PDFAttachmentView_reset() {
var container = this.container;
while (container.firstChild) {
container.removeChild(container.firstChild);
}
},
/**
* @private
*/
_dispatchEvent: function PDFAttachmentView_dispatchEvent(attachmentsCount) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('attachmentsloaded', true, true, {
attachmentsCount: attachmentsCount
});
this.container.dispatchEvent(event);
},
/**
* @private
*/
_bindLink: function PDFAttachmentView_bindLink(button, content, filename) {
button.onclick = function downloadFile(e) {
this.downloadManager.downloadData(content, filename, '');
return false;
}.bind(this);
},
render: function PDFAttachmentView_render() {
var attachments = this.attachments;
var attachmentsCount = 0;
this.reset();
if (!attachments) {
this._dispatchEvent(attachmentsCount);
return;
}
var names = Object.keys(attachments).sort(function(a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
attachmentsCount = names.length;
for (var i = 0; i < attachmentsCount; i++) {
var item = attachments[names[i]];
var filename = getFileName(item.filename);
var div = document.createElement('div');
div.className = 'attachmentsItem';
var button = document.createElement('button');
this._bindLink(button, item.content, filename);
button.textContent = PDFJS.removeNullCharacters(filename);
div.appendChild(button);
this.container.appendChild(div);
}
this._dispatchEvent(attachmentsCount);
}
};
return PDFAttachmentView;
})();
var PDFViewerApplication = {
initialBookmark: document.location.hash.substring(1),
initialDestination: null,
initialized: false,
fellback: false,
pdfDocument: null,
pdfLoadingTask: null,
sidebarOpen: false,
printing: false,
/** @type {PDFViewer} */
pdfViewer: null,
/** @type {PDFThumbnailViewer} */
pdfThumbnailViewer: null,
/** @type {PDFRenderingQueue} */
pdfRenderingQueue: null,
/** @type {PDFPresentationMode} */
pdfPresentationMode: null,
/** @type {PDFDocumentProperties} */
pdfDocumentProperties: null,
/** @type {PDFLinkService} */
pdfLinkService: null,
/** @type {PDFHistory} */
pdfHistory: null,
pageRotation: 0,
isInitialViewSet: false,
animationStartedPromise: null,
preferenceSidebarViewOnLoad: SidebarView.NONE,
preferencePdfBugEnabled: false,
preferenceShowPreviousViewOnLoad: true,
preferenceDefaultZoomValue: '',
isViewerEmbedded: (window.parent !== window),
url: '',
// called once when the document is loaded
initialize: function pdfViewInitialize() {
var pdfRenderingQueue = new PDFRenderingQueue();
pdfRenderingQueue.onIdle = this.cleanup.bind(this);
this.pdfRenderingQueue = pdfRenderingQueue;
var pdfLinkService = new PDFLinkService();
this.pdfLinkService = pdfLinkService;
var container = document.getElementById('viewerContainer');
var viewer = document.getElementById('viewer');
this.pdfViewer = new PDFViewer({
container: container,
viewer: viewer,
renderingQueue: pdfRenderingQueue,
linkService: pdfLinkService
});
pdfRenderingQueue.setViewer(this.pdfViewer);
pdfLinkService.setViewer(this.pdfViewer);
var thumbnailContainer = document.getElementById('thumbnailView');
this.pdfThumbnailViewer = new PDFThumbnailViewer({
container: thumbnailContainer,
renderingQueue: pdfRenderingQueue,
linkService: pdfLinkService
});
pdfRenderingQueue.setThumbnailViewer(this.pdfThumbnailViewer);
Preferences.initialize();
this.pdfHistory = new PDFHistory({
linkService: pdfLinkService
});
pdfLinkService.setHistory(this.pdfHistory);
this.findController = new PDFFindController({
pdfViewer: this.pdfViewer,
integratedFind: this.supportsIntegratedFind
});
this.pdfViewer.setFindController(this.findController);
this.findBar = new PDFFindBar({
bar: document.getElementById('findbar'),
toggleButton: document.getElementById('viewFind'),
findField: document.getElementById('findInput'),
highlightAllCheckbox: document.getElementById('findHighlightAll'),
caseSensitiveCheckbox: document.getElementById('findMatchCase'),
findMsg: document.getElementById('findMsg'),
findResultsCount: document.getElementById('findResultsCount'),
findStatusIcon: document.getElementById('findStatusIcon'),
findPreviousButton: document.getElementById('findPrevious'),
findNextButton: document.getElementById('findNext'),
findController: this.findController
});
this.findController.setFindBar(this.findBar);
HandTool.initialize({
container: container,
toggleHandTool: document.getElementById('toggleHandTool')
});
this.pdfDocumentProperties = new PDFDocumentProperties({
overlayName: 'documentPropertiesOverlay',
closeButton: document.getElementById('documentPropertiesClose'),
fields: {
'fileName': document.getElementById('fileNameField'),
'fileSize': document.getElementById('fileSizeField'),
'title': document.getElementById('titleField'),
'author': document.getElementById('authorField'),
'subject': document.getElementById('subjectField'),
'keywords': document.getElementById('keywordsField'),
'creationDate': document.getElementById('creationDateField'),
'modificationDate': document.getElementById('modificationDateField'),
'creator': document.getElementById('creatorField'),
'producer': document.getElementById('producerField'),
'version': document.getElementById('versionField'),
'pageCount': document.getElementById('pageCountField')
}
});
SecondaryToolbar.initialize({
toolbar: document.getElementById('secondaryToolbar'),
toggleButton: document.getElementById('secondaryToolbarToggle'),
presentationModeButton:
document.getElementById('secondaryPresentationMode'),
openFile: document.getElementById('secondaryOpenFile'),
print: document.getElementById('secondaryPrint'),
download: document.getElementById('secondaryDownload'),
viewBookmark: document.getElementById('secondaryViewBookmark'),
firstPage: document.getElementById('firstPage'),
lastPage: document.getElementById('lastPage'),
pageRotateCw: document.getElementById('pageRotateCw'),
pageRotateCcw: document.getElementById('pageRotateCcw'),
documentPropertiesButton: document.getElementById('documentProperties')
});
if (this.supportsFullscreen) {
var toolbar = SecondaryToolbar;
this.pdfPresentationMode = new PDFPresentationMode({
container: container,
viewer: viewer,
pdfViewer: this.pdfViewer,
pdfThumbnailViewer: this.pdfThumbnailViewer,
contextMenuItems: [
{ element: document.getElementById('contextFirstPage'),
handler: toolbar.firstPageClick.bind(toolbar) },
{ element: document.getElementById('contextLastPage'),
handler: toolbar.lastPageClick.bind(toolbar) },
{ element: document.getElementById('contextPageRotateCw'),
handler: toolbar.pageRotateCwClick.bind(toolbar) },
{ element: document.getElementById('contextPageRotateCcw'),
handler: toolbar.pageRotateCcwClick.bind(toolbar) }
]
});
}
PasswordPrompt.initialize({
overlayName: 'passwordOverlay',
passwordField: document.getElementById('password'),
passwordText: document.getElementById('passwordText'),
passwordSubmit: document.getElementById('passwordSubmit'),
passwordCancel: document.getElementById('passwordCancel')
});
var self = this;
var initializedPromise = Promise.all([
Preferences.get('enableWebGL').then(function resolved(value) {
PDFJS.disableWebGL = !value;
}),
Preferences.get('sidebarViewOnLoad').then(function resolved(value) {
self.preferenceSidebarViewOnLoad = value;
}),
Preferences.get('pdfBugEnabled').then(function resolved(value) {
self.preferencePdfBugEnabled = value;
}),
Preferences.get('showPreviousViewOnLoad').then(function resolved(value) {
self.preferenceShowPreviousViewOnLoad = value;
}),
Preferences.get('defaultZoomValue').then(function resolved(value) {
self.preferenceDefaultZoomValue = value;
}),
Preferences.get('disableTextLayer').then(function resolved(value) {
if (PDFJS.disableTextLayer === true) {
return;
}
PDFJS.disableTextLayer = value;
}),
Preferences.get('disableRange').then(function resolved(value) {
if (PDFJS.disableRange === true) {
return;
}
PDFJS.disableRange = value;
}),
Preferences.get('disableStream').then(function resolved(value) {
if (PDFJS.disableStream === true) {
return;
}
PDFJS.disableStream = value;
}),
Preferences.get('disableAutoFetch').then(function resolved(value) {
PDFJS.disableAutoFetch = value;
}),
Preferences.get('disableFontFace').then(function resolved(value) {
if (PDFJS.disableFontFace === true) {
return;
}
PDFJS.disableFontFace = value;
}),
Preferences.get('useOnlyCssZoom').then(function resolved(value) {
PDFJS.useOnlyCssZoom = value;
}),
Preferences.get('externalLinkTarget').then(function resolved(value) {
if (PDFJS.isExternalLinkTargetSet()) {
return;
}
PDFJS.externalLinkTarget = value;
}),
// TODO move more preferences and other async stuff here
]).catch(function (reason) { });
return initializedPromise.then(function () {
if (self.isViewerEmbedded && !PDFJS.isExternalLinkTargetSet()) {
// Prevent external links from "replacing" the viewer,
// when it's embedded in e.g. an iframe or an object.
PDFJS.externalLinkTarget = PDFJS.LinkTarget.TOP;
}
self.initialized = true;
});
},
zoomIn: function pdfViewZoomIn(ticks) {
var newScale = this.pdfViewer.currentScale;
do {
newScale = (newScale * DEFAULT_SCALE_DELTA).toFixed(2);
newScale = Math.ceil(newScale * 10) / 10;
newScale = Math.min(MAX_SCALE, newScale);
} while (--ticks > 0 && newScale < MAX_SCALE);
this.pdfViewer.currentScaleValue = newScale;
},
zoomOut: function pdfViewZoomOut(ticks) {
var newScale = this.pdfViewer.currentScale;
do {
newScale = (newScale / DEFAULT_SCALE_DELTA).toFixed(2);
newScale = Math.floor(newScale * 10) / 10;
newScale = Math.max(MIN_SCALE, newScale);
} while (--ticks > 0 && newScale > MIN_SCALE);
this.pdfViewer.currentScaleValue = newScale;
},
get pagesCount() {
return this.pdfDocument.numPages;
},
set page(val) {
this.pdfLinkService.page = val;
},
get page() { // TODO remove
return this.pdfLinkService.page;
},
get supportsPrinting() {
var canvas = document.createElement('canvas');
var value = 'mozPrintCallback' in canvas;
return PDFJS.shadow(this, 'supportsPrinting', value);
},
get supportsFullscreen() {
var doc = document.documentElement;
var support = !!(doc.requestFullscreen || doc.mozRequestFullScreen ||
doc.webkitRequestFullScreen || doc.msRequestFullscreen);
if (document.fullscreenEnabled === false ||
document.mozFullScreenEnabled === false ||
document.webkitFullscreenEnabled === false ||
document.msFullscreenEnabled === false) {
support = false;
}
if (support && PDFJS.disableFullscreen === true) {
support = false;
}
return PDFJS.shadow(this, 'supportsFullscreen', support);
},
get supportsIntegratedFind() {
var support = false;
return PDFJS.shadow(this, 'supportsIntegratedFind', support);
},
get supportsDocumentFonts() {
var support = true;
return PDFJS.shadow(this, 'supportsDocumentFonts', support);
},
get supportsDocumentColors() {
var support = true;
return PDFJS.shadow(this, 'supportsDocumentColors', support);
},
get loadingBar() {
var bar = new ProgressBar('#loadingBar', {});
return PDFJS.shadow(this, 'loadingBar', bar);
},
get supportedMouseWheelZoomModifierKeys() {
var support = {
ctrlKey: true,
metaKey: true,
};
return PDFJS.shadow(this, 'supportedMouseWheelZoomModifierKeys', support);
},
setTitleUsingUrl: function pdfViewSetTitleUsingUrl(url) {
this.url = url;
try {
this.setTitle(decodeURIComponent(getFileName(url)) || url);
} catch (e) {
// decodeURIComponent may throw URIError,
// fall back to using the unprocessed url in that case
this.setTitle(url);
}
},
setTitle: function pdfViewSetTitle(title) {
if (this.isViewerEmbedded) {
// Embedded PDF viewers should not be changing their parent page's title.
return;
}
document.title = title;
},
/**
* Closes opened PDF document.
* @returns {Promise} - Returns the promise, which is resolved when all
* destruction is completed.
*/
close: function pdfViewClose() {
var errorWrapper = document.getElementById('errorWrapper');
errorWrapper.setAttribute('hidden', 'true');
if (!this.pdfLoadingTask) {
return Promise.resolve();
}
var promise = this.pdfLoadingTask.destroy();
this.pdfLoadingTask = null;
if (this.pdfDocument) {
this.pdfDocument = null;
this.pdfThumbnailViewer.setDocument(null);
this.pdfViewer.setDocument(null);
this.pdfLinkService.setDocument(null, null);
}
if (typeof PDFBug !== 'undefined') {
PDFBug.cleanup();
}
return promise;
},
/**
* Opens PDF document specified by URL or array with additional arguments.
* @param {string|TypedArray|ArrayBuffer} file - PDF location or binary data.
* @param {Object} args - (optional) Additional arguments for the getDocument
* call, e.g. HTTP headers ('httpHeaders') or
* alternative data transport ('range').
* @returns {Promise} - Returns the promise, which is resolved when document
* is opened.
*/
open: function pdfViewOpen(file, args) {
var scale = 0;
if (arguments.length > 2 || typeof args === 'number') {
console.warn('Call of open() with obsolete signature.');
if (typeof args === 'number') {
scale = args; // scale argument was found
}
args = arguments[4] || null;
if (arguments[3] && typeof arguments[3] === 'object') {
// The pdfDataRangeTransport argument is present.
args = Object.create(args);
args.range = arguments[3];
}
if (typeof arguments[2] === 'string') {
// The password argument is present.
args = Object.create(args);
args.password = arguments[2];
}
}
if (this.pdfLoadingTask) {
// We need to destroy already opened document.
return this.close().then(function () {
// Reload the preferences if a document was previously opened.
Preferences.reload();
// ... and repeat the open() call.
return this.open(file, args);
}.bind(this));
}
var parameters = Object.create(null);
if (typeof file === 'string') { // URL
this.setTitleUsingUrl(file);
parameters.url = file;
} else if (file && 'byteLength' in file) { // ArrayBuffer
parameters.data = file;
} else if (file.url && file.originalUrl) {
this.setTitleUsingUrl(file.originalUrl);
parameters.url = file.url;
}
if (args) {
for (var prop in args) {
parameters[prop] = args[prop];
}
}
var self = this;
self.downloadComplete = false;
var loadingTask = PDFJS.getDocument(parameters);
this.pdfLoadingTask = loadingTask;
loadingTask.onPassword = function passwordNeeded(updatePassword, reason) {
PasswordPrompt.updatePassword = updatePassword;
PasswordPrompt.reason = reason;
PasswordPrompt.open();
};
loadingTask.onProgress = function getDocumentProgress(progressData) {
self.progress(progressData.loaded / progressData.total);
};
// Listen for unsupported features to trigger the fallback UI.
loadingTask.onUnsupportedFeature = this.fallback.bind(this);
var result = loadingTask.promise.then(
function getDocumentCallback(pdfDocument) {
self.load(pdfDocument, scale);
},
function getDocumentError(exception) {
var message = exception && exception.message;
var loadingErrorMessage = mozL10n.get('loading_error', null,
'An error occurred while loading the PDF.');
if (exception instanceof PDFJS.InvalidPDFException) {
// change error message also for other builds
loadingErrorMessage = mozL10n.get('invalid_file_error', null,
'Invalid or corrupted PDF file.');
} else if (exception instanceof PDFJS.MissingPDFException) {
// special message for missing PDF's
loadingErrorMessage = mozL10n.get('missing_file_error', null,
'Missing PDF file.');
} else if (exception instanceof PDFJS.UnexpectedResponseException) {
loadingErrorMessage = mozL10n.get('unexpected_response_error', null,
'Unexpected server response.');
}
var moreInfo = {
message: message
};
self.error(loadingErrorMessage, moreInfo);
throw new Error(loadingErrorMessage);
}
);
if (args && args.length) {
PDFViewerApplication.pdfDocumentProperties.setFileSize(args.length);
}
return result;
},
download: function pdfViewDownload() {
function downloadByUrl() {
downloadManager.downloadUrl(url, filename);
}
var url = this.url.split('#')[0];
var filename = getPDFFileNameFromURL(url);
var downloadManager = new DownloadManager();
downloadManager.onerror = function (err) {
// This error won't really be helpful because it's likely the
// fallback won't work either (or is already open).
PDFViewerApplication.error('PDF failed to download.');
};
if (!this.pdfDocument) { // the PDF is not ready yet
downloadByUrl();
return;
}
if (!this.downloadComplete) { // the PDF is still downloading
downloadByUrl();
return;
}
this.pdfDocument.getData().then(
function getDataSuccess(data) {
var blob = PDFJS.createBlob(data, 'application/pdf');
downloadManager.download(blob, url, filename);
},
downloadByUrl // Error occurred try downloading with just the url.
).then(null, downloadByUrl);
},
fallback: function pdfViewFallback(featureId) {
},
/**
* Show the error box.
* @param {String} message A message that is human readable.
* @param {Object} moreInfo (optional) Further information about the error
* that is more technical. Should have a 'message'
* and optionally a 'stack' property.
*/
error: function pdfViewError(message, moreInfo) {
var moreInfoText = mozL10n.get('error_version_info',
{version: PDFJS.version || '?', build: PDFJS.build || '?'},
'PDF.js v{{version}} (build: {{build}})') + '\n';
if (moreInfo) {
moreInfoText +=
mozL10n.get('error_message', {message: moreInfo.message},
'Message: {{message}}');
if (moreInfo.stack) {
moreInfoText += '\n' +
mozL10n.get('error_stack', {stack: moreInfo.stack},
'Stack: {{stack}}');
} else {
if (moreInfo.filename) {
moreInfoText += '\n' +
mozL10n.get('error_file', {file: moreInfo.filename},
'File: {{file}}');
}
if (moreInfo.lineNumber) {
moreInfoText += '\n' +
mozL10n.get('error_line', {line: moreInfo.lineNumber},
'Line: {{line}}');
}
}
}
var errorWrapper = document.getElementById('errorWrapper');
errorWrapper.removeAttribute('hidden');
var errorMessage = document.getElementById('errorMessage');
errorMessage.textContent = message;
var closeButton = document.getElementById('errorClose');
closeButton.onclick = function() {
errorWrapper.setAttribute('hidden', 'true');
};
var errorMoreInfo = document.getElementById('errorMoreInfo');
var moreInfoButton = document.getElementById('errorShowMore');
var lessInfoButton = document.getElementById('errorShowLess');
moreInfoButton.onclick = function() {
errorMoreInfo.removeAttribute('hidden');
moreInfoButton.setAttribute('hidden', 'true');
lessInfoButton.removeAttribute('hidden');
errorMoreInfo.style.height = errorMoreInfo.scrollHeight + 'px';
};
lessInfoButton.onclick = function() {
errorMoreInfo.setAttribute('hidden', 'true');
moreInfoButton.removeAttribute('hidden');
lessInfoButton.setAttribute('hidden', 'true');
};
moreInfoButton.oncontextmenu = noContextMenuHandler;
lessInfoButton.oncontextmenu = noContextMenuHandler;
closeButton.oncontextmenu = noContextMenuHandler;
moreInfoButton.removeAttribute('hidden');
lessInfoButton.setAttribute('hidden', 'true');
errorMoreInfo.value = moreInfoText;
},
progress: function pdfViewProgress(level) {
var percent = Math.round(level * 100);
// When we transition from full request to range requests, it's possible
// that we discard some of the loaded data. This can cause the loading
// bar to move backwards. So prevent this by only updating the bar if it
// increases.
if (percent > this.loadingBar.percent || isNaN(percent)) {
this.loadingBar.percent = percent;
// When disableAutoFetch is enabled, it's not uncommon for the entire file
// to never be fetched (depends on e.g. the file structure). In this case
// the loading bar will not be completely filled, nor will it be hidden.
// To prevent displaying a partially filled loading bar permanently, we
// hide it when no data has been loaded during a certain amount of time.
if (PDFJS.disableAutoFetch && percent) {
if (this.disableAutoFetchLoadingBarTimeout) {
clearTimeout(this.disableAutoFetchLoadingBarTimeout);
this.disableAutoFetchLoadingBarTimeout = null;
}
this.loadingBar.show();
this.disableAutoFetchLoadingBarTimeout = setTimeout(function () {
this.loadingBar.hide();
this.disableAutoFetchLoadingBarTimeout = null;
}.bind(this), DISABLE_AUTO_FETCH_LOADING_BAR_TIMEOUT);
}
}
},
load: function pdfViewLoad(pdfDocument, scale) {
var self = this;
scale = scale || UNKNOWN_SCALE;
this.findController.reset();
this.pdfDocument = pdfDocument;
this.pdfDocumentProperties.setDocumentAndUrl(pdfDocument, this.url);
var downloadedPromise = pdfDocument.getDownloadInfo().then(function() {
self.downloadComplete = true;
self.loadingBar.hide();
});
var pagesCount = pdfDocument.numPages;
document.getElementById('numPages').textContent =
mozL10n.get('page_of', {pageCount: pagesCount}, 'of {{pageCount}}');
document.getElementById('pageNumber').max = pagesCount;
var id = this.documentFingerprint = pdfDocument.fingerprint;
var store = this.store = new ViewHistory(id);
var baseDocumentUrl = null;
this.pdfLinkService.setDocument(pdfDocument, baseDocumentUrl);
var pdfViewer = this.pdfViewer;
pdfViewer.currentScale = scale;
pdfViewer.setDocument(pdfDocument);
var firstPagePromise = pdfViewer.firstPagePromise;
var pagesPromise = pdfViewer.pagesPromise;
var onePageRendered = pdfViewer.onePageRendered;
this.pageRotation = 0;
this.isInitialViewSet = false;
this.pdfThumbnailViewer.setDocument(pdfDocument);
firstPagePromise.then(function(pdfPage) {
downloadedPromise.then(function () {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('documentload', true, true, {});
window.dispatchEvent(event);
});
self.loadingBar.setWidth(document.getElementById('viewer'));
if (!PDFJS.disableHistory && !self.isViewerEmbedded) {
// The browsing history is only enabled when the viewer is standalone,
// i.e. not when it is embedded in a web page.
if (!self.preferenceShowPreviousViewOnLoad) {
self.pdfHistory.clearHistoryState();
}
self.pdfHistory.initialize(self.documentFingerprint);
if (self.pdfHistory.initialDestination) {
self.initialDestination = self.pdfHistory.initialDestination;
} else if (self.pdfHistory.initialBookmark) {
self.initialBookmark = self.pdfHistory.initialBookmark;
}
}
var initialParams = {
destination: self.initialDestination,
bookmark: self.initialBookmark,
hash: null,
};
store.initializedPromise.then(function resolved() {
var storedHash = null;
if (self.preferenceShowPreviousViewOnLoad &&
store.get('exists', false)) {
var pageNum = store.get('page', '1');
var zoom = self.preferenceDefaultZoomValue ||
store.get('zoom', DEFAULT_SCALE_VALUE);
var left = store.get('scrollLeft', '0');
var top = store.get('scrollTop', '0');
storedHash = 'page=' + pageNum + '&zoom=' + zoom + ',' +
left + ',' + top;
} else if (self.preferenceDefaultZoomValue) {
storedHash = 'page=1&zoom=' + self.preferenceDefaultZoomValue;
}
self.setInitialView(storedHash, scale);
initialParams.hash = storedHash;
// Make all navigation keys work on document load,
// unless the viewer is embedded in a web page.
if (!self.isViewerEmbedded) {
self.pdfViewer.focus();
}
}, function rejected(reason) {
console.error(reason);
self.setInitialView(null, scale);
});
// For documents with different page sizes,
// ensure that the correct location becomes visible on load.
pagesPromise.then(function resolved() {
if (!initialParams.destination && !initialParams.bookmark &&
!initialParams.hash) {
return;
}
if (self.hasEqualPageSizes) {
return;
}
self.initialDestination = initialParams.destination;
self.initialBookmark = initialParams.bookmark;
self.pdfViewer.currentScaleValue = self.pdfViewer.currentScaleValue;
self.setInitialView(initialParams.hash, scale);
});
});
pagesPromise.then(function() {
if (self.supportsPrinting) {
pdfDocument.getJavaScript().then(function(javaScript) {
if (javaScript.length) {
console.warn('Warning: JavaScript is not supported');
self.fallback(PDFJS.UNSUPPORTED_FEATURES.javaScript);
}
// Hack to support auto printing.
var regex = /\bprint\s*\(/;
for (var i = 0, ii = javaScript.length; i < ii; i++) {
var js = javaScript[i];
if (js && regex.test(js)) {
setTimeout(function() {
window.print();
});
return;
}
}
});
}
});
// outline depends on pagesRefMap
var promises = [pagesPromise, this.animationStartedPromise];
Promise.all(promises).then(function() {
pdfDocument.getOutline().then(function(outline) {
var container = document.getElementById('outlineView');
self.outline = new PDFOutlineView({
container: container,
outline: outline,
linkService: self.pdfLinkService
});
self.outline.render();
document.getElementById('viewOutline').disabled = !outline;
if (!outline && !container.classList.contains('hidden')) {
self.switchSidebarView('thumbs');
}
if (outline &&
self.preferenceSidebarViewOnLoad === SidebarView.OUTLINE) {
self.switchSidebarView('outline', true);
}
});
pdfDocument.getAttachments().then(function(attachments) {
var container = document.getElementById('attachmentsView');
self.attachments = new PDFAttachmentView({
container: container,
attachments: attachments,
downloadManager: new DownloadManager()
});
self.attachments.render();
document.getElementById('viewAttachments').disabled = !attachments;
if (!attachments && !container.classList.contains('hidden')) {
self.switchSidebarView('thumbs');
}
if (attachments &&
self.preferenceSidebarViewOnLoad === SidebarView.ATTACHMENTS) {
self.switchSidebarView('attachments', true);
}
});
});
if (self.preferenceSidebarViewOnLoad === SidebarView.THUMBS) {
Promise.all([firstPagePromise, onePageRendered]).then(function () {
self.switchSidebarView('thumbs', true);
});
}
pdfDocument.getMetadata().then(function(data) {
var info = data.info, metadata = data.metadata;
self.documentInfo = info;
self.metadata = metadata;
// Provides some basic debug information
console.log('PDF ' + pdfDocument.fingerprint + ' [' +
info.PDFFormatVersion + ' ' + (info.Producer || '-').trim() +
' / ' + (info.Creator || '-').trim() + ']' +
' (PDF.js: ' + (PDFJS.version || '-') +
(!PDFJS.disableWebGL ? ' [WebGL]' : '') + ')');
var pdfTitle;
if (metadata && metadata.has('dc:title')) {
var title = metadata.get('dc:title');
// Ghostscript sometimes return 'Untitled', sets the title to 'Untitled'
if (title !== 'Untitled') {
pdfTitle = title;
}
}
if (!pdfTitle && info && info['Title']) {
pdfTitle = info['Title'];
}
if (pdfTitle) {
self.setTitle(pdfTitle + ' - ' + document.title);
}
if (info.IsAcroFormPresent) {
console.warn('Warning: AcroForm/XFA is not supported');
self.fallback(PDFJS.UNSUPPORTED_FEATURES.forms);
}
});
},
setInitialView: function pdfViewSetInitialView(storedHash, scale) {
this.isInitialViewSet = true;
// When opening a new file, when one is already loaded in the viewer,
// ensure that the 'pageNumber' element displays the correct value.
document.getElementById('pageNumber').value =
this.pdfViewer.currentPageNumber;
if (this.initialDestination) {
this.pdfLinkService.navigateTo(this.initialDestination);
this.initialDestination = null;
} else if (this.initialBookmark) {
this.pdfLinkService.setHash(this.initialBookmark);
this.pdfHistory.push({ hash: this.initialBookmark }, true);
this.initialBookmark = null;
} else if (storedHash) {
this.pdfLinkService.setHash(storedHash);
} else if (scale) {
this.pdfViewer.currentScaleValue = scale;
this.page = 1;
}
if (!this.pdfViewer.currentScaleValue) {
// Scale was not initialized: invalid bookmark or scale was not specified.
// Setting the default one.
this.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
}
},
cleanup: function pdfViewCleanup() {
if (!this.pdfDocument) {
return; // run cleanup when document is loaded
}
this.pdfViewer.cleanup();
this.pdfThumbnailViewer.cleanup();
this.pdfDocument.cleanup();
},
forceRendering: function pdfViewForceRendering() {
this.pdfRenderingQueue.printing = this.printing;
this.pdfRenderingQueue.isThumbnailViewEnabled = this.sidebarOpen;
this.pdfRenderingQueue.renderHighestPriority();
},
refreshThumbnailViewer: function pdfViewRefreshThumbnailViewer() {
var pdfViewer = this.pdfViewer;
var thumbnailViewer = this.pdfThumbnailViewer;
// set thumbnail images of rendered pages
var pagesCount = pdfViewer.pagesCount;
for (var pageIndex = 0; pageIndex < pagesCount; pageIndex++) {
var pageView = pdfViewer.getPageView(pageIndex);
if (pageView && pageView.renderingState === RenderingStates.FINISHED) {
var thumbnailView = thumbnailViewer.getThumbnail(pageIndex);
thumbnailView.setImage(pageView);
}
}
thumbnailViewer.scrollThumbnailIntoView(this.page);
},
switchSidebarView: function pdfViewSwitchSidebarView(view, openSidebar) {
if (openSidebar && !this.sidebarOpen) {
document.getElementById('sidebarToggle').click();
}
var thumbsView = document.getElementById('thumbnailView');
var outlineView = document.getElementById('outlineView');
var attachmentsView = document.getElementById('attachmentsView');
var thumbsButton = document.getElementById('viewThumbnail');
var outlineButton = document.getElementById('viewOutline');
var attachmentsButton = document.getElementById('viewAttachments');
switch (view) {
case 'thumbs':
var wasAnotherViewVisible = thumbsView.classList.contains('hidden');
thumbsButton.classList.add('toggled');
outlineButton.classList.remove('toggled');
attachmentsButton.classList.remove('toggled');
thumbsView.classList.remove('hidden');
outlineView.classList.add('hidden');
attachmentsView.classList.add('hidden');
this.forceRendering();
if (wasAnotherViewVisible) {
this.pdfThumbnailViewer.ensureThumbnailVisible(this.page);
}
break;
case 'outline':
if (outlineButton.disabled) {
return;
}
thumbsButton.classList.remove('toggled');
outlineButton.classList.add('toggled');
attachmentsButton.classList.remove('toggled');
thumbsView.classList.add('hidden');
outlineView.classList.remove('hidden');
attachmentsView.classList.add('hidden');
break;
case 'attachments':
if (attachmentsButton.disabled) {
return;
}
thumbsButton.classList.remove('toggled');
outlineButton.classList.remove('toggled');
attachmentsButton.classList.add('toggled');
thumbsView.classList.add('hidden');
outlineView.classList.add('hidden');
attachmentsView.classList.remove('hidden');
break;
}
},
beforePrint: function pdfViewSetupBeforePrint() {
if (!this.supportsPrinting) {
var printMessage = mozL10n.get('printing_not_supported', null,
'Warning: Printing is not fully supported by this browser.');
this.error(printMessage);
return;
}
var alertNotReady = false;
var i, ii;
if (!this.pdfDocument || !this.pagesCount) {
alertNotReady = true;
} else {
for (i = 0, ii = this.pagesCount; i < ii; ++i) {
if (!this.pdfViewer.getPageView(i).pdfPage) {
alertNotReady = true;
break;
}
}
}
if (alertNotReady) {
var notReadyMessage = mozL10n.get('printing_not_ready', null,
'Warning: The PDF is not fully loaded for printing.');
window.alert(notReadyMessage);
return;
}
this.printing = true;
this.forceRendering();
var body = document.querySelector('body');
body.setAttribute('data-mozPrintCallback', true);
if (!this.hasEqualPageSizes) {
console.warn('Not all pages have the same size. The printed result ' +
'may be incorrect!');
}
// Insert a @page + size rule to make sure that the page size is correctly
// set. Note that we assume that all pages have the same size, because
// variable-size pages are not supported yet (at least in Chrome & Firefox).
// TODO(robwu): Use named pages when size calculation bugs get resolved
// (e.g. https://crbug.com/355116) AND when support for named pages is
// added (http://www.w3.org/TR/css3-page/#using-named-pages).
// In browsers where @page + size is not supported (such as Firefox,
// https://bugzil.la/851441), the next stylesheet will be ignored and the
// user has to select the correct paper size in the UI if wanted.
this.pageStyleSheet = document.createElement('style');
var pageSize = this.pdfViewer.getPageView(0).pdfPage.getViewport(1);
this.pageStyleSheet.textContent =
// "size:<width> <height>" is what we need. But also add "A4" because
// Firefox incorrectly reports support for the other value.
'@supports ((size:A4) and (size:1pt 1pt)) {' +
'@page { size: ' + pageSize.width + 'pt ' + pageSize.height + 'pt;}' +
// The canvas and each ancestor node must have a height of 100% to make
// sure that each canvas is printed on exactly one page.
'#printContainer {height:100%}' +
'#printContainer > div {width:100% !important;height:100% !important;}' +
'}';
body.appendChild(this.pageStyleSheet);
for (i = 0, ii = this.pagesCount; i < ii; ++i) {
this.pdfViewer.getPageView(i).beforePrint();
}
},
// Whether all pages of the PDF have the same width and height.
get hasEqualPageSizes() {
var firstPage = this.pdfViewer.getPageView(0);
for (var i = 1, ii = this.pagesCount; i < ii; ++i) {
var pageView = this.pdfViewer.getPageView(i);
if (pageView.width !== firstPage.width ||
pageView.height !== firstPage.height) {
return false;
}
}
return true;
},
afterPrint: function pdfViewSetupAfterPrint() {
var div = document.getElementById('printContainer');
while (div.hasChildNodes()) {
div.removeChild(div.lastChild);
}
if (this.pageStyleSheet && this.pageStyleSheet.parentNode) {
this.pageStyleSheet.parentNode.removeChild(this.pageStyleSheet);
this.pageStyleSheet = null;
}
this.printing = false;
this.forceRendering();
},
rotatePages: function pdfViewRotatePages(delta) {
var pageNumber = this.page;
this.pageRotation = (this.pageRotation + 360 + delta) % 360;
this.pdfViewer.pagesRotation = this.pageRotation;
this.pdfThumbnailViewer.pagesRotation = this.pageRotation;
this.forceRendering();
this.pdfViewer.scrollPageIntoView(pageNumber);
},
requestPresentationMode: function pdfViewRequestPresentationMode() {
if (!this.pdfPresentationMode) {
return;
}
this.pdfPresentationMode.request();
},
/**
* @param {number} delta - The delta value from the mouse event.
*/
scrollPresentationMode: function pdfViewScrollPresentationMode(delta) {
if (!this.pdfPresentationMode) {
return;
}
this.pdfPresentationMode.mouseScroll(delta);
}
};
window.PDFView = PDFViewerApplication; // obsolete name, using it as an alias
var HOSTED_VIEWER_ORIGINS = ['null',
'http://mozilla.github.io', 'https://mozilla.github.io'];
function validateFileURL(file) {
try {
var viewerOrigin = new URL(window.location.href).origin || 'null';
if (HOSTED_VIEWER_ORIGINS.indexOf(viewerOrigin) >= 0) {
// Hosted or local viewer, allow for any file locations
return;
}
var fileOrigin = new URL(file, window.location.href).origin;
// Removing of the following line will not guarantee that the viewer will
// start accepting URLs from foreign origin -- CORS headers on the remote
// server must be properly configured.
if (fileOrigin !== viewerOrigin) {
throw new Error('file origin does not match viewer\'s');
}
} catch (e) {
var message = e && e.message;
var loadingErrorMessage = mozL10n.get('loading_error', null,
'An error occurred while loading the PDF.');
var moreInfo = {
message: message
};
PDFViewerApplication.error(loadingErrorMessage, moreInfo);
throw e;
}
}
function webViewerLoad(evt) {
configure(PDFJS);
PDFViewerApplication.initialize().then(webViewerInitialized);
}
function webViewerInitialized() {
var queryString = document.location.search.substring(1);
var params = parseQueryString(queryString);
var file = 'file' in params ? params.file : DEFAULT_URL;
validateFileURL(file);
var fileInput = document.createElement('input');
fileInput.id = 'fileInput';
fileInput.className = 'fileInput';
fileInput.setAttribute('type', 'file');
fileInput.oncontextmenu = noContextMenuHandler;
document.body.appendChild(fileInput);
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
document.getElementById('openFile').setAttribute('hidden', 'true');
document.getElementById('secondaryOpenFile').setAttribute('hidden', 'true');
} else {
document.getElementById('fileInput').value = null;
}
var locale = PDFJS.locale || navigator.language;
if (PDFViewerApplication.preferencePdfBugEnabled) {
// Special debugging flags in the hash section of the URL.
var hash = document.location.hash.substring(1);
var hashParams = parseQueryString(hash);
if ('disableworker' in hashParams) {
PDFJS.disableWorker = (hashParams['disableworker'] === 'true');
}
if ('disablerange' in hashParams) {
PDFJS.disableRange = (hashParams['disablerange'] === 'true');
}
if ('disablestream' in hashParams) {
PDFJS.disableStream = (hashParams['disablestream'] === 'true');
}
if ('disableautofetch' in hashParams) {
PDFJS.disableAutoFetch = (hashParams['disableautofetch'] === 'true');
}
if ('disablefontface' in hashParams) {
PDFJS.disableFontFace = (hashParams['disablefontface'] === 'true');
}
if ('disablehistory' in hashParams) {
PDFJS.disableHistory = (hashParams['disablehistory'] === 'true');
}
if ('webgl' in hashParams) {
PDFJS.disableWebGL = (hashParams['webgl'] !== 'true');
}
if ('useonlycsszoom' in hashParams) {
PDFJS.useOnlyCssZoom = (hashParams['useonlycsszoom'] === 'true');
}
if ('verbosity' in hashParams) {
PDFJS.verbosity = hashParams['verbosity'] | 0;
}
if ('ignorecurrentpositiononzoom' in hashParams) {
IGNORE_CURRENT_POSITION_ON_ZOOM =
(hashParams['ignorecurrentpositiononzoom'] === 'true');
}
if ('locale' in hashParams) {
locale = hashParams['locale'];
}
if ('textlayer' in hashParams) {
switch (hashParams['textlayer']) {
case 'off':
PDFJS.disableTextLayer = true;
break;
case 'visible':
case 'shadow':
case 'hover':
var viewer = document.getElementById('viewer');
viewer.classList.add('textLayer-' + hashParams['textlayer']);
break;
}
}
if ('pdfbug' in hashParams) {
PDFJS.pdfBug = true;
var pdfBug = hashParams['pdfbug'];
var enabled = pdfBug.split(',');
PDFBug.enable(enabled);
PDFBug.init();
}
}
mozL10n.setLanguage(locale);
if (!PDFViewerApplication.supportsPrinting) {
document.getElementById('print').classList.add('hidden');
document.getElementById('secondaryPrint').classList.add('hidden');
}
if (!PDFViewerApplication.supportsFullscreen) {
document.getElementById('presentationMode').classList.add('hidden');
document.getElementById('secondaryPresentationMode').
classList.add('hidden');
}
if (PDFViewerApplication.supportsIntegratedFind) {
document.getElementById('viewFind').classList.add('hidden');
}
// Suppress context menus for some controls
document.getElementById('scaleSelect').oncontextmenu = noContextMenuHandler;
var mainContainer = document.getElementById('mainContainer');
var outerContainer = document.getElementById('outerContainer');
mainContainer.addEventListener('transitionend', function(e) {
if (e.target === mainContainer) {
var event = document.createEvent('UIEvents');
event.initUIEvent('resize', false, false, window, 0);
window.dispatchEvent(event);
outerContainer.classList.remove('sidebarMoving');
}
}, true);
document.getElementById('sidebarToggle').addEventListener('click',
function() {
this.classList.toggle('toggled');
outerContainer.classList.add('sidebarMoving');
outerContainer.classList.toggle('sidebarOpen');
PDFViewerApplication.sidebarOpen =
outerContainer.classList.contains('sidebarOpen');
if (PDFViewerApplication.sidebarOpen) {
PDFViewerApplication.refreshThumbnailViewer();
}
PDFViewerApplication.forceRendering();
});
document.getElementById('viewThumbnail').addEventListener('click',
function() {
PDFViewerApplication.switchSidebarView('thumbs');
});
document.getElementById('viewOutline').addEventListener('click',
function() {
PDFViewerApplication.switchSidebarView('outline');
});
document.getElementById('viewOutline').addEventListener('dblclick',
function() {
PDFViewerApplication.outline.toggleOutlineTree();
});
document.getElementById('viewAttachments').addEventListener('click',
function() {
PDFViewerApplication.switchSidebarView('attachments');
});
document.getElementById('previous').addEventListener('click',
function() {
PDFViewerApplication.page--;
});
document.getElementById('next').addEventListener('click',
function() {
PDFViewerApplication.page++;
});
document.getElementById('zoomIn').addEventListener('click',
function() {
PDFViewerApplication.zoomIn();
});
document.getElementById('zoomOut').addEventListener('click',
function() {
PDFViewerApplication.zoomOut();
});
document.getElementById('pageNumber').addEventListener('click', function() {
this.select();
});
document.getElementById('pageNumber').addEventListener('change', function() {
// Handle the user inputting a floating point number.
PDFViewerApplication.page = (this.value | 0);
if (this.value !== (this.value | 0).toString()) {
this.value = PDFViewerApplication.page;
}
});
document.getElementById('scaleSelect').addEventListener('change', function() {
if (this.value === 'custom') {
return;
}
PDFViewerApplication.pdfViewer.currentScaleValue = this.value;
});
document.getElementById('presentationMode').addEventListener('click',
SecondaryToolbar.presentationModeClick.bind(SecondaryToolbar));
document.getElementById('openFile').addEventListener('click',
SecondaryToolbar.openFileClick.bind(SecondaryToolbar));
document.getElementById('print').addEventListener('click',
SecondaryToolbar.printClick.bind(SecondaryToolbar));
document.getElementById('download').addEventListener('click',
SecondaryToolbar.downloadClick.bind(SecondaryToolbar));
if (file && file.lastIndexOf('file:', 0) === 0) {
// file:-scheme. Load the contents in the main thread because QtWebKit
// cannot load file:-URLs in a Web Worker. file:-URLs are usually loaded
// very quickly, so there is no need to set up progress event listeners.
PDFViewerApplication.setTitleUsingUrl(file);
var xhr = new XMLHttpRequest();
xhr.onload = function() {
PDFViewerApplication.open(new Uint8Array(xhr.response));
};
try {
xhr.open('GET', file);
xhr.responseType = 'arraybuffer';
xhr.send();
} catch (e) {
PDFViewerApplication.error(mozL10n.get('loading_error', null,
'An error occurred while loading the PDF.'), e);
}
return;
}
if (file) {
PDFViewerApplication.open(file);
}
}
document.addEventListener('DOMContentLoaded', webViewerLoad, true);
document.addEventListener('pagerendered', function (e) {
var pageNumber = e.detail.pageNumber;
var pageIndex = pageNumber - 1;
var pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
if (PDFViewerApplication.sidebarOpen) {
var thumbnailView = PDFViewerApplication.pdfThumbnailViewer.
getThumbnail(pageIndex);
thumbnailView.setImage(pageView);
}
if (PDFJS.pdfBug && Stats.enabled && pageView.stats) {
Stats.add(pageNumber, pageView.stats);
}
if (pageView.error) {
PDFViewerApplication.error(mozL10n.get('rendering_error', null,
'An error occurred while rendering the page.'), pageView.error);
}
// If the page is still visible when it has finished rendering,
// ensure that the page number input loading indicator is hidden.
if (pageNumber === PDFViewerApplication.page) {
var pageNumberInput = document.getElementById('pageNumber');
pageNumberInput.classList.remove(PAGE_NUMBER_LOADING_INDICATOR);
}
}, true);
document.addEventListener('textlayerrendered', function (e) {
var pageIndex = e.detail.pageNumber - 1;
var pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
}, true);
document.addEventListener('pagemode', function (evt) {
if (!PDFViewerApplication.initialized) {
return;
}
// Handle the 'pagemode' hash parameter, see also `PDFLinkService_setHash`.
var mode = evt.detail.mode;
switch (mode) {
case 'bookmarks':
// Note: Our code calls this property 'outline', even though the
// Open Parameter specification calls it 'bookmarks'.
mode = 'outline';
/* falls through */
case 'thumbs':
case 'attachments':
PDFViewerApplication.switchSidebarView(mode, true);
break;
case 'none':
if (PDFViewerApplication.sidebarOpen) {
document.getElementById('sidebarToggle').click();
}
break;
}
}, true);
document.addEventListener('namedaction', function (e) {
if (!PDFViewerApplication.initialized) {
return;
}
// Processing couple of named actions that might be useful.
// See also PDFLinkService.executeNamedAction
var action = e.detail.action;
switch (action) {
case 'GoToPage':
document.getElementById('pageNumber').focus();
break;
case 'Find':
if (!PDFViewerApplication.supportsIntegratedFind) {
PDFViewerApplication.findBar.toggle();
}
break;
}
}, true);
window.addEventListener('presentationmodechanged', function (e) {
var active = e.detail.active;
var switchInProgress = e.detail.switchInProgress;
PDFViewerApplication.pdfViewer.presentationModeState =
switchInProgress ? PresentationModeState.CHANGING :
active ? PresentationModeState.FULLSCREEN : PresentationModeState.NORMAL;
});
window.addEventListener('updateviewarea', function (evt) {
if (!PDFViewerApplication.initialized) {
return;
}
var location = evt.location;
PDFViewerApplication.store.initializedPromise.then(function() {
PDFViewerApplication.store.setMultiple({
'exists': true,
'page': location.pageNumber,
'zoom': location.scale,
'scrollLeft': location.left,
'scrollTop': location.top
}).catch(function() {
// unable to write to storage
});
});
var href =
PDFViewerApplication.pdfLinkService.getAnchorUrl(location.pdfOpenParams);
document.getElementById('viewBookmark').href = href;
document.getElementById('secondaryViewBookmark').href = href;
// Update the current bookmark in the browsing history.
PDFViewerApplication.pdfHistory.updateCurrentBookmark(location.pdfOpenParams,
location.pageNumber);
// Show/hide the loading indicator in the page number input element.
var pageNumberInput = document.getElementById('pageNumber');
var currentPage =
PDFViewerApplication.pdfViewer.getPageView(PDFViewerApplication.page - 1);
if (currentPage.renderingState === RenderingStates.FINISHED) {
pageNumberInput.classList.remove(PAGE_NUMBER_LOADING_INDICATOR);
} else {
pageNumberInput.classList.add(PAGE_NUMBER_LOADING_INDICATOR);
}
}, true);
window.addEventListener('resize', function webViewerResize(evt) {
if (PDFViewerApplication.initialized) {
var currentScaleValue = PDFViewerApplication.pdfViewer.currentScaleValue;
if (currentScaleValue === 'auto' ||
currentScaleValue === 'page-fit' ||
currentScaleValue === 'page-width') {
// Note: the scale is constant for 'page-actual'.
PDFViewerApplication.pdfViewer.currentScaleValue = currentScaleValue;
} else if (!currentScaleValue) {
// Normally this shouldn't happen, but if the scale wasn't initialized
// we set it to the default value in order to prevent any issues.
// (E.g. the document being rendered with the wrong scale on load.)
PDFViewerApplication.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
}
PDFViewerApplication.pdfViewer.update();
}
// Set the 'max-height' CSS property of the secondary toolbar.
SecondaryToolbar.setMaxHeight(document.getElementById('viewerContainer'));
});
window.addEventListener('hashchange', function webViewerHashchange(evt) {
if (PDFViewerApplication.pdfHistory.isHashChangeUnlocked) {
var hash = document.location.hash.substring(1);
if (!hash) {
return;
}
if (!PDFViewerApplication.isInitialViewSet) {
PDFViewerApplication.initialBookmark = hash;
} else {
PDFViewerApplication.pdfLinkService.setHash(hash);
}
}
});
window.addEventListener('change', function webViewerChange(evt) {
var files = evt.target.files;
if (!files || files.length === 0) {
return;
}
var file = files[0];
if (!PDFJS.disableCreateObjectURL &&
typeof URL !== 'undefined' && URL.createObjectURL) {
PDFViewerApplication.open(URL.createObjectURL(file));
} else {
// Read the local file into a Uint8Array.
var fileReader = new FileReader();
fileReader.onload = function webViewerChangeFileReaderOnload(evt) {
var buffer = evt.target.result;
var uint8Array = new Uint8Array(buffer);
PDFViewerApplication.open(uint8Array);
};
fileReader.readAsArrayBuffer(file);
}
PDFViewerApplication.setTitleUsingUrl(file.name);
// URL does not reflect proper document location - hiding some icons.
document.getElementById('viewBookmark').setAttribute('hidden', 'true');
document.getElementById('secondaryViewBookmark').
setAttribute('hidden', 'true');
document.getElementById('download').setAttribute('hidden', 'true');
document.getElementById('secondaryDownload').setAttribute('hidden', 'true');
}, true);
function selectScaleOption(value) {
var options = document.getElementById('scaleSelect').options;
var predefinedValueFound = false;
for (var i = 0, ii = options.length; i < ii; i++) {
var option = options[i];
if (option.value !== value) {
option.selected = false;
continue;
}
option.selected = true;
predefinedValueFound = true;
}
return predefinedValueFound;
}
window.addEventListener('localized', function localized(evt) {
document.getElementsByTagName('html')[0].dir = mozL10n.getDirection();
PDFViewerApplication.animationStartedPromise.then(function() {
// Adjust the width of the zoom box to fit the content.
// Note: If the window is narrow enough that the zoom box is not visible,
// we temporarily show it to be able to adjust its width.
var container = document.getElementById('scaleSelectContainer');
if (container.clientWidth === 0) {
container.setAttribute('style', 'display: inherit;');
}
if (container.clientWidth > 0) {
var select = document.getElementById('scaleSelect');
select.setAttribute('style', 'min-width: inherit;');
var width = select.clientWidth + SCALE_SELECT_CONTAINER_PADDING;
select.setAttribute('style', 'min-width: ' +
(width + SCALE_SELECT_PADDING) + 'px;');
container.setAttribute('style', 'min-width: ' + width + 'px; ' +
'max-width: ' + width + 'px;');
}
// Set the 'max-height' CSS property of the secondary toolbar.
SecondaryToolbar.setMaxHeight(document.getElementById('viewerContainer'));
});
}, true);
window.addEventListener('scalechange', function scalechange(evt) {
document.getElementById('zoomOut').disabled = (evt.scale === MIN_SCALE);
document.getElementById('zoomIn').disabled = (evt.scale === MAX_SCALE);
// Update the 'scaleSelect' DOM element.
var predefinedValueFound = selectScaleOption(evt.presetValue ||
'' + evt.scale);
if (!predefinedValueFound) {
var customScaleOption = document.getElementById('customScaleOption');
var customScale = Math.round(evt.scale * 10000) / 100;
customScaleOption.textContent =
mozL10n.get('page_scale_percent', { scale: customScale }, '{{scale}}%');
customScaleOption.selected = true;
}
if (!PDFViewerApplication.initialized) {
return;
}
PDFViewerApplication.pdfViewer.update();
}, true);
window.addEventListener('pagechange', function pagechange(evt) {
var page = evt.pageNumber;
if (evt.previousPageNumber !== page) {
document.getElementById('pageNumber').value = page;
if (PDFViewerApplication.sidebarOpen) {
PDFViewerApplication.pdfThumbnailViewer.scrollThumbnailIntoView(page);
}
}
var numPages = PDFViewerApplication.pagesCount;
document.getElementById('previous').disabled = (page <= 1);
document.getElementById('next').disabled = (page >= numPages);
document.getElementById('firstPage').disabled = (page <= 1);
document.getElementById('lastPage').disabled = (page >= numPages);
// we need to update stats
if (PDFJS.pdfBug && Stats.enabled) {
var pageView = PDFViewerApplication.pdfViewer.getPageView(page - 1);
if (pageView.stats) {
Stats.add(page, pageView.stats);
}
}
}, true);
function handleMouseWheel(evt) {
var MOUSE_WHEEL_DELTA_FACTOR = 40;
var ticks = (evt.type === 'DOMMouseScroll') ? -evt.detail :
evt.wheelDelta / MOUSE_WHEEL_DELTA_FACTOR;
var direction = (ticks < 0) ? 'zoomOut' : 'zoomIn';
var pdfViewer = PDFViewerApplication.pdfViewer;
if (pdfViewer.isInPresentationMode) {
evt.preventDefault();
PDFViewerApplication.scrollPresentationMode(ticks *
MOUSE_WHEEL_DELTA_FACTOR);
} else if (evt.ctrlKey || evt.metaKey) {
var support = PDFViewerApplication.supportedMouseWheelZoomModifierKeys;
if ((evt.ctrlKey && !support.ctrlKey) ||
(evt.metaKey && !support.metaKey)) {
return;
}
// Only zoom the pages, not the entire viewer.
evt.preventDefault();
var previousScale = pdfViewer.currentScale;
PDFViewerApplication[direction](Math.abs(ticks));
var currentScale = pdfViewer.currentScale;
if (previousScale !== currentScale) {
// After scaling the page via zoomIn/zoomOut, the position of the upper-
// left corner is restored. When the mouse wheel is used, the position
// under the cursor should be restored instead.
var scaleCorrectionFactor = currentScale / previousScale - 1;
var rect = pdfViewer.container.getBoundingClientRect();
var dx = evt.clientX - rect.left;
var dy = evt.clientY - rect.top;
pdfViewer.container.scrollLeft += dx * scaleCorrectionFactor;
pdfViewer.container.scrollTop += dy * scaleCorrectionFactor;
}
}
}
window.addEventListener('DOMMouseScroll', handleMouseWheel);
window.addEventListener('mousewheel', handleMouseWheel);
window.addEventListener('click', function click(evt) {
if (SecondaryToolbar.opened &&
PDFViewerApplication.pdfViewer.containsElement(evt.target)) {
SecondaryToolbar.close();
}
}, false);
window.addEventListener('keydown', function keydown(evt) {
if (OverlayManager.active) {
return;
}
var handled = false;
var cmd = (evt.ctrlKey ? 1 : 0) |
(evt.altKey ? 2 : 0) |
(evt.shiftKey ? 4 : 0) |
(evt.metaKey ? 8 : 0);
var pdfViewer = PDFViewerApplication.pdfViewer;
var isViewerInPresentationMode = pdfViewer && pdfViewer.isInPresentationMode;
// First, handle the key bindings that are independent whether an input
// control is selected or not.
if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) {
// either CTRL or META key with optional SHIFT.
switch (evt.keyCode) {
case 70: // f
if (!PDFViewerApplication.supportsIntegratedFind) {
PDFViewerApplication.findBar.open();
handled = true;
}
break;
case 71: // g
if (!PDFViewerApplication.supportsIntegratedFind) {
PDFViewerApplication.findBar.dispatchEvent('again',
cmd === 5 || cmd === 12);
handled = true;
}
break;
case 61: // FF/Mac '='
case 107: // FF '+' and '='
case 187: // Chrome '+'
case 171: // FF with German keyboard
if (!isViewerInPresentationMode) {
PDFViewerApplication.zoomIn();
}
handled = true;
break;
case 173: // FF/Mac '-'
case 109: // FF '-'
case 189: // Chrome '-'
if (!isViewerInPresentationMode) {
PDFViewerApplication.zoomOut();
}
handled = true;
break;
case 48: // '0'
case 96: // '0' on Numpad of Swedish keyboard
if (!isViewerInPresentationMode) {
// keeping it unhandled (to restore page zoom to 100%)
setTimeout(function () {
// ... and resetting the scale after browser adjusts its scale
pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
});
handled = false;
}
break;
}
}
// CTRL or META without shift
if (cmd === 1 || cmd === 8) {
switch (evt.keyCode) {
case 83: // s
PDFViewerApplication.download();
handled = true;
break;
}
}
// CTRL+ALT or Option+Command
if (cmd === 3 || cmd === 10) {
switch (evt.keyCode) {
case 80: // p
PDFViewerApplication.requestPresentationMode();
handled = true;
break;
case 71: // g
// focuses input#pageNumber field
document.getElementById('pageNumber').select();
handled = true;
break;
}
}
if (handled) {
evt.preventDefault();
return;
}
// Some shortcuts should not get handled if a control/input element
// is selected.
var curElement = document.activeElement || document.querySelector(':focus');
var curElementTagName = curElement && curElement.tagName.toUpperCase();
if (curElementTagName === 'INPUT' ||
curElementTagName === 'TEXTAREA' ||
curElementTagName === 'SELECT') {
// Make sure that the secondary toolbar is closed when Escape is pressed.
if (evt.keyCode !== 27) { // 'Esc'
return;
}
}
var ensureViewerFocused = false;
if (cmd === 0) { // no control key pressed at all.
switch (evt.keyCode) {
case 38: // up arrow
case 33: // pg up
case 8: // backspace
if (!isViewerInPresentationMode &&
pdfViewer.currentScaleValue !== 'page-fit') {
break;
}
/* in presentation mode */
/* falls through */
case 37: // left arrow
// horizontal scrolling using arrow keys
if (pdfViewer.isHorizontalScrollbarEnabled) {
break;
}
/* falls through */
case 75: // 'k'
case 80: // 'p'
PDFViewerApplication.page--;
handled = true;
break;
case 27: // esc key
if (SecondaryToolbar.opened) {
SecondaryToolbar.close();
handled = true;
}
if (!PDFViewerApplication.supportsIntegratedFind &&
PDFViewerApplication.findBar.opened) {
PDFViewerApplication.findBar.close();
handled = true;
}
break;
case 40: // down arrow
case 34: // pg down
case 32: // spacebar
if (!isViewerInPresentationMode &&
pdfViewer.currentScaleValue !== 'page-fit') {
break;
}
/* falls through */
case 39: // right arrow
// horizontal scrolling using arrow keys
if (pdfViewer.isHorizontalScrollbarEnabled) {
break;
}
/* falls through */
case 74: // 'j'
case 78: // 'n'
PDFViewerApplication.page++;
handled = true;
break;
case 36: // home
if (isViewerInPresentationMode || PDFViewerApplication.page > 1) {
PDFViewerApplication.page = 1;
handled = true;
ensureViewerFocused = true;
}
break;
case 35: // end
if (isViewerInPresentationMode || (PDFViewerApplication.pdfDocument &&
PDFViewerApplication.page < PDFViewerApplication.pagesCount)) {
PDFViewerApplication.page = PDFViewerApplication.pagesCount;
handled = true;
ensureViewerFocused = true;
}
break;
case 72: // 'h'
if (!isViewerInPresentationMode) {
HandTool.toggle();
}
break;
case 82: // 'r'
PDFViewerApplication.rotatePages(90);
break;
}
}
if (cmd === 4) { // shift-key
switch (evt.keyCode) {
case 32: // spacebar
if (!isViewerInPresentationMode &&
pdfViewer.currentScaleValue !== 'page-fit') {
break;
}
PDFViewerApplication.page--;
handled = true;
break;
case 82: // 'r'
PDFViewerApplication.rotatePages(-90);
break;
}
}
if (!handled && !isViewerInPresentationMode) {
// 33=Page Up 34=Page Down 35=End 36=Home
// 37=Left 38=Up 39=Right 40=Down
// 32=Spacebar
if ((evt.keyCode >= 33 && evt.keyCode <= 40) ||
(evt.keyCode === 32 && curElementTagName !== 'BUTTON')) {
ensureViewerFocused = true;
}
}
if (cmd === 2) { // alt-key
switch (evt.keyCode) {
case 37: // left arrow
if (isViewerInPresentationMode) {
PDFViewerApplication.pdfHistory.back();
handled = true;
}
break;
case 39: // right arrow
if (isViewerInPresentationMode) {
PDFViewerApplication.pdfHistory.forward();
handled = true;
}
break;
}
}
if (ensureViewerFocused && !pdfViewer.containsElement(curElement)) {
// The page container is not focused, but a page navigation key has been
// pressed. Change the focus to the viewer container to make sure that
// navigation by keyboard works as expected.
pdfViewer.focus();
}
if (handled) {
evt.preventDefault();
}
});
window.addEventListener('beforeprint', function beforePrint(evt) {
PDFViewerApplication.beforePrint();
});
window.addEventListener('afterprint', function afterPrint(evt) {
PDFViewerApplication.afterPrint();
});
(function animationStartedClosure() {
// The offsetParent is not set until the pdf.js iframe or object is visible.
// Waiting for first animation.
PDFViewerApplication.animationStartedPromise = new Promise(
function (resolve) {
window.requestAnimationFrame(resolve);
});
})();
|
//place the URL of the showdown server you are aiming to connect to
exports.url = 'play.pokemonshowdown.com';
// The nick and password to log in with
var nick = exports.nick = 'Lord Haji's Butler
exports.pass = 'navanalanda';
// A list of private rooms that the bot will not leak through the seen command
exports.privaterooms = [];
// The character text should start with to be seen as a command.
// Note that using / and ! might be 'dangerous' since these are used in
// Showdown itself.
// Using only alphanumeric characters and spaces is not allowed.
// Add more command characters
var comChar = exports.commandcharacter = ['+', '.'];
// The default rank is the minimum rank that can use a command in a room when
// no rank is specified in settings.json
exports.defaultrank = '@';
// Whether this file should be watched for changes or not.
// If you change this option, the server has to be restarted in order for it to
// take effect.
exports.watchconfig = false;
// Secondary websocket protocols should be defined here, however, Showdown
// doesn't support that yet, so it's best to leave this empty.
exports.secprotocols = [];
// What should be logged?
// 0 = error, ok, info, debug, recv, send
// 1 = error, ok, info, debug, cmdr, send
// 2 = error, ok, info, debug (recommended for development)
// 3 = error, ok, info (recommended for production)
// 4 = error, ok
// 5 = error
exports.debuglevel = 3;
// Users who can use all commands regardless of their rank. Be very cautious
// with this, especially on servers other than main.
// This, however does NOT give dev permissions which are declared in parser.js
exports.excepts = [];
// Add a link to the help for the bot here. When there is a link here, .help and .guide
// will link to it.
exports.botguide = 'http://pastebin.com/zT0eFG8a';
// This allows the bot to act as an automated moderator. If enabled, the bot will
// mute users who send 6 lines or more in 6 or fewer seconds for 7 minutes. NOTE: THIS IS
// BY NO MEANS A PERFECT MODERATOR OR SCRIPT. It is a bot and so cannot think for itself or
// exercise moderator discretion. In addition, it currently uses a very simple method of
// determining who to mute and so may miss people who should be muted, or mute those who
// shouldn't. Use with caution.
exports.allowmute = true;
// The punishment values system allows you to customise how you want the bot to deal with
// rulebreakers. Spamming has a points value of 2, all caps has a points value of 1, etc.
exports.punishvals = {
1: 'warn',
2: 'mute',
3: 'mute',
4: 'hourmute',
5: 'roomban'
};
// This key is used to deliver requests from Google Spreadsheets. Used by the wifi room.
exports.googleapikey = '';
// Alt tracking - generally disabled bc it takes up a LOT of memory.
// If you use this, you will need to uncomment out the neccessary parts in the parser.js and commands.js
exports.alts = false;
// Default avatar
exports.avatar = null;
// When you pm the bot but don't use a command, it replies you this message.
// Example: "Hi, I'm a bot. Use .guide to view a command guide"
exports.pmmessage = "Hi, I am only a bot. Please PM another staff member for assistance. Use " + comChar[0] + "guide to see my commands. Have a nice day! n_n.Contact Haji(ashyudhajit) for more info";
exports.override = {
server: "sim.smogon.com",
port: 8000,
serverid: "showdown"
}
exports.override = {
server: "158.69.205.118",
port: 7000,
serverid: "origin"
}
exports.override = {
server: "54.183.91.190",
port: 8000,
serverid: "horizon"
}
|
import { toNumber } from '../../utils/helpers'
import { Song, validateSong } from './model'
export const getSongs = async (req, res) => {
try {
const docs = await Song.find()
.populate('artist', 'name')
.select('name artist')
.limit(toNumber(req.query.limit || 40))
.skip(toNumber(req.query.offset))
res.status(200).json({ data: docs })
} catch (err) {
console.error(err)
res.status(400).end()
}
}
export const addSong = async (req, res) => {
const { error } = validateSong(req.body)
if (error) return res.status(400).send(error.details[0].message)
const song = new Song({
name: req.body.name,
artist: req.body.artist
})
try {
await song.save()
} catch (err) {
for (let e in err.errors) {
console.log(err.errors[e].message)
}
}
res.send(song)
|
/*!
* Ext JS Library 3.3.0
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
/*
* Calendar sample code originally written by Brian Moeskau (brian@ext-calendar.com)
* See additional calendar examples at http://ext-calendar.com
*/
App = function() {
return {
init : function() {
Ext.BLANK_IMAGE_URL = 'http://extjs.cachefly.net/ext-3.1.0/resources/images/default/s.gif';
// This is an example calendar store that enables the events to have
// different colors based on CalendarId. This is not a fully-implmented
// multi-calendar implementation, which is beyond the scope of this sample app
this.calendarStore = new Ext.data.JsonStore({
storeId: 'calendarStore',
root: 'calendars',
idProperty: 'id',
data: calendarList, // defined in calendar-list.js
proxy: new Ext.data.MemoryProxy(),
autoLoad: true,
fields: [
{name:'CalendarId', mapping: 'id', type: 'int'},
{name:'Title', mapping: 'title', type: 'string'}
],
sortInfo: {
field: 'CalendarId',
direction: 'ASC'
}
});
// A sample event store that loads static JSON from a local file. Obviously a real
// implementation would likely be loading remote data via an HttpProxy, but the
// underlying store functionality is the same. Note that if you would like to
// provide custom data mappings for events, see EventRecord.js.
this.eventStore = new Ext.data.JsonStore({
id: 'eventStore',
root: 'evts',
data: eventList, // defined in event-list.js
proxy: new Ext.data.MemoryProxy(),
fields: Ext.calendar.EventRecord.prototype.fields.getRange(),
sortInfo: {
field: 'StartDate',
direction: 'ASC'
}
});
// This is the app UI layout code. All of the calendar views are subcomponents of
// CalendarPanel, but the app title bar and sidebar/navigation calendar are separate
// pieces that are composed in app-specific layout code since they could be ommitted
// or placed elsewhere within the application.
new Ext.Viewport({
layout: 'border',
renderTo: 'calendar-ct',
items: [{
id: 'app-header',
region: 'north',
height: 35,
border: false,
contentEl: 'app-header-content'
},{
id: 'app-center',
title: '...', // will be updated to view date range
region: 'center',
layout: 'border',
items: [{
id:'app-west',
region: 'west',
width: 176,
border: false,
items: [{
xtype: 'datepicker',
id: 'app-nav-picker',
cls: 'ext-cal-nav-picker',
listeners: {
'select': {
fn: function(dp, dt){
App.calendarPanel.setStartDate(dt);
},
scope: this
}
}
}]
},{
xtype: 'calendarpanel',
eventStore: this.eventStore,
calendarStore: this.calendarStore,
border: false,
id:'app-calendar',
region: 'center',
activeItem: 2, // month view
// CalendarPanel supports view-specific configs that are passed through to the
// underlying views to make configuration possible without explicitly having to
// create those views at this level:
monthViewCfg: {
showHeader: true,
showWeekLinks: true,
showWeekNumbers: true
},
// Some optional CalendarPanel configs to experiment with:
//showDayView: false,
//showWeekView: false,
//showMonthView: false,
//showNavBar: false,
//showTodayText: false,
//showTime: false,
//title: 'My Calendar', // the header of the calendar, could be a subtitle for the app
// Once this component inits it will set a reference to itself as an application
// member property for easy reference in other functions within App.
initComponent: function() {
App.calendarPanel = this;
this.constructor.prototype.initComponent.apply(this, arguments);
},
listeners: {
'eventclick': {
fn: function(vw, rec, el){
this.showEditWindow(rec, el);
this.clearMsg();
},
scope: this
},
'eventover': function(vw, rec, el){
//console.log('Entered evt rec='+rec.data.Title+', view='+ vw.id +', el='+el.id);
},
'eventout': function(vw, rec, el){
//console.log('Leaving evt rec='+rec.data.Title+', view='+ vw.id +', el='+el.id);
},
'eventadd': {
fn: function(cp, rec){
this.showMsg('Event '+ rec.data.Title +' was added');
},
scope: this
},
'eventupdate': {
fn: function(cp, rec){
this.showMsg('Event '+ rec.data.Title +' was updated');
},
scope: this
},
'eventdelete': {
fn: function(cp, rec){
this.showMsg('Event '+ rec.data.Title +' was deleted');
},
scope: this
},
'eventcancel': {
fn: function(cp, rec){
// edit canceled
},
scope: this
},
'viewchange': {
fn: function(p, vw, dateInfo){
if(this.editWin){
this.editWin.hide();
};
if(dateInfo !== null){
// will be null when switching to the event edit form so ignore
Ext.getCmp('app-nav-picker').setValue(dateInfo.activeDate);
this.updateTitle(dateInfo.viewStart, dateInfo.viewEnd);
}
},
scope: this
},
'dayclick': {
fn: function(vw, dt, ad, el){
this.showEditWindow({
StartDate: dt,
IsAllDay: ad
}, el);
this.clearMsg();
},
scope: this
},
'rangeselect': {
fn: function(win, dates, onComplete){
this.showEditWindow(dates);
this.editWin.on('hide', onComplete, this, {single:true});
this.clearMsg();
},
scope: this
},
'eventmove': {
fn: function(vw, rec){
rec.commit();
var time = rec.data.IsAllDay ? '' : ' \\a\\t g:i a';
this.showMsg('Event '+ rec.data.Title +' was moved to '+rec.data.StartDate.format('F jS'+time));
},
scope: this
},
'eventresize': {
fn: function(vw, rec){
rec.commit();
this.showMsg('Event '+ rec.data.Title +' was updated');
},
scope: this
},
'eventdelete': {
fn: function(win, rec){
this.eventStore.remove(rec);
this.showMsg('Event '+ rec.data.Title +' was deleted');
},
scope: this
},
'initdrag': {
fn: function(vw){
if(this.editWin && this.editWin.isVisible()){
this.editWin.hide();
}
},
scope: this
}
}
}]
}]
});
},
// The edit popup window is not part of the CalendarPanel itself -- it is a separate component.
// This makes it very easy to swap it out with a different type of window or custom view, or omit
// it altogether. Because of this, it's up to the application code to tie the pieces together.
// Note that this function is called from various event handlers in the CalendarPanel above.
showEditWindow : function(rec, animateTarget){
if(!this.editWin){
this.editWin = new Ext.calendar.EventEditWindow({
calendarStore: this.calendarStore,
listeners: {
'eventadd': {
fn: function(win, rec){
win.hide();
rec.data.IsNew = false;
this.eventStore.add(rec);
this.showMsg('Event '+ rec.data.Title +' was added');
},
scope: this
},
'eventupdate': {
fn: function(win, rec){
win.hide();
rec.commit();
this.showMsg('Event '+ rec.data.Title +' was updated');
},
scope: this
},
'eventdelete': {
fn: function(win, rec){
this.eventStore.remove(rec);
win.hide();
this.showMsg('Event '+ rec.data.Title +' was deleted');
},
scope: this
},
'editdetails': {
fn: function(win, rec){
win.hide();
App.calendarPanel.showEditForm(rec);
}
}
}
});
}
this.editWin.show(rec, animateTarget);
},
// The CalendarPanel itself supports the standard Panel title config, but that title
// only spans the calendar views. For a title that spans the entire width of the app
// we added a title to the layout's outer center region that is app-specific. This code
// updates that outer title based on the currently-selected view range anytime the view changes.
updateTitle: function(startDt, endDt){
var p = Ext.getCmp('app-center');
if(startDt.clearTime().getTime() == endDt.clearTime().getTime()){
p.setTitle(startDt.format('F j, Y'));
}
else if(startDt.getFullYear() == endDt.getFullYear()){
if(startDt.getMonth() == endDt.getMonth()){
p.setTitle(startDt.format('F j') + ' - ' + endDt.format('j, Y'));
}
else{
p.setTitle(startDt.format('F j') + ' - ' + endDt.format('F j, Y'));
}
}
else{
p.setTitle(startDt.format('F j, Y') + ' - ' + endDt.format('F j, Y'));
}
},
// This is an application-specific way to communicate CalendarPanel event messages back to the user.
// This could be replaced with a function to do "toast" style messages, growl messages, etc. This will
// vary based on application requirements, which is why it's not baked into the CalendarPanel.
showMsg: function(msg){
Ext.fly('app-msg').update(msg).removeClass('x-hidden');
},
clearMsg: function(){
Ext.fly('app-msg').update('').addClass('x-hidden');
}
}
}();
Ext.onReady(App.init, App);
|
const app = require('../index');
const fs = require('fs');
const path = require('path');
// eslint-disable-next-line no-console
const testPath = path.resolve(__dirname,'./cases/split-with-bom/');
process.chdir(testPath)
app.split(
fs.createReadStream('input.csv'), {
lineLimit: 5,
initHeader: 'FILE ID: c87b092e-31b9-4db7-bc63-ee33884d32d7'
},
(index) => fs.createWriteStream(`${path.resolve(testPath,'output')}-${index}.csv`)
);
|
'use strict';
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const resolve = require('resolve');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const ESLintPlugin = require('eslint-webpack-plugin');
const paths = require('./paths');
const modules = require('./modules');
const getClientEnvironment = require('./env');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const ForkTsCheckerWebpackPlugin =
process.env.TSC_COMPILE_ON_ERROR === 'true'
? require('react-dev-utils/ForkTsCheckerWarningWebpackPlugin')
: require('react-dev-utils/ForkTsCheckerWebpackPlugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const createEnvironmentHash = require('./webpack/persistentCache/createEnvironmentHash');
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
const reactRefreshRuntimeEntry = require.resolve('react-refresh/runtime');
const reactRefreshWebpackPluginRuntimeEntry = require.resolve(
'@pmmmwh/react-refresh-webpack-plugin'
);
const babelRuntimeEntry = require.resolve('babel-preset-react-app');
const babelRuntimeEntryHelpers = require.resolve(
'@babel/runtime/helpers/esm/assertThisInitialized',
{ paths: [babelRuntimeEntry] }
);
const babelRuntimeRegenerator = require.resolve('@babel/runtime/regenerator', {
paths: [babelRuntimeEntry],
});
// Some apps do not need the benefits of saving a web request, so not inlining the chunk
// makes for a smoother build process.
const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
const emitErrorsAsWarnings = process.env.ESLINT_NO_DEV_ERRORS === 'true';
const disableESLintPlugin = process.env.DISABLE_ESLINT_PLUGIN === 'true';
const imageInlineSizeLimit = parseInt(
process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
);
// Check if TypeScript is setup
const useTypeScript = fs.existsSync(paths.appTsConfig);
// Check if Tailwind config exists
const useTailwind = fs.existsSync(
path.join(paths.appPath, 'tailwind.config.js')
);
// Get the path to the uncompiled service worker (if it exists).
const swSrc = paths.swSrc;
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
const hasJsxRuntime = (() => {
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
return false;
}
try {
require.resolve('react/jsx-runtime');
return true;
} catch (e) {
return false;
}
})();
// This is the production and development configuration.
// It is focused on developer experience, fast rebuilds, and a minimal bundle.
module.exports = function (webpackEnv) {
const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production';
// Variable used for enabling profiling in Production
// passed into alias object. Uses a flag if passed into the build command
const isEnvProductionProfile =
isEnvProduction && process.argv.includes('--profile');
// We will provide `paths.publicUrlOrPath` to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
// Get environment variables to inject into our app.
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
const shouldUseReactRefresh = env.raw.FAST_REFRESH;
// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
// css is located in `static/css`, use '../../' to locate index.html folder
// in production `paths.publicUrlOrPath` can be a relative path
options: paths.publicUrlOrPath.startsWith('.')
? { publicPath: '../../' }
: {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
postcssOptions: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
config: false,
plugins: !useTailwind
? [
'postcss-flexbugs-fixes',
[
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
},
],
// Adds PostCSS Normalize as the reset css with default options,
// so that it honors browserslist config in package.json
// which in turn let's users customize the target behavior as per their needs.
'postcss-normalize',
]
: [
'tailwindcss',
'postcss-flexbugs-fixes',
[
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
},
],
],
},
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
},
},
].filter(Boolean);
if (preProcessor) {
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
root: paths.appSrc,
},
},
{
loader: require.resolve(preProcessor),
options: {
sourceMap: true,
},
}
);
}
return loaders;
};
return {
target: ['browserslist'],
mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
// Stop compilation early in production
bail: isEnvProduction,
devtool: isEnvProduction
? shouldUseSourceMap
? 'source-map'
: false
: isEnvDevelopment && 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
entry: paths.appIndexJs,
output: {
// The build folder.
path: paths.appBuild,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: isEnvDevelopment,
// There will be one main bundle, and one file per asynchronous chunk.
// In development, it does not produce real files.
filename: isEnvProduction
? 'static/js/[name].[contenthash:8].js'
: isEnvDevelopment && 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: isEnvProduction
? 'static/js/[name].[contenthash:8].chunk.js'
: isEnvDevelopment && 'static/js/[name].chunk.js',
assetModuleFilename: 'static/media/[name].[hash][ext]',
// webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: paths.publicUrlOrPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: isEnvProduction
? info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/')
: isEnvDevelopment &&
(info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
},
cache: {
type: 'filesystem',
version: createEnvironmentHash(env.raw),
cacheDirectory: paths.appWebpackCache,
store: 'pack',
buildDependencies: {
defaultWebpack: ['webpack/lib/'],
config: [__filename],
tsconfig: [paths.appTsConfig, paths.appJsConfig].filter(f =>
fs.existsSync(f)
),
},
},
infrastructureLogging: {
level: 'none',
},
optimization: {
minimize: isEnvProduction,
minimizer: [
// This is only used in production mode
new TerserPlugin({
terserOptions: {
parse: {
// We want terser to parse ecma 8 code. However, we don't want it
// to apply any minification steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
// Disabled because of an issue with Terser breaking valid code:
// https://github.com/facebook/create-react-app/issues/5250
// Pending further investigation:
// https://github.com/terser-js/terser/issues/120
inline: 2,
},
mangle: {
safari10: true,
},
// Added for profiling in devtools
keep_classnames: isEnvProductionProfile,
keep_fnames: isEnvProductionProfile,
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
}),
// This is only used in production mode
new CssMinimizerPlugin(),
],
},
resolve: {
// This allows you to set a fallback for where webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebook/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
modules.additionalModulePaths || []
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebook/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: paths.moduleFileExtensions
.map(ext => `.${ext}`)
.filter(ext => useTypeScript || !ext.includes('ts')),
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
// Allows for better profiling with ReactDevTools
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [
paths.appPackageJson,
reactRefreshRuntimeEntry,
reactRefreshWebpackPluginRuntimeEntry,
babelRuntimeEntry,
babelRuntimeEntryHelpers,
babelRuntimeRegenerator,
]),
],
},
module: {
strictExportPresence: true,
rules: [
// Handle node_modules packages that contain sourcemaps
shouldUseSourceMap && {
enforce: 'pre',
exclude: /@babel(?:\/|\\{1,2})runtime/,
test: /\.(js|mjs|jsx|ts|tsx|css)$/,
loader: require.resolve('source-map-loader'),
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// TODO: Merge this config once `image/avif` is in the mime-db
// https://github.com/jshttp/mime-db
{
test: [/\.avif$/],
type: 'asset',
mimetype: 'image/avif',
parser: {
dataUrlCondition: {
maxSize: imageInlineSizeLimit,
},
},
},
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: imageInlineSizeLimit,
},
},
},
{
test: /\.svg$/,
use: [
{
loader: require.resolve('@svgr/webpack'),
options: {
prettier: false,
svgo: false,
svgoConfig: {
plugins: [{ removeViewBox: false }],
},
titleProp: true,
ref: true,
},
},
{
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash].[ext]',
},
},
],
issuer: {
and: [/\.(ts|tsx|js|jsx|md|mdx)$/],
},
},
// Process application JS with Babel.
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
plugins: [
isEnvDevelopment &&
shouldUseReactRefresh &&
require.resolve('react-refresh/babel'),
].filter(Boolean),
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
compact: isEnvProduction,
},
},
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.(js|mjs)$/,
exclude: /@babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
],
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
// Babel sourcemaps are needed for debugging into node_modules
// code. Without the options below, debuggers like VSCode
// show incorrect code and set breakpoints on the wrong lines.
sourceMaps: shouldUseSourceMap,
inputSourceMap: shouldUseSourceMap,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'icss',
},
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'local',
getLocalIdent: getCSSModuleLocalIdent,
},
}),
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'icss',
},
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'local',
getLocalIdent: getCSSModuleLocalIdent,
},
},
'sass-loader'
),
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/^$/, /\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
type: 'asset/resource',
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
].filter(Boolean),
},
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
},
isEnvProduction
? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: undefined
)
),
// Inlines the webpack runtime script. This script is too small to warrant
// a network request.
// https://github.com/facebook/create-react-app/issues/5358
isEnvProduction &&
shouldInlineRuntimeChunk &&
new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
// It will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// This gives some necessary context to module not found errors, such as
// the requesting resource.
new ModuleNotFoundPlugin(paths.appPath),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV is set to production
// during a production build.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// Experimental hot reloading for React .
// https://github.com/facebook/react/tree/main/packages/react-refresh
isEnvDevelopment &&
shouldUseReactRefresh &&
new ReactRefreshWebpackPlugin({
overlay: false,
}),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebook/create-react-app/issues/240
isEnvDevelopment && new CaseSensitivePathsPlugin(),
isEnvProduction &&
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'static/css/[name].[contenthash:8].css',
chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
}),
// Generate an asset manifest file with the following content:
// - "files" key: Mapping of all asset filenames to their corresponding
// output file so that tools can pick it up without having to parse
// `index.html`
// - "entrypoints" key: Array of files which are included in `index.html`,
// can be used to reconstruct the HTML if necessary
new WebpackManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: paths.publicUrlOrPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[file.name] = file.path;
return manifest;
}, seed);
const entrypointFiles = entrypoints.main.filter(
fileName => !fileName.endsWith('.map')
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/,
}),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the webpack build.
isEnvProduction &&
fs.existsSync(swSrc) &&
new WorkboxWebpackPlugin.InjectManifest({
swSrc,
dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./,
exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/],
// Bump up the default maximum size (2mb) that's precached,
// to make lazy-loading failure scenarios less likely.
// See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
}),
// TypeScript type checking
useTypeScript &&
new ForkTsCheckerWebpackPlugin({
async: isEnvDevelopment,
typescript: {
typescriptPath: resolve.sync('typescript', {
basedir: paths.appNodeModules,
}),
configOverwrite: {
compilerOptions: {
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
skipLibCheck: true,
inlineSourceMap: false,
declarationMap: false,
noEmit: true,
incremental: true,
tsBuildInfoFile: paths.appTsBuildInfoFile,
},
},
context: paths.appPath,
diagnosticOptions: {
syntactic: true,
},
mode: 'write-references',
// profile: true,
},
issue: {
// This one is specifically to match during CI tests,
// as micromatch doesn't match
// '../cra-template-typescript/template/src/App.tsx'
// otherwise.
include: [
{ file: '../**/src/**/*.{ts,tsx}' },
{ file: '**/src/**/*.{ts,tsx}' },
],
exclude: [
{ file: '**/src/**/__tests__/**' },
{ file: '**/src/**/?(*.){spec|test}.*' },
{ file: '**/src/setupProxy.*' },
{ file: '**/src/setupTests.*' },
],
},
logger: {
infrastructure: 'silent',
},
}),
!disableESLintPlugin &&
new ESLintPlugin({
// Plugin options
extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
formatter: require.resolve('react-dev-utils/eslintFormatter'),
eslintPath: require.resolve('eslint'),
failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
context: paths.appSrc,
cache: true,
cacheLocation: path.resolve(
paths.appNodeModules,
'.cache/.eslintcache'
),
// ESLint class options
cwd: paths.appPath,
resolvePluginsRelativeTo: __dirname,
baseConfig: {
extends: [require.resolve('eslint-config-react-app/base')],
rules: {
...(!hasJsxRuntime && {
'react/react-in-jsx-scope': 'error',
}),
},
},
}),
].filter(Boolean),
// Turn off performance processing because we utilize
// our own hints via the FileSizeReporter
performance: false,
};
};
|
/**
* Welcome to Pebble.js!
*
* This is where you write your app.
*/
var UI = require('ui');
var Vector2 = require('vector2');
var Feature = require('platform/feature');
var wind = new UI.Window({
backgroundColor: 'white'
});
var cupolan = [];
var x = Feature.resolution().x;
var y = Feature.resolution().y;
for(var i = 0; i < 10; i++){
cupolan.push(new UI.Image({
position: new Vector2(0, (y-x)/4),
size: new Vector2(x,x),
backgroundColor: 'white',
image: 'images/cupolan-pose'+i+'.png'
}));
}
var timeText = new UI.TimeText({
position: new Vector2(0, y-76),
size: new Vector2(x,74),
text: "%m-%d\n%X",
font: 'leco-28-light-numbers',
color: 'vividCerulean',
textAlign: 'center',
backgroundColor: 'white',
textOverflow:'wrap'
});
var currentCupolan = null;
var currentMin = null;
var clockThread = function(){
var now = new Date();
var min = now.getMinutes() ;
if( currentMin !== min ){
if( null !== currentCupolan ){
wind.remove(currentCupolan);
}
if( null !== timeText ){
wind.remove(timeText);
}
currentCupolan = cupolan[min % 10];
wind.add(currentCupolan);
wind.add(timeText);
currentMin = min;
}
};
setInterval(clockThread,1000);
wind.show();
|
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/5/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("../../addon/mode/simple"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../../addon/mode/simple"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineSimpleMode("rust",{
start: [
// string and byte string
{regex: /b?"/, token: "string", next: "string"},
// raw string and raw byte string
{regex: /b?r"/, token: "string", next: "string_raw"},
{regex: /b?r#+"/, token: "string", next: "string_raw_hash"},
// character
{regex: /'(?:[^'\\]|\\(?:[nrt0'"]|x[\da-fA-F]{2}|u\{[\da-fA-F]{6}\}))'/, token: "string-2"},
// byte
{regex: /b'(?:[^']|\\(?:['\\nrt0]|x[\da-fA-F]{2}))'/, token: "string-2"},
{regex: /(?:(?:[0-9][0-9_]*)(?:(?:[Ee][+-]?[0-9_]+)|\.[0-9_]+(?:[Ee][+-]?[0-9_]+)?)(?:f32|f64)?)|(?:0(?:b[01_]+|(?:o[0-7_]+)|(?:x[0-9a-fA-F_]+))|(?:[0-9][0-9_]*))(?:u8|u16|u32|u64|i8|i16|i32|i64|isize|usize)?/,
token: "number"},
{regex: /(let(?:\s+mut)?|fn|enum|mod|struct|type|union)(\s+)([a-zA-Z_][a-zA-Z0-9_]*)/, token: ["keyword", null, "def"]},
{regex: /(?:abstract|alignof|as|async|await|box|break|continue|const|crate|do|dyn|else|enum|extern|fn|for|final|if|impl|in|loop|macro|match|mod|move|offsetof|override|priv|proc|pub|pure|ref|return|self|sizeof|static|struct|super|trait|type|typeof|union|unsafe|unsized|use|virtual|where|while|yield)\b/, token: "keyword"},
{regex: /\b(?:Self|isize|usize|char|bool|u8|u16|u32|u64|f16|f32|f64|i8|i16|i32|i64|str|Option)\b/, token: "atom"},
{regex: /\b(?:true|false|Some|None|Ok|Err)\b/, token: "builtin"},
{regex: /\b(fn)(\s+)([a-zA-Z_][a-zA-Z0-9_]*)/,
token: ["keyword", null ,"def"]},
{regex: /#!?\[.*\]/, token: "meta"},
{regex: /\/\/.*/, token: "comment"},
{regex: /\/\*/, token: "comment", next: "comment"},
{regex: /[-+\/*=<>!]+/, token: "operator"},
{regex: /[a-zA-Z_]\w*!/,token: "variable-3"},
{regex: /[a-zA-Z_]\w*/, token: "variable"},
{regex: /[\{\[\(]/, indent: true},
{regex: /[\}\]\)]/, dedent: true}
],
string: [
{regex: /"/, token: "string", next: "start"},
{regex: /(?:[^\\"]|\\(?:.|$))*/, token: "string"}
],
string_raw: [
{regex: /"/, token: "string", next: "start"},
{regex: /[^"]*/, token: "string"}
],
string_raw_hash: [
{regex: /"#+/, token: "string", next: "start"},
{regex: /(?:[^"]|"(?!#))*/, token: "string"}
],
comment: [
{regex: /.*?\*\//, token: "comment", next: "start"},
{regex: /.*/, token: "comment"}
],
meta: {
dontIndentStates: ["comment"],
electricInput: /^\s*\}$/,
blockCommentStart: "/*",
blockCommentEnd: "*/",
lineComment: "//",
fold: "brace"
}
});
CodeMirror.defineMIME("text/x-rustsrc", "rust");
CodeMirror.defineMIME("text/rust", "rust");
});
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const weekSchema = new Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
},
creator: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
creator: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
workoutDays: [{
type: Schema.Types.ObjectId,
ref: 'Day'
}]
}, { timestamps: true });
module.exports = mongoose.model('Week', weekSchema);
|
import React from 'react'
import {Trans} from '@lingui/react'
import {Interrupts} from 'parser/core/modules/Interrupts'
import ACTIONS from 'data/ACTIONS'
import {ActionLink} from 'components/ui/DbLink'
export default class SchInterrupts extends Interrupts {
suggestionContent = <Trans id="sch.interrupts.suggestion.content">If you can, try to preposition yourself so you don't have to move during mechanics as much as possible. Utilizing slidecasting will lower the need to use <ActionLink {...ACTIONS.SCH_RUIN_II}/> to instantly relocate or interrupt your current Broil III cast</Trans>
}
|
const express = require('express');
const path = require('path');
const { ApolloServer } = require('apollo-server-express');
const { authMiddleware } = require('./utils/auth');
const db = require('./config/connection');
const { typeDefs, resolvers } = require('./schemas');
const app = express();
const PORT = process.env.PORT || 3001;
const server = new ApolloServer({
typeDefs,
resolvers,
context: authMiddleware
});
server.applyMiddleware({ app });
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
// if we're in production, serve client/build as static assets
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '../client/build')));
}
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../client/build/index.html'));
});
db.once('open', () => {
app.listen(PORT, () => {
console.log(`API server running on port ${PORT}!`);
// log where we can go to test our GQL API
console.log(`Use GraphQL at http://localhost:${PORT}${server.graphqlPath}`);
});
});
|
var Test = require('../config/testConfig.js');
contract('Flight Surety Tests', async (accounts) => {
var config;
before('setup contract', async () => {
config = await Test.Config(accounts);
});
const fundingFee = web3.utils.toWei("10", "ether");
/****************************************************************************************/
/* Operations and Settings */
/****************************************************************************************/
it(`(multiparty) has correct initial isOperational() value`, async function () {
// Get operating status
let status = await config.flightSuretyData.isOperational.call();
assert.equal(status, true, "Incorrect initial operating status value");
});
it(`(multiparty) can block access to setOperatingStatus() for non-Contract Owner account`, async function () {
// Ensure that access is denied for non-Contract Owner account
let accessDenied = false;
try {
await config.flightSuretyData.setOperatingStatus(false, {from: config.testAddresses[2]});
} catch (e) {
accessDenied = true;
}
assert.equal(accessDenied, true, "Access not restricted to Contract Owner");
});
it(`(multiparty) can allow access to setOperatingStatus() for Contract Owner account`, async function () {
// Ensure that access is allowed for Contract Owner account
let accessDenied = false;
try {
await config.flightSuretyData.setOperatingStatus(false);
} catch (e) {
accessDenied = true;
}
assert.equal(accessDenied, false, "Access not restricted to Contract Owner");
});
it(`(multiparty) can block access to functions using requireIsOperational when operating status is false`, async function () {
let newAirline = accounts[2];
await config.flightSuretyData.setOperatingStatus(false);
let reverted = false;
try {
await config.flightSuretyData.isAirline.call(newAirline);
} catch (e) {
reverted = true;
}
assert.equal(reverted, true, "Access not blocked for requireIsOperational");
// Set it back for other tests to work
await config.flightSuretyData.setOperatingStatus(true);
});
it(`(multiparty) first airline is registered when contract is deployed`, async function () {
let isAirline = await config.flightSuretyData.isAirline.call(config.firstAirline);
assert.equal(isAirline, true, "First airline is not registered");
let isFunded = await config.flightSuretyData.isFundedAirline.call(config.firstAirline);
assert.equal(isFunded, false, "First airline is expected not to be funded");
});
it('(airline) cannot register an Airline using registerAirline() if it is not funded', async () => {
// ARRANGE
let newAirline = accounts[2];
// ACT
try {
await config.flightSuretyApp.registerAirline(newAirline, "Duo Airlines", {from: config.firstAirline});
} catch (e) {
}
let result = await config.flightSuretyData.isAirline.call(newAirline);
// ASSERT
assert.equal(result, false, "Airline should not be able to register another airline if it hasn't provided funding");
});
it('(airline) is funded after sending 10 ETH as funding fee', async () => {
const airline = config.firstAirline;
let isFunded = await config.flightSuretyData.isFundedAirline.call(airline);
assert.equal(isFunded, false, "Airline should not be funded initially");
try {
await config.flightSuretyApp.fund({value: fundingFee, from: airline});
} catch (e) {
}
isFunded = await config.flightSuretyData.isFundedAirline.call(airline);
assert.equal(isFunded, true, "Airline should be funded");
});
it('(airline) can register another airline using registerAirline() if it is funded', async () => {
// ARRANGE
const fundedAirline = config.firstAirline;
const newAirline = accounts[2];
const newAirline2 = accounts[3];
const newAirline3 = accounts[4];
// PREREQUISITES
const isFunded = await config.flightSuretyData.isFundedAirline.call(fundedAirline);
assert.equal(isFunded, true, "Airline should be funded");
// ACT
try {
await config.flightSuretyApp.registerAirline(newAirline, "Up In The Air", {from: fundedAirline});
await config.flightSuretyApp.registerAirline(newAirline2, "Sky Is The Limit", {from: fundedAirline});
await config.flightSuretyApp.registerAirline(newAirline3, "Flyer", {from: fundedAirline});
} catch (e) {
}
const registered1 = await config.flightSuretyData.isAirline.call(newAirline);
const registered2 = await config.flightSuretyData.isAirline.call(newAirline2);
const registered3 = await config.flightSuretyData.isAirline.call(newAirline3);
const result = registered1 && registered2 && registered3;
// ASSERT
assert.equal(result, true, "Airline should be able to register another airline if it has provided funding");
// FUND CREATED AIRLINES
await config.flightSuretyApp.fund({value: fundingFee, from: newAirline});
const isFunded2 = await config.flightSuretyData.isFundedAirline.call(newAirline);
assert.equal(isFunded2, true, "Airline 2 should be funded");
await config.flightSuretyApp.fund({value: fundingFee, from: newAirline2});
const isFunded3 = await config.flightSuretyData.isFundedAirline.call(newAirline2);
assert.equal(isFunded3, true, "Airline 3 should be funded");
await config.flightSuretyApp.fund({value: fundingFee, from: newAirline3});
const isFunded4 = await config.flightSuretyData.isFundedAirline.call(newAirline3);
assert.equal(isFunded4, true, "Airline 4 should be funded");
});
it('(airline) 5th airline can only be registered when more than 50% of funded arilines vote for it', async () => {
// ARRANGE
const airline1 = accounts[1];
const airline2 = accounts[2];
const airline3 = accounts[3];
const newAirline = accounts[5];
// PREREQUISITES
const airlinesCount = await config.flightSuretyData.airlinesCount.call();
assert.equal(airlinesCount, 4, "4 airlines should be registered");
// 1st vote
try {
await config.flightSuretyApp.registerAirline(newAirline, "My Airline", {from: airline1});
} catch (e) {
}
let registered = await config.flightSuretyData.isAirline.call(newAirline);
assert.equal(registered, false, "New airline should not be registered until >50% of other airlines vote for it");
// 2nd vote
try {
await config.flightSuretyApp.registerAirline(newAirline, "My Airline", {from: airline2});
} catch (e) {
}
registered = await config.flightSuretyData.isAirline.call(newAirline);
assert.equal(registered, false, "New airline should not be registered until >50% of other airlines vote for it");
// 3rd vote
try {
await config.flightSuretyApp.registerAirline(newAirline, "My Airline", {from: airline3});
} catch (e) {
}
registered = await config.flightSuretyData.isAirline.call(newAirline);
assert.equal(registered, true, "New airline should be registered after >50% of other airlines vote for it");
});
it('(airline) airline that is not funded does not participate in the contract', async () => {
// ARRANGE
const airline1 = accounts[1];
const airline2 = accounts[2];
const airline3 = accounts[3];
const notFundedAirline = accounts[5];
const newAirline = accounts[6];
// PREREQUISITES
const airlinesCount = await config.flightSuretyData.airlinesCount.call();
assert.equal(airlinesCount, 5, "5 airlines should be registered");
// 1st vote
try {
await config.flightSuretyApp.registerAirline(newAirline, "Other Airline", {from: airline1});
} catch (e) {
}
let registered = await config.flightSuretyData.isAirline.call(newAirline);
assert.equal(registered, false, "New airline should not be registered until >50% of other airlines vote for it");
// 2nd vote
try {
await config.flightSuretyApp.registerAirline(newAirline, "Other Airline", {from: airline2});
} catch (e) {
}
registered = await config.flightSuretyData.isAirline.call(newAirline);
assert.equal(registered, false, "New airline should not be registered until >50% of other airlines vote for it");
// 3rd vote - not funded airline
let exceptionCaught = false;
try {
await config.flightSuretyApp.registerAirline(newAirline, "Other Airline", {from: notFundedAirline});
} catch (e) {
exceptionCaught = true;
}
registered = await config.flightSuretyData.isAirline.call(newAirline);
assert.equal(exceptionCaught, true, "Should raise exception when not funded airline votes");
assert.equal(registered, false, "Not funded airline should not effectively participate in voting");
// 4th vote
try {
await config.flightSuretyApp.registerAirline(newAirline, "Other Airline", {from: airline3});
} catch (e) {
}
registered = await config.flightSuretyData.isAirline.call(newAirline);
assert.equal(registered, true, "New airline should be registered after >50% of other airlines vote for it");
});
it('(airline) can register a flight', async () => {
const airline = config.firstAirline;
let flightsCount = await config.flightSuretyApp.flightsCount.call();
assert.equal(flightsCount, 0, "There should be no flights registered initially");
try {
await config.flightSuretyApp.registerFlight(airline, 'FL123', Date.now(), {from: airline});
} catch (e) {
}
flightsCount = await config.flightSuretyApp.flightsCount.call();
assert.equal(flightsCount, 1, "Registered flight should increase flights count");
});
it('(passenger) can buy insurance for existing flight', async () => {
const airline = accounts[2];
const passenger = accounts[7];
const flight = 'FL900';
const flightTimestamp = Date.now();
try {
await config.flightSuretyApp.registerFlight(airline, flight, flightTimestamp, {from: airline});
} catch (e) {
}
const premium = web3.utils.toWei("1", "ether");
let purchased = true;
try {
await config.flightSuretyApp.buy(airline, flight, flightTimestamp, {value: premium, from: passenger});
} catch (e) {
purchased = false;
}
assert.equal(purchased, true, "An error occured when buying insurance");
try {
await config.flightSuretyApp.buy(airline, flight, flightTimestamp, {value: premium, from: passenger});
} catch (e) {
purchased = false;
}
assert.equal(purchased, false, "Buying double insurance for the same flight should not be allowed");
});
it('(passenger) cannot buy insurance with premium > 1 ETH', async () => {
const airline = accounts[3];
const passenger = accounts[7];
const flight = 'FL901';
const flightTimestamp = Date.now();
try {
await config.flightSuretyApp.registerFlight(airline, flight, flightTimestamp, {from: airline});
} catch (e) {
}
const premium = web3.utils.toWei("1.01", "ether");
let purchased = true;
try {
await config.flightSuretyApp.buy(airline, flight, flightTimestamp, {value: premium, from: passenger});
} catch (e) {
purchased = false;
}
assert.equal(purchased, false, "Insurance should not be purchased");
});
it('(passenger) cannot buy insurance for unregistered flight', async () => {
const airline = accounts[4];
const passenger = accounts[7];
const flight = 'FL902';
const flightTimestamp = Date.now() + 1000;
const premium = web3.utils.toWei("1", "ether");
let purchased = true;
try {
await config.flightSuretyApp.buy(airline, flight, flightTimestamp, {value: premium, from: passenger});
} catch (e) {
purchased = false;
}
assert.equal(purchased, false, "Insurance should not be purchased");
});
});
|
/**
*SMOOTH SCROLLING LIBRARY
* Copyright (c) 2007-2015 Ariel Flesler - aflesler ○ gmail • com | http://flesler.blogspot.com
* Licensed under MIT
* @author Ariel Flesler
* @version 2.1.3
*/
;(function(f){"use strict";"function"===typeof define&&define.amd?define(["jquery"],f):"undefined"!==typeof module&&module.exports?module.exports=f(require("jquery")):f(jQuery)})(function($){"use strict";function n(a){return!a.nodeName||-1!==$.inArray(a.nodeName.toLowerCase(),["iframe","#document","html","body"])}function h(a){return $.isFunction(a)||$.isPlainObject(a)?a:{top:a,left:a}}var p=$.scrollTo=function(a,d,b){return $(window).scrollTo(a,d,b)};p.defaults={axis:"xy",duration:0,limit:!0};$.fn.scrollTo=function(a,d,b){"object"=== typeof d&&(b=d,d=0);"function"===typeof b&&(b={onAfter:b});"max"===a&&(a=9E9);b=$.extend({},p.defaults,b);d=d||b.duration;var u=b.queue&&1<b.axis.length;u&&(d/=2);b.offset=h(b.offset);b.over=h(b.over);return this.each(function(){function k(a){var k=$.extend({},b,{queue:!0,duration:d,complete:a&&function(){a.call(q,e,b)}});r.animate(f,k)}if(null!==a){var l=n(this),q=l?this.contentWindow||window:this,r=$(q),e=a,f={},t;switch(typeof e){case "number":case "string":if(/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(e)){e= h(e);break}e=l?$(e):$(e,q);case "object":if(e.length===0)return;if(e.is||e.style)t=(e=$(e)).offset()}var v=$.isFunction(b.offset)&&b.offset(q,e)||b.offset;$.each(b.axis.split(""),function(a,c){var d="x"===c?"Left":"Top",m=d.toLowerCase(),g="scroll"+d,h=r[g](),n=p.max(q,c);t?(f[g]=t[m]+(l?0:h-r.offset()[m]),b.margin&&(f[g]-=parseInt(e.css("margin"+d),10)||0,f[g]-=parseInt(e.css("border"+d+"Width"),10)||0),f[g]+=v[m]||0,b.over[m]&&(f[g]+=e["x"===c?"width":"height"]()*b.over[m])):(d=e[m],f[g]=d.slice&& "%"===d.slice(-1)?parseFloat(d)/100*n:d);b.limit&&/^\d+$/.test(f[g])&&(f[g]=0>=f[g]?0:Math.min(f[g],n));!a&&1<b.axis.length&&(h===f[g]?f={}:u&&(k(b.onAfterFirst),f={}))});k(b.onAfter)}})};p.max=function(a,d){var b="x"===d?"Width":"Height",h="scroll"+b;if(!n(a))return a[h]-$(a)[b.toLowerCase()]();var b="client"+b,k=a.ownerDocument||a.document,l=k.documentElement,k=k.body;return Math.max(l[h],k[h])-Math.min(l[b],k[b])};$.Tween.propHooks.scrollLeft=$.Tween.propHooks.scrollTop={get:function(a){return $(a.elem)[a.prop]()}, set:function(a){var d=this.get(a);if(a.options.interrupt&&a._last&&a._last!==d)return $(a.elem).stop();var b=Math.round(a.now);d!==b&&($(a.elem)[a.prop](b),a._last=this.get(a))}};return p});
//Trigger Navbar animation if transition is not supported
whenAvailable($('#navBar li').eq(7),function(){
$("#navBar a").click(function(evn){
evn.preventDefault();
$('html,body').scrollTo(this.hash, this.hash);
});
if(!Modernizr.csstransitions){
$('#navBar li').hover(function(){
$(this).find('svg').css('fill', '#76A634');
$(this).find('p').css('color', '#000');
$(this).animate({"width": '200'}, 'linear').css('background-color', '#76A634');
}, function(){
$(this).animate({"width": '40'}, 'linear', function(){
$(this).find('p').css('color', 'transparent');
$(this).css('background-color', 'transparent');
$(this).find('svg').css('fill', '#76A634');
});
});
}
});
//Animation for contact form errors
function quake(element){
$(element).animate({left: '-=10px'}, 100, function(){
$(element).animate({left: '+=20px'}, 100, function(){
$(element).animate({left: '-=20px'}, 100, function(){
$(element).animate({left: '+=20px'}, 100, function(){
$(element).animate({left: '-=10px'}, 100, function(){
$(element).animate({left: '0px'}, 100);
});
});
});
});
});
}function closeMobileMenu(menu){
menu.removeClass('menuOpen');
menu.animate({left: '-=200px'}, 250);
}
function openMobileMenu(menu){
menu.addClass('menuOpen');
menu.animate({left: '+=200px'}, 250);
}
|
import {Link} from "react-router-dom";
export default function Footer() {
return (
<div className="footer-container">
<div className="footer-controls">
<Link to="/privacy">Privacy</Link>
<Link to="/contact">Contact</Link>
</div>
</div>
);
}
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BookSchema = new Schema({
title: {type: String, required: true},
author: {type: Schema.ObjectId, ref: 'Author', required: true},
summary: {type: String, required: true},
isbn: {type: String, required: true},
genre: [{type: Schema.ObjectId, ref: 'Genre'}]
});
// Virtual for book's URL
BookSchema
.virtual('url')
.get(function () {
return '/catalog/book/' + this._id;
});
//Export model
module.exports = mongoose.model('Book', BookSchema);
|
// This file was automatically generated. Do not modify.
'use strict';
goog.provide('Blockly.Msg.pms');
goog.require('Blockly.Msg');
Blockly.Msg.ABOUT = "about"; // untranslated
Blockly.Msg.ACCELERATION_TOOLTIP = "Get the acceleration value in milli-gravities."; // untranslated
Blockly.Msg.ACCELEROMETER_ROTATION_TOOLTIP = "Get the tilt or rotations in degrees."; // untranslated
Blockly.Msg.ACTION_ANALOGIN = "actuator analog"; // untranslated
Blockly.Msg.ACTION_BUZZER = "buzzer"; // untranslated
Blockly.Msg.ACTION_BUZZER_ARDUINO = "buzzer HYT120"; // untranslated
Blockly.Msg.ACTION_DIGITALIN = "actuator digital"; // untranslated
Blockly.Msg.ACTION_IN = "actuator"; // untranslated
Blockly.Msg.ACTION_INFRARED = "infrared emitter"; // untranslated
Blockly.Msg.ACTION_LCD = "LCD 1602"; // untranslated
Blockly.Msg.ACTION_LCDI2C = "LCD 1602 I²C"; // untranslated
Blockly.Msg.ACTION_LCDI2C_SENSEBOX = "OLED Display I²C"; // untranslated
Blockly.Msg.ACTION_LED = "LED"; // untranslated
Blockly.Msg.ACTION_MOTOR = "motor"; // untranslated
Blockly.Msg.ACTION_PLAY = "play"; // untranslated
Blockly.Msg.ACTION_PLOTTING = "plot"; // untranslated
Blockly.Msg.ACTION_PLOT_CLEAR = "clear the plot"; // untranslated
Blockly.Msg.ACTION_PLOT_POINT = "plot a point"; // untranslated
Blockly.Msg.ACTION_PLOT_TICKMARK = "at tickmark"; // untranslated
Blockly.Msg.ACTION_RELAY = "relay SRD-05VDC-SL-C"; // untranslated
Blockly.Msg.ACTION_RGBLED = "RGB LED"; // untranslated
Blockly.Msg.ACTION_SDCARD = "SD card"; // untranslated
Blockly.Msg.ACTION_SERIAL_PRINT = "show on Serial Monitor"; // untranslated
Blockly.Msg.ACTION_SERIAL_PRINT_TOOLTIP = "Show data on the Serial Monitor. You can find the Serial Monitor in the USB Programm on top, under View."; // untranslated
Blockly.Msg.ACTION_SERVO = "servo motor"; // untranslated
Blockly.Msg.ACTION_SERVO_ARDUINO = "servo motor SG90"; // untranslated
Blockly.Msg.ACTION_STEPMOTOR = "step motor"; // untranslated
Blockly.Msg.ACTION_WIRELESS = "WiFi connection"; // untranslated
Blockly.Msg.ACTIVITY_TOOLTIP = "Marker for an additional activity."; // untranslated
Blockly.Msg.ACTOR_MODE_ANALOGIN_TOOLTIP = "Writes an analog value (PWM wave) to a pin. Only values between 0 and 255 should be used"; // untranslated
Blockly.Msg.ACTOR_MODE_DIGITALIN_TOOLTIP = "Writes a HIGH or a LOW value to a digital pin. Only the values HIGH »1« and LOW »0« should be used."; // untranslated
Blockly.Msg.ACTOR_TOOLTIP = "Represents any actor."; // untranslated
Blockly.Msg.ADD_COMMENT = "Gionté un coment";
Blockly.Msg.ANALOG = "analog"; // untranslated
Blockly.Msg.ANALOGIN_TOOLTIP = "Represents any actuator connected to an analog pin"; // untranslated
Blockly.Msg.ANALOGOUT_TOOLTIP = "Represents any sensor connected to an analog pin"; // untranslated
Blockly.Msg.AND = "and"; // untranslated
Blockly.Msg.ARDUBRICK_TOOLTIP = "Represents the Bot'n Roll board with connected actors and sensors. There are also inbuilt actors and sensors available, e.g. pushbuttons, display ..."; // untranslated
Blockly.Msg.AUTH = "Për piasì, ch'a autorisa costa aplicassion a përmëtte ëd salvé sò travaj e a autoriselo a esse partagià da chiel.";
Blockly.Msg.BATTERY_GETSAMPLE_TOOLTIP = "Gets the current voltage from the battery."; // untranslated
Blockly.Msg.BLOCK_NOT_EXECUTED = "The exection of this block will have no effect!"; // untranslated
Blockly.Msg.BOB3_READNUMBER_TOOLTIP = "Returns the previously stored number."; // untranslated
Blockly.Msg.BOB3_RECALL_NUMBER = "recall number"; // untranslated
Blockly.Msg.BOB3_REMEMBER_NUMBER = "remember number"; // untranslated
Blockly.Msg.BOB3_SAVENUMBER_TOOLTIP = "The number to store should be an integer in the range of 0 to 255"; // untranslated
Blockly.Msg.BOTH = "both"; // untranslated
Blockly.Msg.BOX_ID = "Device ID"; // untranslated
Blockly.Msg.BRICKLIGHT = "brick light"; // untranslated
Blockly.Msg.BRICKLIGHT_BLUE = "blue"; // untranslated
Blockly.Msg.BRICKLIGHT_COLOR = "colour"; // untranslated
Blockly.Msg.BRICKLIGHT_DOUBLE_FLASH = "double flashing"; // untranslated
Blockly.Msg.BRICKLIGHT_FLASH = "flashing"; // untranslated
Blockly.Msg.BRICKLIGHT_GREEN = "green"; // untranslated
Blockly.Msg.BRICKLIGHT_OFF_TOOLTIP = "Turns bricklight off."; // untranslated
Blockly.Msg.BRICKLIGHT_ON = "on"; // untranslated
Blockly.Msg.BRICKLIGHT_ON_TOOLTIP = "Turns bricklight on."; // untranslated
Blockly.Msg.BRICKLIGHT_ORANGE = "orange"; // untranslated
Blockly.Msg.BRICKLIGHT_RED = "red"; // untranslated
Blockly.Msg.BRICKLIGHT_RESET_TOOLTIP = "Resets bricklight. Sets the default bricklight: green and blinking."; // untranslated
Blockly.Msg.BRICKNAME_WEDO = "WeDo"; // untranslated
Blockly.Msg.BRICK_IPADDRESS = "ip address"; // untranslated
Blockly.Msg.BRICK_PASSWORD = "password"; // untranslated
Blockly.Msg.BRICK_PHENOMENON = "Phenomenon"; // untranslated
Blockly.Msg.BRICK_PORT = "port"; // untranslated
Blockly.Msg.BRICK_TRACK_WIDTH = "track width"; // untranslated
Blockly.Msg.BRICK_USERNAME = "user name"; // untranslated
Blockly.Msg.BRICK_WHEEL_DIAMETER = "wheel diameter"; // untranslated
Blockly.Msg.BRUSH_OFF = "turn brush Off"; // untranslated
Blockly.Msg.BRUSH_OFF_TOOLTIP = "Turns the brush off."; // untranslated
Blockly.Msg.BRUSH_ON = "turn brush on (RPM)"; // untranslated
Blockly.Msg.BRUSH_ON_TOOLTIP = "Turns on the brush with RPM of the motor (0<=RPM<=10000)"; // untranslated
Blockly.Msg.BUTTON_DO_UPLOAD_GALLERY = "Upload »$« to the gallery"; // untranslated
Blockly.Msg.BUTTON_EMPTY_LIST = "Empty list"; // untranslated
Blockly.Msg.BUZZER_TOOLTIP = "Represents a buzzer"; // untranslated
Blockly.Msg.CALLIOPEBRICK_TOOLTIP = "Represents Calliope, a pocket-sized codeable computer. There are also inbuilt actors and sensors available, e.g. buttons, display ..."; // untranslated
Blockly.Msg.CENTER = "center"; // untranslated
Blockly.Msg.CHANGE_VALUE_TITLE = "Modifiché ël valor:";
Blockly.Msg.CHAT = "Ch'a ciaciara con sò colaborator an scrivend an costa casela!";
Blockly.Msg.CLEAN_UP = "Dëscancelé ij blòch";
Blockly.Msg.COLLAPSE_ALL = "Arduve ij blòch";
Blockly.Msg.COLLAPSE_BLOCK = "Arduve ël blòch";
Blockly.Msg.COLON = "colon"; // untranslated
Blockly.Msg.COLOUR_BLEND_COLOUR1 = "color 1";
Blockly.Msg.COLOUR_BLEND_COLOUR2 = "color 2";
Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/"; // untranslated
Blockly.Msg.COLOUR_BLEND_RATIO = "rapòrt";
Blockly.Msg.COLOUR_BLEND_TITLE = "mës-cé";
Blockly.Msg.COLOUR_BLEND_TOOLTIP = "A mës-cia doi color ansema con un rapòrt dàit (0,0 - 1,0).";
Blockly.Msg.COLOUR_GETSAMPLE_TOOLTIP = "Gets the current reading from the colour sensor."; // untranslated
Blockly.Msg.COLOUR_PICKER_HELPURL = "https://en.wikipedia.org/wiki/Color";
Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Serne un color ant la taulòssa.";
Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; // untranslated
Blockly.Msg.COLOUR_RANDOM_TITLE = "color a asar";
Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Serne un color a asar.";
Blockly.Msg.COLOUR_RGB_BLUE = "bleu";
Blockly.Msg.COLOUR_RGB_GREEN = "verd";
Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html"; // untranslated
Blockly.Msg.COLOUR_RGB_RED = "ross";
Blockly.Msg.COLOUR_RGB_TITLE = "coloré con";
Blockly.Msg.COLOUR_RGB_TOOLTIP = "Creé un color con la quantità spessificà ëd ross, verd e bleu. Tuti ij valor a devo esse antra 0 e 100.";
Blockly.Msg.COLOUR_RGB_WHITE = "white"; // untranslated
Blockly.Msg.COLOUR_TOOLTIP = "Represents a colour sensor."; // untranslated
Blockly.Msg.COMPASS_CALIBRATE_TOOLTIP = "Calibrates the compass. Turn the compass sensor VERY slowly for two times (about 40 seconds)."; // untranslated
Blockly.Msg.COMPASS_GETSAMPLE_TOOLTIP = "Gets the current reading from the compass sensor."; // untranslated
Blockly.Msg.COMPASS_TOOLTIP = "Represents a compass sensor."; // untranslated
Blockly.Msg.COMPASS_TOOLTIP_EV3 = "Represents a HiTechnic NXT compass sensor."; // untranslated
Blockly.Msg.CONFIGURATION_ERROR_ACTOR_MISSING = "This actuator is not set to the port!"; // untranslated
Blockly.Msg.CONFIGURATION_ERROR_MOTORS_ROTATION_DIRECTION = "The direction of rotation of the left and right motor is different!"; // untranslated
Blockly.Msg.CONFIGURATION_ERROR_MOTOR_LEFT_MISSING = "Left motor missing in the configuration!"; // untranslated
Blockly.Msg.CONFIGURATION_ERROR_MOTOR_LEFT_UNREGULATED = "Left motor is not regulated!"; // untranslated
Blockly.Msg.CONFIGURATION_ERROR_MOTOR_MISSING = "Motor is missing on the given port!"; // untranslated
Blockly.Msg.CONFIGURATION_ERROR_MOTOR_RIGHT_MISSING = "Right motor missing in the configuration!"; // untranslated
Blockly.Msg.CONFIGURATION_ERROR_MOTOR_RIGHT_UNREGULATED = "Right motor is not regulated!"; // untranslated
Blockly.Msg.CONFIGURATION_ERROR_MULTIPLE_LEFT_MOTORS = "You have multiple left motors assigned to your configuration!"; // untranslated
Blockly.Msg.CONFIGURATION_ERROR_MULTIPLE_RIGHT_MOTORS = "You have multiple right motors assigned to your configuration!"; // untranslated
Blockly.Msg.CONFIGURATION_ERROR_OTHER_NOT_SUPPORTED = "Other power consumer does not support this type of block!"; // untranslated
Blockly.Msg.CONFIGURATION_ERROR_SENSOR_MISSING = "This sensor is not set to the port!"; // untranslated
Blockly.Msg.CONFIGURATION_ERROR_SENSOR_WRONG = "Connected wrong sensor to the given port!"; // untranslated
Blockly.Msg.CONFIGURATION_NO_PHENOMENON = "no phenomenon"; // untranslated
Blockly.Msg.CONFIGURATION_NO_PORT = "no port"; // untranslated
Blockly.Msg.CONFIGURATION_PORT = "Port1"; // untranslated
Blockly.Msg.CONFLIST_DELETE_ALL_TOOLTIP = "Click here to delete all selected programs."; // untranslated
Blockly.Msg.CONFLIST_DELETE_TOOLTIP = "Click here to delete your robot configuration."; // untranslated
Blockly.Msg.CONFLIST_LOAD_TOOLTIP = "Click here to load your robot configuration in the configuration environment."; // untranslated
Blockly.Msg.CONNECTION_CHECK = "connection to robot %1 active?"; // untranslated
Blockly.Msg.CONNECTION_CHECK_TOOLTIP = "Check if the connection to the robot is active."; // untranslated
Blockly.Msg.CONNECTION_CONNECT = "connect to robot name"; // untranslated
Blockly.Msg.CONNECTION_FROM_CONNECTION = "from connection"; // untranslated
Blockly.Msg.CONNECTION_FROM_ROBOT = "from robot"; // untranslated
Blockly.Msg.CONNECTION_MBED_RECEIVE_TOOLTIP = "Reads a message over one of the channels (0 - 255). The default channel is 0."; // untranslated
Blockly.Msg.CONNECTION_MBED_SEND_TOOLTIP = "Sends a message to another system. You can specify a signal strength from 0 - 7, where 0 is very low and 7 is the strongests. The message is send over channel 0 unless you specify another one."; // untranslated
Blockly.Msg.CONNECTION_OVER_CHANNEL = "over channel"; // untranslated
Blockly.Msg.CONNECTION_POWER = "with strength"; // untranslated
Blockly.Msg.CONNECTION_PROTOCOL_BLUETOOTH = "Bluetooth"; // untranslated
Blockly.Msg.CONNECTION_RECEIVED_DATA = "receive message"; // untranslated
Blockly.Msg.CONNECTION_RECEIVE_TOOLTIP = "Waits for a message from the robot which you declare in the connection."; // untranslated
Blockly.Msg.CONNECTION_RECEIVE_TOOLTIP_BOB3 = "Reads a message via the IR receiver. Only numbers can be received."; // untranslated
Blockly.Msg.CONNECTION_RECEIVE_TOOLTIP_MBOT = "Reads a message from the IR receiver. Only strings can be received."; // untranslated
Blockly.Msg.CONNECTION_SEND_DATA = "send message"; // untranslated
Blockly.Msg.CONNECTION_SEND_TOOLTIP = "Sends a message to another robot."; // untranslated
Blockly.Msg.CONNECTION_SEND_TOOLTIP_BOB3 = "Sends a message of type number to another Bob3. Hold the Bob3's face to face!"; // untranslated
Blockly.Msg.CONNECTION_SEND_TOOLTIP_MBOT = "Sends a message of type string to another mBot. Hold the mBots's face to face!"; // untranslated
Blockly.Msg.CONNECTION_SET_CHANNEL = "set channel to %1"; // untranslated
Blockly.Msg.CONNECTION_SET_CHANNEL_TOOLTIP = "Sets the channel for sending and receiving messages. Can be set from 0 to 255."; // untranslated
Blockly.Msg.CONNECTION_START_TOOLTIP = "Tries to make a connection to another robot via Bluetooth."; // untranslated
Blockly.Msg.CONNECTION_TOOLTIP = "A robot's connection"; // untranslated
Blockly.Msg.CONNECTION_TO_CONNECTION = "to connection"; // untranslated
Blockly.Msg.CONNECTION_TO_ROBOT = "to robot"; // untranslated
Blockly.Msg.CONNECTION_WAIT_FOR_CONNECTION = "wait for connection"; // untranslated
Blockly.Msg.CONNECTION_WAIT_TOOLTIP = "Waits for a connection via Bluetooth."; // untranslated
Blockly.Msg.CONNECTOR = "Connector"; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "seurte da la liassa";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "continué con l'iterassion sucessiva dla liassa";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Seurte da la liassa anglobanta.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Sauté ël rest ëd sa liassa, e continué con l'iterassion apress.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Atension: Ës blòch a peul mach esse dovrà andrinta a na liassa.";
Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://github.com/google/blockly/wiki/Loops#for-each"; // untranslated
Blockly.Msg.CONTROLS_FOREACH_TITLE = "për minca n'element %1 ant la lista %2";
Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "Për minca element an na lista, dé ël valor ëd l'element a la variàbil '%1', peui eseguì chèiche anstrussion.";
Blockly.Msg.CONTROLS_FOR_HELPURL = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated
Blockly.Msg.CONTROLS_FOR_TITLE = "conté con %1 da %2 a %3 për %4";
Blockly.Msg.CONTROLS_FOR_TOOLTIP = "Fé an manera che la variàbil \"%1\" a pija ij valor dal nùmer inissial fin-a al nùmer final, an contand për l'antërval ëspessificà, e eseguì ij bloch ëspessificà.";
Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "Gionté na condission al blòch si.";
Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "Gionté na condission final ch'a cheuj tut al blòch si.";
Blockly.Msg.CONTROLS_IF_HELPURL = "https://github.com/google/blockly/wiki/IfElse"; // untranslated
Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Gionté, gavé o riordiné le session për cinfiguré torna ës blòch si.";
Blockly.Msg.CONTROLS_IF_MSG_ELSE = "dësnò";
Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "dësnò si";
Blockly.Msg.CONTROLS_IF_MSG_IF = "si";
Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "Si un valor a l'é ver, antlora eseguì chèiche anstrussion.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "Si un valor a l'é ver, antlora eseguì ël prim blòch d'anstrussion. Dësnò, eseguì ël second blòch d'anstrussion.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "Si ël prim valor a l'é ver, antlora fé andé ël prim blòch d'anstrussion. Dësnò, si ël second valor a l'é ver, fé andé ël second blòch d'anstrussion.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "Si ël prim valor a l'é ver, antlora fé andé ël prim blòch d'anstrussion. Dësnò, si ël second valor a l'é ver, fé andé ël second blòcj d'anstrussion. Si gnun dij valor a l'é ver, fé andé l'ùltim blòch d'anstrussion.";
Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://en.wikipedia.org/wiki/For_loop";
Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "fé";
Blockly.Msg.CONTROLS_REPEAT_TITLE = "arpete %1 vire";
Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Eseguì chèiche anstrussion vàire vire.";
Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "arpete fin-a a";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "arpete antramentre che";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "Cand un valor a l'é fàuss, eseguì chèiche anstrussion.";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "Cand un valor a l'é ver, eseguì chèiche anstrussion.";
Blockly.Msg.DATATABLE_ACTUALIZATION = "Actualization date"; // untranslated
Blockly.Msg.DATATABLE_CONFIGURATIONS = "configurations"; // untranslated
Blockly.Msg.DATATABLE_CONFIGURATION_NAME = "Configuration name"; // untranslated
Blockly.Msg.DATATABLE_CREATED_BY = "Creator"; // untranslated
Blockly.Msg.DATATABLE_CREATED_ON = "Creation date"; // untranslated
Blockly.Msg.DATATABLE_PROGRAMS = "programs"; // untranslated
Blockly.Msg.DATATABLE_PROGRAM_NAME = "Program name"; // untranslated
Blockly.Msg.DATATABLE_SHARED = "Shared"; // untranslated
Blockly.Msg.DATATABLE_SHARED_WITH = "Shared with"; // untranslated
Blockly.Msg.DELETE_ALL_BLOCKS = "Scancelé tuti ij %1 blòch?";
Blockly.Msg.DELETE_BLOCK = "Scancelé ël blòch";
Blockly.Msg.DELETE_X_BLOCKS = "Scancelé %1 blòch";
Blockly.Msg.DIGITAL = "digital"; // untranslated
Blockly.Msg.DIGITALIN_TOOLTIP = "Represents any actuator connected to a digital pin."; // untranslated
Blockly.Msg.DIGITALOUT_TOOLTIP = "Represents any sensor connected to a digital."; // untranslated
Blockly.Msg.DISABLE_BLOCK = "Disativé ël blòch";
Blockly.Msg.DISPLAY_ANIMATION = "animation"; // untranslated
Blockly.Msg.DISPLAY_CHARACTER = "character"; // untranslated
Blockly.Msg.DISPLAY_CLEAR = "clear display"; // untranslated
Blockly.Msg.DISPLAY_CLEAR_TOOLTIP = "Clears the display."; // untranslated
Blockly.Msg.DISPLAY_COL = "in column"; // untranslated
Blockly.Msg.DISPLAY_GET_BRIGHTNESS_TOOLTIP = "Returns the brightness for all leds of the display. 0 means all leds are turned off, 9 is the brightest value."; // untranslated
Blockly.Msg.DISPLAY_GET_PIXEL_TOOLTIP = "Returns the brightness for this led. 0 means the led is turned off, 9 is the brightest value."; // untranslated
Blockly.Msg.DISPLAY_IMAGE = "image"; // untranslated
Blockly.Msg.DISPLAY_PICTURE = "picture"; // untranslated
Blockly.Msg.DISPLAY_PICTURE_EYES_CLOSED = "eyes closed"; // untranslated
Blockly.Msg.DISPLAY_PICTURE_EYES_OPEN = "eyes open"; // untranslated
Blockly.Msg.DISPLAY_PICTURE_FLOWERS = "flowers"; // untranslated
Blockly.Msg.DISPLAY_PICTURE_GLASSES = "glasses"; // untranslated
Blockly.Msg.DISPLAY_PICTURE_TACHO = "speedo"; // untranslated
Blockly.Msg.DISPLAY_PICTURE_TOOLTIP = "Displays a picture on the screen."; // untranslated
Blockly.Msg.DISPLAY_PIXEL_BRIGHTNESS = "brightness"; // untranslated
Blockly.Msg.DISPLAY_PIXEL_TITLE = "LED"; // untranslated
Blockly.Msg.DISPLAY_ROW = "in row"; // untranslated
Blockly.Msg.DISPLAY_SET_BRIGHTNESS_TOOLTIP = "Sets the brightness for all leds of the display. 0 means all leds are turned off, 9 is the brightest value."; // untranslated
Blockly.Msg.DISPLAY_SET_PIXEL_TOOLTIP = "Sets the brightness for this led. 0 means the led is turned off, 9 is the brightest value. With x and y you can determine the position of the led you would like to change."; // untranslated
Blockly.Msg.DISPLAY_SHOW = "show"; // untranslated
Blockly.Msg.DISPLAY_TEXT = "text"; // untranslated
Blockly.Msg.DISPLAY_TEXT_TOOLTIP = "Displays a text on the screen."; // untranslated
Blockly.Msg.DROP_TOOLTIP = "Represents a drop sensor."; // untranslated
Blockly.Msg.DUPLICATE_BLOCK = "Dupliché";
Blockly.Msg.ENABLE_BLOCK = "Ativé ël blòch";
Blockly.Msg.ENCODER_GETSAMPLE_TOOLTIP = "Gets the current reading from the motor encoder."; // untranslated
Blockly.Msg.ENCODER_RESET_TOOLTIP = "Resets the motor encoder."; // untranslated
Blockly.Msg.ENCODER_TOOLTIP = "Represents an encoder."; // untranslated
Blockly.Msg.ERROR_MISSING_PARAMETER = "An input value is missing!"; // untranslated
Blockly.Msg.ERROR_MISSING_RETURN = "The function return value is missing!"; // untranslated
Blockly.Msg.EV3BRICK_TOOLTIP = "Represents the EV3 brick with connected actors and sensors. There are also inbuilt actors and sensors available, e.g. buttons, display ..."; // untranslated
Blockly.Msg.EXPAND_ALL = "Dësvlupé ij blòch";
Blockly.Msg.EXPAND_BLOCK = "Dësvlupé ël blòch";
Blockly.Msg.EXTERNAL_INPUTS = "Imission esterne";
Blockly.Msg.FLAME_GETSAMPLE_TOOLTIP = "Gets the current reading from the flame sensor."; // untranslated
Blockly.Msg.FLAME_TOOLTIP = "Represents a flame sensor."; // untranslated
Blockly.Msg.FLYOUT_VARIABLE_TEXT = "You need a variable? Please declare it first with a click on the + sign at the »start« block."; // untranslated
Blockly.Msg.FOR = "for"; // untranslated
Blockly.Msg.FOURDIGITDISPLAY = "4-Digit Display"; // untranslated
Blockly.Msg.FOURDIGITDISPLAY_CLEAR_TOOLTIP = "Clears the Grove 4-Digit Display by Seeed."; // untranslated
Blockly.Msg.FOURDIGITDISPLAY_SHOW_TOOLTIP = "Displays a number [0-9999] on the Grove 4-Digit Display by Seeed. Position [0-3] represents the starting position of the number. The display has to be connected to the A1 (right) Grove connector."; // untranslated
Blockly.Msg.FROM_POSITION = "from position"; // untranslated
Blockly.Msg.FSR_TOOLTIP = "Get the current reading from the force sensitive resistor under the feet of the robot."; // untranslated
Blockly.Msg.GALLERY_BY = "by"; // untranslated
Blockly.Msg.GALLERY_DATE = "created"; // untranslated
Blockly.Msg.GALLERY_DISLIKE = "dislike"; // untranslated
Blockly.Msg.GALLERY_LIKE = "like"; // untranslated
Blockly.Msg.GALLERY_SHARED_ALREADY = "You have already uploaded this program to the gallery. If you want to change it, look for the copy from the gallery and modify it. You can also remove it from the gallery while deleting the copy from the gallery."; // untranslated
Blockly.Msg.GEARED_MOTOR = "geared motor"; // untranslated
Blockly.Msg.GET = "get"; // untranslated
Blockly.Msg.GETSAMPLE_TOOLTIP = "Gets the current reading from chosen sensor."; // untranslated
Blockly.Msg.GET_CODE_TOOLTIP = "Returns the value of the solderable code pad in the head piece. Values are in range 0-31."; // untranslated
Blockly.Msg.GO_TO_GROUPS = "Go to groups"; // untranslated
Blockly.Msg.GYRO_GETSAMPLE_TOOLTIP = "Gets the current reading from the gyro sensor."; // untranslated
Blockly.Msg.GYRO_RESET_TOOLTIP = "Resets the gyro sensor."; // untranslated
Blockly.Msg.GYRO_TOOLTIP = "Represents a gyro sensor."; // untranslated
Blockly.Msg.HELP = "Agiut";
Blockly.Msg.HINT_USER_ACCOUNT = "»IAmBotman« or »RobellaStracciatella«? Not everyone needs to know your real name. Think of a cool nickname that you can easily remember."; // untranslated
Blockly.Msg.HINT_USER_AGE = "Are you under 16? Then please ask your parents to help you. They can specify their e-mail address to confirm your account."; // untranslated
Blockly.Msg.HINT_USER_EMAIL = "This is voluntary! However, some functions of the lab are only available if you have verified your account by e-mail. You are younger than 16? Please ask your parents to help you out with one of their e-mail addresses. <br><a href='https://www.roberta-home.de/index.php?id=138&L=1' target='_blank'>Further information ...</a>"; // untranslated
Blockly.Msg.HINT_USER_NAME = "Enter your real name here if you like. This is just for you, no one else will see it."; // untranslated
Blockly.Msg.HINT_USER_PASSWORT = "12345 is no secure password. Rather think of a safe combination of numbers and letters that you will not forget."; // untranslated
Blockly.Msg.HINT_USER_PASSWORT_CONFIRM = "Got it? Better make sure!"; // untranslated
Blockly.Msg.HUMIDITY_TOOLTIP = "Represents a humidity sensor."; // untranslated
Blockly.Msg.ID = "ID"; // untranslated
Blockly.Msg.IF_TOOLTIP = "Checks the condition in »if«. If the condition is true, executes the »do« action."; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP = "Returns the chosen image."; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_ANGRY = "angry"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_ASLEEP = "asleep"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_BUTTERFLY = "butterfly"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_CHESSBOARD = "chessboard"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_CONFUSED = "confused"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_COW = "cow"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_DIAMOND = "diamond"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_DIAMOND_SMALL = "small diamond"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_DUCK = "duck"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_FABULOUS = "fabulous"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_GHOST = "ghost"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_GIRAFFE = "giraffe"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_HEART = "heart"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_HEART_SMALL = "small heart"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_HOUSE = "house"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_MEH = "meh!"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_MUSIC_CROTCHET = "music crotchet"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_MUSIC_QUAVER = "music quaver"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_MUSIC_QUAVERS = "music quavers"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_NO = "no"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_PACMAN = "pacman"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_PITCHFORK = "pitchfork"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_RABBIT = "rabbit"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_ROLLERSKATE = "rollerskate"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_SAD = "sad"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_SILLY = "silly"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_SKULL = "skull"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_SMILE = "smile"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_SNAKE = "snake"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_SQUARE = "square"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_SQUARE_SMALL = "small square"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_STICKFIGURE = "stickfigure"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_SWORD = "sword"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_TARGET = "target"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_TORTOISE = "tortoise"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_TRIANGLE = "triangle"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_TRIANGLE_LEFT = "triangle left"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_TSHIRT = "T-shirt"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_UMBRELLA = "umbrella"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_XMAS = "xmas"; // untranslated
Blockly.Msg.IMAGE_GET_TOOLTIP_YES = "yes"; // untranslated
Blockly.Msg.IMAGE_INVERT = "invert"; // untranslated
Blockly.Msg.IMAGE_INVERT_TOOLTIP = "Inverts the image. Each pixel with value 0 or none will be set to # or 9 and pixels with value # or 9 will be set to 0 or none."; // untranslated
Blockly.Msg.IMAGE_SHIFT = "shift"; // untranslated
Blockly.Msg.IMAGE_SHIFT_TOOLTIP = "Shifts the image in the given direction by the given number"; // untranslated
Blockly.Msg.IMAGE_TOOLTIP = "Creates an image for the display. You can specify the brightness of each pixel from 0 to 9 or # where 0 means no light, 1 is a bit bright and 9 or # is the brightest value."; // untranslated
Blockly.Msg.INFO_DOCUMENTATION_HINT = "Document your program here ..."; // untranslated
Blockly.Msg.INFO_TAGS = "Tags"; // untranslated
Blockly.Msg.INFRARED_DISTANCE_GETSAMPLE_TOOLTIP = "Gets the current relative distance from the infrared sensor. The values are between 1 and 75 cm."; // untranslated
Blockly.Msg.INFRARED_GETSAMPLE_TOOLTIP = "Gets the current reading from the infrared sensor."; // untranslated
Blockly.Msg.INFRARED_GETSAMPLE_TOOLTIP_MBOT = "Gets the current reading from the light sensor -- if a black line is detected (true/false)."; // untranslated
Blockly.Msg.INFRARED_PRESENCE_GETSAMPLE_TOOLTIP = "Returns an array of measurements for the presence of a beacon."; // untranslated
Blockly.Msg.INFRARED_TOOLTIP = "Represents an infrared sensor."; // untranslated
Blockly.Msg.INLINE_INPUTS = "Imission an linia";
Blockly.Msg.INPUT = "input"; // untranslated
Blockly.Msg.INTERNAL_PORT = "internal"; // untranslated
Blockly.Msg.IRSEEKER_TOOLTIP = "Represents a HiTechnic NXT IRSeeker V2 sensor."; // untranslated
Blockly.Msg.JOYSTICK_GETSAMPLE_TOOLTIP = "Gets the current reading of one of the axises of the joystick"; // untranslated
Blockly.Msg.KEY_ISPRESSED_TOOLTIP = "Is the selected button pressed?"; // untranslated
Blockly.Msg.KEY_TOOLTIP = "Represents a button."; // untranslated
Blockly.Msg.LANGUAGE = "language"; // untranslated
Blockly.Msg.LANGUAGE_ARABIC = "Arabic"; // untranslated
Blockly.Msg.LANGUAGE_BRAZILIAN = "Brazilian"; // untranslated
Blockly.Msg.LANGUAGE_CHINESE = "Chinese"; // untranslated
Blockly.Msg.LANGUAGE_CZECH = "Czech"; // untranslated
Blockly.Msg.LANGUAGE_DANISH = "Danish"; // untranslated
Blockly.Msg.LANGUAGE_DUTCH = "Dutch"; // untranslated
Blockly.Msg.LANGUAGE_ENGLISH = "English"; // untranslated
Blockly.Msg.LANGUAGE_FINNISH = "Finnish"; // untranslated
Blockly.Msg.LANGUAGE_FRENCH = "French"; // untranslated
Blockly.Msg.LANGUAGE_GERMAN = "German"; // untranslated
Blockly.Msg.LANGUAGE_GREEK = "Greek"; // untranslated
Blockly.Msg.LANGUAGE_ITALIAN = "Italian"; // untranslated
Blockly.Msg.LANGUAGE_JAPANESE = "Japanese"; // untranslated
Blockly.Msg.LANGUAGE_KOREAN = "Korean"; // untranslated
Blockly.Msg.LANGUAGE_NORWEGIAN = "Norwegian"; // untranslated
Blockly.Msg.LANGUAGE_POLISH = "Polish"; // untranslated
Blockly.Msg.LANGUAGE_PORTUGUESE = "Portuguese"; // untranslated
Blockly.Msg.LANGUAGE_RUSSIAN = "Russian"; // untranslated
Blockly.Msg.LANGUAGE_SPANISH = "Spanish"; // untranslated
Blockly.Msg.LANGUAGE_SWEDISH = "Swedish"; // untranslated
Blockly.Msg.LANGUAGE_TURKISH = "Turkish"; // untranslated
Blockly.Msg.LCDI2C_TOOLTIP = "Represents an LCD 1602 display with a soldered I²C module."; // untranslated
Blockly.Msg.LCD_TOOLTIP = "Represents an LCD display."; // untranslated
Blockly.Msg.LED = "LED"; // untranslated
Blockly.Msg.LEDBAR = "LED Bar"; // untranslated
Blockly.Msg.LEDBAR_SET_TOOLTIP = "Sets the specified LED [0-9] on the Grove LED Bar v2.0 by Seeed to the given brightness [0-8]. The LED Bar has to be connected to the A1 (right) Grove connector."; // untranslated
Blockly.Msg.LED_MATRIX = "LED matrix"; // untranslated
Blockly.Msg.LED_OFF = "turn LED off"; // untranslated
Blockly.Msg.LED_OFF_TOOLTIP = "Turns the LED off."; // untranslated
Blockly.Msg.LED_ON = "turn LED on"; // untranslated
Blockly.Msg.LED_ON_TOOLTIP = "Turns the LED on and changes the color."; // untranslated
Blockly.Msg.LED_ON_WHITE_TOOLTIP = "Turns the LED on. Watch out, it's very bright!"; // untranslated
Blockly.Msg.LED_TOOLTIP = "Represents an LED."; // untranslated
Blockly.Msg.LEFT = "left"; // untranslated
Blockly.Msg.LIGHT_ARDU_TOOLTIP = "Represents 8 light sensors."; // untranslated
Blockly.Msg.LIGHT_GETSAMPLE_TOOLTIP = "Gets the current reading from the light sensor in percent."; // untranslated
Blockly.Msg.LIGHT_TOOLTIP = "Represents a light sensor."; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "creé na lista veuida";
Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Smon-e na lista, ëd longheur 0, ch'a conten gnun-a argistrassion";
Blockly.Msg.LISTS_CREATE_TITLE = "list"; // untranslated
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "lista";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Gionté, gavé o riordiné le session për configuré torna cost blòch ëd lista.";
Blockly.Msg.LISTS_CREATE_WITH_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with";
Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "creé na lista con";
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Gionté n'element a la lista.";
Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "Creé na lista con un nùmer qualsëssìa d'element.";
Blockly.Msg.LISTS_GET_INDEX_FIRST = "prim";
Blockly.Msg.LISTS_GET_INDEX_FROM_END = "# da la fin";
Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#"; // untranslated
Blockly.Msg.LISTS_GET_INDEX_GET = "oten-e";
Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "oten-e e eliminé";
Blockly.Msg.LISTS_GET_INDEX_LAST = "ùltim";
Blockly.Msg.LISTS_GET_INDEX_RANDOM = "a l'ancàpit";
Blockly.Msg.LISTS_GET_INDEX_REMOVE = "eliminé";
Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "A smon ël prim element an na lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_END = "A smon l'element a la posission ëspessificà an na lista. #1 a l'é l'ùltim element.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_START = "A smon l'element a la posission ëspessificà an na lista. #1 a l'é ël prim element.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "A smon l'ùltim element an na lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "A smon n'element a l'ancàpit an na lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "A gava e a smon ël prim element an na lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_END = "A gava e a smon l'element a la posission ëspessificà an na lista. #1 a l'é l'ùltim element.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_START = "A gava e a smon l'element a la posission ëspessificà an na lista. #1 a l'é 'l prim element.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "A gava e a smon l'ùltim element an na lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "A gava e a smon n'element a l'ancàpit an na lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "A gava ël prim element an na lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_END = "A gava l'element a la posission ëspessificà an na lista. #1 a l'é l'ùltim element.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_START = "A gava l'element a la posission ëspessificà an na lista. #1 a l'é ël prim element.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "A gava l'ùltim element an na lista.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "A gava n'element a l'ancàpit da na lista.";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "fin-a a # da la fin";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "fin-a a #";
Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "fin-a a l'ùltim";
Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "oten-e la sot-lista dal prim";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "oten-e la sot-lista da # da la fin";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "oten-e la sot-lista da #";
Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "A crea na còpia dël tòch ëspessificà ëd na lista.";
Blockly.Msg.LISTS_INDEX_OF_FIRST = "trové la prima ocorensa dl'element";
Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated
Blockly.Msg.LISTS_INDEX_OF_LAST = "trové l'ùltima ocorensa dl'element";
Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "A smon l'ìndes ëd la prima/ùltima ocorensa dl'element ant la lista. A smon 0 se l'element a l'é nen trovà.";
Blockly.Msg.LISTS_INLIST = "ant la lista";
Blockly.Msg.LISTS_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated
Blockly.Msg.LISTS_ISEMPTY_TITLE = "%1 a l'é veuid";
Blockly.Msg.LISTS_ISEMPTY_TOOLTIP = "A smon ver se la lista a l'é veuida.";
Blockly.Msg.LISTS_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated
Blockly.Msg.LISTS_LENGTH_TITLE = "longheur ëd %1";
Blockly.Msg.LISTS_LENGTH_TOOLTIP = "A smon la longheur ¨d na lista.";
Blockly.Msg.LISTS_REPEAT_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg.LISTS_REPEAT_TITLE = "creé na lista con l'element %1 arpetù %2 vire";
Blockly.Msg.LISTS_REPEAT_TOOLTIP = "A crea na lista ch'a consist dël valor dàit arpetù ël nùmer ëspessificà ëd vire.";
Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated
Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "tanme";
Blockly.Msg.LISTS_SET_INDEX_INSERT = "anserì an";
Blockly.Msg.LISTS_SET_INDEX_SET = "buté";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "A anseriss l'element al prinsipi ëd na lista.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_END = "A anseriss l'element a la posission ëspessificà an na lista. #1 a l'é l'ùltim element.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_START = "A anseriss l'element a la posission ëspessificà an na lista. #1 a l'é ël prim element.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Gionté l'element a la fin ëd na lista.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "A anseriss l'element a l'ancàpit an na lista.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "A fissa ël prim element an na lista.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_END = "A fissa l'element a la posission ëspessificà an na lista. #1 a l'é l'ùltim element.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_START = "A fissa l'element a la posission ëspessificà an na lista. #1 a l'é ël prim element.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "A fissa l'ùltim element an na lista.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "A fissa n'element a l'ancàpit an na lista.";
Blockly.Msg.LISTS_SORT_HELPURL = "https://github.com/google/blockly/wiki/Lists#sorting-a-list";
Blockly.Msg.LISTS_SORT_ORDER_ASCENDING = "chërsent";
Blockly.Msg.LISTS_SORT_ORDER_DESCENDING = "descending"; // untranslated
Blockly.Msg.LISTS_SORT_TITLE = "ordiné %1 %2 %3";
Blockly.Msg.LISTS_SORT_TOOLTIP = "Ordiné na còpia ëd na lista.";
Blockly.Msg.LISTS_SORT_TYPE_IGNORECASE = "alphabetic, ignore case"; // untranslated
Blockly.Msg.LISTS_SORT_TYPE_NUMERIC = "numeric"; // untranslated
Blockly.Msg.LISTS_SORT_TYPE_TEXT = "alphabetic"; // untranslated
Blockly.Msg.LISTS_SPLIT_HELPURL = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists";
Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT = "fé na lista da 'n test";
Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST = "fé 'n test da na lista";
Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN = "Gionze na lista ëd test ant un test sol, separandje con un separator.";
Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT = "Divide un test an na lista ëd test, tajand a minca 'n separator.";
Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER = "con ël separator";
Blockly.Msg.LIST_BACK_TOOLTIP = "Back to previous view."; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_FALSE = "fàuss";
Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "A rëspond ver o fàuss.";
Blockly.Msg.LOGIC_BOOLEAN_TRUE = "ver";
Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://en.wikipedia.org/wiki/Inequality_(mathematics)";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Rësponde ver si le doe imission a son uguaj.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Rësponde ver si la prima imission a l'é pi granda che la sconda.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Rësponde ver si la prima imission a l'é pi granda o ugual a la sconda.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Rësponde ver si la prima imission a l'é pi cita dla sconda.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Rësponde ver si la prima imission a l'é pi cita o ugual a la sconda.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Rësponde ver si le doe imission a son nen uguaj.";
Blockly.Msg.LOGIC_NEGATE_HELPURL = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated
Blockly.Msg.LOGIC_NEGATE_TITLE = "nen %1";
Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "A rëspond ver se l'imission a l'é fàussa. A rëspond fàuss se l'imission a l'é vera.";
Blockly.Msg.LOGIC_NULL = "gnente";
Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type"; // untranslated
Blockly.Msg.LOGIC_NULL_TOOLTIP = "A rëspond gnente.";
Blockly.Msg.LOGIC_OPERATION_AND = "e";
Blockly.Msg.LOGIC_OPERATION_HELPURL = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated
Blockly.Msg.LOGIC_OPERATION_OR = "o";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Rësponde ver se tute doe j'imission a son vere.";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Rësponde ver se almanch un-a d'imission a l'é vera.";
Blockly.Msg.LOGIC_TERNARY_CONDITION = "preuva";
Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:"; // untranslated
Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "se fàuss";
Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "se ver";
Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "Controlé la condission an 'preuva'. Se la condission a l'é vera, a rëspond con ël valor 'se ver'; dësnò a rëspond con ël valor 'se fàuss'.";
Blockly.Msg.LOOP = "repeat until"; // untranslated
Blockly.Msg.LOOPFOREVER_TOOLTIP = "Repeats indefinitely an action."; // untranslated
Blockly.Msg.LOOP_FOREVER = "repeat indefinitely"; // untranslated
Blockly.Msg.MATH_ADDITION_SYMBOL = "+"; // untranslated
Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://en.wikipedia.org/wiki/Arithmetic";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "A smon la soma ëd doi nùmer.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "A smon ël cossient dij doi nùmer.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "A smon la diferensa dij doi nùmer.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "A smon ël prodot dij doi nùmer.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "A smon ël prim nùmer alvà a la potensa dël second.";
Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter";
Blockly.Msg.MATH_CHANGE_TITLE = "ancrementé %1 për %2";
Blockly.Msg.MATH_CHANGE_TOOLTIP = "Gionté un nùmer a la variàbil '%1'.";
Blockly.Msg.MATH_CONSTANT_HELPURL = "https://en.wikipedia.org/wiki/Mathematical_constant";
Blockly.Msg.MATH_CONSTANT_TOOLTIP = "A smon un-a dle costante comun-e π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…) o ∞ (infinì).";
Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29"; // untranslated
Blockly.Msg.MATH_CONSTRAIN_TITLE = "limité %1 antra %2 e %3";
Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Limité un nùmer a esse antra le limitassion ëspessificà (comprèise).";
Blockly.Msg.MATH_DIVISION_SYMBOL = "÷"; // untranslated
Blockly.Msg.MATH_IS_DIVISIBLE_BY = "a l'é divisìbil për";
Blockly.Msg.MATH_IS_EVEN = "a l'é cobi";
Blockly.Msg.MATH_IS_NEGATIVE = "a l'é negativ";
Blockly.Msg.MATH_IS_ODD = "a l'é dëscobi";
Blockly.Msg.MATH_IS_POSITIVE = "a l'é positiv";
Blockly.Msg.MATH_IS_PRIME = "a l'é prim";
Blockly.Msg.MATH_IS_TOOLTIP = "A contròla si un nùmer a l'é cobi, dëscobi, prim, antreghm positiv, negativ, o s'a l'é divisìbil për un nùmer dàit. A rëspond ver o fàuss.";
Blockly.Msg.MATH_IS_WHOLE = "a l'é antregh";
Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation";
Blockly.Msg.MATH_MODULO_TITLE = "resta ëd %1:%2";
Blockly.Msg.MATH_MODULO_TOOLTIP = "A smon la resta ëd la division dij doi nùmer.";
Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×"; // untranslated
Blockly.Msg.MATH_NUMBER_HELPURL = "https://en.wikipedia.org/wiki/Number";
Blockly.Msg.MATH_NUMBER_TOOLTIP = "Un nùmer.";
Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "media dla lista";
Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "màssim ëd la lista";
Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "mesan-a dla lista";
Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "mìnim ëd la lista";
Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "mòde dla lista";
Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "element a l'ancàpit ëd la lista";
Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "deviassion ëstàndard ëd la lista";
Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "soma dla lista";
Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "A smon la media (aritmética) dij valor numérich ant la lista.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "A smon ël pi gròss nùmer ëd la lista.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "A smon ël nùmer mesan ëd la lista.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "A smon ël pi cit nùmer ëd la lista.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "A smon na lista dj'element pi frequent ëd la lista.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "A smon n'element a l'ancàpit da la lista.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "A smon la deviassion ëstàndard ëd la lista.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "A smon la soma ëd tuti ij nùmer ant la lista.";
Blockly.Msg.MATH_POWER_SYMBOL = "^"; // untranslated
Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation";
Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "frassion aleatòria";
Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "A smon na frassion aleatòria antra 0,0 (comprèis) e 1,0 (esclus).";
Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation";
Blockly.Msg.MATH_RANDOM_INT_TITLE = "antregh aleatòri antra %1 e %2";
Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "A smon n'antregh aleatòri antra ij doi lìmit ëspessificà, comprèis.";
Blockly.Msg.MATH_ROUND_HELPURL = "https://en.wikipedia.org/wiki/Rounding";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "ariondé";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "ariondé për difet";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "ariondé për ecess";
Blockly.Msg.MATH_ROUND_TOOLTIP = "A arionda un nùmer për difet o ecess.";
Blockly.Msg.MATH_SINGLE_HELPURL = "https://en.wikipedia.org/wiki/Square_root";
Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "assolù";
Blockly.Msg.MATH_SINGLE_OP_ROOT = "rèis quadra";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "A smon ël valor assolù d'un nùmer.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "A smon e a la potensa d'un nùmer.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "A smon ël logaritm natural d'un nùmer.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "A smon ël logaritm an base 10 d'un nùmer.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "A smon l'opòst d'un nùmer.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "A smon 10 a la potensa d'un nùmer.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "A smon la rèis quadra d'un nùmer.";
Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-"; // untranslated
Blockly.Msg.MATH_TRIG_ACOS = "acos"; // untranslated
Blockly.Msg.MATH_TRIG_ASIN = "asin"; // untranslated
Blockly.Msg.MATH_TRIG_ATAN = "atan"; // untranslated
Blockly.Msg.MATH_TRIG_COS = "cos"; // untranslated
Blockly.Msg.MATH_TRIG_HELPURL = "https://en.wikipedia.org/wiki/Trigonometric_functions";
Blockly.Msg.MATH_TRIG_SIN = "sin"; // untranslated
Blockly.Msg.MATH_TRIG_TAN = "tan"; // untranslated
Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "A smon l'arch-cosen d'un nùmer.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "A smon l'arch-sen d'un nùmer.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "A smon l'arch-tangenta d'un nùmer.";
Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "A smon ël cosen ëd n'àngol an gré (pa an radiant).";
Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "A smon ël sen ëd n'àngol an gré (pa an radiant).";
Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "A smon la tangenta ëd n'àngol an gré (pa an radiant).";
Blockly.Msg.ME = "Mi";
Blockly.Msg.MENU_ABOUT = "about the Open Roberta Lab"; // untranslated
Blockly.Msg.MENU_ABOUT_PROJECT = "about the Open Roberta Project"; // untranslated
Blockly.Msg.MENU_ATTACH = "attach ..."; // untranslated
Blockly.Msg.MENU_BEGINNER = "beginner"; // untranslated
Blockly.Msg.MENU_CHANGE = "change ..."; // untranslated
Blockly.Msg.MENU_CHECK = "check"; // untranslated
Blockly.Msg.MENU_CODE_DOWNLOAD_TOOLTIP = "Download the source code of your program on the computer"; // untranslated
Blockly.Msg.MENU_CODE_REFRESH_TOOLTIP = "Refresh the source code, if you have changed the NEPO Blocks."; // untranslated
Blockly.Msg.MENU_CONNECT = "connect ..."; // untranslated
Blockly.Msg.MENU_CREATE_LINK = "create program link ..."; // untranslated
Blockly.Msg.MENU_DELETE_USER = "delete user ..."; // untranslated
Blockly.Msg.MENU_EDIT = "edit"; // untranslated
Blockly.Msg.MENU_EDIT_TOOLTIP = "edit"; // untranslated
Blockly.Msg.MENU_EV3 = "Robot preparation"; // untranslated
Blockly.Msg.MENU_EXPERT = "expert"; // untranslated
Blockly.Msg.MENU_EXPORT_PROG = "export program"; // untranslated
Blockly.Msg.MENU_FAQ = "FAQ"; // untranslated
Blockly.Msg.MENU_GALLERY = "gallery"; // untranslated
Blockly.Msg.MENU_GALLERY_TOOLTIP = "gallery"; // untranslated
Blockly.Msg.MENU_GENERAL = "general help"; // untranslated
Blockly.Msg.MENU_HELP = "help"; // untranslated
Blockly.Msg.MENU_HELP_TOOLTIP = "help"; // untranslated
Blockly.Msg.MENU_IMPORT_PROG = "import program ..."; // untranslated
Blockly.Msg.MENU_LANGUAGE = "languages"; // untranslated
Blockly.Msg.MENU_LANGUAGE_TOOLTIP = "languages"; // untranslated
Blockly.Msg.MENU_LIST = "list ..."; // untranslated
Blockly.Msg.MENU_LIST_CONF = "my configurations ..."; // untranslated
Blockly.Msg.MENU_LIST_PROG = "my programs ..."; // untranslated
Blockly.Msg.MENU_LIST_PROG_EXAMPLES = "example programs ..."; // untranslated
Blockly.Msg.MENU_LOGGING = "logging"; // untranslated
Blockly.Msg.MENU_LOG_IN = "login ..."; // untranslated
Blockly.Msg.MENU_LOG_OUT = "logout"; // untranslated
Blockly.Msg.MENU_MESSAGE_DOWNLOAD = "Your program has been successfully downloaded."; // untranslated
Blockly.Msg.MENU_NEW = "new"; // untranslated
Blockly.Msg.MENU_PROGRAMMING = "programming with NEPO"; // untranslated
Blockly.Msg.MENU_PROPERTIES = "properties"; // untranslated
Blockly.Msg.MENU_RIGHT_CODE_TOOLTIP = "Open/close the source code view."; // untranslated
Blockly.Msg.MENU_RIGHT_HELP_TOOLTIP = "Open/close the help view."; // untranslated
Blockly.Msg.MENU_RIGHT_INFO_TOOLTIP = "Open/close the program documentation view."; // untranslated
Blockly.Msg.MENU_RIGHT_SIM_TOOLTIP = "Open/close the simulation view."; // untranslated
Blockly.Msg.MENU_RIGHT_TUTORIAL_TOOLTIP = "open/close the tutorial's view"; // untranslated
Blockly.Msg.MENU_ROBOT = "robot"; // untranslated
Blockly.Msg.MENU_ROBOT_STATE_INFO = "info"; // untranslated
Blockly.Msg.MENU_ROBOT_STATE_TOOLTIP = "robot info"; // untranslated
Blockly.Msg.MENU_ROBOT_STOP_HINT_EV3 = "Press <span class='typcn typcn-media-stop'></span>+<span class='typcn typcn-arrow-sorted-down'></span> buttons on the robot to abort the program!"; // untranslated
Blockly.Msg.MENU_ROBOT_STOP_HINT_NXT = "Press <span class='typcn typcn-media-cancel'></span> button on the robot to abort the program!"; // untranslated
Blockly.Msg.MENU_ROBOT_TOOLTIP = "robots"; // untranslated
Blockly.Msg.MENU_RUN_MULT_SIM = "multiple robot simulation ..."; // untranslated
Blockly.Msg.MENU_SAVE = "save"; // untranslated
Blockly.Msg.MENU_SAVE_AS = "save as ..."; // untranslated
Blockly.Msg.MENU_SHOW_AGAIN = "show welcome note again"; // untranslated
Blockly.Msg.MENU_SHOW_CODE = "open/close source code view"; // untranslated
Blockly.Msg.MENU_SIM_BACK = "Back"; // untranslated
Blockly.Msg.MENU_SIM_DRAW = "Drawing Scene"; // untranslated
Blockly.Msg.MENU_SIM_IMPORT_TOOLTIP = "Upload your own simulation background image, it will be appended at the end of the background's list."; // untranslated
Blockly.Msg.MENU_SIM_MATH = "Math Scene"; // untranslated
Blockly.Msg.MENU_SIM_POSE_TOOLTIP = "Move the robot back to it's initial position."; // untranslated
Blockly.Msg.MENU_SIM_RESCUE = "Rescue Scene"; // untranslated
Blockly.Msg.MENU_SIM_ROBERTA = "Roberta Scene"; // untranslated
Blockly.Msg.MENU_SIM_ROBOT_TOOLTIP = "open/close the robot's view"; // untranslated
Blockly.Msg.MENU_SIM_SCENE_TOOLTIP = "change the scene"; // untranslated
Blockly.Msg.MENU_SIM_SIMPLE = "Simple Scene"; // untranslated
Blockly.Msg.MENU_SIM_START_TOOLTIP = "Start your program in the simulation."; // untranslated
Blockly.Msg.MENU_SIM_STOP = "Stop"; // untranslated
Blockly.Msg.MENU_SIM_STOP_TOOLTIP = "Stop your program in the simulation."; // untranslated
Blockly.Msg.MENU_SIM_VALUES_TOOLTIP = "Open/close the sensors' data view."; // untranslated
Blockly.Msg.MENU_SIM_WRO = "World Robot Olympiad scene"; // untranslated
Blockly.Msg.MENU_START_BRICK = "run on »$«"; // untranslated
Blockly.Msg.MENU_START_SIM = "open/close simulation view"; // untranslated
Blockly.Msg.MENU_STATE_INFO = "state information"; // untranslated
Blockly.Msg.MENU_STOP_BRICK = "stop program on »$«"; // untranslated
Blockly.Msg.MENU_TOOLBOX = "NEPO-Blocks"; // untranslated
Blockly.Msg.MENU_TOOLBOX_BEGINNER = "NEPO-Blocks beginner"; // untranslated
Blockly.Msg.MENU_TOOLBOX_EXPERT = "NEPO-Blocks expert"; // untranslated
Blockly.Msg.MENU_TUTORIAL = "tutorials"; // untranslated
Blockly.Msg.MENU_TUTORIAL_TOOLTIP = "tutorials"; // untranslated
Blockly.Msg.MENU_USER = "login"; // untranslated
Blockly.Msg.MENU_USER_STATE_TOOLTIP = "user info"; // untranslated
Blockly.Msg.MENU_USER_TOOLTIP = "user"; // untranslated
Blockly.Msg.MENU_ZOOM = "zoom"; // untranslated
Blockly.Msg.MENU_ZOOM_IN = "zoom in"; // untranslated
Blockly.Msg.MENU_ZOOM_OUT = "zoom out"; // untranslated
Blockly.Msg.MENU_ZOOM_RESET = "reset zoom"; // untranslated
Blockly.Msg.MESSAGE_ADDED_USER = "User »$« was added"; // untranslated
Blockly.Msg.MESSAGE_CONFIGURATION_DELETED = "Configuration »$« was deleted"; // untranslated
Blockly.Msg.MESSAGE_EDIT_CHECK = "Your program is now checked!"; // untranslated
Blockly.Msg.MESSAGE_EDIT_SAVE_CONFIGURATION = "Your configuration has been saved"; // untranslated
Blockly.Msg.MESSAGE_EDIT_SAVE_CONFIGURATION_AS = "Your configuration has been saved as »$«"; // untranslated
Blockly.Msg.MESSAGE_EDIT_SAVE_GROUP_AS = "Your group has been created"; // untranslated
Blockly.Msg.MESSAGE_EDIT_SAVE_PROGRAM = "Your program has been saved"; // untranslated
Blockly.Msg.MESSAGE_EDIT_SAVE_PROGRAM_AS = "Your program has been saved as »$«"; // untranslated
Blockly.Msg.MESSAGE_EDIT_START = "Your program »$« will run in a moment!"; // untranslated
Blockly.Msg.MESSAGE_FIRMWARE_ERROR = "The firmware of your robot is newer than that of the Open Roberta Lab. Please tell your server admin, that the server needs to be updated."; // untranslated
Blockly.Msg.MESSAGE_GROUP_DELETED = "Group »$« was deleted"; // untranslated
Blockly.Msg.MESSAGE_INVALID_CONF_NAME = "Please fill in a correct name. A correct name begins with a letter and can only contain letters or numbers. The default name »[robot]basis« can't be used here."; // untranslated
Blockly.Msg.MESSAGE_INVALID_NAME = "Please fill in a correct name. A correct name begins with a letter and can only contain letters or numbers."; // untranslated
Blockly.Msg.MESSAGE_NOT_AVAILABLE = "Not available."; // untranslated
Blockly.Msg.MESSAGE_PROGRAM_DELETED = "Program »$« was deleted"; // untranslated
Blockly.Msg.MESSAGE_RESTART_ROBOT = "Please reconnect the robot to the Open Roberta Lab."; // untranslated
Blockly.Msg.MESSAGE_ROBOT_CONNECTED = "Your robot »$« is connected"; // untranslated
Blockly.Msg.MESSAGE_ROBOT_DISCONNECTED = "An active robot was disconnected"; // untranslated
Blockly.Msg.MESSAGE_USER_DELETED = "User deleted"; // untranslated
Blockly.Msg.MESSAGE_USER_GROUP_DELETED = "User »$« was deleted"; // untranslated
Blockly.Msg.MESSAGE_USER_LOGIN = "Hello »$«"; // untranslated
Blockly.Msg.MESSAGE_USER_LOGOUT = "You are logged out"; // untranslated
Blockly.Msg.MICROBITBRICK_TOOLTIP = "Represents micro:bit, a pocket-sized codeable computer. There are also inbuilt actors and sensors available, e.g. buttons, display ..."; // untranslated
Blockly.Msg.MICROPHONE_GETSAMPLE_TOOLTIP = "Gets the current reading from the microphone in % (mapped to 0 - 100). If the value is always low, the value has to be multiplied by 10, because the amplification is missing on the hardware."; // untranslated
Blockly.Msg.MODE = "mode"; // untranslated
Blockly.Msg.MODE_ACCELERATION = "acceleration"; // untranslated
Blockly.Msg.MODE_AMBIENTLIGHT = "ambient light"; // untranslated
Blockly.Msg.MODE_ANALOG = "analog value"; // untranslated
Blockly.Msg.MODE_ANGLE = "angle"; // untranslated
Blockly.Msg.MODE_CLOSE = "close"; // untranslated
Blockly.Msg.MODE_COLOUR = "colour"; // untranslated
Blockly.Msg.MODE_COMPASS = "compass"; // untranslated
Blockly.Msg.MODE_CURRENT = "current"; // untranslated
Blockly.Msg.MODE_DEGREE = "degree"; // untranslated
Blockly.Msg.MODE_DIGITAL = "digital value"; // untranslated
Blockly.Msg.MODE_DISTANCE = "distance"; // untranslated
Blockly.Msg.MODE_HUMIDITY = "humidity"; // untranslated
Blockly.Msg.MODE_IDALL = "IDs (list)"; // untranslated
Blockly.Msg.MODE_IDONE = "ID"; // untranslated
Blockly.Msg.MODE_INFO = "information"; // untranslated
Blockly.Msg.MODE_LIGHT = "light"; // untranslated
Blockly.Msg.MODE_LINE = "line"; // untranslated
Blockly.Msg.MODE_MODULATED = "modulated"; // untranslated
Blockly.Msg.MODE_MOISTURE = "moisture"; // untranslated
Blockly.Msg.MODE_NAMEALL = "names (list)"; // untranslated
Blockly.Msg.MODE_NAMEONE = "name"; // untranslated
Blockly.Msg.MODE_OBSTACLE = "obstacle"; // untranslated
Blockly.Msg.MODE_OPEN = "open"; // untranslated
Blockly.Msg.MODE_ORIENTATION = "orientation"; // untranslated
Blockly.Msg.MODE_PRESENCE = "presence"; // untranslated
Blockly.Msg.MODE_PRESSED = "pressed"; // untranslated
Blockly.Msg.MODE_PRESSURE = "pressure"; // untranslated
Blockly.Msg.MODE_PULSEHIGH = "pulse time HIGH"; // untranslated
Blockly.Msg.MODE_PULSELOW = "pulse time LOW"; // untranslated
Blockly.Msg.MODE_RATE = "rate"; // untranslated
Blockly.Msg.MODE_REFLEXION = "reflected light"; // untranslated
Blockly.Msg.MODE_RGB = "RGB"; // untranslated
Blockly.Msg.MODE_ROTATION = "rotation"; // untranslated
Blockly.Msg.MODE_SENSOR1 = "Light Sensor1"; // untranslated
Blockly.Msg.MODE_SENSOR2 = "Light Sensor2"; // untranslated
Blockly.Msg.MODE_SOUND = "sound"; // untranslated
Blockly.Msg.MODE_TEMPERATURE = "temperature"; // untranslated
Blockly.Msg.MODE_TILTED = "tilted"; // untranslated
Blockly.Msg.MODE_UNMODULATED = "unmodulated"; // untranslated
Blockly.Msg.MODE_UVLIGHT = "UV light"; // untranslated
Blockly.Msg.MODE_VALUE = "value"; // untranslated
Blockly.Msg.MODE_WORD = "word"; // untranslated
Blockly.Msg.MODE_X = "X-value"; // untranslated
Blockly.Msg.MODE_Y = "Y-value"; // untranslated
Blockly.Msg.MODE_Z = "Z-value"; // untranslated
Blockly.Msg.MOISTURE_TOOLTIP = "Represents a moisture sensor."; // untranslated
Blockly.Msg.MOTION_TOOLTIP = "Represents a motion sensor."; // untranslated
Blockly.Msg.MOTOR = "motor"; // untranslated
Blockly.Msg.MOTORDIFF_ON_FOR_TOOLTIP = "Starts the robot with specific speed and stops after specific distance."; // untranslated
Blockly.Msg.MOTORDIFF_ON_TOOLTIP = "Starts the robot with specific speed."; // untranslated
Blockly.Msg.MOTORDIFF_STOP_TOOLTIP = "Stops the robot."; // untranslated
Blockly.Msg.MOTORDIFF_TURN_FOR_TOOLTIP = "Turns the robot for number of degrees."; // untranslated
Blockly.Msg.MOTORDIFF_TURN_TOOLTIP = "Turns the robot."; // untranslated
Blockly.Msg.MOTORS_ON_TOOLTIP_CALLIOPE = "Turns motor A and B on with a specific power."; // untranslated
Blockly.Msg.MOTORS_STOP_TOOLTIP = "Stops both motors, A and B."; // untranslated
Blockly.Msg.MOTOR_ARDU_TOOLTIP = "Represents a Bot'n Roll chassis motor."; // untranslated
Blockly.Msg.MOTOR_BACKWARD = "backwards"; // untranslated
Blockly.Msg.MOTOR_BIG = "big"; // untranslated
Blockly.Msg.MOTOR_BIG_TOOLTIP = "Represents a big motor."; // untranslated
Blockly.Msg.MOTOR_BRAKE = "brake"; // untranslated
Blockly.Msg.MOTOR_DEGREE = "degree"; // untranslated
Blockly.Msg.MOTOR_DISTANCE = "distance cm"; // untranslated
Blockly.Msg.MOTOR_DRIVE = "drive"; // untranslated
Blockly.Msg.MOTOR_FLOAT = "float"; // untranslated
Blockly.Msg.MOTOR_FOREWARD = "forwards"; // untranslated
Blockly.Msg.MOTOR_GETPOWER_TOOLTIP = "Gets current power of this motor."; // untranslated
Blockly.Msg.MOTOR_LEFT = "left"; // untranslated
Blockly.Msg.MOTOR_MIDDLE = "middle"; // untranslated
Blockly.Msg.MOTOR_MIDDLE_TOOLTIP = "Represents a middle motor."; // untranslated
Blockly.Msg.MOTOR_NONE = "none"; // untranslated
Blockly.Msg.MOTOR_ON_FOR_TOOLTIP = "Turns motor on and stops motor after execution of rotations/degrees."; // untranslated
Blockly.Msg.MOTOR_ON_FOR_TOOLTIP_MS = "Sets servo motor to certain position in degrees."; // untranslated
Blockly.Msg.MOTOR_ON_FOR_TOOLTIP_RPM = "Turns motor on at speed in rpms (rotation per minute) and stops motor after execution of rotations/degrees."; // untranslated
Blockly.Msg.MOTOR_ON_FOR_TOOLTIP_SERVO = "Turns motor on and stops motor after execution of rotations/degrees."; // untranslated
Blockly.Msg.MOTOR_ON_TOOLTIP = "Turns motor on with specific power."; // untranslated
Blockly.Msg.MOTOR_ON_TOOLTIP_CALLIOPE = "Turns motor A, B or A+B on with a specific power."; // untranslated
Blockly.Msg.MOTOR_OTHER = "other power consumer"; // untranslated
Blockly.Msg.MOTOR_PAN = "pan"; // untranslated
Blockly.Msg.MOTOR_PORT = "motor port"; // untranslated
Blockly.Msg.MOTOR_PORT_ARDUINO = "motor 28BYJ-48 port"; // untranslated
Blockly.Msg.MOTOR_REGULATION = "regulation"; // untranslated
Blockly.Msg.MOTOR_RIGHT = "right"; // untranslated
Blockly.Msg.MOTOR_ROTATION = "rotation"; // untranslated
Blockly.Msg.MOTOR_ROTATION_PER_MINUTE = "rpm"; // untranslated
Blockly.Msg.MOTOR_ROTATION_REVERSE = "direction of rotation"; // untranslated
Blockly.Msg.MOTOR_SETPOWER_TOOLTIP = "Sets power of this motor."; // untranslated
Blockly.Msg.MOTOR_SIDE = "side"; // untranslated
Blockly.Msg.MOTOR_SPEED = "speed %"; // untranslated
Blockly.Msg.MOTOR_SPEED_0 = "Motor Speed is 0!"; // untranslated
Blockly.Msg.MOTOR_STEER = "steer"; // untranslated
Blockly.Msg.MOTOR_STOP = "stop"; // untranslated
Blockly.Msg.MOTOR_STOP_TOOLTIP = "Stops this motor."; // untranslated
Blockly.Msg.MOTOR_TILT = "tilt"; // untranslated
Blockly.Msg.MOTOR_TURN = "turn"; // untranslated
Blockly.Msg.NAO_ABSOLUTE = "absolute"; // untranslated
Blockly.Msg.NAO_ACCELEROMETER = "accelerometer"; // untranslated
Blockly.Msg.NAO_ACCELEROMETER_TOOLTIP = "Get the current reading from the accelerometer in the given direction"; // untranslated
Blockly.Msg.NAO_ANIMATION_TOOLTIP = "Perform the selected animation. TaiChi is a complex and artistic set of moves. Blink will only make the robot blink by using its LEDs. The wink and wipe forehead animation can be performed while siting and standing."; // untranslated
Blockly.Msg.NAO_ANSWER = "answer"; // untranslated
Blockly.Msg.NAO_APPLYPOSTURE = "let NAO"; // untranslated
Blockly.Msg.NAO_APPLYPOSTURE_TOOLTIP = "Robot will take the selected posture or position. Use the dropdown menu to choose one."; // untranslated
Blockly.Msg.NAO_AUTONOMOUS = "turn autonomous behaviour"; // untranslated
Blockly.Msg.NAO_AUTONOMOUS_TOOLTIP = "Turn the robots autonomous behaviour on or off. While 'on' the robot will react to sounds, move slightly from side to side and try to track faces. Turn it off if this behaviour interrupts your program."; // untranslated
Blockly.Msg.NAO_BLINK = "blink"; // untranslated
Blockly.Msg.NAO_CAMERA = "camera"; // untranslated
Blockly.Msg.NAO_CAMERA_BOTTOM = "bottom"; // untranslated
Blockly.Msg.NAO_CAMERA_TOP = "top"; // untranslated
Blockly.Msg.NAO_FACE_GET_INFORMATION_TOOLTIP = "Returns additional information about the given detected in an array with following values: [XAngle, YAngle, XSize, YSize, Heading], please note that all values are given in camera angles."; // untranslated
Blockly.Msg.NAO_FILENAME = "filename"; // untranslated
Blockly.Msg.NAO_FORGETFACEOF = "forget face of"; // untranslated
Blockly.Msg.NAO_FORGETFACE_TOOLTIP = "Delete a face previously saved under a given name from the vision recognition database on the robot. "; // untranslated
Blockly.Msg.NAO_FRAME = "frame"; // untranslated
Blockly.Msg.NAO_FRAME_TORSO = "torso"; // untranslated
Blockly.Msg.NAO_FRAME_WORLD = "world"; // untranslated
Blockly.Msg.NAO_FSR = "force sensitive resistor"; // untranslated
Blockly.Msg.NAO_GETLANGUAGE_TOOLTIP = "Get the active language. This is the language the robot is currently using for Text to Speech and Voice recognition."; // untranslated
Blockly.Msg.NAO_GETVOLUME_TOOLTIP = "Get current volume."; // untranslated
Blockly.Msg.NAO_GYROMETER = "gyrometer"; // untranslated
Blockly.Msg.NAO_GYROMETER_TOOLTIP = "Get the current reading from the gyrometer in the given direction."; // untranslated
Blockly.Msg.NAO_HAND = "hand"; // untranslated
Blockly.Msg.NAO_HAND_TOOLTIP = "Open or close a single hand (wrist) of the robot."; // untranslated
Blockly.Msg.NAO_HEADSENSOR = "head sensor"; // untranslated
Blockly.Msg.NAO_INTENSITY = "intensity"; // untranslated
Blockly.Msg.NAO_JOINT_ANKLEPITCH = "ankle pitch"; // untranslated
Blockly.Msg.NAO_JOINT_ANKLEROLL = "ankle roll"; // untranslated
Blockly.Msg.NAO_JOINT_ELBOWROLL = "elbow roll"; // untranslated
Blockly.Msg.NAO_JOINT_ELBOWYAW = "elbow yaw"; // untranslated
Blockly.Msg.NAO_JOINT_HAND = "hand"; // untranslated
Blockly.Msg.NAO_JOINT_HEADPITCH = "head pitch"; // untranslated
Blockly.Msg.NAO_JOINT_HEADYAW = "head yaw"; // untranslated
Blockly.Msg.NAO_JOINT_HIPPITCH = "hip pitch"; // untranslated
Blockly.Msg.NAO_JOINT_HIPROLL = "hip roll"; // untranslated
Blockly.Msg.NAO_JOINT_HIPYAWPITCH = "hip yaw pitch"; // untranslated
Blockly.Msg.NAO_JOINT_KNEEPITCH = "knee pitch"; // untranslated
Blockly.Msg.NAO_JOINT_SHOULDERPITCH = "shoulder pitch"; // untranslated
Blockly.Msg.NAO_JOINT_SHOULDERROLL = "shoulder roll"; // untranslated
Blockly.Msg.NAO_JOINT_WRISTYAW = "wrist yaw"; // untranslated
Blockly.Msg.NAO_LEARNFACEOF = "learn face of"; // untranslated
Blockly.Msg.NAO_LEARNFACE_TOOLTIP = "Learn and save a face under a given name in the vision recognition database on the robot."; // untranslated
Blockly.Msg.NAO_LED = "LED"; // untranslated
Blockly.Msg.NAO_LEDOFF_TOOLTIP = "Turn the selected LED(s) off."; // untranslated
Blockly.Msg.NAO_LEDRESET_TOOLTIP = "Reset the selected LEDs to their original state regarding colour and intensity."; // untranslated
Blockly.Msg.NAO_LED_ALL = "all"; // untranslated
Blockly.Msg.NAO_LED_CHEST = "chest"; // untranslated
Blockly.Msg.NAO_LED_EAR = "ear"; // untranslated
Blockly.Msg.NAO_LED_EARS = "ears"; // untranslated
Blockly.Msg.NAO_LED_EYE = "eye"; // untranslated
Blockly.Msg.NAO_LED_EYES = "eyes"; // untranslated
Blockly.Msg.NAO_LED_FOOT = "foot"; // untranslated
Blockly.Msg.NAO_LED_HEAD = "head"; // untranslated
Blockly.Msg.NAO_LED_TOOLTIP = "Set the color of selected LED(s). Eyes and feet LEDs are available."; // untranslated
Blockly.Msg.NAO_LOOKAT = "look at"; // untranslated
Blockly.Msg.NAO_MARK_GET_INFORMATION_TOOLTIP = "Returns additional information about the given NAO mark in an array with following values: [XAngle, YAngle, XSize, YSize, Heading], please note that all values are given in camera angles."; // untranslated
Blockly.Msg.NAO_MOVE = "move"; // untranslated
Blockly.Msg.NAO_MOVEJOINT_TOOLTIP = "Move a single joint of the robot. A relative movement means that the current position of the selected joint is used to calculate the new position. Be aware that every joint has different limits. Therefore the input range for the degerees varies."; // untranslated
Blockly.Msg.NAO_PART_ARM = "arm"; // untranslated
Blockly.Msg.NAO_PART_ARMS = "arms"; // untranslated
Blockly.Msg.NAO_PART_BODY = "body"; // untranslated
Blockly.Msg.NAO_PART_HEAD = "head"; // untranslated
Blockly.Msg.NAO_PART_LEG = "leg"; // untranslated
Blockly.Msg.NAO_PART_LEGS = "legs"; // untranslated
Blockly.Msg.NAO_PERFORM = "perform"; // untranslated
Blockly.Msg.NAO_PHRASE = "phrase"; // untranslated
Blockly.Msg.NAO_PLAYFILE_TOOLTIP = "Plays a sound file from the robot. Enter the name of the file. The file needs to be transferred to the robot beforehand."; // untranslated
Blockly.Msg.NAO_PLAY_FILE = "play file"; // untranslated
Blockly.Msg.NAO_POINTAT = "point at"; // untranslated
Blockly.Msg.NAO_POINTLOOKAT_TOOLTIP = "Robot points or looks at a given position. The robot will move one of its hands or the head. Select the frame that is the point of reference. The values are entered in centimeter. Refer to the wiki for more information about the coordinate systems."; // untranslated
Blockly.Msg.NAO_POSTURE_CROUCH = "crouch"; // untranslated
Blockly.Msg.NAO_POSTURE_LYINGBACK = "lie back"; // untranslated
Blockly.Msg.NAO_POSTURE_LYINGBELLY = "lie belly"; // untranslated
Blockly.Msg.NAO_POSTURE_REST = "rest"; // untranslated
Blockly.Msg.NAO_POSTURE_SIT = "sit"; // untranslated
Blockly.Msg.NAO_POSTURE_SITRELAX = "sit relaxed"; // untranslated
Blockly.Msg.NAO_POSTURE_STAND = "stand"; // untranslated
Blockly.Msg.NAO_POSTURE_STANDINIT = "stand init"; // untranslated
Blockly.Msg.NAO_POSTURE_STANDZERO = "stand zero"; // untranslated
Blockly.Msg.NAO_QQVGA = "160*120"; // untranslated
Blockly.Msg.NAO_QVGA = "320*240"; // untranslated
Blockly.Msg.NAO_RANDOMEYES = "random eyes"; // untranslated
Blockly.Msg.NAO_RANDOMEYES_TOOLTIP = "The color of the eyes is changed randomly for a specified amount of time entered in milliseconds."; // untranslated
Blockly.Msg.NAO_RASTA = "rasta"; // untranslated
Blockly.Msg.NAO_RASTA_TOOLTIP = "The color of the eyes is changed between green, yellow and red for a specified amount of time entered in milliseconds."; // untranslated
Blockly.Msg.NAO_RECOGNIZEWORD = "speech recognizer of"; // untranslated
Blockly.Msg.NAO_RECOGNIZEWORD_TOOLTIP = "Returns a word from the given list when recognized by NAO"; // untranslated
Blockly.Msg.NAO_RECORDVIDEO = "record video"; // untranslated
Blockly.Msg.NAO_RECORDVIDEO_TOOLTIP = "Records a video and saves it on the robot. Access the robots file system to view the video."; // untranslated
Blockly.Msg.NAO_RELATIVE = "relative"; // untranslated
Blockly.Msg.NAO_RESOLUTION = "resolution"; // untranslated
Blockly.Msg.NAO_SETINTENSITY_TOOLTIP = "Set the intensity of selected LED(s) in a range from 0 to 100. Ears, head and chest LEDs are available"; // untranslated
Blockly.Msg.NAO_SETLANGUAGE_TOOLTIP = "Set the language. Be aware that it is necessary to download the language pack before you can use it. For more information refer to the manual of your robot."; // untranslated
Blockly.Msg.NAO_SETVOLUME_TOOLTIP = "Set the volume in a range from 0 to 100."; // untranslated
Blockly.Msg.NAO_STIFFNESS = "lock motors"; // untranslated
Blockly.Msg.NAO_STIFFNESS_TOOLTIP = "The stiffness of the selected body part of the robot will be turned on or off. Be aware that releasing the leg motors while the robot is standing may result in robot collapsing."; // untranslated
Blockly.Msg.NAO_STOP = "stop movement"; // untranslated
Blockly.Msg.NAO_STOP_TOOLTIP = "The robot immediately stops all movement. Be aware that this can lead to situations where downfall is possible."; // untranslated
Blockly.Msg.NAO_TAI_CHI = "tai chi"; // untranslated
Blockly.Msg.NAO_TAKEPICTURE = "take picture"; // untranslated
Blockly.Msg.NAO_TAKEPICTURE_TOOLTIP = "Takes a picture and saves it on the robot. Access the robots file system to view the picture."; // untranslated
Blockly.Msg.NAO_TOUCHSENSOR_TOOLTIP = "Is true if the selected touchsensor on the robot was touched."; // untranslated
Blockly.Msg.NAO_TURN_TOOLTIP = "Turns the robot for number of degrees. Only enter positive values and use the dropdown to select the direction. It is possible to enter values up to 360 degrees."; // untranslated
Blockly.Msg.NAO_VGA = "640*480"; // untranslated
Blockly.Msg.NAO_WALK = "walk"; // untranslated
Blockly.Msg.NAO_WALKTO = "walk to"; // untranslated
Blockly.Msg.NAO_WALKTO_TOOLTIP = "The robot walks to the given position. The values are entered in cm and radians and are based on the coordinate system in NAOs body. Please refer to the wiki for more information on the coordinate system and how to calculate the coordinates."; // untranslated
Blockly.Msg.NAO_WALK_ASYNC_TOOLTIP = "Makes the robot walk infinitely"; // untranslated
Blockly.Msg.NAO_WALK_TOOLTIP = "Makes the robot walk a distance entered in cm. Distances below 10cm might lead to no movement at all. Depending on your robot and the surface the robots is walking on the distance might not be exact."; // untranslated
Blockly.Msg.NAO_WAVE = "wave"; // untranslated
Blockly.Msg.NAO_WIPE_FOREHEAD = "wipe forehead"; // untranslated
Blockly.Msg.NEW_VARIABLE = "Neuva variàbil...";
Blockly.Msg.NEW_VARIABLE_TITLE = "Nòm ëd la neuva variàbil:";
Blockly.Msg.NO = "no"; // untranslated
Blockly.Msg.NXTBRICK_TOOLTIP = "Represents the NXT brick with connected actors and sensors. There are also inbuilt actors and sensors available, e.g. buttons, display ..."; // untranslated
Blockly.Msg.OFF = "off"; // untranslated
Blockly.Msg.OLDER_THEN_14 = "I am 16 or older than 16!"; // untranslated
Blockly.Msg.ON = "on"; // untranslated
Blockly.Msg.ORA_ACCESS_RIGHT_CHANGED = "The shared right is updated!"; // untranslated
Blockly.Msg.ORA_ACCESS_RIGHT_DELETED = "The shared right is deleted!"; // untranslated
Blockly.Msg.ORA_ACCOUNT_NOT_ACTIVATED_TO_SHARE = "Your are not allowed to share. Please activate your account! <br><a href='https://www.roberta-home.de/index.php?id=138&L=1' target='_blank'>Further information ...</a>"; // untranslated
Blockly.Msg.ORA_COMMAND_INVALID = "Invalid Javascript-command"; // untranslated
Blockly.Msg.ORA_COMPILERWORKFLOW_ERROR_CONFIGURATION_NOT_FOUND = "The robot configuration could not be found on the server."; // untranslated
Blockly.Msg.ORA_COMPILERWORKFLOW_ERROR_CONFIGURATION_TRANSFORM_FAILED = "The robot configuration could not be transformed into the robots programming language."; // untranslated
Blockly.Msg.ORA_COMPILERWORKFLOW_ERROR_PROGRAM_COMPILE_FAILED = "Please check the error messages in your progamming blocks and the configuration! Your program has errors so it cannot be compiled."; // untranslated
Blockly.Msg.ORA_COMPILERWORKFLOW_ERROR_PROGRAM_GENERATION_FAILED = "The program could not be generated."; // untranslated
Blockly.Msg.ORA_COMPILERWORKFLOW_ERROR_PROGRAM_NOT_FOUND = "The program could not be transformed into the robots programming language."; // untranslated
Blockly.Msg.ORA_COMPILERWORKFLOW_ERROR_PROGRAM_STORE_FAILED = "The program could not be saved because of an internal error."; // untranslated
Blockly.Msg.ORA_COMPILERWORKFLOW_ERROR_PROGRAM_TRANSFORM_FAILED = "The program could not be transformed into the robots programming language."; // untranslated
Blockly.Msg.ORA_CONFIGURATION_DELETE_ERROR = "An error has occurred while deleting the robot configuration, please try it again!"; // untranslated
Blockly.Msg.ORA_CONFIGURATION_DELETE_SUCCESS = "Configuration deleted"; // untranslated
Blockly.Msg.ORA_CONFIGURATION_ERROR_ID_INVALID = "Configuration name is not a valid identifier."; // untranslated
Blockly.Msg.ORA_CONFIGURATION_GET_ALL_SUCCESS = "Configuration loaded"; // untranslated
Blockly.Msg.ORA_CONFIGURATION_GET_ONE_ERROR_NOT_FOUND = "The robot configuration could not be found in the database."; // untranslated
Blockly.Msg.ORA_CONFIGURATION_GET_ONE_SUCCESS = "Configuration loaded"; // untranslated
Blockly.Msg.ORA_CONFIGURATION_SAVE_ERROR = "An error has occurred while saving the robot configuration."; // untranslated
Blockly.Msg.ORA_CONFIGURATION_SAVE_ERROR_NOT_SAVED_TO_DB = "An error error has occurred while saving the configuration in the database."; // untranslated
Blockly.Msg.ORA_CONFIGURATION_SAVE_SUCCESS = "Configuration saved"; // untranslated
Blockly.Msg.ORA_GALLERY_UPLOAD_ERROR = "Your program »$« couldn't be uploaded to the gallery, it seems as if it is already uploaded."; // untranslated
Blockly.Msg.ORA_GALLERY_UPLOAD_SUCCESS = "Your program »$« is now in the gallery!"; // untranslated
Blockly.Msg.ORA_GROUP_CREATE_ERROR_NOT_SAVED_TO_DB = "This group already exists"; // untranslated
Blockly.Msg.ORA_LIKE_DELETE_SUCCESS = "You do not like program »$« anymore!"; // untranslated
Blockly.Msg.ORA_LIKE_SAVE_ERROR_EXISTS = "You couldn't like program »$«. Maybe you have already liked it."; // untranslated
Blockly.Msg.ORA_LIKE_SAVE_SUCCESS = "You like program »$« now!"; // untranslated
Blockly.Msg.ORA_LIST_CREATE_WITH_ERROR = "Error: This block may be used only within a variable declaration."; // untranslated
Blockly.Msg.ORA_OWNER_DOES_NOT_EXIST = "The owner does not exist."; // untranslated
Blockly.Msg.ORA_PROGRAM_CONFIGURATION_NOT_COMPATIBLE = "Program is not compatible with the configuration"; // untranslated
Blockly.Msg.ORA_PROGRAM_DELETE_ERROR = "An error error has occurred while deleting the configuration. Please try it again!"; // untranslated
Blockly.Msg.ORA_PROGRAM_DELETE_SUCCESS = "Program deleted"; // untranslated
Blockly.Msg.ORA_PROGRAM_ERROR_ID_INVALID = "The name of your program is already used by the system. Please choose another name and try it again!"; // untranslated
Blockly.Msg.ORA_PROGRAM_GET_ALL_SUCCESS = "Programs loaded"; // untranslated
Blockly.Msg.ORA_PROGRAM_GET_ONE_ERROR_NOT_FOUND = "Program not found."; // untranslated
Blockly.Msg.ORA_PROGRAM_GET_ONE_ERROR_NOT_LOGGED_IN = "You are not logged in, please log in with your username and password or create a new user."; // untranslated
Blockly.Msg.ORA_PROGRAM_GET_ONE_SUCCESS = "Program loaded"; // untranslated
Blockly.Msg.ORA_PROGRAM_IMPORT_ERROR = "»$.xml« is not a valid NEPO program and cannot be uploaded!"; // untranslated
Blockly.Msg.ORA_PROGRAM_IMPORT_ERROR_WRONG_ROBOT_TYPE = "You are trying to import a program for a robot of a different type as selected in the menu. <br> Please switch the robot type in the robot's menu and try to import again!"; // untranslated
Blockly.Msg.ORA_PROGRAM_INVALID_STATEMETNS = "There are errors in your program. Please check the messages"; // untranslated
Blockly.Msg.ORA_PROGRAM_SAVE_AS_ERROR_PROGRAM_EXISTS = "This program already exists."; // untranslated
Blockly.Msg.ORA_PROGRAM_SAVE_ERROR_NO_WRITE_PERMISSION = "You don't have the permission to modify this program!"; // untranslated
Blockly.Msg.ORA_PROGRAM_SAVE_ERROR_OPTIMISTIC_TIMESTAMP_LOCKING = "This program has been changed recently by someone else. You can save your changes in a new program, choose >save as< !"; // untranslated
Blockly.Msg.ORA_PROGRAM_SAVE_ERROR_PROGRAM_TO_UPDATE_NOT_FOUND = "The program could not be found, so it is impossible to update it."; // untranslated
Blockly.Msg.ORA_PROGRAM_SAVE_SUCCESS = "Program saved"; // untranslated
Blockly.Msg.ORA_PROGRAM_TO_SHARE_DOES_NOT_EXIST = "The program that you would like to share does not exist."; // untranslated
Blockly.Msg.ORA_ROBOT_DOES_NOT_EXIST = "It seems that we do not support the desired robot system!<br>Please choose another one."; // untranslated
Blockly.Msg.ORA_ROBOT_FIRMWAREUPDATE_IMPOSSIBLE = "An error has occurred while updating the new firmware on your robot."; // untranslated
Blockly.Msg.ORA_ROBOT_FIRMWAREUPDATE_POSSIBLE = "The firmware was updated"; // untranslated
Blockly.Msg.ORA_ROBOT_NOT_CONNECTED = "There is no robot connected. Check if your robot is switched on, connect it to the server and type in the robot's password under robot - connect in the menu. <br /> If you have problems to do this, please have a look at our help pages."; // untranslated
Blockly.Msg.ORA_ROBOT_NOT_WAITING = "The robot does not wait for a run command."; // untranslated
Blockly.Msg.ORA_ROBOT_PUSH_RUN = "Robot waited and now the jar is pushed to the robot"; // untranslated
Blockly.Msg.ORA_ROBOT_PUSH_RUN_CALLIOPE2016 = "Your program »$« is downloaded to Calliope, press the reset button to start it!"; // untranslated
Blockly.Msg.ORA_ROBOT_PUSH_RUN_NXT = "Your program »$« is downloaded to the NXT, start it on the robot!"; // untranslated
Blockly.Msg.ORA_ROBOT_SET_SUCCESS = "Switched to robot system »$«!"; // untranslated
Blockly.Msg.ORA_SERVER_ERROR = "Server-Error"; // untranslated
Blockly.Msg.ORA_TOKEN_SET_ERROR_NO_ROBOT_WAITING = "Check if your robot is switched on and connected to the server. <br />If you have problems to do this, please have a look at our help pages."; // untranslated
Blockly.Msg.ORA_TOKEN_SET_ERROR_WRONG_ROBOTTYPE = "You are trying to connect a robot of a different type as selected in the menu. <br> Please switch the robot type in the robot's menu and try to connect again!"; // untranslated
Blockly.Msg.ORA_TOKEN_SET_SUCCESS = "Token set"; // untranslated
Blockly.Msg.ORA_TOOLBOX_DELETE_ERROR = "An error has occurred while deleting the toolbox, please try it again!"; // untranslated
Blockly.Msg.ORA_TOOLBOX_DELETE_SUCCESS = "Toolbox deleted"; // untranslated
Blockly.Msg.ORA_TOOLBOX_ERROR_ID_INVALID = "Toolbox name is not a valid identifier."; // untranslated
Blockly.Msg.ORA_TOOLBOX_GET_ALL_SUCCESS = "Toolbox loaded"; // untranslated
Blockly.Msg.ORA_TOOLBOX_GET_ONE_ERROR_NOT_FOUND = "The toolbox could not be found in the database."; // untranslated
Blockly.Msg.ORA_TOOLBOX_GET_ONE_SUCCESS = "Toolbox loaded"; // untranslated
Blockly.Msg.ORA_TOOLBOX_SAVE_ERROR = "An error has occurred while saving the toolbox."; // untranslated
Blockly.Msg.ORA_TOOLBOX_SAVE_ERROR_NOT_SAVED_TO_DB = "An error error has occurred while saving the configuration in the database."; // untranslated
Blockly.Msg.ORA_TOOLBOX_SAVE_SUCCESS = "Toolbox saved"; // untranslated
Blockly.Msg.ORA_TOOLBOX_TRANSFORM_ERROR = "Transformation error?"; // untranslated
Blockly.Msg.ORA_USER_ACTIVATION_INVALID_URL = "The link is not valid anymore. Please ask for resending your verification mail again"; // untranslated
Blockly.Msg.ORA_USER_ACTIVATION_SENT_MAIL_FAIL = "Sorry, we cannot send a mail to you, please contact »support-o-r@iais.fraunhofer.de«"; // untranslated
Blockly.Msg.ORA_USER_ACTIVATION_SENT_MAIL_SUCCESS = "We send a mail to you, please check your mailbox!"; // untranslated
Blockly.Msg.ORA_USER_ACTIVATION_SUCCESS = "Your account is successfully verified! Please login!"; // untranslated
Blockly.Msg.ORA_USER_CREATE_ERROR_ACCOUNT_LENGTH = "Your account name or your user name is to long. Please make sure that they are not longer then 25 digits. Your account couldn't be created."; // untranslated
Blockly.Msg.ORA_USER_CREATE_ERROR_CONTAINS_SPECIAL_CHARACTERS = "You are using some one or more special characters in your account name! Please remove them. Your account couldn't be created."; // untranslated
Blockly.Msg.ORA_USER_CREATE_ERROR_MISSING_REQ_FIELDS = "Please make sure you have filled in all required fields! Your account couldn't be created."; // untranslated
Blockly.Msg.ORA_USER_CREATE_ERROR_NOT_SAVED_TO_DB = "The given user name already exists in the database, please choose another user name."; // untranslated
Blockly.Msg.ORA_USER_CREATE_SUCCESS = "Your user account »$« was successfully created!"; // untranslated
Blockly.Msg.ORA_USER_DEACTIVATION_SUCCESS = "Your account is currently not verified, please check your mailbox!"; // untranslated
Blockly.Msg.ORA_USER_DELETE_ERROR_ID_NOT_FOUND = "Error while deleting user."; // untranslated
Blockly.Msg.ORA_USER_DELETE_ERROR_NOT_DELETED_IN_DB = "Error while deleting user in database."; // untranslated
Blockly.Msg.ORA_USER_DELETE_SUCCESS = "Your account »$« was successfully deleted. Hope to see you soon again!"; // untranslated
Blockly.Msg.ORA_USER_EMAIL_ONE_ERROR_USER_NOT_EXISTS_WITH_THIS_EMAIL = "This email address is unknown, maybe you have spelled it wrong!"; // untranslated
Blockly.Msg.ORA_USER_ERROR_EMAIL_USED = "There is already an account with this email address registered. Please enter another email address!"; // untranslated
Blockly.Msg.ORA_USER_GET_ALL_SUCCESS = "Users loaded"; // untranslated
Blockly.Msg.ORA_USER_GET_ONE_ERROR_ID_OR_PASSWORD_WRONG = "You have entered wrong user name or password. Please try again!"; // untranslated
Blockly.Msg.ORA_USER_GET_ONE_SUCCESS = "Login successful"; // untranslated
Blockly.Msg.ORA_USER_GROUP_SAVE_AS_ERROR_USER_GROUP_EXISTS = "This user already belongs to the group"; // untranslated
Blockly.Msg.ORA_USER_PASSWORD_RECOVERY_EXPIRED_URL = "The link is not valid anymore. Please ask for resetting your password again, if you still cannot remember it!"; // untranslated
Blockly.Msg.ORA_USER_PASSWORD_RECOVERY_SENT_MAIL_FAIL = "Sorry, we cannot send a mail to you, please contact »support-o-r@iais.fraunhofer.de«"; // untranslated
Blockly.Msg.ORA_USER_PASSWORD_RECOVERY_SENT_MAIL_SUCCESS = "We send a mail to you, please check your mailbox!"; // untranslated
Blockly.Msg.ORA_USER_TO_ADD_NOT_FOUND = "User was not found"; // untranslated
Blockly.Msg.ORA_USER_TO_SHARE_DOES_NOT_EXIST = "The user with which you would like to share the program does not exist. <br />Try it again!"; // untranslated
Blockly.Msg.ORA_USER_TO_SHARE_SAME_AS_LOGIN_USER = "You cannot share any programs with yourself."; // untranslated
Blockly.Msg.ORA_USER_UPDATE_SUCCESS = "Your password has been successfully changed!"; // untranslated
Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; // untranslated
Blockly.Msg.OUTPUT = "output"; // untranslated
Blockly.Msg.PASSWORD = "Password"; // untranslated
Blockly.Msg.PIN_ISTOUCHED_TOOLTIP = "Is the selected pin touched?"; // untranslated
Blockly.Msg.PIN_PULL = "pull"; // untranslated
Blockly.Msg.PIN_PULL_DOWN = "down"; // untranslated
Blockly.Msg.PIN_PULL_NONE = "none"; // untranslated
Blockly.Msg.PIN_PULL_UP = "up"; // untranslated
Blockly.Msg.PIN_SET_PULL_TOOLTIP = "Sets the pull of the chosen pin"; // untranslated
Blockly.Msg.PIN_WRITE = "write"; // untranslated
Blockly.Msg.PITCH = "pitch"; // untranslated
Blockly.Msg.PLAY = "play"; // untranslated
Blockly.Msg.PLAY_DURATION = "duration ms"; // untranslated
Blockly.Msg.PLAY_EIGHTH = "eighth note"; // untranslated
Blockly.Msg.PLAY_FILE = "file"; // untranslated
Blockly.Msg.PLAY_FILE_TOOLTIP = "Plays a sound file."; // untranslated
Blockly.Msg.PLAY_FREQUENZ = "frequency Hz"; // untranslated
Blockly.Msg.PLAY_GETVOLUME_TOOLTIP = "Gets current volume."; // untranslated
Blockly.Msg.PLAY_HALF = "half note"; // untranslated
Blockly.Msg.PLAY_NOTE = "note"; // untranslated
Blockly.Msg.PLAY_NOTE_TOOLTIP = "Plays a music note"; // untranslated
Blockly.Msg.PLAY_QUARTER = "quarter note"; // untranslated
Blockly.Msg.PLAY_SETVOLUME_TOOLTIP = "Sets volume."; // untranslated
Blockly.Msg.PLAY_SIXTEENTH = "sixteenth note"; // untranslated
Blockly.Msg.PLAY_TONE = "tone"; // untranslated
Blockly.Msg.PLAY_TONE_TOOLTIP = "Plays a tone. Use frequency and duration to determin the tone pitch and duration."; // untranslated
Blockly.Msg.PLAY_TOOLTIP = "Represents a buzzer."; // untranslated
Blockly.Msg.PLAY_VOLUME = "volume"; // untranslated
Blockly.Msg.PLAY_WHOLE = "whole note"; // untranslated
Blockly.Msg.POPUP_ABOUT_JOIN = "I want to help"; // untranslated
Blockly.Msg.POPUP_ABOUT_TEXT = "The Open Roberta Lab is a cloud-based integrated programming environment that enables children and adolescents to program easily different robot/microcontroller systems. This platform is completely open source so taking part is desirable! Both the software and the open source developer tools are available via Fraunhofer servers."; // untranslated
Blockly.Msg.POPUP_ABOUT_TEXT_DEV = "The Open Roberta Lab is an open-source programming platform developed by Fraunhofer IAIS within the initiative <a href='http://www.roberta-home.de/' target='_blank'>»Roberta – Learning with Robots«</a>"; // untranslated
Blockly.Msg.POPUP_ABOUT_TEXT_GOOG = "Open Roberta was initiated in collaboration with Google Germany to reduce the hurdles for students, teachers and schools programming educational robots.</a>"; // untranslated
Blockly.Msg.POPUP_AGE = "Age"; // untranslated
Blockly.Msg.POPUP_ATTENTION = "Attention"; // untranslated
Blockly.Msg.POPUP_BEFOREUNLOAD = "You have unsaved changes in your program or configuration. Sign in and save your program or configuration."; // untranslated
Blockly.Msg.POPUP_BEFOREUNLOAD_LOGGEDIN = "You have unsaved changes in your program or configuration."; // untranslated
Blockly.Msg.POPUP_CANCEL = "Cancel"; // untranslated
Blockly.Msg.POPUP_CHANGE_PASSWORD = "change password ..."; // untranslated
Blockly.Msg.POPUP_CONFIRM_CONTINUE = "<br><br><i>Press »OK« to discard your work. Press »Cancel« to stay here and save your work first.</i>"; // untranslated
Blockly.Msg.POPUP_CONFIRM_DELETE_CONFIGURATION = "Do you really want to delete the configuration ?"; // untranslated
Blockly.Msg.POPUP_CONFIRM_DELETE_GROUP = "Do you really want to delete these groups?"; // untranslated
Blockly.Msg.POPUP_CONFIRM_DELETE_PROGRAM = "Do you really want to delete the following program or programs?<br>If you delete a shared program, you do not delete the program but the sharing.<br><br>If you delete a program with the owner »Gallery«, you remove your program from the gallery!"; // untranslated
Blockly.Msg.POPUP_CONFIRM_DELETE_USER_GROUP = "Do you really want to remove these users below from the current group?"; // untranslated
Blockly.Msg.POPUP_CONFIRM_UPDATE_FIRMWARE = "There is a new firmware version for your robot available. You can try to run programs with the old version, but best bet is to update your robot now! You just have to click »Update now«."; // untranslated
Blockly.Msg.POPUP_CONTINUE = "continue anyway"; // untranslated
Blockly.Msg.POPUP_DISPLAY_HEADER = "output of your program"; // untranslated
Blockly.Msg.POPUP_DOWNLOAD = "Download your program to »$«"; // untranslated
Blockly.Msg.POPUP_DOWNLOAD_CHECK = "Okay, I've changed the download folder of my browser permanently. Don't show this popup again and download my programs directly."; // untranslated
Blockly.Msg.POPUP_DOWNLOAD_STEP_1 = "Right click on your program link below and"; // untranslated
Blockly.Msg.POPUP_DOWNLOAD_STEP_1_SENSEBOX = "Check that your device is in programming mode (LED dimming in a pattern), if not, double press the red button. Right click on you program link below and"; // untranslated
Blockly.Msg.POPUP_DOWNLOAD_STEP_2 = "choose »Save link as ...«, then"; // untranslated
Blockly.Msg.POPUP_DOWNLOAD_STEP_3 = "click on your connected »$« in the left column,"; // untranslated
Blockly.Msg.POPUP_DOWNLOAD_STEP_4 = "now click on the »Save« button on the bottom right.<br><span style='font-size: 14px;'>If your program doesn't start automatically press the reset button after a while.</span>"; // untranslated
Blockly.Msg.POPUP_DOWNLOAD_STEP_4_SENSEBOX = "now click on the »Save« button on the bottom right."; // untranslated
Blockly.Msg.POPUP_DO_UPDATE_FIRMWARE = "Update now"; // untranslated
Blockly.Msg.POPUP_EMAIL = "E-Mail"; // untranslated
Blockly.Msg.POPUP_EMAIL_SEND = "Send now"; // untranslated
Blockly.Msg.POPUP_GET_LINK = "Here is the link to your actual program. Please don't change it, it probably won't work anymore. It's already copied to your clipboard!</br>$"; // untranslated
Blockly.Msg.POPUP_MULTIPLE_ROBOTS = "Select multiple programs for the simulation"; // untranslated
Blockly.Msg.POPUP_MULTROBOTS_NOPROGRAMS = "Please create and store at least two programs which then can be executed each by a simulated robot!"; // untranslated
Blockly.Msg.POPUP_NAME = "Name"; // untranslated
Blockly.Msg.POPUP_NEW_PASSWORD = "New Password"; // untranslated
Blockly.Msg.POPUP_OLD_PASSWORD = "Old Password"; // untranslated
Blockly.Msg.POPUP_PASSWORD = "Password"; // untranslated
Blockly.Msg.POPUP_PASSWORD_RECOVERY = "reset password ..."; // untranslated
Blockly.Msg.POPUP_PROGRAM_TERMINATED_UNEXPECTED = "The execution of the program on the robot has terminated unexpectedly!"; // untranslated
Blockly.Msg.POPUP_REGISTER_USER = "Register now"; // untranslated
Blockly.Msg.POPUP_REPEAT_PASSWORD = "Repeat password"; // untranslated
Blockly.Msg.POPUP_ROBOT_BATTERY = "Voltage"; // untranslated
Blockly.Msg.POPUP_ROBOT_NAME = "Name"; // untranslated
Blockly.Msg.POPUP_ROBOT_NOT_CONNECTED = "You have to make a connection to your robot first."; // untranslated
Blockly.Msg.POPUP_ROBOT_STATE = "State"; // untranslated
Blockly.Msg.POPUP_ROBOT_STATE_BUSY = "busy"; // untranslated
Blockly.Msg.POPUP_ROBOT_STATE_DISCONNECTED = "disconnected"; // untranslated
Blockly.Msg.POPUP_ROBOT_STATE_WAIT = "wait"; // untranslated
Blockly.Msg.POPUP_ROBOT_SYSTEM = "System"; // untranslated
Blockly.Msg.POPUP_ROBOT_WAIT = "Waiting time"; // untranslated
Blockly.Msg.POPUP_SCANNED_ROBOTS = "found robots"; // untranslated
Blockly.Msg.POPUP_STARTUP_COOKIES = "We use cookies to personalise content and to analyse our traffic."; // untranslated
Blockly.Msg.POPUP_STARTUP_HELP = "Do you need help?"; // untranslated
Blockly.Msg.POPUP_STARTUP_HELP_TEXT = "In our detailed help, we will explain everything you need, from building instructions to frequently asked questions."; // untranslated
Blockly.Msg.POPUP_STARTUP_HIDE = "Okay, don't show this window again and remember my choice."; // untranslated
Blockly.Msg.POPUP_STARTUP_START = "Choose your system!"; // untranslated
Blockly.Msg.POPUP_STARTUP_TOUR_TEXT = "Would you like to get started, but do not know exactly how? We will show you the first steps in an interactive tutorial."; // untranslated
Blockly.Msg.POPUP_TOUR = "take a tour"; // untranslated
Blockly.Msg.POPUP_USERNAME = "Username"; // untranslated
Blockly.Msg.POPUP_USERNAME_LOGOFF = "You are not logged in."; // untranslated
Blockly.Msg.POPUP_VALUE = "Value"; // untranslated
Blockly.Msg.PORT_ANKLE = "ankle"; // untranslated
Blockly.Msg.PORT_BUMPER = "bumper"; // untranslated
Blockly.Msg.PORT_ELBOW = "elbow"; // untranslated
Blockly.Msg.PORT_HAND = "hand"; // untranslated
Blockly.Msg.PORT_HEAD = "head"; // untranslated
Blockly.Msg.PORT_HIP = "hip"; // untranslated
Blockly.Msg.PORT_KNEE = "knee"; // untranslated
Blockly.Msg.PORT_SHOULDER = "shoulder"; // untranslated
Blockly.Msg.PORT_WRIST = "wrist"; // untranslated
Blockly.Msg.POTENTIOMETER_TOOLTIP = "Represents a potentiometer ."; // untranslated
Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS = "përmëtte le diciairassion";
Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "con:";
Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29";
Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Eseguì la fonsion '%1' definìa da l'utent.";
Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29";
Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Eseguì la fonsion '%1' definìa da l'utent e dovré sò arzultà.";
Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS = "con:";
Blockly.Msg.PROCEDURES_CREATE_DO = "Creé '%1'";
Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT = "Descrive sa fonsion...";
Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "fé cheicòs";
Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "a";
Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "A crea na fonsion sensa surtìa.";
Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "artorn";
Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "A crea na fonsion con na surtìa.";
Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Atension: Costa fonsion a l'ha dij paràmeter duplicà.";
Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Sot-ligné la definission dla fonsion";
Blockly.Msg.PROCEDURES_IFRETURN_HELPURL = "http://c2.com/cgi/wiki?GuardClause";
Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "Se un valor a l'é ver, antlora smon-e un second valor.";
Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Atension: Ës blòch a podria esse dovrà mach an na definission ëd fonsion.";
Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "nòm ëd l'imission:";
Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = "Gionté n'imission a la fonsion.";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "imission";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = "Gionté, gavé o riordiné j'imission ëd sa fonsion.";
Blockly.Msg.PROCEDURES_TITLE = "« procedure"; // untranslated
Blockly.Msg.PROCEDURES_VARIABLES_ERROR = "Error: This block may be used only within the »"; // untranslated
Blockly.Msg.PROCEDURES_VARIABLES_LOOP_ERROR = "Error: This block may be used only within a loop which declares "; // untranslated
Blockly.Msg.PROGLIST_DELETE_ALL_TOOLTIP = "Click here to delete all selected programs."; // untranslated
Blockly.Msg.PROGLIST_DELETE_TOOLTIP = "Click here to delete your program."; // untranslated
Blockly.Msg.PROGLIST_LOAD_TOOLTIP = "Click here to load your robot configuration in the configuration environment."; // untranslated
Blockly.Msg.PROGLIST_SHARE_TOOLTIP = "Click here to share your program with a friend."; // untranslated
Blockly.Msg.PROGLIST_SHARE_WITH_GALLERY = "Do you really want to share your program with everybody? If you are not sure please check the question and answers <a href='https://www.roberta-home.de/index.php?id=138&L=1' target='_blank'>here</a>."; // untranslated
Blockly.Msg.PROGLIST_SHARE_WITH_GALLERY_TOOLTIP = "Click here to upload your program to the gallery hence share it with all other users."; // untranslated
Blockly.Msg.PULSEHIGH = "pulse time HIGH"; // untranslated
Blockly.Msg.PULSELOW = "pulse time LOW"; // untranslated
Blockly.Msg.PULSETOOLTIP = "Represents a pulse sensor."; // untranslated
Blockly.Msg.RADIO_GET_RSSI_TOOLTIP = "Gets the RSSI of the last package."; // untranslated
Blockly.Msg.REDO = "Fé torna";
Blockly.Msg.RELAY = "relay"; // untranslated
Blockly.Msg.RELAY_ARDUINO = "relay SRD-05VDC-SL-C"; // untranslated
Blockly.Msg.RELAY_TOOLTIP = "Represents a relay."; // untranslated
Blockly.Msg.REMOVE_COMMENT = "Scancelé un coment";
Blockly.Msg.RENAME_VARIABLE = "Arnomé la variàbil...";
Blockly.Msg.RENAME_VARIABLE_TITLE = "Arnomé tute le variàbij '%1' 'me:";
Blockly.Msg.RESEND_ACTIVATION = "resend verification email"; // untranslated
Blockly.Msg.RETURN = "return"; // untranslated
Blockly.Msg.RFID_TOOLTIP = "Represents an RFID reader."; // untranslated
Blockly.Msg.RGBLED_TOOLTIP = "Represents an RGB LED."; // untranslated
Blockly.Msg.RGB_LED_TOOLTIP = "Turns the LED on or off and changes the color."; // untranslated
Blockly.Msg.RIGHT = "right"; // untranslated
Blockly.Msg.ROLL = "roll"; // untranslated
Blockly.Msg.ROTATIONS_PER_MINUTE = "rpm"; // untranslated
Blockly.Msg.SAY = "say"; // untranslated
Blockly.Msg.SAY_PARAMETERS_TOOLTIP = "The robot says the given text. It is also possible to enter special charaters. The robot will use the selected language to try and speak the entered text. Modify the speed (range: 0-100) and the pitch of the voice (range: 0-100) with the input fields"; // untranslated
Blockly.Msg.SAY_TOOLTIP = "The robot says the given text. It is also possible to enter special charaters. The robot will use the selected language to try and speak the entered text."; // untranslated
Blockly.Msg.SEND_DATA = "data to send"; // untranslated
Blockly.Msg.SEND_DATA_SENSEMAP = "openSenseMap"; // untranslated
Blockly.Msg.SEND_DATA_TO = "send data to"; // untranslated
Blockly.Msg.SEND_DATA_TO_OSM_TOOLTIP = "This block is used to send data from sensors to the openSenseMap. Please configure the IDs in the configuration prior to the usage of this block."; // untranslated
Blockly.Msg.SENSEBOXBRICK_TOOLTIP = "Represents the senseBox. Please configure here the id's from the openSenseMap, if you want to use them."; // untranslated
Blockly.Msg.SENSOR_ACCELEROMETER = "accelerometer"; // untranslated
Blockly.Msg.SENSOR_AMBIENTLIGHT = "ambientlight sensor"; // untranslated
Blockly.Msg.SENSOR_ANALOGOUT = "sensor analog"; // untranslated
Blockly.Msg.SENSOR_ANY = "anyplace"; // untranslated
Blockly.Msg.SENSOR_ARM_TOOLTIP = "Returns true, if the selected part of the arm is touched, otherwise false."; // untranslated
Blockly.Msg.SENSOR_BATTERY = "battery charge"; // untranslated
Blockly.Msg.SENSOR_BOTTOM = "bottom"; // untranslated
Blockly.Msg.SENSOR_CALIBRATE = "calibrate"; // untranslated
Blockly.Msg.SENSOR_CODE = "code pad"; // untranslated
Blockly.Msg.SENSOR_COLOUR = "colour sensor"; // untranslated
Blockly.Msg.SENSOR_COMPASS = "compass sensor"; // untranslated
Blockly.Msg.SENSOR_COMPASS_EV3 = "HT compass sensor"; // untranslated
Blockly.Msg.SENSOR_DETECTFACE = "face detector"; // untranslated
Blockly.Msg.SENSOR_DETECTFACE_GETSAMPLE_TOOLTIP = "Detect a face previously learned and saved."; // untranslated
Blockly.Msg.SENSOR_DETECTMARK = "NAO Mark sensor"; // untranslated
Blockly.Msg.SENSOR_DETECTMARK_GETSAMPLE_TOOLTIP = "Returns one or an array of IDs (number) of the last detected NAO Mark(s). If no marks are detected, -1 or an array consisting of 1 element with value -1 is returned. For a list of NAO marks with corresponding numbers refer to the wiki."; // untranslated
Blockly.Msg.SENSOR_DIGITALOUT = "sensor digital"; // untranslated
Blockly.Msg.SENSOR_DROP = "drop sensor"; // untranslated
Blockly.Msg.SENSOR_DROP_GETSAMPLE_TOOLTIP = "Gets the current reading from the drop sensor in percent."; // untranslated
Blockly.Msg.SENSOR_DROP_OFF = "drop-off sensor"; // untranslated
Blockly.Msg.SENSOR_ELECTRICCURRENT = "current sensor"; // untranslated
Blockly.Msg.SENSOR_ELECTRICCURRENT_GETSAMPLE_TOOLTIP = "Get the electric current from the motorboard in the selected joint."; // untranslated
Blockly.Msg.SENSOR_ENCODER = "encoder"; // untranslated
Blockly.Msg.SENSOR_FLAME = "flame sensor"; // untranslated
Blockly.Msg.SENSOR_FSR = "force-sensing resistor"; // untranslated
Blockly.Msg.SENSOR_FSR_GETSAMPLE_TOOLTIP = "Get the current reading from the force sensitive resistor under the feet of the robot."; // untranslated
Blockly.Msg.SENSOR_GESTURE = "gesture"; // untranslated
Blockly.Msg.SENSOR_GESTURE_ACTIVE = "active?"; // untranslated
Blockly.Msg.SENSOR_GESTURE_DOWN = "upside down"; // untranslated
Blockly.Msg.SENSOR_GESTURE_DOWN_GETSAMPLE_TOOLTIP = "Returns »true« if the posture is down."; // untranslated
Blockly.Msg.SENSOR_GESTURE_FACE_DOWN = "at the front side"; // untranslated
Blockly.Msg.SENSOR_GESTURE_FACE_DOWN_GETSAMPLE_TOOLTIP = "Returns »true« if the posture is face down."; // untranslated
Blockly.Msg.SENSOR_GESTURE_FACE_UP = "at the back"; // untranslated
Blockly.Msg.SENSOR_GESTURE_FACE_UP_GETSAMPLE_TOOLTIP = "Returns »true« if the posture is face up."; // untranslated
Blockly.Msg.SENSOR_GESTURE_FREEFALL = "freely falling"; // untranslated
Blockly.Msg.SENSOR_GESTURE_FREEFALL_GETSAMPLE_TOOLTIP = "Returns »true« if it is free falling."; // untranslated
Blockly.Msg.SENSOR_GESTURE_SHAKE = "shaking"; // untranslated
Blockly.Msg.SENSOR_GESTURE_SHAKE_GETSAMPLE_TOOLTIP = "Returns »true« if it is shaken."; // untranslated
Blockly.Msg.SENSOR_GESTURE_TOOLTIP = "Is the system in the selected state?"; // untranslated
Blockly.Msg.SENSOR_GESTURE_UP = "upright"; // untranslated
Blockly.Msg.SENSOR_GESTURE_UP_GETSAMPLE_TOOLTIP = "Returns »true« if the posture is upright."; // untranslated
Blockly.Msg.SENSOR_GET = "get"; // untranslated
Blockly.Msg.SENSOR_GET_SAMPLE = "get value"; // untranslated
Blockly.Msg.SENSOR_GROVE = "Grove"; // untranslated
Blockly.Msg.SENSOR_GYRO = "gyroscope"; // untranslated
Blockly.Msg.SENSOR_GYRO_GETSAMPLE_TOOLTIP_WEDO = "Is the gyro sensor tilted in the indicated manner?"; // untranslated
Blockly.Msg.SENSOR_HUMIDITY = "humidity sensor"; // untranslated
Blockly.Msg.SENSOR_HUMIDITY_ARDUINO = "humidity sensor DHT11"; // untranslated
Blockly.Msg.SENSOR_HUMIDITY_GETSAMPLE_TOOLTIP = "Gets the current reading from the humidity sensor in percent."; // untranslated
Blockly.Msg.SENSOR_HUMIDITY_SENSEBOX = "humidity/temperature sensor HDC1080"; // untranslated
Blockly.Msg.SENSOR_INFRARED = "infrared sensor"; // untranslated
Blockly.Msg.SENSOR_INFRARED_DISTANCE_GETSAMPLE_TOOLTIP_WEDO = "Gets the current relative distance from the infrared sensor. The values are between 1, close, and 10, further away."; // untranslated
Blockly.Msg.SENSOR_IRSEEKER = "HT infrared sensor"; // untranslated
Blockly.Msg.SENSOR_IRSEEKER_GETSAMPLE_TOOLTIP = "Gets the position of an infrared beacon."; // untranslated
Blockly.Msg.SENSOR_IS_ARM = "is arm"; // untranslated
Blockly.Msg.SENSOR_IS_PIN = "is"; // untranslated
Blockly.Msg.SENSOR_IS_PRESSED = "pressed?"; // untranslated
Blockly.Msg.SENSOR_IS_TILTED = "tilted?"; // untranslated
Blockly.Msg.SENSOR_IS_TOUCHED = "touched?"; // untranslated
Blockly.Msg.SENSOR_JOYSTICK = "joystick"; // untranslated
Blockly.Msg.SENSOR_KEY = "button"; // untranslated
Blockly.Msg.SENSOR_KEY_ANY = "any"; // untranslated
Blockly.Msg.SENSOR_KEY_DOWN = "down"; // untranslated
Blockly.Msg.SENSOR_KEY_ENTER = "enter"; // untranslated
Blockly.Msg.SENSOR_KEY_ESCAPE = "escape"; // untranslated
Blockly.Msg.SENSOR_KEY_LEFT = "left"; // untranslated
Blockly.Msg.SENSOR_KEY_RIGHT = "right"; // untranslated
Blockly.Msg.SENSOR_KEY_UP = "up"; // untranslated
Blockly.Msg.SENSOR_LIGHT = "light sensor"; // untranslated
Blockly.Msg.SENSOR_LIGHTVEML = "visible/UV light sensor"; // untranslated
Blockly.Msg.SENSOR_LIGHTVEML_GETSAMPLE_TOOLTIP = "the current reading visible/UV light sensor"; // untranslated
Blockly.Msg.SENSOR_MIC = "microphone"; // untranslated
Blockly.Msg.SENSOR_MOISTURE = "moisture sensor"; // untranslated
Blockly.Msg.SENSOR_MOISTURE_GETSAMPLE_TOOLTIP = "Gets the current reading from the moisture sensor in percent."; // untranslated
Blockly.Msg.SENSOR_MOTION = "motion sensor"; // untranslated
Blockly.Msg.SENSOR_MOTION_ARDUINO = "motion sensor HC-SR501"; // untranslated
Blockly.Msg.SENSOR_MOTION_GETSAMPLE_TOOLTIP = "Gets the current reading from the motion sensor (true/false)."; // untranslated
Blockly.Msg.SENSOR_MS_TIMER = "in ms"; // untranslated
Blockly.Msg.SENSOR_OUT = "sensor"; // untranslated
Blockly.Msg.SENSOR_OUT_ANALOG_GETSAMPLE_TOOLTIP = "Returns the value from the specified analog pin. The value is between 0 and 1024."; // untranslated
Blockly.Msg.SENSOR_OUT_DIGITAL_GETSAMPLE_TOOLTIP = "Returns the value from the specified digital pin. The value is either HIGH »1« or LOW »0«."; // untranslated
Blockly.Msg.SENSOR_PIN = "pin"; // untranslated
Blockly.Msg.SENSOR_PINTOUCH = "pin"; // untranslated
Blockly.Msg.SENSOR_PINTOUCH_BOB3 = "arm"; // untranslated
Blockly.Msg.SENSOR_PIN_ANALOG_GETSAMPLE_TOOLTIP = "Returns the value from the specified analog pin. The value is between 0 and 1024."; // untranslated
Blockly.Msg.SENSOR_PIN_DIGITAL_GETSAMPLE_TOOLTIP = "Returns the value from the specified digital pin. The value is either HIGH »1« or LOW »0«."; // untranslated
Blockly.Msg.SENSOR_PIN_PULSEHIGH_GETSAMPLE_TOOLTIP = "Returns the pulse HIGH on a pin in microseconds or -1 if no complete pulse was received within the timeout."; // untranslated
Blockly.Msg.SENSOR_PIN_PULSELOW_GETSAMPLE_TOOLTIP = "Returns the pulse LOW on a pin in microseconds or -1 if no complete pulse was received within the timeout."; // untranslated
Blockly.Msg.SENSOR_POTENTIOMETER = "potentiometer"; // untranslated
Blockly.Msg.SENSOR_POTENTIOMETER_GETSAMPLE_TOOLTIP = "Gets the current reading from the potentiometer in volts (0-5V)."; // untranslated
Blockly.Msg.SENSOR_PULSE = "pulse sensor"; // untranslated
Blockly.Msg.SENSOR_PULSE_GETSAMPLE_TOOLTIP = "Gets the current reading from the pulse sensor."; // untranslated
Blockly.Msg.SENSOR_PULSE_GETSAMPLE_TOOLTIP_ARDUINO = "Gets the current reading from the pulse sensor. The value is between 0 and 1023."; // untranslated
Blockly.Msg.SENSOR_RADIO_RSSI = "radio RSSI sensor"; // untranslated
Blockly.Msg.SENSOR_RESET = "reset"; // untranslated
Blockly.Msg.SENSOR_RESET_II = ""; // untranslated
Blockly.Msg.SENSOR_RFID = "RFID reader"; // untranslated
Blockly.Msg.SENSOR_RFID_ARDUINO = "RFID-RC522 reader"; // untranslated
Blockly.Msg.SENSOR_RFID_GETSAMPLE_TOOLTIP = "Gets the current reading from the RFID reader."; // untranslated
Blockly.Msg.SENSOR_RSSI = "signal strength"; // untranslated
Blockly.Msg.SENSOR_RSSI_VALUE_GETSAMPLE_TOOLTIP = "Gets the signal strength from the last received message."; // untranslated
Blockly.Msg.SENSOR_SONAR = "sonar"; // untranslated
Blockly.Msg.SENSOR_SOUND = "sound sensor"; // untranslated
Blockly.Msg.SENSOR_SOUND_CALLIOPE = "microphone"; // untranslated
Blockly.Msg.SENSOR_TEMPERATURE = "temperature sensor"; // untranslated
Blockly.Msg.SENSOR_TEMPERATURE_ARDUINO = "temperature sensor TMP36"; // untranslated
Blockly.Msg.SENSOR_TEMPERATURE_SENSEBOX = "temperature/pressure sensor BMP280"; // untranslated
Blockly.Msg.SENSOR_TIME = "time"; // untranslated
Blockly.Msg.SENSOR_TIMER = "timer"; // untranslated
Blockly.Msg.SENSOR_TOP = "top"; // untranslated
Blockly.Msg.SENSOR_TOUCH = "touch sensor"; // untranslated
Blockly.Msg.SENSOR_ULTRASONIC = "ultrasonic sensor"; // untranslated
Blockly.Msg.SENSOR_ULTRASONIC_ARDUINO = "ultrasonic sensor HC-SR04"; // untranslated
Blockly.Msg.SENSOR_ULTRASONIC_DISTANCE_GETSAMPLE_TOOLTIP_ARDUINO = "Gets the current reading from the ultrasonic sensor in cm. Maximum distance to messure is 400 cm."; // untranslated
Blockly.Msg.SENSOR_ULTRASONIC_DISTANCE_GETSAMPLE_TOOLTIP_MBOT = "Gets the current reading from the ultrasonic sensor in cm. Maximum distance to messure is 400 cm. Minimum distance tp measure is 3 cm."; // untranslated
Blockly.Msg.SENSOR_UNIT_ACCEL = "m/s²"; // untranslated
Blockly.Msg.SENSOR_UNIT_AMPERE = "A"; // untranslated
Blockly.Msg.SENSOR_UNIT_CM = "cm"; // untranslated
Blockly.Msg.SENSOR_UNIT_DEGREE = "°"; // untranslated
Blockly.Msg.SENSOR_UNIT_MILLIG = "milli-g"; // untranslated
Blockly.Msg.SENSOR_UNIT_MM = "mm"; // untranslated
Blockly.Msg.SENSOR_UNIT_MS = "ms"; // untranslated
Blockly.Msg.SENSOR_UNIT_NEWTON = "N"; // untranslated
Blockly.Msg.SENSOR_UNIT_OMEGA = "ω"; // untranslated
Blockly.Msg.SENSOR_UNIT_PASCAL = "Pascal"; // untranslated
Blockly.Msg.SENSOR_UNIT_PERCENT = "%"; // untranslated
Blockly.Msg.SENSOR_UNIT_VOLT = "V"; // untranslated
Blockly.Msg.SENSOR_VALUE = "value"; // untranslated
Blockly.Msg.SENSOR_WALL = "wall sensor"; // untranslated
Blockly.Msg.SERVER_NOT_AVAILABLE = "The Open Roberta Lab is currently not available. </br>Your internet connection was interrupted. If you currently have an EV3 connected via the USB cable solve this with a click on the programming environment.<br>If this problem persists please check your internet connection and try to reload this website. If you have this problem again, please don't hesitate to contact us via mail:</br>support-o-r@iais.fraunhofer.de"; // untranslated
Blockly.Msg.SERVO_MOTOR = "servo motor"; // untranslated
Blockly.Msg.SERVO_MOTOR_ARDUINO = "servo motor SG90"; // untranslated
Blockly.Msg.SERVO_TOOLTIP = "Represents a servo motor."; // untranslated
Blockly.Msg.SET = "set"; // untranslated
Blockly.Msg.SETLANGUAGE_TOOLTIP = "Set the language."; // untranslated
Blockly.Msg.SET_LED = "turn LED"; // untranslated
Blockly.Msg.SET_RELAY = "turn relay"; // untranslated
Blockly.Msg.SET_RELAY_ARDUINO = "turn relay SRD-05VDC-SL-C"; // untranslated
Blockly.Msg.SET_RELAY_TOOLTIP = "Turns the relay on or off"; // untranslated
Blockly.Msg.SET_RGB_LED = "turn RGB LED"; // untranslated
Blockly.Msg.SIDE_BRUSH_OFF = "turn side brush off"; // untranslated
Blockly.Msg.SIDE_BRUSH_OFF_TOOLTIP = "Turns the side brush off."; // untranslated
Blockly.Msg.SIDE_BRUSH_STATUS = "turn side brush"; // untranslated
Blockly.Msg.SIDE_BRUSH_TOOLTIP = "Turns the side brush on or off ."; // untranslated
Blockly.Msg.SIM_BLOCK_NOT_SUPPORTED = "Unfortunately you can not use this block in the simulation!"; // untranslated
Blockly.Msg.SIM_CONFIGURATION_WARNING_SENSOR_MISSING = "This sensor is not in the configuration! The behaviour of the program on the real robot will be different than expected!"; // untranslated
Blockly.Msg.SIM_CONFIGURATION_WARNING_WRONG_INFRARED_SENSOR_PORT = "The infrared sensor is not connected in the configuration! The behaviour of the program on the real robot will be different than expected, please check the robot configuration!"; // untranslated
Blockly.Msg.SIM_CONFIGURATION_WARNING_WRONG_SENSOR_PORT = "In this block you have used a wrong sensor port! The behaviour of the program on the real robot will be different than expected, please check the robot configuration!"; // untranslated
Blockly.Msg.SINGLE_MOTOR_ON_TOOLTIP_CALLIOPE = "Turns the single motor on with a specific power. Power can be positiv or negativ for reverse direction."; // untranslated
Blockly.Msg.SLEEP = "sleep"; // untranslated
Blockly.Msg.SLOT_FRONT = "front"; // untranslated
Blockly.Msg.SLOT_LEFT = "left"; // untranslated
Blockly.Msg.SLOT_LEFT_PITCH = "left pitch"; // untranslated
Blockly.Msg.SLOT_LEFT_ROLL = "left roll"; // untranslated
Blockly.Msg.SLOT_LEFT_YAW = "left yaw"; // untranslated
Blockly.Msg.SLOT_LEFT_YAW_PITCH = "left yaw pitch"; // untranslated
Blockly.Msg.SLOT_MIDDLE = "middle"; // untranslated
Blockly.Msg.SLOT_PITCH = "pitch"; // untranslated
Blockly.Msg.SLOT_REAR = "rear"; // untranslated
Blockly.Msg.SLOT_RIGHT = "right"; // untranslated
Blockly.Msg.SLOT_RIGHT_PITCH = "right pitch"; // untranslated
Blockly.Msg.SLOT_RIGHT_ROLL = "right roll"; // untranslated
Blockly.Msg.SLOT_RIGHT_YAW = "right yaw"; // untranslated
Blockly.Msg.SLOT_RIGHT_YAW_PITCH = "right yaw pitch"; // untranslated
Blockly.Msg.SLOT_SIDE = "side"; // untranslated
Blockly.Msg.SLOT_TILTED_ANY = "any"; // untranslated
Blockly.Msg.SLOT_TILTED_BACK = "back"; // untranslated
Blockly.Msg.SLOT_TILTED_DOWN = "down"; // untranslated
Blockly.Msg.SLOT_TILTED_FRONT = "front"; // untranslated
Blockly.Msg.SLOT_TILTED_NO = "not"; // untranslated
Blockly.Msg.SLOT_TILTED_UP = "up"; // untranslated
Blockly.Msg.SLOT_YAW = "yaw"; // untranslated
Blockly.Msg.SOUND_GETSAMPLE_TOOLTIP = "Gets the current reading from the sound sensor in the range 0 to 100. 0 is quiet and 100 is loud."; // untranslated
Blockly.Msg.SOUND_TOOLTIP = "Represents a sound sensor."; // untranslated
Blockly.Msg.SSID = "SSID"; // untranslated
Blockly.Msg.START = "start"; // untranslated
Blockly.Msg.START_ACTIVITY = "activity"; // untranslated
Blockly.Msg.START_ACTIVITY_TOOLTIP = "Starts additional activity."; // untranslated
Blockly.Msg.START_PROGRAM = "start"; // untranslated
Blockly.Msg.START_PROGRAM_AUTOMOMOUSLIFE = "autonomous behaviour"; // untranslated
Blockly.Msg.START_PROGRAM_DEBUG = "show sensor data"; // untranslated
Blockly.Msg.START_TOOLTIP = "The starting point for the main program."; // untranslated
Blockly.Msg.STEPMOTOR_TOOLTIP = "Represents a step motor."; // untranslated
Blockly.Msg.STEPS_PER_REVOLUTION = "steps per revolution"; // untranslated
Blockly.Msg.STEP_MOTOR = "step motor"; // untranslated
Blockly.Msg.STEP_MOTOR_ARDUINO = "step motor 28BYJ-48"; // untranslated
Blockly.Msg.STEP_MOTOR_ON_TOOLTIP = "Turns motor on with a provided speed in rpm and stops motor after execution of provided number of rotations."; // untranslated
Blockly.Msg.STRENGTH = "strength"; // untranslated
Blockly.Msg.SWITCH = "switch"; // untranslated
Blockly.Msg.SWITCH_LED_MATRIX_TOOLTIP = "Enables/Disables the LED matrix to use the dual purpose pins."; // untranslated
Blockly.Msg.TAB_CONFIGURATION = "Robot configuration"; // untranslated
Blockly.Msg.TAB_PROGRAM = "Program"; // untranslated
Blockly.Msg.TEMPERATURE_GETSAMPLE_TOOLTIP = "Gets the current reading from the temperatur in °C sensor."; // untranslated
Blockly.Msg.TEMPERATURE_TOOLTIP = "Represents a temperature sensor."; // untranslated
Blockly.Msg.TEXT_APPEND_APPENDTEXT = "taché ël test";
Blockly.Msg.TEXT_APPEND_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_APPEND_TO = "a";
Blockly.Msg.TEXT_APPEND_TOOLTIP = "Taché dël test a la variàbil '%1'.";
Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "an minùscul";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "an Majùscol A L'Ancamin Ëd Minca Paròla";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "an MAJÙSCOL";
Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "A smon na còpia dël test ant un caràter diferent.";
Blockly.Msg.TEXT_CHARAT_FIRST = "oten-e la prima litra";
Blockly.Msg.TEXT_CHARAT_FROM_END = "oten-e la litra # da la fin";
Blockly.Msg.TEXT_CHARAT_FROM_START = "oten-e la litra #";
Blockly.Msg.TEXT_CHARAT_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated
Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "ant ël test";
Blockly.Msg.TEXT_CHARAT_LAST = "oten-e l'ùltima litra";
Blockly.Msg.TEXT_CHARAT_RANDOM = "oten-e na litra a l'ancàpit";
Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated
Blockly.Msg.TEXT_CHARAT_TOOLTIP = "A smon la litra ant la posission ëspessificà.";
Blockly.Msg.TEXT_COMMENT_TOOLTIP = "Write a comment to your code here, to make it easier for you and others to read and understand your code. It will also generate an inline comment in the generated source code"; // untranslated
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Gionté n'element al test.";
Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "gionze";
Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Gionté, gavé o riordiné le session për configuré torna ës blòch ëd test.";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "fin-a a la litra # da la fin";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "fin-a a la litra #";
Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "fin-a a l'ùltima litra";
Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "ant ël test";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "oten-e la sota-stringa da la prima litra";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "oten-e la sota-stringa da la litra # da la fin";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "oten-e la sota-stringa da la litra #";
Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "A smon un tòch ëspessificà dël test.";
Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated
Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "ant ël test";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "trové la prima ocorensa dël test";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "trové l'ùltima ocorensa dël test";
Blockly.Msg.TEXT_INDEXOF_TAIL = ""; // untranslated
Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "A smon l'ìndes dla prima/ùltima ocorensa dël prim test ant ël second test. A smon 0 se ël test a l'é nen trovà.";
Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated
Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 a l'é veuid";
Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "A smon ver se ël test fornì a l'é veuid.";
Blockly.Msg.TEXT_JOIN_HELPURL = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated
Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "creé ël test con";
Blockly.Msg.TEXT_JOIN_TOOLTIP = "Creé un tòch ëd test an gionzend un nùmer qualsëssìa d'element.";
Blockly.Msg.TEXT_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_LENGTH_TITLE = "longheur ëd %1";
Blockly.Msg.TEXT_LENGTH_TOOLTIP = "A smon ël nùmer ëd litre (spassi comprèis) ant ël test fornì.";
Blockly.Msg.TEXT_PRINT_HELPURL = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated
Blockly.Msg.TEXT_PRINT_TITLE = "smon-e %1";
Blockly.Msg.TEXT_PRINT_TOOLTIP = "Smon-e ël test, ël nùmer o n'àutr valor ëspessificà.";
Blockly.Msg.TEXT_PROMPT_HELPURL = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "Ciamé un nùmer a l'utent.";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "Ciamé un test a l'utent.";
Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "anvit për un nùmer con un mëssagi";
Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "anvit për un test con un mëssagi";
Blockly.Msg.TEXT_TEXT_HELPURL = "https://en.wikipedia.org/wiki/String_(computer_science)";
Blockly.Msg.TEXT_TEXT_TOOLTIP = "Na litra, na paròla o na linia ëd test.";
Blockly.Msg.TEXT_TRIM_HELPURL = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated
Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "gavé jë spassi da le doe bande ëd";
Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "gavé jë spassi da la banda snistra ëd";
Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "gavé jë spassi da la banda drita ëd";
Blockly.Msg.TEXT_TRIM_TOOLTIP = "A smon na còpia dël test con jë spassi gavà da n'estremità o da tute doe.";
Blockly.Msg.THETA = "theta"; // untranslated
Blockly.Msg.TIMEOUT = "timeout"; // untranslated
Blockly.Msg.TIMER_GETSAMPLE_TOOLTIP = "Gets the current reading from the timer."; // untranslated
Blockly.Msg.TIMER_RESET_TOOLTIP = "Resets the timer."; // untranslated
Blockly.Msg.TITLE = "title"; // untranslated
Blockly.Msg.TO = "to"; // untranslated
Blockly.Msg.TODAY = "Ancheuj";
Blockly.Msg.TOOLBOX_ACTION = "Action"; // untranslated
Blockly.Msg.TOOLBOX_ANIMATION = "Animation"; // untranslated
Blockly.Msg.TOOLBOX_CLEANING = "Cleaning"; // untranslated
Blockly.Msg.TOOLBOX_COLOUR = "Colours"; // untranslated
Blockly.Msg.TOOLBOX_COMMUNICATION = "Messages"; // untranslated
Blockly.Msg.TOOLBOX_CONTROL = "Control"; // untranslated
Blockly.Msg.TOOLBOX_DECISION = "Decisions"; // untranslated
Blockly.Msg.TOOLBOX_DISPLAY = "Display"; // untranslated
Blockly.Msg.TOOLBOX_DRIVE = "Drive"; // untranslated
Blockly.Msg.TOOLBOX_IMAGE = "Images"; // untranslated
Blockly.Msg.TOOLBOX_LIGHT = "Lights"; // untranslated
Blockly.Msg.TOOLBOX_LIST = "Lists"; // untranslated
Blockly.Msg.TOOLBOX_LOGIC = "Logic"; // untranslated
Blockly.Msg.TOOLBOX_LOOP = "Loops"; // untranslated
Blockly.Msg.TOOLBOX_MATH = "Math"; // untranslated
Blockly.Msg.TOOLBOX_MOVE = "Move"; // untranslated
Blockly.Msg.TOOLBOX_PIN = "Pin"; // untranslated
Blockly.Msg.TOOLBOX_PROCEDURE = "Functions"; // untranslated
Blockly.Msg.TOOLBOX_SENSOR = "Sensors"; // untranslated
Blockly.Msg.TOOLBOX_SOUND = "Sounds"; // untranslated
Blockly.Msg.TOOLBOX_TEXT = "Text"; // untranslated
Blockly.Msg.TOOLBOX_VARIABLE = "Variables"; // untranslated
Blockly.Msg.TOOLBOX_VISION = "Vision"; // untranslated
Blockly.Msg.TOOLBOX_WAIT = "Wait"; // untranslated
Blockly.Msg.TOOLBOX_WALK = "Walk"; // untranslated
Blockly.Msg.TOUCH_ISPRESSED_TOOLTIP = "Is the touch sensor pressed?"; // untranslated
Blockly.Msg.TOUCH_TOOLTIP = "Is the touch sensor pressed?"; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION00 = "next"; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION01 = "Welcome,<br>click on »next« and start a tour through the Open Roberta Lab.<br>I'll show you how you can program your robot with NEPO.<br>You can end this tour all the time with a click on »X« in the right upper corner."; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION02 = "The menu ;-)"; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION03 = "Here you can find everything you need to program the robot!<br><span class='typcn typcn-document-text'></span> Save and load programs<br><span class='typcn typcn-ev3'></span> Connect your robot to the Open Roberta Lab or switch to another system<br><span class='typcn typcn-lightbulb'></span> Help for all kinds of problems<br><span class='typcn typcn-user'></span>Everything about user accounts, e.g. login or logoff<br><span class='typcn typcn-th-large-outline'></span> Look at the gallery and try great programs from other users!<br><span class='typcn typcn-world'></span> Click here to switch to another language"; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION04 = "Click here and switch to the robot configuration"; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION05 = "You can adapt the robot configuration later,<br>if you've constructed another robot.<br>If you don't have a robot and want to test your program in the simulation <br>this configuration is applied."; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION06 = "Click here and switch back to the programming area!"; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION07 = "The toolbox.<br>Here you can find all programming blocks."; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION07a = "Once you are an experienced user you can switch here to the expert mode of the toolbox.<br>You will then find more blocks to program your robot.<br><span class='typcn typcn-media-stop-outline'></span> beginner mode<br><span class='typcn typcn-star-outline'></span> expert mode"; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION08 = "Each program starts with the »program start« block.<br>Further programming blocks, which the robot should execute, should be attached to this block.<br>Just drag'n drop the desired block right under the start block."; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION09 = "Here you find some shortcuts!<br>From left to right:<br><span class='typcn typcn-media-play'></span> Click here to execute the program on the real robot<br><span class='typcn typcn-cloud-storage'></span> Save your program, but before that you need to sign in<br><span class='typcn typcn-zoom'></span> Click here and zoom in on the blocks, if you want to<br><span class='typcn typcn-archive'></span> The trashcan! Just move blocks into the trashcan and they will be deleted.<br> Attention: You cannot recover blocks once they are deleted!<br>"; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION10 = "Click on »Action«"; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION12 = "Now drag'n drop the new block just below the start-program-block so that they are connected"; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION13 = "Now open the simulation ..."; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION13a = "and test your program in the simulation!"; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION15 = "Perfect,<br>your robot is driving 20 cm forward,<br>this is what you have programmed!"; // untranslated
Blockly.Msg.TOUR1_DESCRIPTION16 = "Bye and have fun trying out more!"; // untranslated
Blockly.Msg.ULTRASONIC_GETSAMPLE_TOOLTIP = "Gets the current reading from the ultrasonic sensor in cm. Maximum distance to messure is 255 cm."; // untranslated
Blockly.Msg.ULTRASONIC_TOOLTIP = "Represents an ultrasonic sensor."; // untranslated
Blockly.Msg.UNDO = "Anulé";
Blockly.Msg.VACUUM_OFF = "turn vacuum off"; // untranslated
Blockly.Msg.VACUUM_OFF_TOOLTIP = "Turns the vacuum off."; // untranslated
Blockly.Msg.VACUUM_ON = "turn vacuum on %"; // untranslated
Blockly.Msg.VACUUM_ON_TOOLTIP = "Turns on the vacuum speed in procent"; // untranslated
Blockly.Msg.VALIDATION_CONTAINS_SPECIAL_CHARACTERS = "Valid special characters: »=+!?.,%#+&^@_-«"; // untranslated
Blockly.Msg.VALIDATION_FIELD_REQUIRED = "This field cannot be empty!"; // untranslated
Blockly.Msg.VALIDATION_MAX_LENGTH = "The max. lenght is 25 characters!"; // untranslated
Blockly.Msg.VALIDATION_PASSWORD_MIN_LENGTH = "Password min. length is 6!"; // untranslated
Blockly.Msg.VALIDATION_SECOND_PASSWORD_EQUAL = "The two passwords must be equal!"; // untranslated
Blockly.Msg.VALIDATION_TOKEN_LENGTH = "Token length is 8 characters!"; // untranslated
Blockly.Msg.VALIDATION_VALID_EMAIL_ADDRESS = "Please enter a valid email address!"; // untranslated
Blockly.Msg.VALUE_TO = "value to"; // untranslated
Blockly.Msg.VARIABLES_DEFAULT_NAME = "element";
Blockly.Msg.VARIABLES_GET_CREATE_SET = "Creé 'fissé %1'";
Blockly.Msg.VARIABLES_GET_HELPURL = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated
Blockly.Msg.VARIABLES_GET_TOOLTIP = "A smon ël valor ëd sa variàbil.";
Blockly.Msg.VARIABLES_GLOBAL_DECLARE_TOOLTIP = "Declares a global variable."; // untranslated
Blockly.Msg.VARIABLES_LOCAL_DECLARE_TOOLTIP = "Declares a local variable."; // untranslated
Blockly.Msg.VARIABLES_SET = "fissé %1 a %2";
Blockly.Msg.VARIABLES_SET_CREATE_GET = "Creé 'oten-e %1'";
Blockly.Msg.VARIABLES_SET_HELPURL = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated
Blockly.Msg.VARIABLES_SET_TOOLTIP = "Fissé costa variàbil ugual al valor d'imission.";
Blockly.Msg.VARIABLES_TITLE = "variable"; // untranslated
Blockly.Msg.VARIABLES_TYPE_ARRAY_BOOLEAN = "List Boolean"; // untranslated
Blockly.Msg.VARIABLES_TYPE_ARRAY_COLOUR = "List Colour"; // untranslated
Blockly.Msg.VARIABLES_TYPE_ARRAY_CONNECTION = "List Connection"; // untranslated
Blockly.Msg.VARIABLES_TYPE_ARRAY_IMAGE = "List Image"; // untranslated
Blockly.Msg.VARIABLES_TYPE_ARRAY_NUMBER = "List Number"; // untranslated
Blockly.Msg.VARIABLES_TYPE_ARRAY_STRING = "List String"; // untranslated
Blockly.Msg.VARIABLES_TYPE_BOOLEAN = "Boolean"; // untranslated
Blockly.Msg.VARIABLES_TYPE_COLOUR = "Colour"; // untranslated
Blockly.Msg.VARIABLES_TYPE_CONNECTION = "Connection"; // untranslated
Blockly.Msg.VARIABLES_TYPE_IMAGE = "Image"; // untranslated
Blockly.Msg.VARIABLES_TYPE_NUMBER = "Number"; // untranslated
Blockly.Msg.VARIABLES_TYPE_STRING = "String"; // untranslated
Blockly.Msg.VARIABLE_USED_BEFORE_DECLARATION = "The variable is used before declaration."; // untranslated
Blockly.Msg.VOICE_PITCH = "voice pitch"; // untranslated
Blockly.Msg.VOICE_SPEED = "voice speed"; // untranslated
Blockly.Msg.WAIT = "wait ms"; // untranslated
Blockly.Msg.WAIT_FOR_TOOLTIP = "Waits for sensor values."; // untranslated
Blockly.Msg.WAIT_OR = "or wait for"; // untranslated
Blockly.Msg.WAIT_TIME_TOOLTIP = "Waits for a certain time in milliseconds."; // untranslated
Blockly.Msg.WAIT_TOOLTIP = "Waits for a condition becoming true."; // untranslated
Blockly.Msg.WAIT_UNTIL = "wait until"; // untranslated
Blockly.Msg.WIRELESS_TOOLTIP = "Represents a wireless connection"; // untranslated
Blockly.Msg.WRITE_TO_PIN_TOOLTIP = "Sends the value to chosen pin."; // untranslated
Blockly.Msg.X = "x"; // untranslated
Blockly.Msg.XEND = "end of X axis"; // untranslated
Blockly.Msg.XLABEL = "X axis label"; // untranslated
Blockly.Msg.XSTART = "start of X axis"; // untranslated
Blockly.Msg.XTICK = "distance between X ticks"; // untranslated
Blockly.Msg.Y = "y"; // untranslated
Blockly.Msg.YAW = "yaw"; // untranslated
Blockly.Msg.YEND = "end of Y axis"; // untranslated
Blockly.Msg.YES = "yes"; // untranslated
Blockly.Msg.YLABEL = "Y axis label"; // untranslated
Blockly.Msg.YOUNGER_THEN_14 = "I am younger than 16!"; // untranslated
Blockly.Msg.YSTART = "start of Y axis"; // untranslated
Blockly.Msg.YTICK = "distance between Y ticks"; // untranslated
Blockly.Msg.Z = "z"; // untranslated
Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE;
Blockly.Msg.SENSOR_PINTOUCH_PRESSED_GETSAMPLE_TOOLTIP = Blockly.Msg.PIN_ISTOUCHED_TOOLTIP;
Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.KEY_GETSAMPLE_TOOLTIP = Blockly.Msg.KEY_ISPRESSED_TOOLTIP;
Blockly.Msg.SENSOR_INFRARED_GETSAMPLE_TOOLTIP = Blockly.Msg.INFRARED_GETSAMPLE_TOOLTIP;
Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.MODE_DOWN = Blockly.Msg.SENSOR_GESTURE_DOWN;
Blockly.Msg.SENSOR_ULTRASONIC_GETSAMPLE_TOOLTIP = Blockly.Msg.ULTRASONIC_GETSAMPLE_TOOLTIP;
Blockly.Msg.MODE_SHAKE = Blockly.Msg.SENSOR_GESTURE_SHAKE;
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.SENSOR_ENCODER_GETSAMPLE_TOOLTIP = Blockly.Msg.ENCODER_GETSAMPLE_TOOLTIP;
Blockly.Msg.MODE_FACE_UP = Blockly.Msg.SENSOR_GESTURE_FACE_UP;
Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.MODE_FACE_DOWN = Blockly.Msg.SENSOR_GESTURE_FACE_DOWN;
Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE;
Blockly.Msg.SENSOR_COLOUR_GETSAMPLE_TOOLTIP = Blockly.Msg.COLOUR_GETSAMPLE_TOOLTIP;
Blockly.Msg.SENSOR_SOUND_GETSAMPLE_TOOLTIP_CALLIOPE = Blockly.Msg.MICROPHONE_GETSAMPLE_TOOLTIP;
Blockly.Msg.MODE_FREEFALL = Blockly.Msg.SENSOR_GESTURE_FREEFALL;
Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO;
Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL;
Blockly.Msg.SENSOR_TIMER_GETSAMPLE_TOOLTIP = Blockly.Msg.TIMER_GETSAMPLE_TOOLTIP;
Blockly.Msg.SENSOR_ACCELEROMETER_VALUE_GETSAMPLE_TOOLTIP = Blockly.Msg.ACCELEROMETER_ROTATION_TOOLTIP;
Blockly.Msg.ORA_ROBOT_PUSH_RUN = Blockly.Msg.MESSAGE_EDIT_START;
Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT = Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT;
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.MODE_UP = Blockly.Msg.SENSOR_GESTURE_UP;
Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE;
Blockly.Msg.SENSOR_GYRO_GETSAMPLE_TOOLTIP = Blockly.Msg.GYRO_GETSAMPLE_TOOLTIP;
Blockly.Msg.SENSOR_BATTERY_GETSAMPLE_TOOLTIP = Blockly.Msg.BATTERY_GETSAMPLE_TOOLTIP;
Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF;
Blockly.Msg.SENSOR_LIGHT_GETSAMPLE_TOOLTIP = Blockly.Msg.LIGHT_GETSAMPLE_TOOLTIP;
Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.SENSOR_INFRARED_PRESENCE_GETSAMPLE_TOOLTIP = Blockly.Msg.INFRARED_PRESENCE_GETSAMPLE_TOOLTIP;
Blockly.Msg.SENSOR_COMPASS_GETSAMPLE_TOOLTIP = Blockly.Msg.COMPASS_GETSAMPLE_TOOLTIP;
Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF;
Blockly.Msg.SENSOR_SOUND_GETSAMPLE_TOOLTIP = Blockly.Msg.SOUND_GETSAMPLE_TOOLTIP;
Blockly.Msg.SENSOR_FLAME_GETSAMPLE_TOOLTIP = Blockly.Msg.FLAME_GETSAMPLE_TOOLTIP;
Blockly.Msg.TOUCH_GETSAMPLE_TOOLTIP = Blockly.Msg.TOUCH_ISPRESSED_TOOLTIP;
Blockly.Msg.SENSOR_INFRARED_DISTANCE_GETSAMPLE_TOOLTIP = Blockly.Msg.INFRARED_DISTANCE_GETSAMPLE_TOOLTIP;
Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.SENSOR_KEY_GETSAMPLE_TOOLTIP = Blockly.Msg.KEY_GETSAMPLE_TOOLTIP;
Blockly.Msg.SENSOR_TEMPERATURE_GETSAMPLE_TOOLTIP = Blockly.Msg.TEMPERATURE_GETSAMPLE_TOOLTIP;
Blockly.Msg.SENSOR_TOUCH_GETSAMPLE_TOOLTIP = Blockly.Msg.TOUCH_GETSAMPLE_TOOLTIP;
Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
|
import React from 'react';
import { connect } from 'react-redux';
import { firebase } from '../firebase';
const withAuthentication = (Component) => {
class WithAuthentication extends React.Component {
constructor(props) {
super(props);
this.state = {
authUser: null,
};
}
componentDidMount() {
const { onSetAuthUser } = this.props;
firebase.auth.onAuthStateChanged(authUser => {
authUser
? onSetAuthUser(authUser)
: onSetAuthUser(null);
});
}
render() {
return (
<Component />
);
}
}
const mapDispatchToProps = (dispatch) => ({
onSetAuthUser: (authUser) => dispatch({ type: 'AUTH_USER_SET', authUser }),
});
return connect(null, mapDispatchToProps)(WithAuthentication);
}
export default withAuthentication;
|
/******************************
* Applied To | Yashas Shah *
* Role | Software Dev *
* --------------------------- *
* Replit | @YashasShah *
* GitHub | @YashasTheDev *
* --------------------------- *
* Badge Type | Headmaster *
******************************/
/******************************
* Applied To | Yashas Shah *
* Role | Software Dev *
* --------------------------- *
* Replit | @YashasShah *
* GitHub | @YashasTheDev *
* --------------------------- *
* Badge Type | ID *
******************************/
// You'll need both to join and they have to be authorized by Admin/Headmaster (same role)
|
var TableDatatablesAjax=function(){var a=function(){$(".date-picker").datepicker({rtl:App.isRTL(),autoclose:!0})},e=function(){var a=new Datatable;a.init({src:$("#datatable_ajax"),onSuccess:function(a,e){},onError:function(a){},onDataLoad:function(a){},loadingMessage:"Loading...",dataTable:{bStateSave:!0,fnStateSaveParams:function(a,e){return $("#datatable_ajax tr.filter .form-control").each(function(){e[$(this).attr("name")]=$(this).val()}),e},fnStateLoadParams:function(a,e){return $("#datatable_ajax tr.filter .form-control").each(function(){var a=$(this);e[a.attr("name")]&&a.val(e[a.attr("name")])}),!0},lengthMenu:[[10,20,50,100,150,-1],[10,20,50,100,150,"All"]],pageLength:50,ajax:{url:"../demo/table_ajax.php"},ordering:!1,order:[[1,"asc"]]}}),a.getTableWrapper().on("click",".table-group-action-submit",function(e){e.preventDefault();var t=$(".table-group-action-input",a.getTableWrapper());""!=t.val()&&a.getSelectedRowsCount()>0?(a.setAjaxParam("customActionType","group_action"),a.setAjaxParam("customActionName",t.val()),a.setAjaxParam("id",a.getSelectedRows()),a.getDataTable().ajax.reload(),a.clearAjaxParams()):""==t.val()?App.alert({type:"danger",icon:"warning",message:"Please select an action",container:a.getTableWrapper(),place:"prepend"}):0===a.getSelectedRowsCount()&&App.alert({type:"danger",icon:"warning",message:"No record selected",container:a.getTableWrapper(),place:"prepend"})})},t=function(){var a=new Datatable;a.init({src:$("#datatable_ajax_2"),onSuccess:function(a,e){},onError:function(a){},onDataLoad:function(a){},dataTable:{dom:"<'row'<'col-md-8 col-sm-12'i><'col-md-4 col-sm-12'<'table-group-actions pull-right'>>r>t<'row'<'col-md-8 col-sm-12'i><'col-md-4 col-sm-12'>>",bStateSave:!0,fnStateSaveParams:function(a,e){return $("#datatable_ajax_2 tr.filter .form-control").each(function(){e[$(this).attr("name")]=$(this).val()}),e},fnStateLoadParams:function(a,e){return $("#datatable_ajax_2 tr.filter .form-control").each(function(){var a=$(this);e[a.attr("name")]&&a.val(e[a.attr("name")])}),!0},pageLength:10,ajax:{url:"../demo/table_ajax.php"},order:[[1,"asc"]],language:{loadingRecords:"Please wait ...",zeroRecords:"No records",emptyTable:"No data available in table",info:"Showing _START_ to _END_ of _TOTAL_ entries"},scrollY:400,deferRender:!0,scroller:{loadingIndicator:!0}}}),a.getTableWrapper().on("click",".table-group-action-submit",function(e){e.preventDefault();var t=$(".table-group-action-input",a.getTableWrapper());""!=t.val()&&a.getSelectedRowsCount()>0?(a.setAjaxParam("customActionType","group_action"),a.setAjaxParam("customActionName",t.val()),a.setAjaxParam("id",a.getSelectedRows()),a.getDataTable().ajax.reload(),a.clearAjaxParams()):""==t.val()?App.alert({type:"danger",icon:"warning",message:"Please select an action",container:a.getTableWrapper(),place:"prepend"}):0===a.getSelectedRowsCount()&&App.alert({type:"danger",icon:"warning",message:"No record selected",container:a.getTableWrapper(),place:"prepend"})})};return{init:function(){a(),e(),t()}}}();jQuery(document).ready(function(){TableDatatablesAjax.init()});
|
webpackJsonpmavon_editor([132],{347:function(e,a){e.exports=function(e){var a=e.COMMENT(/^\s*@?rem\b/,/$/,{relevance:10});return{aliases:["bat","cmd"],case_insensitive:!0,illegal:/\/\*/,keywords:{keyword:"if else goto for in do call exit not exist errorlevel defined equ neq lss leq gtr geq",built_in:"prn nul lpt3 lpt2 lpt1 con com4 com3 com2 com1 aux shift cd dir echo setlocal endlocal set pause copy append assoc at attrib break cacls cd chcp chdir chkdsk chkntfs cls cmd color comp compact convert date dir diskcomp diskcopy doskey erase fs find findstr format ftype graftabl help keyb label md mkdir mode more move path pause print popd pushd promt rd recover rem rename replace restore rmdir shiftsort start subst time title tree type ver verify vol ping net ipconfig taskkill xcopy ren del"},contains:[{className:"variable",begin:/%%[^ ]|%[^ ]+?%|![^ ]+?!/},{className:"function",begin:{className:"symbol",begin:"^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)",relevance:0}.begin,end:"goto:eof",contains:[e.inherit(e.TITLE_MODE,{begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),a]},{className:"number",begin:"\\b\\d+",relevance:0},a]}}}});
|
export function eventOn(eventTarget, successEvent, errorEvent = "error") {
let $resolve, $reject;
const promise = new Promise((resolve, reject) => {
$resolve = resolve;
$reject = reject;
});
eventTarget.addEventListener(successEvent, $resolve);
eventTarget.addEventListener(errorEvent, $reject);
promise.finally(() => {
eventTarget.removeEventListener(successEvent, $resolve);
eventTarget.removeEventListener(errorEvent, $reject);
});
return promise;
}
export function timeout(delay) {
return new Promise(
resolve => setTimeout(resolve, delay)
);
}
|
// Grunt Configuration
'use strict';
module.exports = function(grunt) {
// Task Configuration
grunt.initConfig({
// Package info and environment variables
pkg: grunt.file.readJSON('package.json'),
env: {
src: 'src', // Source
dev: 'dev', // Development
dist: 'dist' // Production / Distribution
},
/**
* LESS Compiler
*/
less: {
dev: {
options: {
strictMath: true,
sourceMap: true,
sourceMapURL: 'styles.css.map',
sourceMapFilename: '<%%= env.dev %>/assets/css/styles.css.map'
},
src: '<%%= env.src %>/assets/less/styles.less',
dest: '<%%= env.dev %>/assets/css/styles.css'
},
dist: {
options: {
strictMath: true,
sourceMap: false
},
src: '<%%= env.src %>/assets/less/styles.less',
dest: '<%%= env.dist %>/assets/css/styles.css'
}
},
/**
* Autoprefixer
*/
autoprefixer: {
options: {
browsers: ['last 3 versions', 'ie 8', 'ie 9']
},
dev: {
options: {
map: true
},
src: '<%%= env.dev %>/assets/css/styles.css'
},
dist: {
src: '<%%= env.dist %>/assets/css/styles.css'
}
},
/**
* CSS Minimization
*/
cssmin: {
options: {
shorthandCompacting: true,
roundingPrecision: -1
},
dist: {
src: '<%%= env.dev %>/assets/css/styles.css',
dest: '<%%= env.dist %>/assets/css/styles.css'
}
},
/**
* Image Compressor
*/
imagemin: {
dev: {
files: [{
expand: true,
cwd: '<%%= env.src %>/assets/img/',
src: ['{,*/}*.{png,jpg,gif,svg}'],
dest: '<%%= env.dev %>/assets/img/'
}]
},
dist: {
files: [{
expand: true,
cwd: '<%%= env.src %>/assets/img/',
src: ['{,*/}*.{png,jpg,gif,svg}'],
dest: '<%%= env.dist %>/assets/img/'
}]
}
},
/**
* HTML Templating
*/
assemble: {
options: {
layout: 'default.hbs',
layoutdir: '<%%= env.src %>/templates/layouts/',
partials: '<%%= env.src %>/templates/partials/*.hbs',
helpers: 'prettify',
prettify: {
condense: true,
padcomments: true,
indent_inner_html: false,
indent: 4,
wrap_line_length: 0
}
},
dev: {
options: {
assets: '<%%= env.dev %>/assets',
site: { root: '<%%= env.dev %>' }
},
expand: true,
cwd: '<%%= env.src %>/pages/',
src: '**/*.{hbs,html,md}',
dest: '<%%= env.dev %>/'
},
dist: {
options: {
assets: '<%%= env.dist %>/assets',
site: { root: '<%%= env.dist %>' }
},
expand: true,
cwd: '<%%= env.src %>/pages/',
src: '**/*.{hbs,html,md}',
dest: '<%%= env.dist %>/'
}
},
/**
* File Copying
*/
copy: {
dev: {
files: [{
expand: true,
cwd: '<%%= env.src %>/assets/',
src: ['type/*','js/lib/*.js','js/main.js'],
dest: '<%%= env.dev %>/assets/'
}]
},
dist: {
files: [{
expand: true,
cwd: '<%%= env.src %>/assets/',
src: ['type/*','js/lib/*.js','js/main.js'],
dest: '<%%= env.dist %>/assets/'
}]
}
},
/**
* JS Plugin Concatenating
*/
concat: {
options: {
separator: ';\n',
nonull: true
},
dev: {
src: ['<%%= env.src %>/assets/js/plugins/*.js'],
dest: '<%%= env.dev %>/assets/js/plugins.js'
},
dist: {
src: ['<%%= env.src %>/assets/js/plugins/*.js'],
dest: '<%%= env.dist %>/assets/js/plugins.js'
}
},
/**
* JS Minimization
*/
uglify: {
dist: {
files: [{
expand: true,
cwd: '<%%= env.dev %>/assets/js',
src: '{,*/}*.js',
dest: '<%%= env.dist %>/assets/js'
}]
}
},
/**
* File Monitoring
*/
watch: {
options: {
spawn: false
},
less: {
files: '<%%= env.src %>/assets/less/{,*/}*.less',
tasks: ['less:dev','autoprefixer:dev']
},
html: {
files: '<%%= env.src %>/**/*.{hbs,json,yml,html,md}',
tasks: ['assemble:dev']
},
img: {
files: '<%%= env.src %>/assets/img/{,*/}*.{jpg,gif,png,svg}',
tasks: 'newer:imagemin:dev'
},
js: {
files: '<%%= env.src %>/assets/js/{,*/}*.js',
tasks: ['newer:copy:dev','concat:dev']
},
config: {
files: ['Gruntfile.js']
}
}
});
// Task Loading
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-newer');
grunt.loadNpmTasks('assemble');
// Task Registering
grunt.registerTask('default', ['watch']);
grunt.registerTask('build:dev', ['less:dev', 'autoprefixer:dev', 'copy:dev', 'imagemin:dev', 'concat:dev', 'assemble:dev']);
grunt.registerTask('build:dist', ['less:dist', 'autoprefixer:dist', 'cssmin:dist', 'copy:dist', 'concat:dist', 'uglify:dist', 'imagemin:dist', 'assemble:dist']);
};
|
import $ from '@zhennann/dom7';
export default {
render() {
return `
<div class="color-picker-module color-picker-module-sb-spectrum">
<div class="color-picker-sb-spectrum" style="background-color: hsl(0, 100%, 50%)">
<div class="color-picker-sb-spectrum-handle"></div>
</div>
</div>
`;
},
init(self) {
const { app } = self;
let isTouched;
let isMoved;
let touchStartX;
let touchStartY;
let touchCurrentX;
let touchCurrentY;
let specterRect;
let specterIsTouched;
let specterHandleIsTouched;
const { $el } = self;
function setSBFromSpecterCoords(x, y) {
let s = (x - specterRect.left) / specterRect.width;
let b = (y - specterRect.top) / specterRect.height;
s = Math.max(0, Math.min(1, s));
b = 1 - Math.max(0, Math.min(1, b));
self.setValue({ hsb: [self.value.hue, s, b] });
}
function handleTouchStart(e) {
if (isMoved || isTouched) return;
touchStartX = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
touchCurrentX = touchStartX;
touchStartY = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
touchCurrentY = touchStartY;
const $targetEl = $(e.target);
specterHandleIsTouched = $targetEl.closest('.color-picker-sb-spectrum-handle').length > 0;
if (!specterHandleIsTouched) {
specterIsTouched = $targetEl.closest('.color-picker-sb-spectrum').length > 0;
}
if (specterIsTouched) {
specterRect = $el.find('.color-picker-sb-spectrum')[0].getBoundingClientRect();
setSBFromSpecterCoords(touchStartX, touchStartY);
}
if (specterHandleIsTouched || specterIsTouched) {
$el.find('.color-picker-sb-spectrum-handle').addClass('color-picker-sb-spectrum-handle-pressed');
}
}
function handleTouchMove(e) {
if (!(specterIsTouched || specterHandleIsTouched)) return;
touchCurrentX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
touchCurrentY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
e.preventDefault();
if (!isMoved) {
// First move
isMoved = true;
if (specterHandleIsTouched) {
specterRect = $el.find('.color-picker-sb-spectrum')[0].getBoundingClientRect();
}
}
if (specterIsTouched || specterHandleIsTouched) {
setSBFromSpecterCoords(touchCurrentX, touchCurrentY);
}
}
function handleTouchEnd() {
isMoved = false;
if (specterIsTouched || specterHandleIsTouched) {
$el.find('.color-picker-sb-spectrum-handle').removeClass('color-picker-sb-spectrum-handle-pressed');
}
specterIsTouched = false;
specterHandleIsTouched = false;
}
function handleResize() {
self.modules['sb-spectrum'].update(self);
}
const passiveListener = app.touchEvents.start === 'touchstart' && app.support.passiveListener ? { passive: true, capture: false } : false;
self.$el.on(app.touchEvents.start, handleTouchStart, passiveListener);
app.on('touchmove:active', handleTouchMove);
app.on('touchend:passive', handleTouchEnd);
app.on('resize', handleResize);
self.destroySpectrumEvents = function destroySpectrumEvents() {
self.$el.off(app.touchEvents.start, handleTouchStart, passiveListener);
app.off('touchmove:active', handleTouchMove);
app.off('touchend:passive', handleTouchEnd);
app.off('resize', handleResize);
};
},
update(self) {
const {
value,
} = self;
const { hsl, hsb } = value;
const specterWidth = self.$el.find('.color-picker-sb-spectrum')[0].offsetWidth;
const specterHeight = self.$el.find('.color-picker-sb-spectrum')[0].offsetHeight;
self.$el.find('.color-picker-sb-spectrum')
.css('background-color', `hsl(${hsl[0]}, 100%, 50%)`);
self.$el.find('.color-picker-sb-spectrum-handle')
.css('background-color', `hsl(${hsl[0]}, ${hsl[1] * 100}%, ${hsl[2] * 100}%)`)
.transform(`translate(${specterWidth * hsb[1]}px, ${specterHeight * (1 - hsb[2])}px)`);
},
destroy(self) {
if (self.destroySpectrumEvents) self.destroySpectrumEvents();
delete self.destroySpectrumEvents;
},
};
|
angular.module('weightapp.controllers', ['weightapp.factory'])
.controller('AppCtrl', function ($rootScope, $scope, $ionicModal, $ionicHistory, $ionicPopup, $timeout, $state, AppFactory, $ionicPlatform) {
/**
* initApp :: function
* description: Main function that initializes the app
*/
$scope.initApp = function () {
// defaults and inits
$scope.socket = {};
$rootScope.host = '192.168.0.101';
$rootScope.port = 2101;
$scope.isConnected = false;
$scope.weight = 0;
$scope.firstTime = true;
$scope.data = '';
$scope.tasks = [];
$scope.loading = true;
$scope.myWeights = [];
$scope.loginData = {};
$rootScope.user = null;
$rootScope.userId = -1;
};
/**
* doLogin :: function
* description: Login Handler function
*/
$scope.doLogin = function () {
var userId = $scope.loginData.userId;
var password = $scope.loginData.password;
if (userId && password && userId.length > 0 && password.length > 0) {
AppFactory.loginUser(userId, password)
.success(function (data) {
console.log(data);
if (data.status) {
$rootScope.userId = data.user._id;
$rootScope.user = data.user;
$state.go('app.taskSelection');
localStorage.userId = $rootScope.userId;
$rootScope.initTasks();
}
else {
$rootScope.alertPopup("Incorrect Username or Password");
}
})
.error(function (e) {
console.log(e);
$rootScope.alertPopup("Error Logging In");
});
}
else {
$rootScope.alertPopup("Please fill in these required fields");
}
};
/**
* doLoginByNFC :: function
* description: NFC Tag Login Handler function
*/
$rootScope.doLoginByNFC = function (nfc) {
if ($rootScope.userId === -1) {
AppFactory.loginUserByNFC(nfc)
.success(function (data) {
console.log(data);
if (data.status) {
$rootScope.userId = data.user._id;
$rootScope.user = data.user;
$state.go('app.taskSelection');
$scope.loginResult = 'Logged In Successfully';
localStorage.userId = $rootScope.userId;
$rootScope.initTasks();
}
else {
$scope.loginResult = 'Incorrect Username or Password';
}
})
.error(function (e) {
console.log(e);
$scope.loginResult = 'Error Logging In';
});
}
else {
$rootScope.alertPopup("Already Logged In");
}
};
/**
* connectToHost :: function
* description: Generic function for connecting to a host via TCP Socket
* @param host
* @param port
*/
$scope.connectToHost = function (host, port) {
if (typeof Socket === 'function') {
$scope.socket = new Socket();
$scope.socket.onData = $scope.receiveData;
$scope.socket.onError = function (errorMessage) {
alert("Error occured, error: " + errorMessage);
};
$scope.socket.onClose = function (hasError) {
console.log("Socket closed, hasErrors=" + hasError);
$scope.setDisconnected();
};
$scope.socket.open(
host,
port,
$scope.setConnected,
function (errorMessage) {
$rootScope.alertPopup("Error during connection", "error: " + errorMessage);
});
}
else {
console.log('Socket is undefined');
}
};
/**
* setConnected :: function
* description: Callback function that sets connection state to true
*/
$scope.setConnected = function () {
$scope.isConnected = true;
console.log('connected to host ' + $rootScope.host + ' on port ' + $rootScope.port);
};
/**
* setDisconnected :: function
* description: Callback function that sets connection state to false
*/
$scope.setDisconnected = function () {
$scope.isConnected = false;
console.log('disconnected from host ' + $rootScope.host + ' on port ' + $rootScope.port);
};
/**
* connectToIndicator :: function
* description: Connects to the RAVAS indicator
*/
$scope.connectToIndicator = function () {
if (!$scope.isConnected) { // CONNECT TO HOST IF NOT ALREADY CONNECTED
$scope.connectToHost($rootScope.host, $rootScope.port);
}
};
/**
* alertPopup :: function
* description: Generic function for Ionic Alert Popup
*/
$rootScope.alertPopup = function (title, subtitle, callback) {
var alertPopup = $ionicPopup.alert({
title: title,
template: subtitle,
buttons: [
{
text: 'OK',
type: 'button-assertive'
}
]
});
alertPopup.then(function (res) {
if (callback) {
callback(res);
}
});
};
/**
* showLocationPopup :: function
* description: Show the location confirmation popup when triggered
*/
$scope.showLocationPopup = function () {
$scope.locations = {};
var myPopup = $ionicPopup.show({
template: '<input type="number" ng-model="locations.inputSku">',
title: 'Enter SKU Number',
//subTitle: 'SKU Number',
scope: $scope,
buttons: [
{text: 'Cancel'},
{
text: '<b>Check</b>',
type: 'button-assertive',
onTap: function (e) {
if (!$scope.locations.inputSku) {
e.preventDefault();
}
else {
return $scope.locations.inputSku;
}
}
}
]
});
myPopup.then(function (res) {
if (!isNaN(res)) {
$scope.checkLocation(res);
}
});
$timeout(function () {
myPopup.close(); //close the popup after 10 seconds for some reason
}, 10000);
};
/**
* checkLocation :: function
* description: Checks if the sku inserted from popup is correct
* if true: connects to the indicator and refers to weighing screen
* else alerts that the sku is wrong
*/
$scope.checkLocation = function (input) {
if (input == $scope.currentTask[$scope.currentItemIdx].sku) {
console.log('sku ok');
$state.go('app.weighInTask');
console.log('weight should be: ' + $scope.currentTask[$scope.currentItemIdx].weight);
$scope.connectToIndicator();
}
else {
console.log('input sku: ' + input);
console.log('wrong sku, sku is: ' + $scope.currentTask[$scope.currentItemIdx].sku);
$rootScope.alertPopup("Wrong SKU", "The SKU inserted is incorrect");
}
};
/**
* backToItem :: function
* description: returns back to item location view from weighing screen
*/
$scope.backToItem = function () {
$state.go('app.task');
};
/**
* startWeighing :: function
* description: starts the free weighing mode
*/
$scope.startWeighing = function () {
$state.go('app.weigh');
$scope.connectToIndicator();
};
/**
* sendCommand :: function
* description: Generic function for sending tcp socket commands
*/
$scope.sendCommand = function (command) {
try {
var bytes = new Uint8Array(command.length + 1);
for (var i = 0; i < command.length; i++) {
bytes[i] = command.charCodeAt(i);
}
bytes[command.length] = "\r\n".charCodeAt(0);
$scope.socket.write(bytes, function () {
// alert('sent successfully');
}, function (e) {
alertPopup('Error sending command', e)
});
}
catch (e) {
alertPopup('Exception', e);
}
};
/**
* receiveData :: function
* description: callback function that handles data received from host
* gathers data received for 300 msec and then handles it
*/
$scope.receiveData = function (data) {
var chars = new Array(data.length);
for (var i = 0; i < data.length; i++) {
chars.push(String.fromCharCode(data[i]));
}
var dataString = chars.join("");
$scope.concatData(dataString.replace(/(?:\r\n|\r|\n)/g, ''));
if ($scope.firstTime) {
$scope.firstTime = false;
// indicator sends the weight in two "waves" separated by about 100msec each
$timeout(function () {
$scope.handleData();
}, 300);
}
};
/**
* concatData :: function
* description: concatenates data string
*/
$scope.concatData = function (data) {
$scope.data += data;
};
/**
* handleData :: function
* description: Handles data string and updates the weight accordingly
*/
$scope.handleData = function () {
if ($scope.data && $scope.data.length > 0) {
if ($scope.data.indexOf('N+') === 0) { // PC Mode
$scope.data = $scope.data.substring(2);
if (!isNaN($scope.data)) {
$scope.weight = parseFloat($scope.data);
}
}
else if ($scope.data.indexOf('+') === 0) { // Repeating Send Mode
$scope.data = $scope.data.substring(1);
if (!isNaN($scope.data)) {
$scope.weight = parseFloat($scope.data);
}
}
else if ($scope.data.toLowerCase().indexOf('ok') > -1) { // Tare
$scope.weight = 0;
}
$scope.$apply();
}
$scope.firstTime = true;
$scope.data = '';
};
/**
* getWeight :: function
* description: Sends weight request to the indicator
*/
$scope.getWeight = function () {
console.log('Get weight button clicked');
if ($scope.isConnected) {
$scope.sendCommand('GN');
}
};
/**
* goToSettings :: function
* description: Refers to settings screen
*/
$scope.goToSettings = function () {
$state.go('app.settings');
};
/**
* tare :: function
* description: Sends tare request to the indicator
*/
$scope.tare = function () {
console.log('Tare button clicked');
if ($scope.isConnected) {
$scope.sendCommand('SR');
$scope.weight = 0;
}
};
$scope.tareAndGoToTask = function(){
$scope.tare();
$state.go('app.task');
};
/**
* saveSettings :: function
* description: Saves the settings for current and further (localStorage) use
*/
$scope.saveSettings = function (host, port) {
if (host && host.length > 0 && port && !isNaN(port)) {
$rootScope.host = host;
$rootScope.port = port;
localStorage.host = host;
localStorage.port = port;
console.log('Setings saved, connection is set to: ' + host + ':' + port);
$ionicHistory.goBack();
}
else {
$rootScope.alertPopup("Settings not saved", "Please review the data inserted");
}
};
/**
* selectTask :: function
* description: Selects a task (order) from list, gets its data and refers to task view
*/
$scope.selectTask = function (index) {
$scope.loading = true;
var selectedTaskId = $scope.tasks[index];
if (selectedTaskId) {
$scope.currentTaskId = selectedTaskId;
$scope.currentItemIdx = 0;
AppFactory.getOrderData(selectedTaskId)
.success(function (data) {
$scope.loading = false;
if (data.status) {
$scope.currentTask = data.data;
console.log('Got task data!');
console.log($scope.currentTask);
$state.go('app.palletZero');
$scope.connectToIndicator();
}
else {
$rootScope.alertPopup("Task Not Found", "Please refresh and try again");
console.log('Task not found');
}
})
.error(function (e) {
$scope.loading = false;
$rootScope.alertPopup("Error Loading Task Data", "Please try again");
console.log(e);
});
}
};
/**
* sendWeight :: function
* description: Checks if the weight (from the scale) is within the range of the item's weight
* if true: checks if it's the last item in the order
* if true: sets the order as done
* else: continues to the next item
* else: notifies an incorrect weight
*/
$scope.sendWeight = function () {
var weight = $scope.weight,
dbWeight = $scope.currentTask[$scope.currentItemIdx].weight;
console.log('weight: ' + weight);
console.log('dbWeight: ' + dbWeight);
console.log('weight/dbWeight: ' + parseFloat(weight) / parseFloat(dbWeight));
console.log('result: ' + Math.abs(1 - (parseFloat(weight) / parseFloat(dbWeight))));
if (Math.abs(1 - (parseFloat(weight) / parseFloat(dbWeight))) > 0.1) {
$rootScope.alertPopup("Incorrect weight", "Please try again");
}
else {
if ($scope.currentItemIdx === $scope.currentTask.length - 1) {
$state.go('app.taskSelection');
AppFactory.setOrderAsFinished($scope.currentTaskId)
.success(function (data) {
if (data.status) {
$rootScope.initTasks();
$rootScope.alertPopup("Task Finished", "Great Job!");
}
else {
$rootScope.alertPopup("Error", "Error updating task. Please try again.");
}
})
.error(function (e) {
$rootScope.alertPopup("Error", "Error updating task. Please try again.");
console.log(e);
});
}
else {
$rootScope.alertPopup("Correct weight", "Proceeding to next item");
$scope.tare();
$scope.currentItemIdx++;
$state.go('app.task');
}
}
};
/**
* initTasks :: function
* description: Gets all the ACTIVE tasks for the current user
*/
$rootScope.initTasks = function () {
if ($rootScope.userId !== -1 && $rootScope.user) {
AppFactory.getOrdersByUsername($rootScope.user.userName)
.success(function (data) {
if (data.status) {
console.log('Got new tasks');
console.log(data.data);
$scope.tasks = data.data;
}
else {
console.log('No tasks');
}
$scope.loading = false;
$scope.autoLoginMsg = '';
})
.error(function (e) {
console.log(e);
$scope.loading = false;
});
}
};
/**
* initMyWeights :: function
* decription: Gets all of the users saved weights and refers to myweights view
*/
$scope.initMyWeights = function () {
if ($rootScope.userId !== -1 && $rootScope.user) {
$scope.loading = true;
$state.go('app.myWeights');
AppFactory.showAllWeightsByUserName($rootScope.user.userName)
.success(function (data) {
if (data.status) {
$scope.myWeights = data.data;
}
else {
console.log('No data in my weights');
}
$scope.loading = false;
})
.error(function (e) {
console.log(e);
$scope.loading = false;
});
}
};
/**
* logout :: function
* description: Logs out the current user
*/
$scope.logout = function () {
$rootScope.userId = -1;
$rootScope.user = null;
$scope.loginData = {};
$scope.tasks = [];
localStorage.removeItem('userId');
$rootScope.alertPopup("Logged out successfully");
$state.go('app.login');
};
/**
* saveWeight :: function
* description: Saving free weight and location for user
* GPS must be open
*/
$scope.saveWeight = function () {
navigator.geolocation.getCurrentPosition(
function (position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
AppFactory.insertNewWeight($rootScope.user.userName, $scope.weight, latitude, longitude)
.success(function (data) {
console.log(data);
if (data.status) {
$rootScope.alertPopup("Saved successfully");
} else {
$rootScope.alertPopup("Error", "Weight Not Saved");
}
})
.error(function (e) {
console.log(e);
$rootScope.alertPopup("Exception", e);
});
},
function (error) {
$rootScope.alertPopup("Geolocation Error", 'code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
});
};
/**
* selectWeight :: function
* description: get GoogleMap by coords
* @param index
*/
$scope.selectWeight = function (index) {
var selectWeightId = $scope.myWeights[index];
if (selectWeightId) {
var latitude = selectWeightId.latitude;
var longitude = selectWeightId.longitude;
$scope.mapPopup(latitude, longitude);
}
};
/**
* mapPopup :: function
* description:
* @param latitude
* @param longitude
*/
$scope.mapPopup = function (latitude, longitude) {
navigator.vibrate(300);
var mapPopup = $ionicPopup.alert({
title: "Google Map",
template: '<div></div>',
buttons: [{
text: 'OK',
type: 'button-assertive'
}]
});
mapPopup.then(function (res) {
// console.log('Thank you for not eating my delicious ice cream cone');
});
document.getElementsByClassName("popup")[0].style.maxHeight = '100%';
document.getElementsByClassName("popup")[0].style.height = '400px';
document.getElementsByClassName("popup")[0].style.maxWidth = '100%';
document.getElementsByClassName("popup")[0].style.width = '300px';
document.getElementsByClassName("popup-body")[0].style.height = '100%';
setTimeout(function () {
var mapDiv = document.createElement("div");
mapDiv.setAttribute("id", "map");
mapDiv.style.height = '100%';
document.getElementsByClassName("popup-body")[0].appendChild(mapDiv);
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var latLong = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: latLong
});
marker.setMap(map);
map.setZoom(8);
map.setCenter(marker.getPosition());
}, 0);
};
/**
* takeScreenShotAndShare :: function
* description: Takes a screenshot and prompts sharing option
*/
$scope.takeScreenShotAndShare = function () {
if (navigator.screenshot) {
var imageLink;
navigator.screenshot.save(function (error, res) {
if (error) {
console.error(error);
} else {
imageLink = res.filePath;
window.plugins.socialsharing.share(null, null, 'file://' + imageLink, null);
}
}, 'jpg', 50, 'myScreenShot');
}
else {
$rootScope.alertPopup('Screenshot is disabled','');
}
};
$scope.scanBarcode = function(){
if (window.cordova && window.cordova.plugins && window.cordova.plugins.barcodeScanner) {
window.cordova.plugins.barcodeScanner.scan(
function (result) {
console.log("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
$scope.checkLocation(result.text);
},
function (error) {
$rootScope.alertPopup("Scanning failed: ", error);
},
{
"preferFrontCamera": false, // iOS and Android
"showFlipCameraButton": true, // iOS and Android
"prompt": "Place a barcode inside the scan area", // supported on Android only
"orientation": "landscape" // Android only (portrait|landscape), default unset so it rotates with the device
}
);
}
else {
$rootScope.alertPopup("Error","Barcode scanning is disabled for your device");
}
};
if (window.cordova) {
$ionicPlatform.ready(function () {
nfc.addTagDiscoveredListener(
function (nfcEvent) {
var tag = nfcEvent.tag;
var tagId = nfc.bytesToHexString(tag.id);
if (!$rootScope.user) {
$scope.alertPopup('NFC Detected','Logging in...');
$rootScope.doLoginByNFC(tagId);
}
else {
$rootScope.alertPopup('NFC Detected', 'User already logged in');
}
},
function () { // success callback
// alert("Waiting for NDEF tag");
},
function (error) { // error callback
$rootScope.alertPopup("Error adding NDEF listener ", JSON.stringify(error));
}
);
});
}
// Trigger App on js load
$scope.initApp();
});
|
import React from 'react'
import Grid from '@material-ui/core/Grid'
import Typography from '@material-ui/core/Typography'
import { withTheme } from '@material-ui/core/styles'
import { Translation } from 'react-i18next'
import distanceIcon from './img/keep-distance.png'
import stayHomeIcon from './img/stay-home.png'
const initialState = {
exposureStatus: false,
loaded: false,
mode: 'default'
}
class Exposures extends React.Component {
constructor () {
super()
this.state = initialState
}
async reset () {
this.setState(initialState)
}
render () {
const { status, statusLoaded, theme } = this.props
const { mode } = this.state
const statusMessageLoading = (<Translation>{t => t('statusLoadingMessage')}</Translation>)
const statusMessageNegative = (<Translation>{t => t('statusNegativeMessage')}</Translation>)
const statusMessagePositive = (<Translation>{t => t('statusPositiveMessage')}</Translation>)
const riskLevelLoading = (<Translation>{t => t('statusLoadingMessage')}</Translation>)
const riskLevelNegative = (<Translation>{t => t('standardRiskLevelMessage')}</Translation>)
const riskLevelPositive = (<Translation>{t => t('elevatedRiskLevelMessage')}</Translation>)
const statusMessage = statusLoaded
? (status
? statusMessagePositive
: statusMessageNegative)
: statusMessageLoading
const riskLevel = statusLoaded
? (status
? riskLevelPositive
: riskLevelNegative)
: riskLevelLoading
const riskLevelColor = status
? 'error'
: 'success'
const icon = status
? stayHomeIcon
: distanceIcon
return (
<Grid
container
>
{
((mode === 'default') && (
<Grid
container
direction='column'
justify='center'
alignItems='center'
>
<img src={icon} width={200} style={{ maxWidth: '80px', marginTop: 20 }} />
<Typography style={{ marginTop: 25 }}>
<Translation>{t => t('yourRiskLevelMessage')}</Translation>: <span style={{ color: theme.palette[riskLevelColor].main }}>{riskLevel}</span>
</Typography>
<Typography style={{ marginTop: 15 }}>
{statusMessage}
</Typography>
</Grid>
))
}
</Grid>
)
}
}
export default withTheme(Exposures)
|
$(document).ready(function(){$('.chkClickable').live('click',function(){$(this).next('.hdnStatus').val($(this).is(':checked'));});$('#btnAdd').click(function(){var text=$('#txtCat').val().trim();var regex=/\<[\S* ]*\>/;var alphaRegex=/[a-zA-Z]{1,}/;if(text.match(regex)!=null){showMessage('Category name entered is invalid');return;}
if(text.match(alphaRegex)==null){showMessage('Category name entered is invalid, should have at least 1 alphabet');return;}
if(text!=''&&!isPresent(text)){if(text.length<=50){ajaxAdd(text);}
else{showMessage('Category name cannot be more than 50 characters');}}});});function showMessage(message){alert(message);$('#txtCat').val('').focus();}
function isPresent(text){var status=false;var elements=$("label[for^='chkBox_selectcategories_']");$(elements).each(function(){if($(this).text()==text){status=true;var currentTop=$(this).offset().top;var parentTop=$('.cpCheckBoxContent').position().top;$('.cpCheckBoxContent').scrollTop(currentTop-parentTop);$('#txtCat').val('');}});return status;}
function ajaxAdd(text){$.ajax({type:'GET',url:'/Admin/CategoryAdmin/AddCategory',data:{'categoryName':text},success:function(data){if(data!=null&&data.CategoryID!=0){addCategory(data.CategoryName,data.CategoryID);$(".cpCheckBoxContent").animate({scrollTop:$(".cpCheckBoxContent").prop("scrollHeight")},1000);}
$('#txtCat').val('');},error:function(req,status,err){alert('an error occurred');}});}
function addCategory(name,value){var max=parseInt($("input[id^='valValue_selectcategories_']").last().attr('id').split('_')[2])+1;var element1=document.createElement('input');$(element1).attr('id','valValue_selectcategories_'+max).attr('name','valValue_selectcategories_'+max).attr('type','hidden').attr('value',value);var element2=document.createElement('input');$(element2).attr('id','chkBox_selectcategories_'+max).attr('name','chkBox_selectcategories_'+max).attr('type','checkbox').attr('class','chkClickable').attr('checked','checked').attr('value','true');var element3=document.createElement('input');$(element3).attr('id','hdnChk_selectcategories_'+max).attr('name','hdnChk_selectcategories_'+max).attr('type','hidden').attr('class','hdnStatus').attr('value','true');var element4=document.createElement('label');$(element4).attr('for','chkBox_selectcategories_'+max);element4.innerHTML=" "+name;var element5=document.createElement('input');$(element5).attr('id','lblLabel_selectcategories_'+max).attr('name','lblLabel_selectcategories_'+max).attr('type','hidden').attr('value',name);var element6=document.createElement('br');$('.cpCheckBoxContent').append(element1).append(element2).append(element3).append(element4).append(element5).append(element6);}
(function($){var data_click="unobtrusiveAjaxClick",data_validation="unobtrusiveValidation";function getFunction(code,argNames){var fn=window,parts=(code||"").split(".");while(fn&&parts.length){fn=fn[parts.shift()];}
if(typeof(fn)==="function"){return fn;}
argNames.push(code);return Function.constructor.apply(null,argNames);}
function isMethodProxySafe(method){return method==="GET"||method==="POST";}
function asyncOnBeforeSend(xhr,method){if(!isMethodProxySafe(method)){xhr.setRequestHeader("X-HTTP-Method-Override",method);}}
function asyncOnSuccess(element,data,contentType){var mode;if(contentType.indexOf("application/x-javascript")!==-1){return;}
mode=(element.getAttribute("data-ajax-mode")||"").toUpperCase();$(element.getAttribute("data-ajax-update")).each(function(i,update){var top;switch(mode){case"BEFORE":top=update.firstChild;$("<div />").html(data).contents().each(function(){update.insertBefore(this,top);});break;case"AFTER":$("<div />").html(data).contents().each(function(){update.appendChild(this);});break;default:$(update).html(data);break;}});}
function asyncRequest(element,options){var confirm,loading,method,duration;confirm=element.getAttribute("data-ajax-confirm");if(confirm&&!window.confirm(confirm)){return;}
loading=$(element.getAttribute("data-ajax-loading"));duration=element.getAttribute("data-ajax-loading-duration")||0;$.extend(options,{type:element.getAttribute("data-ajax-method")||undefined,url:element.getAttribute("data-ajax-url")||undefined,beforeSend:function(xhr){var result;asyncOnBeforeSend(xhr,method);result=getFunction(element.getAttribute("data-ajax-begin"),["xhr"]).apply(this,arguments);if(result!==false){loading.show(duration);}
return result;},complete:function(){loading.hide(duration);getFunction(element.getAttribute("data-ajax-complete"),["xhr","status"]).apply(this,arguments);},success:function(data,status,xhr){asyncOnSuccess(element,data,xhr.getResponseHeader("Content-Type")||"text/html");getFunction(element.getAttribute("data-ajax-success"),["data","status","xhr"]).apply(this,arguments);},error:getFunction(element.getAttribute("data-ajax-failure"),["xhr","status","error"])});options.data.push({name:"X-Requested-With",value:"XMLHttpRequest"});method=options.type.toUpperCase();if(!isMethodProxySafe(method)){options.type="POST";options.data.push({name:"X-HTTP-Method-Override",value:method});}
$.ajax(options);}
function validate(form){var validationInfo=$(form).data(data_validation);return!validationInfo||!validationInfo.validate||validationInfo.validate();}
$("a[data-ajax=true]").live("click",function(evt){evt.preventDefault();asyncRequest(this,{url:this.href,type:"GET",data:[]});});$("form[data-ajax=true] input[type=image]").live("click",function(evt){var name=evt.target.name,$target=$(evt.target),form=$target.parents("form")[0],offset=$target.offset();$(form).data(data_click,[{name:name+".x",value:Math.round(evt.pageX-offset.left)},{name:name+".y",value:Math.round(evt.pageY-offset.top)}]);setTimeout(function(){$(form).removeData(data_click);},0);});$("form[data-ajax=true] :submit").live("click",function(evt){var name=evt.target.name,form=$(evt.target).parents("form")[0];$(form).data(data_click,name?[{name:name,value:evt.target.value}]:[]);setTimeout(function(){$(form).removeData(data_click);},0);});$("form[data-ajax=true]").live("submit",function(evt){var clickInfo=$(this).data(data_click)||[];evt.preventDefault();if(!validate(this)){return;}
asyncRequest(this,{url:this.action,type:this.method||"GET",data:clickInfo.concat($(this).serializeArray())});});}(jQuery));(function($){$.extend($.fn,{validate:function(options){if(!this.length){options&&options.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing");return;}
var validator=$.data(this[0],'validator');if(validator){return validator;}
validator=new $.validator(options,this[0]);$.data(this[0],'validator',validator);if(validator.settings.onsubmit){this.find("input, button").filter(".cancel").click(function(){validator.cancelSubmit=true;});if(validator.settings.submitHandler){this.find("input, button").filter(":submit").click(function(){validator.submitButton=this;});}
this.submit(function(event){if(validator.settings.debug)
event.preventDefault();function handle(){if(validator.settings.submitHandler){if(validator.submitButton){var hidden=$("<input type='hidden'/>").attr("name",validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);}
validator.settings.submitHandler.call(validator,validator.currentForm);if(validator.submitButton){hidden.remove();}
return false;}
return true;}
if(validator.cancelSubmit){validator.cancelSubmit=false;return handle();}
if(validator.form()){if(validator.pendingRequest){validator.formSubmitted=true;return false;}
return handle();}else{validator.focusInvalid();return false;}});}
return validator;},valid:function(){if($(this[0]).is('form')){return this.validate().form();}else{var valid=true;var validator=$(this[0].form).validate();this.each(function(){valid&=validator.element(this);});return valid;}},removeAttrs:function(attributes){var result={},$element=this;$.each(attributes.split(/\s/),function(index,value){result[value]=$element.attr(value);$element.removeAttr(value);});return result;},rules:function(command,argument){var element=this[0];if(command){var settings=$.data(element.form,'validator').settings;var staticRules=settings.rules;var existingRules=$.validator.staticRules(element);switch(command){case"add":$.extend(existingRules,$.validator.normalizeRule(argument));staticRules[element.name]=existingRules;if(argument.messages)
settings.messages[element.name]=$.extend(settings.messages[element.name],argument.messages);break;case"remove":if(!argument){delete staticRules[element.name];return existingRules;}
var filtered={};$.each(argument.split(/\s/),function(index,method){filtered[method]=existingRules[method];delete existingRules[method];});return filtered;}}
var data=$.validator.normalizeRules($.extend({},$.validator.metadataRules(element),$.validator.classRules(element),$.validator.attributeRules(element),$.validator.staticRules(element)),element);if(data.required){var param=data.required;delete data.required;data=$.extend({required:param},data);}
return data;}});$.extend($.expr[":"],{blank:function(a){return!$.trim(""+a.value);},filled:function(a){return!!$.trim(""+a.value);},unchecked:function(a){return!a.checked;}});$.validator=function(options,form){this.settings=$.extend(true,{},$.validator.defaults,options);this.currentForm=form;this.init();};$.validator.format=function(source,params){if(arguments.length==1)
return function(){var args=$.makeArray(arguments);args.unshift(source);return $.validator.format.apply(this,args);};if(arguments.length>2&¶ms.constructor!=Array){params=$.makeArray(arguments).slice(1);}
if(params.constructor!=Array){params=[params];}
$.each(params,function(i,n){source=source.replace(new RegExp("\\{"+i+"\\}","g"),n);});return source;};$.extend($.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:$([]),errorLabelContainer:$([]),onsubmit:true,ignore:[],ignoreTitle:false,onfocusin:function(element){this.lastActive=element;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,element,this.settings.errorClass,this.settings.validClass);this.addWrapper(this.errorsFor(element)).hide();}},onfocusout:function(element){if(!this.checkable(element)&&(element.name in this.submitted||!this.optional(element))){this.element(element);}},onkeyup:function(element){if(element.name in this.submitted||element==this.lastElement){this.element(element);}},onclick:function(element){if(element.name in this.submitted)
this.element(element);else if(element.parentNode.name in this.submitted)
this.element(element.parentNode);},highlight:function(element,errorClass,validClass){$(element).addClass(errorClass).removeClass(validClass);},unhighlight:function(element,errorClass,validClass){$(element).removeClass(errorClass).addClass(validClass);}},setDefaults:function(settings){$.extend($.validator.defaults,settings);},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:$.validator.format("Please enter no more than {0} characters."),minlength:$.validator.format("Please enter at least {0} characters."),rangelength:$.validator.format("Please enter a value between {0} and {1} characters long."),range:$.validator.format("Please enter a value between {0} and {1}."),max:$.validator.format("Please enter a value less than or equal to {0}."),min:$.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){this.labelContainer=$(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||$(this.currentForm);this.containers=$(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var groups=(this.groups={});$.each(this.settings.groups,function(key,value){$.each(value.split(/\s/),function(index,name){groups[name]=key;});});var rules=this.settings.rules;$.each(rules,function(key,value){rules[key]=$.validator.normalizeRule(value);});function delegate(event){var validator=$.data(this[0].form,"validator"),eventType="on"+event.type.replace(/^validate/,"");validator.settings[eventType]&&validator.settings[eventType].call(validator,this[0]);}
$(this.currentForm).validateDelegate(":text, :password, :file, select, textarea","focusin focusout keyup",delegate).validateDelegate(":radio, :checkbox, select, option","click",delegate);if(this.settings.invalidHandler)
$(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler);},form:function(){this.checkForm();$.extend(this.submitted,this.errorMap);this.invalid=$.extend({},this.errorMap);if(!this.valid())
$(this.currentForm).triggerHandler("invalid-form",[this]);this.showErrors();return this.valid();},checkForm:function(){this.prepareForm();for(var i=0,elements=(this.currentElements=this.elements());elements[i];i++){this.check(elements[i]);}
return this.valid();},element:function(element){element=this.clean(element);this.lastElement=element;this.prepareElement(element);this.currentElements=$(element);var result=this.check(element);if(result){delete this.invalid[element.name];}else{this.invalid[element.name]=true;}
if(!this.numberOfInvalids()){this.toHide=this.toHide.add(this.containers);}
this.showErrors();return result;},showErrors:function(errors){if(errors){$.extend(this.errorMap,errors);this.errorList=[];for(var name in errors){this.errorList.push({message:errors[name],element:this.findByName(name)[0]});}
this.successList=$.grep(this.successList,function(element){return!(element.name in errors);});}
this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors();},resetForm:function(){if($.fn.resetForm)
$(this.currentForm).resetForm();this.submitted={};this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass);},numberOfInvalids:function(){return this.objectLength(this.invalid);},objectLength:function(obj){var count=0;for(var i in obj)
count++;return count;},hideErrors:function(){this.addWrapper(this.toHide).hide();},valid:function(){return this.size()==0;},size:function(){return this.errorList.length;},focusInvalid:function(){if(this.settings.focusInvalid){try{$(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin");}catch(e){}}},findLastActive:function(){var lastActive=this.lastActive;return lastActive&&$.grep(this.errorList,function(n){return n.element.name==lastActive.name;}).length==1&&lastActive;},elements:function(){var validator=this,rulesCache={};return $([]).add(this.currentForm.elements).filter(":input").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&&validator.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in rulesCache||!validator.objectLength($(this).rules()))
return false;rulesCache[this.name]=true;return true;});},clean:function(selector){return $(selector)[0];},errors:function(){return $(this.settings.errorElement+"."+this.settings.errorClass,this.errorContext);},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=$([]);this.toHide=$([]);this.currentElements=$([]);},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers);},prepareElement:function(element){this.reset();this.toHide=this.errorsFor(element);},check:function(element){element=this.clean(element);if(this.checkable(element)){element=this.findByName(element.name).not(this.settings.ignore)[0];}
var rules=$(element).rules();var dependencyMismatch=false;for(var method in rules){var rule={method:method,parameters:rules[method]};try{var result=$.validator.methods[method].call(this,element.value.replace(/\r/g,""),element,rule.parameters);if(result=="dependency-mismatch"){dependencyMismatch=true;continue;}
dependencyMismatch=false;if(result=="pending"){this.toHide=this.toHide.not(this.errorsFor(element));return;}
if(!result){this.formatAndAdd(element,rule);return false;}}catch(e){this.settings.debug&&window.console&&console.log("exception occured when checking element "+element.id
+", check the '"+rule.method+"' method",e);throw e;}}
if(dependencyMismatch)
return;if(this.objectLength(rules))
this.successList.push(element);return true;},customMetaMessage:function(element,method){if(!$.metadata)
return;var meta=this.settings.meta?$(element).metadata()[this.settings.meta]:$(element).metadata();return meta&&meta.messages&&meta.messages[method];},customMessage:function(name,method){var m=this.settings.messages[name];return m&&(m.constructor==String?m:m[method]);},findDefined:function(){for(var i=0;i<arguments.length;i++){if(arguments[i]!==undefined)
return arguments[i];}
return undefined;},defaultMessage:function(element,method){return this.findDefined(this.customMessage(element.name,method),this.customMetaMessage(element,method),!this.settings.ignoreTitle&&element.title||undefined,$.validator.messages[method],"<strong>Warning: No message defined for "+element.name+"</strong>");},formatAndAdd:function(element,rule){var message=this.defaultMessage(element,rule.method),theregex=/\$?\{(\d+)\}/g;if(typeof message=="function"){message=message.call(this,rule.parameters,element);}else if(theregex.test(message)){message=jQuery.format(message.replace(theregex,'{$1}'),rule.parameters);}
this.errorList.push({message:message,element:element});this.errorMap[element.name]=message;this.submitted[element.name]=message;},addWrapper:function(toToggle){if(this.settings.wrapper)
toToggle=toToggle.add(toToggle.parent(this.settings.wrapper));return toToggle;},defaultShowErrors:function(){for(var i=0;this.errorList[i];i++){var error=this.errorList[i];this.settings.highlight&&this.settings.highlight.call(this,error.element,this.settings.errorClass,this.settings.validClass);this.showLabel(error.element,error.message);}
if(this.errorList.length){this.toShow=this.toShow.add(this.containers);}
if(this.settings.success){for(var i=0;this.successList[i];i++){this.showLabel(this.successList[i]);}}
if(this.settings.unhighlight){for(var i=0,elements=this.validElements();elements[i];i++){this.settings.unhighlight.call(this,elements[i],this.settings.errorClass,this.settings.validClass);}}
this.toHide=this.toHide.not(this.toShow);this.hideErrors();this.addWrapper(this.toShow).show();},validElements:function(){return this.currentElements.not(this.invalidElements());},invalidElements:function(){return $(this.errorList).map(function(){return this.element;});},showLabel:function(element,message){var label=this.errorsFor(element);if(label.length){label.removeClass().addClass(this.settings.errorClass);label.attr("generated")&&label.html(message);}else{label=$("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(element),generated:true}).addClass(this.settings.errorClass).html(message||"");if(this.settings.wrapper){label=label.hide().show().wrap("<"+this.settings.wrapper+"/>").parent();}
if(!this.labelContainer.append(label).length)
this.settings.errorPlacement?this.settings.errorPlacement(label,$(element)):label.insertAfter(element);}
if(!message&&this.settings.success){label.text("");typeof this.settings.success=="string"?label.addClass(this.settings.success):this.settings.success(label);}
this.toShow=this.toShow.add(label);},errorsFor:function(element){var name=this.idOrName(element);return this.errors().filter(function(){return $(this).attr('for')==name;});},idOrName:function(element){return this.groups[element.name]||(this.checkable(element)?element.name:element.id||element.name);},checkable:function(element){return/radio|checkbox/i.test(element.type);},findByName:function(name){var form=this.currentForm;return $(document.getElementsByName(name)).map(function(index,element){return element.form==form&&element.name==name&&element||null;});},getLength:function(value,element){switch(element.nodeName.toLowerCase()){case'select':return $("option:selected",element).length;case'input':if(this.checkable(element))
return this.findByName(element.name).filter(':checked').length;}
return value.length;},depend:function(param,element){return this.dependTypes[typeof param]?this.dependTypes[typeof param](param,element):true;},dependTypes:{"boolean":function(param,element){return param;},"string":function(param,element){return!!$(param,element.form).length;},"function":function(param,element){return param(element);}},optional:function(element){return!$.validator.methods.required.call(this,$.trim(element.value),element)&&"dependency-mismatch";},startRequest:function(element){if(!this.pending[element.name]){this.pendingRequest++;this.pending[element.name]=true;}},stopRequest:function(element,valid){this.pendingRequest--;if(this.pendingRequest<0)
this.pendingRequest=0;delete this.pending[element.name];if(valid&&this.pendingRequest==0&&this.formSubmitted&&this.form()){$(this.currentForm).submit();this.formSubmitted=false;}else if(!valid&&this.pendingRequest==0&&this.formSubmitted){$(this.currentForm).triggerHandler("invalid-form",[this]);this.formSubmitted=false;}},previousValue:function(element){return $.data(element,"previousValue")||$.data(element,"previousValue",{old:null,valid:true,message:this.defaultMessage(element,"remote")});}},classRuleSettings:{required:{required:true},email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},dateDE:{dateDE:true},number:{number:true},numberDE:{numberDE:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(className,rules){className.constructor==String?this.classRuleSettings[className]=rules:$.extend(this.classRuleSettings,className);},classRules:function(element){var rules={};var classes=$(element).attr('class');classes&&$.each(classes.split(' '),function(){if(this in $.validator.classRuleSettings){$.extend(rules,$.validator.classRuleSettings[this]);}});return rules;},attributeRules:function(element){var rules={};var $element=$(element);for(var method in $.validator.methods){var value=$element.attr(method);if(value){rules[method]=value;}}
if(rules.maxlength&&/-1|2147483647|524288/.test(rules.maxlength)){delete rules.maxlength;}
return rules;},metadataRules:function(element){if(!$.metadata)return{};var meta=$.data(element.form,'validator').settings.meta;return meta?$(element).metadata()[meta]:$(element).metadata();},staticRules:function(element){var rules={};var validator=$.data(element.form,'validator');if(validator.settings.rules){rules=$.validator.normalizeRule(validator.settings.rules[element.name])||{};}
return rules;},normalizeRules:function(rules,element){$.each(rules,function(prop,val){if(val===false){delete rules[prop];return;}
if(val.param||val.depends){var keepRule=true;switch(typeof val.depends){case"string":keepRule=!!$(val.depends,element.form).length;break;case"function":keepRule=val.depends.call(element,element);break;}
if(keepRule){rules[prop]=val.param!==undefined?val.param:true;}else{delete rules[prop];}}});$.each(rules,function(rule,parameter){rules[rule]=$.isFunction(parameter)?parameter(element):parameter;});$.each(['minlength','maxlength','min','max'],function(){if(rules[this]){rules[this]=Number(rules[this]);}});$.each(['rangelength','range'],function(){if(rules[this]){rules[this]=[Number(rules[this][0]),Number(rules[this][1])];}});if($.validator.autoCreateRanges){if(rules.min&&rules.max){rules.range=[rules.min,rules.max];delete rules.min;delete rules.max;}
if(rules.minlength&&rules.maxlength){rules.rangelength=[rules.minlength,rules.maxlength];delete rules.minlength;delete rules.maxlength;}}
if(rules.messages){delete rules.messages;}
return rules;},normalizeRule:function(data){if(typeof data=="string"){var transformed={};$.each(data.split(/\s/),function(){transformed[this]=true;});data=transformed;}
return data;},addMethod:function(name,method,message){$.validator.methods[name]=method;$.validator.messages[name]=message!=undefined?message:$.validator.messages[name];if(method.length<3){$.validator.addClassRules(name,$.validator.normalizeRule(name));}},methods:{required:function(value,element,param){if(!this.depend(param,element))
return"dependency-mismatch";switch(element.nodeName.toLowerCase()){case'select':var val=$(element).val();return val&&val.length>0;case'input':if(this.checkable(element))
return this.getLength(value,element)>0;default:return $.trim(value).length>0;}},remote:function(value,element,param){if(this.optional(element))
return"dependency-mismatch";var previous=this.previousValue(element);if(!this.settings.messages[element.name])
this.settings.messages[element.name]={};previous.originalMessage=this.settings.messages[element.name].remote;this.settings.messages[element.name].remote=previous.message;param=typeof param=="string"&&{url:param}||param;if(this.pending[element.name]){return"pending";}
if(previous.old===value){return previous.valid;}
previous.old=value;var validator=this;this.startRequest(element);var data={};data[element.name]=value;$.ajax($.extend(true,{url:param,mode:"abort",port:"validate"+element.name,dataType:"json",data:data,success:function(response){validator.settings.messages[element.name].remote=previous.originalMessage;var valid=response===true;if(valid){var submitted=validator.formSubmitted;validator.prepareElement(element);validator.formSubmitted=submitted;validator.successList.push(element);validator.showErrors();}else{var errors={};var message=response||validator.defaultMessage(element,"remote");errors[element.name]=previous.message=$.isFunction(message)?message(value):message;validator.showErrors(errors);}
previous.valid=valid;validator.stopRequest(element,valid);}},param));return"pending";},minlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)>=param;},maxlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)<=param;},rangelength:function(value,element,param){var length=this.getLength($.trim(value),element);return this.optional(element)||(length>=param[0]&&length<=param[1]);},min:function(value,element,param){return this.optional(element)||value>=param;},max:function(value,element,param){return this.optional(element)||value<=param;},range:function(value,element,param){return this.optional(element)||(value>=param[0]&&value<=param[1]);},email:function(value,element){return this.optional(element)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);},url:function(value,element){return this.optional(element)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);},date:function(value,element){return this.optional(element)||!/Invalid|NaN/.test(new Date(value));},dateISO:function(value,element){return this.optional(element)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);},number:function(value,element){return this.optional(element)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);},digits:function(value,element){return this.optional(element)||/^\d+$/.test(value);},creditcard:function(value,element){if(this.optional(element))
return"dependency-mismatch";if(/[^0-9-]+/.test(value))
return false;var nCheck=0,nDigit=0,bEven=false;value=value.replace(/\D/g,"");for(var n=value.length-1;n>=0;n--){var cDigit=value.charAt(n);var nDigit=parseInt(cDigit,10);if(bEven){if((nDigit*=2)>9)
nDigit-=9;}
nCheck+=nDigit;bEven=!bEven;}
return(nCheck%10)==0;},accept:function(value,element,param){param=typeof param=="string"?param.replace(/,/g,'|'):"png|jpe?g|gif";return this.optional(element)||value.match(new RegExp(".("+param+")$","i"));},equalTo:function(value,element,param){var target=$(param).unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){$(element).valid();});return value==target.val();}}});$.format=$.validator.format;})(jQuery);;(function($){var pendingRequests={};if($.ajaxPrefilter){$.ajaxPrefilter(function(settings,_,xhr){var port=settings.port;if(settings.mode=="abort"){if(pendingRequests[port]){pendingRequests[port].abort();}
pendingRequests[port]=xhr;}});}else{var ajax=$.ajax;$.ajax=function(settings){var mode=("mode"in settings?settings:$.ajaxSettings).mode,port=("port"in settings?settings:$.ajaxSettings).port;if(mode=="abort"){if(pendingRequests[port]){pendingRequests[port].abort();}
return(pendingRequests[port]=ajax.apply(this,arguments));}
return ajax.apply(this,arguments);};}})(jQuery);;(function($){if(!jQuery.event.special.focusin&&!jQuery.event.special.focusout&&document.addEventListener){$.each({focus:'focusin',blur:'focusout'},function(original,fix){$.event.special[fix]={setup:function(){this.addEventListener(original,handler,true);},teardown:function(){this.removeEventListener(original,handler,true);},handler:function(e){arguments[0]=$.event.fix(e);arguments[0].type=fix;return $.event.handle.apply(this,arguments);}};function handler(e){e=$.event.fix(e);e.type=fix;return $.event.handle.call(this,e);}});};$.extend($.fn,{validateDelegate:function(delegate,type,handler){return this.bind(type,function(event){var target=$(event.target);if(target.is(delegate)){return handler.apply(target,arguments);}});}});})(jQuery);
(function($){var $jQval=$.validator,adapters,data_validation="unobtrusiveValidation";function setValidationValues(options,ruleName,value){options.rules[ruleName]=value;if(options.message){options.messages[ruleName]=options.message;}}
function splitAndTrim(value){return value.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g);}
function getModelPrefix(fieldName){return fieldName.substr(0,fieldName.lastIndexOf(".")+1);}
function appendModelPrefix(value,prefix){if(value.indexOf("*.")===0){value=value.replace("*.",prefix);}
return value;}
function onError(error,inputElement){var container=$(this).find("[data-valmsg-for='"+inputElement[0].name+"']"),replace=$.parseJSON(container.attr("data-valmsg-replace"))!==false;container.removeClass("field-validation-valid").addClass("field-validation-error");error.data("unobtrusiveContainer",container);if(replace){container.empty();error.removeClass("input-validation-error").appendTo(container);}
else{error.hide();}}
function onErrors(form,validator){var container=$(this).find("[data-valmsg-summary=true]"),list=container.find("ul");if(list&&list.length&&validator.errorList.length){list.empty();container.addClass("validation-summary-errors").removeClass("validation-summary-valid");$.each(validator.errorList,function(){$("<li />").html(this.message).appendTo(list);});}}
function onSuccess(error){var container=error.data("unobtrusiveContainer"),replace=$.parseJSON(container.attr("data-valmsg-replace"));if(container){container.addClass("field-validation-valid").removeClass("field-validation-error");error.removeData("unobtrusiveContainer");if(replace){container.empty();}}}
function validationInfo(form){var $form=$(form),result=$form.data(data_validation);if(!result){result={options:{errorClass:"input-validation-error",errorElement:"span",errorPlacement:$.proxy(onError,form),invalidHandler:$.proxy(onErrors,form),messages:{},rules:{},success:$.proxy(onSuccess,form)},attachValidation:function(){$form.validate(this.options);},validate:function(){$form.validate();return $form.valid();}};$form.data(data_validation,result);}
return result;}
$jQval.unobtrusive={adapters:[],parseElement:function(element,skipAttach){var $element=$(element),form=$element.parents("form")[0],valInfo,rules,messages;if(!form){return;}
valInfo=validationInfo(form);valInfo.options.rules[element.name]=rules={};valInfo.options.messages[element.name]=messages={};$.each(this.adapters,function(){var prefix="data-val-"+this.name,message=$element.attr(prefix),paramValues={};if(message!==undefined){prefix+="-";$.each(this.params,function(){paramValues[this]=$element.attr(prefix+this);});this.adapt({element:element,form:form,message:message,params:paramValues,rules:rules,messages:messages});}});jQuery.extend(rules,{"__dummy__":true});if(!skipAttach){valInfo.attachValidation();}},parse:function(selector){$(selector).find(":input[data-val=true]").each(function(){$jQval.unobtrusive.parseElement(this,true);});$("form").each(function(){var info=validationInfo(this);if(info){info.attachValidation();}});}};adapters=$jQval.unobtrusive.adapters;adapters.add=function(adapterName,params,fn){if(!fn){fn=params;params=[];}
this.push({name:adapterName,params:params,adapt:fn});return this;};adapters.addBool=function(adapterName,ruleName){return this.add(adapterName,function(options){setValidationValues(options,ruleName||adapterName,true);});};adapters.addMinMax=function(adapterName,minRuleName,maxRuleName,minMaxRuleName,minAttribute,maxAttribute){return this.add(adapterName,[minAttribute||"min",maxAttribute||"max"],function(options){var min=options.params.min,max=options.params.max;if(min&&max){setValidationValues(options,minMaxRuleName,[min,max]);}
else if(min){setValidationValues(options,minRuleName,min);}
else if(max){setValidationValues(options,maxRuleName,max);}});};adapters.addSingleVal=function(adapterName,attribute,ruleName){return this.add(adapterName,[attribute||"val"],function(options){setValidationValues(options,ruleName||adapterName,options.params[attribute]);});};$jQval.addMethod("__dummy__",function(value,element,params){return true;});$jQval.addMethod("regex",function(value,element,params){var match;if(this.optional(element)){return true;}
match=new RegExp(params).exec(value);return(match&&(match.index===0)&&(match[0].length===value.length));});adapters.addSingleVal("accept","exts").addSingleVal("regex","pattern");adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");adapters.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range");adapters.add("equalto",["other"],function(options){var prefix=getModelPrefix(options.element.name),other=options.params.other,fullOtherName=appendModelPrefix(other,prefix),element=$(options.form).find(":input[name="+fullOtherName+"]")[0];setValidationValues(options,"equalTo",element);});adapters.add("required",function(options){if(options.element.tagName.toUpperCase()!=="INPUT"||options.element.type.toUpperCase()!=="CHECKBOX"){setValidationValues(options,"required",true);}});adapters.add("remote",["url","type","additionalfields"],function(options){var value={url:options.params.url,type:options.params.type||"GET",data:{}},prefix=getModelPrefix(options.element.name);$.each(splitAndTrim(options.params.additionalfields||options.element.name),function(i,fieldName){var paramName=appendModelPrefix(fieldName,prefix);value.data[paramName]=function(){return $(options.form).find(":input[name='"+paramName+"']").val();};});setValidationValues(options,"remote",value);});$(function(){$jQval.unobtrusive.parse(document);});}(jQuery));
$(document).ready(function(){updatePublishBtn();$('.privateChkBox').change(function(){updatePublishBtn();});$('.postUrl,.postUrlPrefix,#btnUpdate,#btnCancel').hide();$('.postTitle').change(function(){var postId=parseInt($('#Post_PostID').val());if(postId==0){var text=$(this).val();if(text.trim()!=''){getVerifiedUrl(text);}else{clearUrlFields();}}});if($('.postUrlValue').val()!=null&&$('.postUrlValue').val()!=''){var prefixText='';if($('#Post_PostID').val()!='0'&&$('#Post_EntryType').val()=='1'){prefixText=getDatePrefix()+'/';}
else{prefixText='pages'+'/';}
$('.postUrlLabel').text(prefixText+$('.postUrlValue').val());$('.postUrlLabel').attr('title','click to change the url').bind('click',function(){$('.postUrl').show();$('.postUrlPrefix').show();$('.postUrlPrefix').text(prefixText);$('.postUrlLabel').hide();$('#btnUpdate').show();$('#btnCancel').show();});}
$('#btnUpdate').click(function(){var text=$('.postUrl').val();if(text.trim()==''){text=$('.postTitle').val();}
$('.postUrl,.postUrlPrefix').hide();$('.postUrlLabel').show();$('#btnUpdate').hide();$('#btnCancel').hide();if(text.trim()!=''){getVerifiedUrl(text);}
else{clearUrlFields();}});$('#btnCancel').click(function(){$('.postUrl,.postUrlPrefix').hide();$('.postUrlLabel').show();$('#btnUpdate').hide();$('#btnCancel').hide();});$(document).on('focus','#bitlyLink',function(){$(this).one('mouseup',function(event){event.preventDefault();}).select();});if($('#isPartiallySavable').length==1){setTimeout(function(){savePostOrPage();},30000);}
if($('.hide-column').length>0){var cell=$('.hide-column');var col=$(cell).parent().children().index(cell);var tbl=$(cell).parents('table');var rows=$(tbl).find('tbody').find('tr');$(cell).hide();$(rows).each(function(){$(this).find('td:eq('+col+')').hide();});}});function clearUrlFields(){$('.postUrlLabel').text('---').unbind('click');$('.postUrlPrefix').text('');$('.postUrlValue').val('');$('.postUrl').val('');}
function getDatePrefix(){var postDate=$('#Post_PostAddedDate').val();var prefix='',month='';if(postDate=='1/1/0001 12:00:00 AM'){var date=new Date;month=date.getMonth()+1;prefix=date.getFullYear()+'/'+(month>=10?month:("0"+month));}else{var parsedDate=new Date(Date.parse(postDate));month=parsedDate.getMonth()+1;prefix=parsedDate.getFullYear()+'/'+(month>=10?month:("0"+month));}
return prefix;}
function getVerifiedUrl(postTitle){var entryType=$('#Post_EntryType').val();var postId=$('#Post_PostID').val();$.ajax({type:'GET',url:siteRoot+'admin/post/verifyurlurlexists',data:{'postTitle':postTitle,'entryType':entryType,'postId':postId},dataType:'json',success:function(data){finalizeUrl(data);}});}
function finalizeUrl(text){$('.postUrl').val(text);var entryType=$('#Post_EntryType').val();var prefix='';if(entryType=="1"){prefix=getDatePrefix();text=prefix+'/'+text;}
else{prefix='pages';text='pages/'+text;}
$('.postUrlPrefix').text(prefix+'/');$('.postUrlValue').val(text);$('.postUrlLabel').text(text);$('.postUrlLabel').attr('title','click to change the url').bind('click',function(){$('.postUrl').show();$('.postUrlPrefix').show();$('.postUrlLabel').hide();$('#btnUpdate').show();$('#btnCancel').show();});}
$(document).ready(function(){$('#btnAddTags').click(function(e){e.preventDefault();showTagHelp();if($('#txtTag').val().trim()!=''){var array=getCleanedTagList($('#txtTag').val().trim());createTags(array);}
setHiddenVal();$('#txtTag').val('');$('#txtTag').focus();});$('.tag').live('click',function(){$(this).next().remove();$(this).remove();setHiddenVal();});if($('#hdnAddedTags').val()!=undefined&&$('#hdnAddedTags').val()!=''){var elements=$('#hdnAddedTags').val().split(',');createTags(elements);}});function showTagHelp(){$('#tag-info').show();setTimeout(function(){$('#tag-info').hide('fast');},1000);}
function getCleanedTagList(tagList){var array=tagList.split(',');var regex=/\<[\S* ]*\>/;var alphaRegex=/[a-zA-Z]{1,}/;var cleanedArray=[];var invalidTags=false;$.each(array,function(){var trimmedText=this.trim();if(trimmedText!=''){if(trimmedText.length<=50&&trimmedText.match(regex)==null&&trimmedText.match(alphaRegex)!=null){cleanedArray.push(trimmedText);}
else{invalidTags=true;}}});if(invalidTags){alert('Tags with length greater than 50, tags with html, tags without any alphabets were removed.');}
return cleanedArray;}
function notPresent(text){var result=true;var elements=$('#addedTags').find('span.tag');$(elements).each(function(){if($(this).html().toLowerCase()==text.toLowerCase()){result=false;}});return result;}
function setHiddenVal(){var hdnStr='';$('#addedTags').find('span.tag').each(function(){hdnStr+=$(this).text()+',';});hdnStr=hdnStr.substring(0,hdnStr.length-1);$('#hdnAddedTags').val(hdnStr);}
function createTags(array){$(array).each(function(){if(notPresent(this)){var element=document.createElement('span');$(element).attr('class','tag');$(element).attr('title','click to remove');element.innerHTML=this;$('#addedTags').append(element);var selement=document.createElement('span');selement.innerHTML=' ';$('#addedTags').append(selement);}});}
function updatePublishBtn(){var text=$('.privateChkBox').is(':checked')?"Save":"Publish";$('.publishBtn').attr('value',text);}
function updatePreview(){var selectedTheme=$('#Theme').val();if(selectedTheme==null||selectedTheme==''){selectedTheme="Default";}
var themeUrl=siteRoot+'Content/codeHighlighter/styles/shTheme'+selectedTheme+'.css';$('#themeChoice').attr('href',themeUrl);$('#previewMsg').hide();$('#preview').show();}
$(document).ready(function(){$('.brush-not-selected').hide();$('#chk-show-all').change(function(){if($(this).is(':checked')){$('.brush-not-selected').show();$('.selected-brushes-title').html('All brushes:');}
else{$('.brush-not-selected').hide();$('.selected-brushes-title').html('Selected brushes:');}});setTimeout(function(){updatePreview();},1000);$('#Theme').on('change',function(){updatePreview();});});$(document).ready(function(){var li=$('li.current');var submnu;if($(li).parent().attr('class')!='no-display sub-menu'){submnu=$(li).find('ul.sub-menu');$(submnu).removeClass('no-display').addClass('display');}
else{li=$('li.current').parent().parent();submnu=$(li).find('ul.sub-menu');$(submnu).removeClass('no-display').addClass('display');$(li).addClass('current');}
$('li.collapse').click(function(){$('#content').removeClass('content-actual').addClass('content-collapsed');$('#menu').hide();$('#quickLinks').hide();$('#restore').show();});$('a#restoreMenu').click(function(e){e.preventDefault();$('#content').removeClass('content-collapsed').addClass('content-actual');$('#menu').show();$('#quickLinks').show();$('#restore').hide();});$('.imgSharing').click(function(){var radio=$(this).parent().prev();$(radio).click();});});$(document).ready(function(){$('.deleteFile').click(function(){var prevCell=$(this).parent();var fileName=$(this).attr('data-file-name');var choice=confirm("Are you sure you want to delete "+fileName+"? It cannot be recovered once it is deleted. Click \"Ok\" to delete.");if(choice){$.ajax({type:'GET',url:siteRoot+'Admin/Uploads/DeleteUploadedFile',data:{'fileName':fileName,'token':$('#OneTimeCode').val()},dataType:'json',success:function(data){if(data.FileStatus=="File Deleted"){var zeroRowHtml='<tr><td>there are no items in this section at this point!</td><td></td></tr>';var row=$(prevCell).parent();$(row).remove();if($('#manage-table > tbody').find('tr').length==0){var tbody=$('#manage-table > tbody');$(tbody).append(zeroRowHtml);}}},error:function(req,status,err){alert('an error occurred while trying to delete the selected file, please try again.');}});}});});$(document).ready(function(){$('.trashComment').click(function(e){e.preventDefault();var anchor=this;var commentId=$(anchor).next('.trashCommentID').val();$.ajax({type:'GET',url:siteRoot+'Admin/CommentAdmin/TrashComment',data:{'commentId':parseInt(commentId),'token':$('#OneTimeCode').val()},dataType:'json',success:function(data){if(data.DeleteStatusString=="Delete succeeded"){var row=$(anchor).parent().parent().parent();$(row).remove();}},error:function(req,status,err){alert('an error occurred while trying to delete the selected comment, please try again.');}});});});$(document).ready(function(){$('#btnCreateTags').click(function(){var text=$('#txtTag').val().trim();var regex=/\<[\S* ]*\>/;var alphaRegex=/[a-zA-Z]{1,}/;if(text.match(regex)!=null){alert('Tag name entered is invalid');$('#txtTag').val('').focus();return;}
if(text.match(alphaRegex)==null){alert('Tag entered is invalid, should have at least 1 alphabet');$('#txtTag').val('').focus();return;}
if(text!=''&&text.indexOf(',')<0){ajaxAddTagPartial(text);}
else if(text!=''){$('.add-msg').html('invalid tag, cannot contain a \',\'').show('slow');setTimeout(function(){$('.add-msg').html('');$('#txtTag').val('').focus();},2000);}});$('.deletePost, .deletePage, .deleteCategory, .deleteTag, .deleteAuthor').live('click',function(e){e.preventDefault();var element=this;var url=$(element).attr('href')+"&token="+$('#OneTimeCode').val();var choice=confirm("Are you sure you want to delete the selected item?");if(choice){$.ajax({type:'GET',url:url,dataType:'json',success:function(data){deleteRow(element);},error:function(xhr,ajaxOptions,thrownError){alert('unable to delete the chosen item');}});}});});function deleteRow(element){var zeroRowsHtml='<tr class=\"manage-row\"><td class=\"manage-cell\">there are no items in this section at this point!</td><td class=\"manage-cell\"></td><td class=\"manage-cell\"></td></tr>';var row=$(element).parents('tr');$(row).remove();if($('#manage-table > tbody').find('tr').length==0){var tbody=$('#manage-table > tbody');$(tbody).append(zeroRowsHtml);}}
function ajaxAddTagPartial(text){$.ajax({type:'GET',url:siteRoot+'Admin/TagAdmin/AddTagPartial',data:{'tagName':text,'token':$('#OneTimeCode').val()},dataType:'html',success:function(data){if(data.trim()!=''){var zeroRow=$('tr.manage-row');$('#manage-table tbody tr:first').before(data);$('.add-msg').html('');if(zeroRow.length==1){$(zeroRow).remove();}}
else{$('.add-msg').html('tag already exists').show('slow');setTimeout(function(){$('.add-msg').html('');},2000);}
$('#txtTag').val('');},error:function(req,status,err){alert('an error occurred while trying to add the tag, please try again.');}});}
$(document).ready(function(){showHideMarkdownHelp($('#EditorType').val());$('#EditorType').on('change',function(){showHideMarkdownHelp($(this).val());});$('#AkismetEnabled').change(function(){$('.akismetAdvancedOptions').toggle();});if($('#AkismetEnabled').is(':checked')){$('.akismetAdvancedOptions').show();}});$(document).ready(function(){$('#btnLogin').click(function(){if($('#username').val().trim()==''||$('#password').val().trim()==''){$('.login-errors').html('Username and/or password is required').show();return false;}
$('.login-errors').hide().html('');return true;});});$(document).ready(function(){$('.col-no-display').each(function(){var index=$(this).index();if(index>0){$('#manage-table tr').each(function(){$(this).find('td:eq('+index+')').hide();});$('#manage-table tfoot tr').find('th:eq('+index+')').hide();$('.col-no-display').hide();}});});$(document).ready(function(){$('#btnCreateCategory').click(function(){var text=$('#txtCat').val().trim();var regex=/\<[\S* ]*\>/;var alphaRegex=/[a-zA-Z]{1,}/;if(text.match(regex)!=null){showMessage('Category name entered is invalid');return;}
if(text.match(alphaRegex)==null){showMessage('Category name entered is invalid, should have at least 1 alphabet');return;}
if(text!=''&&text.length<=50){ajaxAddPartial(text);}
else{showMessage('Category name cannot be more than 50 characters');}});});function ajaxAddPartial(text){$.ajax({type:'GET',url:'/Admin/CategoryAdmin/AddCategoryPartial',data:{'categoryName':text,'token':$('#OneTimeCode').val()},dataType:'html',success:function(data){if(data.trim()!=''){$('#manage-table tbody tr:first').before(data);$('.add-msg').html('');var zeroRow=$('tr.manage-row');if(zeroRow.length==1){$(zeroRow).remove();}}
else{$('.add-msg').html('category already exists').show('slow');setTimeout(function(){$('.add-msg').html('');},2000);}
$('#txtCat').val('');},error:function(req,status,err){alert('an error occurred while trying to add the category entered, please try again.');}});}
$('.deactivateAuthor').live('click',function(e){e.preventDefault();var element=this;var url=$(element).attr('href')+"&token="+$('#OneTimeCode').val();$.ajax({type:'GET',url:url,dataType:'json',success:function(data){if(data==true){var newUrl=$(element).attr('href');var statusElement=$(element).parent().parent().find('td:eq(3)');if(newUrl.indexOf('currentStatus=1')>=0){$(element).html('activate');newUrl=newUrl.replace("currentStatus=1","currentStatus=0");$(element).attr('href',newUrl);$(statusElement).html('Inactive');}
else{$(element).html('deactivate');newUrl=newUrl.replace("currentStatus=0","currentStatus=1");$(element).attr('href',newUrl);$(statusElement).html('Active');}}},error:function(req,status,err){alert('an error occurred while trying activate/deactivate the selected author, please try again.');}});});$(function(){$('#username').focus(function(){$(this).val('');}).focusout(function(){if($(this).val()==''){$(this).val('username');}});$('#emailAddress').focus(function(){$(this).val('');}).focusout(function(){if($(this).val()==''){$(this).val('your email address');}});$('#fake-password').focus(function(){$(this).hide();$('#passwd').val('').show().focus();});$('#passwd').focusout(function(){if($(this).val()==''){$(this).val('password').hide();$('#fake-password').val('password').show();}});$('input:text,input:password').focus(function(){$(this).parent().next('.field-info').show();}).blur(function(){$(this).parent().next('.field-info').hide();});$('#showOptions').click(function(){$('.remember-me').toggle('slow');});$('#requestAccount').click(function(){$('#request-account').hide();$('#requestResults').html('');$('.request-form-content input:text,textarea').val('');resetValidation();$('.request-form').show();$('.request-form-content input:text:eq(0)').focus();});$('#sendRequest').click(function(e){e.preventDefault();var regex=/\<[\S* ]*\>/;var validateErrors=null;$('.validate-html').each(function(){if(validateErrors==null&&$(this).val().trim()!=''&&$(this).val().match(regex)!=null){validateErrors=this;}});if(validateErrors!=null){$(validateErrors).focus();alert('Field contains invalid content (like html tags)');return;}
$('#requestAccountFrm').submit();});$('.closeWindow,#closeForm').click(function(){showRequestAccountLink();});$(document).keyup(function(e){var requestForm=$('.request-form');if(requestForm.length==1&&e.keyCode==27){if($(requestForm).is(':visible')){showRequestAccountLink();}}});});function showRequestAccountLink(){$('.request-form').hide();$('#request-account').show();}
function resetValidation(){$('.request-form-content .input-validation-error').addClass('input-validation-valid');$('.request-form-content .input-validation-error').removeClass('input-validation-error');$('.request-form-content .field-validation-error').addClass('field-validation-valid');$('.request-form-content .field-validation-error').removeClass('field-validation-error');}
function savePostOrPage(){if(!canBeSavedPartially()){setTimeout(function(){savePostOrPage();},30000);return;}
if(!$('.privateChkBox').is(':checked')){$('.privateChkBox').trigger('click');}
var rUrl=($('#AjaxSaved').val().toLowerCase()=='true'||/(post\/edit)/i.test(document.location.href))?'edit':'add';var formData=$('form').serializeArray();$.ajax({type:'POST',url:siteRoot+'admin/post/'+rUrl,data:formData,dataType:'json',success:function(data){if(data.IsValid){$('#AjaxSaved').val(true);$('#Post_PostID').val(data.PostId);var msg='Saved a draft of your post at <b>'+getCurrentDateTime()+'</b>';$('#updateAjaxStatus').html(msg).show();}
setTimeout(function(){savePostOrPage();},30000);}});}
function canBeSavedPartially(){var postTitle=$('#Post_PostTitle').val();var postUrl=$('#Post_PostUrl').val();var pattern=/.*\S.*/;if(!pattern.test(postTitle)||!pattern.test(postUrl)){return false;}
return true;}
function getCurrentDateTime(){var now=new Date();var year=""+now.getFullYear();var month=""+(now.getMonth()+1);if(month.length==1){month="0"+month;}
var day=""+now.getDate();if(day.length==1){day="0"+day;}
var hour=""+now.getHours();if(hour.length==1){hour="0"+hour;}
var minute=""+now.getMinutes();if(minute.length==1){minute="0"+minute;}
var second=""+now.getSeconds();if(second.length==1){second="0"+second;}
return month+"/"+day+"/"+year+" "+hour+":"+minute+":"+second;}
function showHideMarkdownHelp(val){if(val=='markdown'){$('#markdownHelp').show();}else{$('#markdownHelp').hide();}}
|
module.exports = handler
module.exports.$config = {
category : 'controller'
, route : '/npm(?:-dl)?/:pkg/?'
}
const validName = require('../valid-name')
function handler (context, callback) {
var pkg = context.params.pkg.replace(/\/$/, '')
if (!validName(pkg)) {
context.model.message = 'Invalid npm package name (' + pkg + ')'
return callback(null, 'error')
}
context.response.writeHead(303, {
'location': 'https://npmjs.org/package/' + pkg
})
context.response.end()
}
|
import axios from 'axios'
import {CART_ADD_ITEM, CART_REMOVE_ITEM} from '../constants/cartConstants'
export const addToCart = (id, qty) => async (dispatch, getState) => {
const { data } = await axios.get(`/api/products/${id}`)
dispatch({
type: CART_ADD_ITEM,
payload: {
product: data._id,
name: data.name,
image: data.image,
price: data.price,
countInStock: data.countInStock,
qty,
}
})
localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems))
}
export const removeFromCart = (id) => (dispatch, getState) => {
dispatch({
type: CART_REMOVE_ITEM,
payload: id
})
localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems))
}
|
// @flow
import Action from './lib/Action';
// ======= WALLET BACKUP ACTIONS =======
export default class WalletBackupActions {
startWalletBackup: Action<any> = new Action();
initiateWalletBackup: Action<{
recoveryPhrase: Array<string>,
}> = new Action();
acceptPrivacyNoticeForWalletBackup: Action<any> = new Action();
continueToRecoveryPhraseForWalletBackup: Action<any> = new Action();
updateWalletBackupVerificationPhrase: Action<{
verificationPhrase: Array<string>,
}> = new Action();
acceptWalletBackupTermOffline: Action<any> = new Action();
acceptWalletBackupTermRecovery: Action<any> = new Action();
acceptWalletBackupTermRewards: Action<any> = new Action();
restartWalletBackup: Action<any> = new Action();
cancelWalletBackup: Action<any> = new Action();
finishWalletBackup: Action<any> = new Action();
}
|
/*!
* Copyright 2017 Telerik AD
*
* 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.
*/
(function(f){
if (typeof define === 'function' && define.amd) {
define(["kendo.core"], f);
} else {
f();
}
}(function(){
(function ($, undefined) {
/* FlatColorPicker messages */
if (kendo.ui.FlatColorPicker) {
kendo.ui.FlatColorPicker.prototype.options.messages =
$.extend(true, kendo.ui.FlatColorPicker.prototype.options.messages,{
"apply": "Alkalmaz",
"cancel": "Mégse",
"noColor": "nincs szín",
"clearColor": "Tiszta szín"
});
}
/* ColorPicker messages */
if (kendo.ui.ColorPicker) {
kendo.ui.ColorPicker.prototype.options.messages =
$.extend(true, kendo.ui.ColorPicker.prototype.options.messages,{
"apply": "Alkalmaz",
"cancel": "Mégse",
"noColor": "nincs szín",
"clearColor": "Tiszta szín"
});
}
/* ColumnMenu messages */
if (kendo.ui.ColumnMenu) {
kendo.ui.ColumnMenu.prototype.options.messages =
$.extend(true, kendo.ui.ColumnMenu.prototype.options.messages,{
"sortAscending": "Rendezés növekvő",
"sortDescending": "Rendezés csökkenő",
"filter": "Szűrés",
"columns": "Oszlopok",
"done": "Kész",
"settings": "Oszlopbeállítások",
"lock": "Rögzít",
"unlock": "Felold"
});
}
/* Editor messages */
if (kendo.ui.Editor) {
kendo.ui.Editor.prototype.options.messages =
$.extend(true, kendo.ui.Editor.prototype.options.messages,{
"bold": "Félkövér",
"italic": "Dőlt",
"underline": "Aláhúzott",
"strikethrough": "Áthúzott",
"superscript": "Felső index",
"subscript": "Alsó index",
"justifyCenter": "Középre igazítás",
"justifyLeft": "Balra igazítás",
"justifyRight": "Jobbra igazítás",
"justifyFull": "Sorkizárás",
"insertUnorderedList": "Számozatlan lista beszúrása",
"insertOrderedList": "Számozott lista beszúrása",
"indent": "Behúzás növelése",
"outdent": "Behúzás csökkentése",
"createLink": "Hivatkozás beszúrása",
"unlink": "Hivatkozás eltávolítása",
"insertImage": "Kép beszúrása",
"insertFile": "Fájl beszúrása",
"insertHtml": "HTML beszúrása",
"viewHtml": "HTML megtekintése",
"fontName": "Betűtípus választás",
"fontNameInherit": "(örökölt betűtípus)",
"fontSize": "Betűméret választás",
"fontSizeInherit": "(örökölt méret)",
"formatBlock": "Formátum",
"formatting": "Formázás",
"foreColor": "Tintaszín",
"backColor": "Háttérszín",
"style": "Stílusok",
"emptyFolder": "Üres mappa",
"uploadFile": "Feltöltés",
"orderBy": "Rendezés:",
"orderBySize": "Méret",
"orderByName": "Név",
"invalidFileType": "A fájl \"{0}\" nem megfelelő típusú. Támogatott fájltípusok: {1}.",
"deleteFile": "Biztos, hogy törli a fájlt: \"{0}\"?",
"overwriteFile": "A mappában már létezik \"{0}\" nevű fájl. Kívánja felülírni?",
"directoryNotFound": "Nincs ilyen nevű könyvtár.",
"imageWebAddress": "Webcím",
"imageAltText": "Alternatív szöveg",
"imageWidth": "Szélesség (px)",
"imageHeight": "Magasság (px)",
"fileWebAddress": "Webcím",
"fileTitle": "Cím",
"linkWebAddress": "Webcím",
"linkText": "Szöveg",
"linkToolTip": "Helyi súgó",
"linkOpenInNewWindow": "Megnyitás új ablakban",
"dialogUpdate": "Frissítés",
"dialogInsert": "Beszúrás",
"dialogButtonSeparator": "vagy",
"dialogCancel": "Mégse",
"cleanFormatting": "Formázás törlése",
"createTable": "Táblázat létrehozása",
"addColumnLeft": "Oszlop beszúrása balra",
"addColumnRight": "Oszlop beszúrása jobbra",
"addRowAbove": "Sor beszúrása fölé",
"addRowBelow": "Sor beszúrása alá",
"deleteRow": "Sor törlése",
"deleteColumn": "Oszlop törlése",
"dialogOk": "OK",
"tableWizard": "Tábla varázsló",
"tableTab": "Tábla",
"cellTab": "Cella",
"accessibilityTab": "Hozzáférhetőség",
"caption": "Szöveg",
"summary": "Összegzés",
"width": "Szélesség",
"height": "Magasság",
"cellSpacing": "Cella térköz",
"cellPadding": "Cella párnázás",
"cellMargin": "Cella margó",
"alignment": "Igazítás",
"background": "Háttér",
"cssClass": "CSS osztály",
"id": "ID",
"border": "Szegély",
"borderStyle": "Szegély stílusa",
"collapseBorders": "Keretek összeomlasztása",
"wrapText": "Szövegtörés",
"associateCellsWithHeaders": "Cellák társítása a fejlécekkel",
"alignLeft": "Balra igazítás",
"alignCenter": "Középre igazítás",
"alignRight": "Jobbra igazítás",
"alignLeftTop": "Igazítás balra és felülre",
"alignCenterTop": "Igazítás vízszintesen középre és felülre",
"alignRightTop": "Igazítás jobbra és felülre",
"alignLeftMiddle": "Igazítás balra és függőlegesen középre",
"alignCenterMiddle": "Igazítás vízszintesen és függőlegesen középre",
"alignRightMiddle": "Igazítás jobbra és függőlegesen középre",
"alignLeftBottom": "Igazítás balra és alulra",
"alignCenterBottom": "Igazítás vízszintesen középre és alulra",
"alignRightBottom": "Igazítás jobbra és alulra",
"alignRemove": "Igazítás törlése",
"columns": "Oszlopok",
"rows": "Sorok",
"selectAllCells": "Összes cella kiválasztása"
});
}
/* FileBrowser messages */
if (kendo.ui.FileBrowser) {
kendo.ui.FileBrowser.prototype.options.messages =
$.extend(true, kendo.ui.FileBrowser.prototype.options.messages,{
"uploadFile": "Feltöltés",
"orderBy": "Rendezés",
"orderByName": "Név",
"orderBySize": "Méret",
"directoryNotFound": "Nincs ilyen nevű könyvtár.",
"emptyFolder": "Üres könyvtár",
"deleteFile": "Biztos, hogy törli a fájlt: \"{0}\"?",
"invalidFileType": "A fájl \"{0}\" nem megfelelő típusú. Támogatott fájltípusok: {1}.",
"overwriteFile": "A mappában már létezik \"{0}\" nevű fájl. Kívánja felülírni?",
"dropFilesHere": "húzza ide a fájlt a feltöltéshez",
"search": "Keresés"
});
}
/* FilterCell messages */
if (kendo.ui.FilterCell) {
kendo.ui.FilterCell.prototype.options.messages =
$.extend(true, kendo.ui.FilterCell.prototype.options.messages,{
"isTrue": "igaz",
"isFalse": "hamis",
"filter": "Szűrés",
"clear": "Törlés",
"operator": "Művelet"
});
}
/* FilterCell operators */
if (kendo.ui.FilterCell) {
kendo.ui.FilterCell.prototype.options.operators =
$.extend(true, kendo.ui.FilterCell.prototype.options.operators,{
"string": {
"eq": "egyenlő",
"neq": "nem egyenlő",
"startswith": "kezdődik",
"contains": "tartalmazza",
"doesnotcontain": "nem tartalmazza",
"endswith": "végződik",
"isnull": "null",
"isnotnull": "nem null",
"isempty": "üres",
"isnotempty": "nem üres"
},
"number": {
"eq": "egyenlő",
"neq": "nem egyenlő",
"gte": "nagyobb vagy egyenlő",
"gt": "nagyobb",
"lte": "kisebb vagy egyenlő",
"lt": "kisebb",
"isnull": "null",
"isnotnull": "nem null"
},
"date": {
"eq": "egyenlő",
"neq": "nem egyenlő",
"gte": "utána vagy ekkor",
"gt": "utána",
"lte": "előtte vagy ekkor",
"lt": "előtte",
"isnull": "null",
"isnotnull": "nem null"
},
"enums": {
"eq": "egyenlő",
"neq": "nem egyenlő",
"isnull": "null",
"isnotnull": "nem null"
}
});
}
/* FilterMenu messages */
if (kendo.ui.FilterMenu) {
kendo.ui.FilterMenu.prototype.options.messages =
$.extend(true, kendo.ui.FilterMenu.prototype.options.messages,{
"info": "Megjelenítendő elemek értéke:",
"isTrue": "igaz",
"isFalse": "hamis",
"filter": "Szűrés",
"clear": "Törlés",
"and": "és",
"or": "vagy",
"selectValue": "-Válasszon-",
"operator": "Művelet",
"value": "Érték",
"cancel": "Mégse"
});
}
/* FilterMenu operator messages */
if (kendo.ui.FilterMenu) {
kendo.ui.FilterMenu.prototype.options.operators =
$.extend(true, kendo.ui.FilterMenu.prototype.options.operators,{
"string": {
"eq": "egyenlő",
"neq": "nem egyenlő",
"startswith": "kezdődik",
"contains": "tartalmazza",
"doesnotcontain": "nem tartalmazza",
"endswith": "végződik",
"isnull": "null",
"isnotnull": "nem null",
"isempty": "üres",
"isnotempty": "nem üres"
},
"number": {
"eq": "egyenlő",
"neq": "nem egyenlő",
"gte": "nagyobb vagy egyenlő",
"gt": "nagyobb",
"lte": "kisebb vagy egyenlő",
"lt": "kisebb",
"isnull": "null",
"isnotnull": "nem null"
},
"date": {
"eq": "egyenlő",
"neq": "nem egyenlő",
"gte": "utána vagy ekkor",
"gt": "utána",
"lte": "előtte vagy ekkor",
"lt": "előtte",
"isnull": "null",
"isnotnull": "nem null"
},
"enums": {
"eq": "egyenlő",
"neq": "nem egyenlő",
"isnull": "null",
"isnotnull": "nem null"
}
});
}
/* FilterMultiCheck messages */
if (kendo.ui.FilterMultiCheck) {
kendo.ui.FilterMultiCheck.prototype.options.messages =
$.extend(true, kendo.ui.FilterMultiCheck.prototype.options.messages,{
"checkAll": "Összes kijelölése",
"clear": "Törlés",
"filter": "Szűrés",
"search": "Keresés"
});
}
/* Gantt messages */
if (kendo.ui.Gantt) {
kendo.ui.Gantt.prototype.options.messages =
$.extend(true, kendo.ui.Gantt.prototype.options.messages,{
"actions": {
"addChild": "Gyermekelem hozzáadása",
"append": "Feladat hozzáadása",
"insertAfter": "Hozzáadás alá",
"insertBefore": "Hozzáadás fölé",
"pdf": "Exportálás PDF-be"
},
"cancel": "Mégse",
"deleteDependencyWindowTitle": "Függőség törlése",
"deleteTaskWindowTitle": "Feladat törlése",
"destroy": "Törlés",
"editor": {
"assingButton": "Hozzárendelés",
"editorTitle": "Feladat",
"end": "Vége",
"percentComplete": "Befejezés",
"resources": "Erőforrások",
"resourcesEditorTitle": "Erőforrások",
"resourcesHeader": "Erőforrások",
"start": "Indítás",
"title": "Cím",
"unitsHeader": "Egységek"
},
"save": "Mentés",
"views": {
"day": "nap",
"end": "vége",
"month": "hónap",
"start": "eleje",
"week": "hét",
"year": "év"
}
});
}
/* Grid messages */
if (kendo.ui.Grid) {
kendo.ui.Grid.prototype.options.messages =
$.extend(true, kendo.ui.Grid.prototype.options.messages,{
"commands": {
"cancel": "Módosítások elvetése",
"canceledit": "Mégse",
"create": "Új elem",
"destroy": "Törlés",
"edit": "Szerkesztés",
"excel": "Exportálás Excel-be",
"pdf": "Exportálás PDF-be",
"save": "Módosítások mentése",
"select": "Választás",
"update": "Frissítés"
},
"editable": {
"cancelDelete": "Mégse",
"confirmation": "Biztos, hogy törli az elemet?",
"confirmDelete": "Törlés"
},
"noRecords": "Nincsenek elérhető elemek."
});
}
/* TreeList messages */
if (kendo.ui.TreeList) {
kendo.ui.TreeList.prototype.options.messages =
$.extend(true, kendo.ui.TreeList.prototype.options.messages,{
"noRows": "Nincsenek megjeleníthető elemek",
"loading": "Betöltés...",
"requestFailed": "A kérés sikertelen.",
"retry": "Újra",
"commands": {
"edit": "Szerkesztés",
"update": "Frissítés",
"canceledit": "Mégse",
"create": "Új elem",
"createchild": "Gyermekelem hozzáadása",
"destroy": "Törlés",
"excel": "Exportálás Excel-be",
"pdf": "Exportálás PDF-be"
}
});
}
/* Groupable messages */
if (kendo.ui.Groupable) {
kendo.ui.Groupable.prototype.options.messages =
$.extend(true, kendo.ui.Groupable.prototype.options.messages,{
"empty": "Húzza ide az oszlopfejlécet a csoportosításhoz"
});
}
/* NumericTextBox messages */
if (kendo.ui.NumericTextBox) {
kendo.ui.NumericTextBox.prototype.options =
$.extend(true, kendo.ui.NumericTextBox.prototype.options,{
"upArrowText": "Érték növelése",
"downArrowText": "Érték csökkentése"
});
}
/* MediaPlayer messages */
if (kendo.ui.MediaPlayer) {
kendo.ui.MediaPlayer.prototype.options.messages =
$.extend(true, kendo.ui.MediaPlayer.prototype.options.messages,{
"pause": "Szünet",
"play": "Lejátszás",
"mute": "Némítás",
"unmute": "Némítás feloldása",
"quality": "Minőség",
"fullscreen": "Teljes képernyő"
});
}
/* Pager messages */
if (kendo.ui.Pager) {
kendo.ui.Pager.prototype.options.messages =
$.extend(true, kendo.ui.Pager.prototype.options.messages,{
"allPages": "Összes",
"display": "{0}-{1} a(z) {2} elemből",
"empty": "Nincsenek megjeleníthető elemek",
"page": "Oldal",
"of": "a(z) {0}",
"itemsPerPage": "elem / oldal",
"first": "Ugrás az első oldalra",
"previous": "Ugrás az előző oldalra",
"next": "Ugrás a következő oldalra",
"last": "Ugrás az utolsó oldalra",
"refresh": "Frissítés",
"morePages": "További oldalak"
});
}
/* PivotGrid messages */
if (kendo.ui.PivotGrid) {
kendo.ui.PivotGrid.prototype.options.messages =
$.extend(true, kendo.ui.PivotGrid.prototype.options.messages,{
"measureFields": "Húzza az adatelemeket ide",
"columnFields": "Húzza az oszlopelemeket ide",
"rowFields": "Húzza a sorelemeket ide"
});
}
/* PivotFieldMenu messages */
if (kendo.ui.PivotFieldMenu) {
kendo.ui.PivotFieldMenu.prototype.options.messages =
$.extend(true, kendo.ui.PivotFieldMenu.prototype.options.messages,{
"info": "Megjelenítendő elemek értéke:",
"filterFields": "Mezőszűrő",
"filter": "Szűrés",
"include": "Mezők befoglalása...",
"title": "Befoglalandó mezők",
"clear": "Törlés",
"ok": "OK",
"cancel": "Mégse",
"operators": {
"contains": "tartalmazza",
"doesnotcontain": "nem tartalmazza",
"startswith": "kezdődik",
"endswith": "végződik",
"eq": "egyenlő",
"neq": "nem egyenlő"
}
});
}
/* RecurrenceEditor messages */
if (kendo.ui.RecurrenceEditor) {
kendo.ui.RecurrenceEditor.prototype.options.messages =
$.extend(true, kendo.ui.RecurrenceEditor.prototype.options.messages,{
"frequencies": {
"never": "Soha",
"hourly": "Óránként",
"daily": "Naponta",
"weekly": "Hetente",
"monthly": "Havonta",
"yearly": "Évente"
},
"hourly": {
"repeatEvery": "Ismételje minden: ",
"interval": " óra(k)"
},
"daily": {
"repeatEvery": "Ismételje minden: ",
"interval": " nap(ok)"
},
"weekly": {
"interval": " hét(ek)",
"repeatEvery": "Ismételje minden: ",
"repeatOn": "Ismételje: "
},
"monthly": {
"repeatEvery": "Ismételje minden: ",
"repeatOn": "Ismételje: ",
"interval": " hónap(ok)",
"day": "nap "
},
"yearly": {
"repeatEvery": "Ismételje minden: ",
"repeatOn": "Ismételje: ",
"interval": " év(ek)",
"of": " a(z) "
},
"end": {
"label": "Vége:",
"mobileLabel": "Végződik",
"never": "Soha",
"after": "Után ",
"occurrence": " előfordulás(ok)",
"on": "Ekkor: "
},
"offsetPositions": {
"first": "első",
"second": "második",
"third": "harmadik",
"fourth": "negyedik",
"last": "utolsó"
},
"weekdays": {
"day": "nap",
"weekday": "munkanap",
"weekend": "pihenőnap"
}
});
}
/* Scheduler messages */
if (kendo.ui.Scheduler) {
kendo.ui.Scheduler.prototype.options.messages =
$.extend(true, kendo.ui.Scheduler.prototype.options.messages,{
"allDay": "egész nap",
"date": "Dátum",
"event": "Esemény",
"time": "Idő",
"showFullDay": "Teljes nap mutatása",
"showWorkDay": "Munkaórák mutatása",
"today": "Ma",
"save": "Mentés",
"cancel": "Mégse",
"destroy": "Törlés",
"deleteWindowTitle": "Esemény törlése",
"ariaSlotLabel": "Kiválasztva {0:t}-tól {1:t}-ig",
"ariaEventLabel": "{0} {1:D} {2:t}",
"editable": {
"confirmation": "Biztos, hogy törölni akarja az eseményt?"
},
"views": {
"day": "nap",
"week": "Hét",
"workWeek": "Munkahét",
"agenda": "Naptár",
"month": "Hónap"
},
"recurrenceMessages": {
"deleteWindowTitle": "Ismétlődő elem törlése",
"deleteWindowOccurrence": "Alkalom törlése",
"deleteWindowSeries": "Összes ismétlődés törlése",
"editWindowTitle": "Ismétlődő elem szerkesztése",
"editWindowOccurrence": "Alkalom szerkesztése",
"editWindowSeries": "Összes ismétlődés szerkesztése",
"deleteRecurring": "Csak ezt az alkalmat szeretné törölni, vagy az összes ismétlődést?",
"editRecurring": "Csak ezt az alkalmat szeretné szerkeszteni, vagy az összes ismétlődést?"
},
"editor": {
"title": "Cím",
"start": "Kezdés",
"end": "Befejezés",
"allDayEvent": "Egész napos esemény",
"description": "Leírás",
"repeat": "Ismétlődés",
"timezone": " ",
"startTimezone": "Kezdés időzónája",
"endTimezone": "Befejezés időzónája",
"separateTimezones": "A kezdés és a befejezés időzónája eltérő",
"timezoneEditorTitle": "Időzónák",
"timezoneEditorButton": "Időzóna",
"timezoneTitle": "Időzónák",
"noTimezone": "Nincs időzóna",
"editorTitle": "Esemény"
}
});
}
/* Spreadsheet messages */
if (kendo.spreadsheet && kendo.spreadsheet.messages.borderPalette) {
kendo.spreadsheet.messages.borderPalette =
$.extend(true, kendo.spreadsheet.messages.borderPalette,{
"allBorders": "Minden szegély",
"insideBorders": "Belső szegélyek",
"insideHorizontalBorders": "Belső vízszintes szegélyek",
"insideVerticalBorders": "Belső függőleges szegélyek",
"outsideBorders": "Külső szegélyek",
"leftBorder": "Bal szegély",
"topBorder": "Felső szegély",
"rightBorder": "Jobb szegély",
"bottomBorder": "Alsó szegély",
"noBorders": "Nincs szegély",
"reset": "Alapértelmezett szín",
"customColor": "Egyéni szín...",
"apply": "Alkalmaz",
"cancel": "Mégse"
});
}
if (kendo.spreadsheet && kendo.spreadsheet.messages.dialogs) {
kendo.spreadsheet.messages.dialogs =
$.extend(true, kendo.spreadsheet.messages.dialogs,{
"apply": "Alkalmaz",
"save": "Mentés",
"cancel": "Mégse",
"remove": "Eltávolítás",
"retry": "Újra",
"revert": "Visszaállítás",
"okText": "OK",
"formatCellsDialog": {
"title": "Formázás",
"categories": {
"number": "Szám",
"currency": "Pénznem",
"date": "Dátum"
}
},
"fontFamilyDialog": {
"title": "Betűtípus"
},
"fontSizeDialog": {
"title": "Betűméret"
},
"bordersDialog": {
"title": "Szegélyek"
},
"alignmentDialog": {
"title": "Igazítás",
"buttons": {
"justtifyLeft": "Balra igazítás",
"justifyCenter": "Középre igazítás",
"justifyRight": "Jobbra igazítás",
"justifyFull": "Sorkizárás",
"alignTop": "Függőleges igazítás felülre",
"alignMiddle": "Függőleges igazítás középre",
"alignBottom": "Függőleges igazítás alulra"
}
},
"mergeDialog": {
"title": "Cellaegyesítés",
"buttons": {
"mergeCells": "Összes egyesítése",
"mergeHorizontally": "Egyesítés vízszintesen",
"mergeVertically": "Egyesítés függőlegesen",
"unmerge": "Szétválasztás"
}
},
"freezeDialog": {
"title": "Ablaktábla rögzítése",
"buttons": {
"freezePanes": "Ablaktábla rögzítése",
"freezeRows": "Sorok rögzítése",
"freezeColumns": "Oszlopok rögzítése",
"unfreeze": "Rögzítés feloldása"
}
},
"confirmationDialog": {
"text": "Biztos, hogy törli ezt a munkalapot?",
"title": "Munkalap törlése"
},
"validationDialog": {
"title": "Adatellenőrzés",
"hintMessage": "Kérem, írjon be egy érvényes {0} értéket {1}.",
"hintTitle": "Ellenőrzés {0}",
"criteria": {
"any": "Bármely érték",
"number": "Szám",
"text": "Szöveg",
"date": "Dátum",
"custom": "Egyéni szabály",
"list": "Lista"
},
"comparers": {
"greaterThan": "nagyobb, mint",
"lessThan": "kisebb, mint",
"between": "a következők közé esik",
"notBetween": "nem esik a következők közé",
"equalTo": "egyenlő",
"notEqualTo": "nem egyenlő",
"greaterThanOrEqualTo": "nagyobb vagy egyenlő",
"lessThanOrEqualTo": "kisebb vagy egyenlő"
},
"comparerMessages": {
"greaterThan": "nagyobb, mint {0}",
"lessThan": "kisebb, mint {0}",
"between": "{0} és {1} közé esik",
"notBetween": "nem esik {0} és {1} közé",
"equalTo": "egyenlő {0}",
"notEqualTo": "nem egyenlő {0}",
"greaterThanOrEqualTo": "nagyobb vagy egyenlő {0}",
"lessThanOrEqualTo": "kisebb vagy egyenlő {0}",
"custom": "megfelel a képletnek: {0}"
},
"labels": {
"criteria": "Feltétel",
"comparer": "Összehasonlító",
"min": "Minimum",
"max": "Maximum",
"value": "Érték",
"start": "Kezdés",
"end": "Befejezés",
"onInvalidData": "Érvénytelen adat beírásakor",
"rejectInput": "Bevitel visszautasítása",
"showWarning": "Figyelmeztetés megjelenítése",
"showHint": "Javaslat megjelenítése",
"hintTitle": "Javaslat címe",
"hintMessage": "Javaslat szövege",
"ignoreBlank": "Üres cellák mellőzése"
},
"placeholders": {
"typeTitle": "Típus cím",
"typeMessage": "Típus üzenet"
}
},
"saveAsDialog": {
"title": "Mentés másként...",
"labels": {
"fileName": "Fájlnév",
"saveAsType": "Fájl típusa"
}
},
"exportAsDialog": {
"title": "Exportálás...",
"labels": {
"fileName": "Fájlnév",
"saveAsType": "Fájl típusa",
"exportArea": "Exportálás",
"paperSize": "Papírméret",
"margins": "Margók",
"orientation": "Tájolás",
"print": "Nyomtatás",
"guidelines": "Segédvonalak",
"center": "Középre",
"horizontally": "Vízszintesen",
"vertically": "Függőlegesen"
}
},
"modifyMergedDialog": {
"errorMessage": "Nem lehet módosítani az egyesített cella egy részét."
},
"useKeyboardDialog": {
"title": "Másolás és beillesztés",
"errorMessage": "Ezek a műveletek nem érhetők el a menüből. Kérem, használja a következő billentyűkombinációkat:",
"labels": {
"forCopy": "másoláshoz",
"forCut": "kivágáshoz",
"forPaste": "beillesztéshez"
}
},
"unsupportedSelectionDialog": {
"errorMessage": "A művelet nem hajtható végre többes kijelölésen."
}
});
}
if (kendo.spreadsheet && kendo.spreadsheet.messages.filterMenu) {
kendo.spreadsheet.messages.filterMenu =
$.extend(true, kendo.spreadsheet.messages.filterMenu,{
"sortAscending": "Tartomány rendezése A-Z",
"sortDescending": "Tartomány rendezése Z-A",
"filterByValue": "Szűrés érték szerint",
"filterByCondition": "Szűrés feltétel alapján",
"apply": "Alkalmaz",
"search": "Keresés",
"addToCurrent": "Hozzáadás az aktuális kijelöléshez",
"clear": "Törlés",
"blanks": "(Üresek)",
"operatorNone": "Egyik sem",
"and": "és",
"or": "vagy",
"operators": {
"string": {
"contains": "A szöveg tartalmazza",
"doesnotcontain": "A szöveg nem tartalmazza",
"startswith": "A szöveg eleje",
"endswith": "A szöveg vége"
},
"date": {
"eq": "A dátum",
"neq": "A dátum nem",
"lt": "Ezen dátum előtt",
"gt": "Ezen dátum után"
},
"number": {
"eq": "egyenlő",
"neq": "nem egyenlő",
"gte": "nagyobb vagy egyenlő",
"gt": "nagyobb",
"lte": "kisebb vagy egyenlő",
"lt": "kisebb"
}
}
});
}
if (kendo.spreadsheet && kendo.spreadsheet.messages.toolbar) {
kendo.spreadsheet.messages.toolbar =
$.extend(true, kendo.spreadsheet.messages.toolbar,{
"addColumnLeft": "Oszlop hozzáadása balra",
"addColumnRight": "Oszlop hozzáadása jobbra",
"addRowAbove": "Sor hozzáadása fölé",
"addRowBelow": "Sor hozzáadása alá",
"alignment": "Igazítás",
"alignmentButtons": {
"justtifyLeft": "Balra igazítás",
"justifyCenter": "Középre igazítás",
"justifyRight": "Jobbra igazítás",
"justifyFull": "Sorkizárás",
"alignTop": "Függőleges igazítás felülre",
"alignMiddle": "Függőleges igazítás középre",
"alignBottom": "Függőleges igazítás alulra"
},
"backgroundColor": "Kitöltőszín",
"bold": "Félkövér",
"borders": "Szegélyek",
"colorPicker": {
"reset": "Alapértelmezett szín",
"customColor": "Egyéni szín..."
},
"copy": "Másolás",
"cut": "Kivágás",
"deleteColumn": "Oszlop törlése",
"deleteRow": "Sor törlése",
"excelImport": "Importálás Excel-ből...",
"filter": "Szűrés",
"fontFamily": "Betűtípus",
"fontSize": "Betűméret",
"format": "Egyéni formátum...",
"formatTypes": {
"automatic": "Automatikus",
"number": "Szám",
"percent": "Százalék",
"financial": "Könyvelési",
"currency": "Pénznem",
"date": "Dátum",
"time": "Idő",
"dateTime": "Dátum-idő",
"duration": "Időtartam",
"moreFormats": "Egyéb formátum..."
},
"formatDecreaseDecimal": "Tizedeshelyek csökkentése",
"formatIncreaseDecimal": "Tizedeshelyek növelése",
"freeze": "Ablaktábla rögzítése",
"freezeButtons": {
"freezePanes": "Ablaktábla rögzítése",
"freezeRows": "Sorok rögzítése",
"freezeColumns": "Oszlopok rögzítése",
"unfreeze": "Rögzítés feloldása"
},
"italic": "Dőlt",
"merge": "Cellaegyesítés",
"mergeButtons": {
"mergeCells": "Összes egyesítése",
"mergeHorizontally": "Egyesítés vízszintesen",
"mergeVertically": "Egyesítés függőlegesen",
"unmerge": "Szétválasztás"
},
"open": "Megnyitás...",
"paste": "Beillesztés",
"quickAccess": {
"redo": "Mégis",
"undo": "Visszavonás"
},
"saveAs": "Mentés másként...",
"sortAsc": "Rendezés növekvő",
"sortDesc": "Rendezés csökkenő",
"sortButtons": {
"sortSheetAsc": "Munkalap rendezése A-Z",
"sortSheetDesc": "Munkalap rendezése Z-A",
"sortRangeAsc": "Tartomány rendezése A-Z",
"sortRangeDesc": "Tartomány rendezése Z-A"
},
"textColor": "Tintaszín",
"textWrap": "Szöveg törése több sorba",
"underline": "Aláhúzott",
"validation": "Adatellenőrzés..."
});
}
if (kendo.spreadsheet && kendo.spreadsheet.messages.view) {
kendo.spreadsheet.messages.view =
$.extend(true, kendo.spreadsheet.messages.view,{
"errors": {
"shiftingNonblankCells": "Adatvesztés nélkül nem lehet a cellákat beszúrni. Válasszon másik beszúrási pozíciót, vagy törölje az adatokat a munkalap végéről.",
"filterRangeContainingMerges": "Nem lehet szűrőt készíteni összevonásokat tartalmazó tartományon belül",
"validationError": "A beírt érték megsérti a cellára beállított adatellenőrzési szabályokat."
},
"tabs": {
"home": "Elejére",
"insert": "Beszúrás",
"data": "Adat"
}
});
}
/* Slider messages */
if (kendo.ui.Slider) {
kendo.ui.Slider.prototype.options =
$.extend(true, kendo.ui.Slider.prototype.options,{
"increaseButtonTitle": "Növelés",
"decreaseButtonTitle": "Csökkentés"
});
}
/* TreeList messages */
if (kendo.ui.TreeList) {
kendo.ui.TreeList.prototype.options.messages =
$.extend(true, kendo.ui.TreeList.prototype.options.messages,{
"noRows": "Nincsenek megjeleníthető elemek",
"loading": "Betöltés...",
"requestFailed": "A kérés sikertelen",
"retry": "Újra",
"commands": {
"edit": "Szerkesztés",
"update": "Frissítés",
"canceledit": "Mégse",
"create": "Új elem",
"createchild": "Gyermekelem hozzáadása",
"destroy": "Törlés",
"excel": "Exportálás Excel-be",
"pdf": "Exportálás PDF-be"
}
});
}
if (kendo.ui.TreeList) {
kendo.ui.TreeList.prototype.options.columnMenu =
$.extend(true, kendo.ui.TreeList.prototype.options.columnMenu, {
"messages": {
"columns": "Oszlopválasztás",
"filter": "Szűrés",
"sortAscending": "Rendezés (növekvő)",
"sortDescending": "Rendezés (csökkenő)"
}
});
}
/* TreeView messages */
if (kendo.ui.TreeView) {
kendo.ui.TreeView.prototype.options.messages =
$.extend(true, kendo.ui.TreeView.prototype.options.messages,{
"loading": "Betöltés...",
"requestFailed": "A kérés sikertelen",
"retry": "Újra"
});
}
/* Upload messages */
if (kendo.ui.Upload) {
kendo.ui.Upload.prototype.options.localization=
$.extend(true, kendo.ui.Upload.prototype.options.localization,{
"select": "Választás...",
"cancel": "Mégse",
"retry": "Újra",
"remove": "Eltávolítás",
"clearSelectedFiles": "Törlés",
"uploadSelectedFiles": "Fájlok feltöltése",
"dropFilesHere": "húzza ide a feltöltendő fájlokat",
"statusUploading": "feltöltés",
"statusUploaded": "feltöltve",
"statusWarning": "figyelem",
"statusFailed": "sikertelen",
"headerStatusUploading": "Feltöltés...",
"headerStatusUploaded": "Kész",
"invalidMaxFileSize": "A fájl túl nagy.",
"invalidMinFileSize": "A fájl túl kicsi.",
"invalidFileExtension": "A fájltípus nem engedélyezett."
});
}
/* Validator messages */
if (kendo.ui.Validator) {
kendo.ui.Validator.prototype.options.messages =
$.extend(true, kendo.ui.Validator.prototype.options.messages,{
"required": "{0} szükséges",
"pattern": "{0} érvénytelen",
"min": "{0} nagyobb vagy egyenlő kell hogy legyen, mint {1}",
"max": "{0} kisebb vagy egyenlő kell hogy legyen, mint {1}",
"step": "{0} érvénytelen",
"email": "{0} érvénytelen email",
"url": "{0} érvénytelen URL",
"date": "{0} érvénytelen dátum",
"dateCompare": "A végdátum nagyobb vagy egyenlő kell hogy legyen, mint a kezdődátum"
});
}
/* kendo.ui.progress method */
if (kendo.ui.progress) {
kendo.ui.progress.messages =
$.extend(true, kendo.ui.progress.messages, {
loading: "Betöltés..."
});
}
/* Dialog */
if (kendo.ui.Dialog) {
kendo.ui.Dialog.prototype.options.messages =
$.extend(true, kendo.ui.Dialog.prototype.options.localization, {
"close": "Bezárás"
});
}
/* Alert */
if (kendo.ui.Alert) {
kendo.ui.Alert.prototype.options.messages =
$.extend(true, kendo.ui.Alert.prototype.options.localization, {
"okText": "OK"
});
}
/* Confirm */
if (kendo.ui.Confirm) {
kendo.ui.Confirm.prototype.options.messages =
$.extend(true, kendo.ui.Confirm.prototype.options.localization, {
"okText": "OK",
"cancel": "Mégse"
});
}
/* Prompt */
if (kendo.ui.Prompt) {
kendo.ui.Prompt.prototype.options.messages =
$.extend(true, kendo.ui.Prompt.prototype.options.localization, {
"okText": "OK",
"cancel": "Mégse"
});
}
})(window.kendo.jQuery);
}));
|
const mongoose = require('mongoose');
const AtmSchema = new mongoose.Schema({
STREET_ADDRESS: String,
LOCATION: {
X: Number,
Y: Number,
},
ZIP: Number,
ATM_DEPOSIT: {
type: Boolean,
},
TRANSACTIONS: {},
CURRENCY: {
}
});
module.exports = mongoose.model('Atm', AtmSchema);
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.optionsDto = void 0;
const class_validator_1 = require("class-validator");
class optionsDto {
}
__decorate([
class_validator_1.IsNotEmpty(),
__metadata("design:type", String)
], optionsDto.prototype, "name", void 0);
__decorate([
class_validator_1.IsNotEmpty(),
__metadata("design:type", String)
], optionsDto.prototype, "value", void 0);
__decorate([
class_validator_1.IsNotEmpty(),
__metadata("design:type", String)
], optionsDto.prototype, "questions_id", void 0);
__decorate([
class_validator_1.IsNotEmpty(),
__metadata("design:type", Number)
], optionsDto.prototype, "score_value", void 0);
exports.optionsDto = optionsDto;
//# sourceMappingURL=options.dto.js.map
|
module.exports = {
'twitter-login': {
'provider': 'twitter',
'module': 'passport-twitter',
'consumerKey': process.env.CONSUMER_KEY,
'consumerSecret': process.env.CONSUMER_SECRET,
'callbackURL': `${process.env.BASE_URL}/api/auth/twitter/callback`,
'authPath': '/api/auth/twitter',
'callbackPath': '/api/auth/twitter/callback',
'successRedirect': '/api/auth/account'
}
}
|
import React from 'react'
import "./index.css";
import { Link } from 'react-router-dom';
const Todo = ({title, id, completed, showCompleted}) => {
return (
<li className={completed && showCompleted ? "checked" : ""}><Link to={`/todos/${id}`}>{title} <span className="close"></span></Link></li>
)
}
export default Todo
|
module.exports = class Cover {
constructor(plugin) {
// create element structure
//#region I am sorry... I know... I am lazy
this.muted = plugin.settings.get('muted', false);
this.plugin = plugin;
this.container = document.createElement('div');
this.container.setAttribute("id", 'pradio-modal');
let sub = document.createElement("div");
sub.classList.add('container-3baos1');
let avatarWrapper = document.createElement("div");
avatarWrapper.classList.add('avatarWrapper-2yR4wp');
this.image = document.createElement("img");
this.image.classList.add('avatar-SmRMf2', 'pradio-cover');
let nametag = document.createElement("div");
nametag.classList.add('nameTag-3uD-yy');
nametag.setAttribute("role", "button");
nametag.setAttribute("tabindex", "0");
let nametagSub = document.createElement("div");
nametagSub.classList.add('colorStandard-2KCXvj', 'size14-e6ZScH', 'pradio-title');
this.title = document.createElement("div");
this.title.classList.add('size14-e6ZScH', 'title-eS5yk3');
this.artist = document.createElement("div");
this.artist.classList.add('size12-3cLvbJ', 'subtext-3CDbHg', 'pradio-artist');
let muteContainer = document.createElement("div");
muteContainer.classList.add("flex-1xMQg5", "flex-1O1GKY", "horizontal-1ae9ci", "horizontal-2EEEnY", "flex-1O1GKY", "directionRow-3v3tfG", "justifyStart-2NDFzi", "alignStretch-DpGPf3", "noWrap-3jynv6");
muteContainer.setAttribute("style", "flex: 0 1 auto");
this.muteButton = document.createElement("button");
this.muteButton.classList.add("button-14-BFJ", "enabled-2cQ-u7", "button-38aScr", "lookBlank-3eh9lL", "colorBrand-3pXr91", "grow-q77ONN");
muteContainer.appendChild(this.muteButton);
let muteIconContainer = document.createElement("div");
muteIconContainer.classList.add("contents-18-Yxp");
this.muteButton.appendChild(muteIconContainer);
muteIconContainer.innerHTML = `<svg id="pradio-mute-button" aria-hidden="false" width="24" height="24" viewBox="0 0 24 24"><path fill="currentColor" fill-rule="evenodd" clip-rule="evenodd" d="M11.383 3.07904C11.009 2.92504 10.579 3.01004 10.293 3.29604L6 8.00204H3C2.45 8.00204 2 8.45304 2 9.00204V15.002C2 15.552 2.45 16.002 3 16.002H6L10.293 20.71C10.579 20.996 11.009 21.082 11.383 20.927C11.757 20.772 12 20.407 12 20.002V4.00204C12 3.59904 11.757 3.23204 11.383 3.07904ZM14 5.00195V7.00195C16.757 7.00195 19 9.24595 19 12.002C19 14.759 16.757 17.002 14 17.002V19.002C17.86 19.002 21 15.863 21 12.002C21 8.14295 17.86 5.00195 14 5.00195ZM14 9.00195C15.654 9.00195 17 10.349 17 12.002C17 13.657 15.654 15.002 14 15.002V13.002C14.551 13.002 15 12.553 15 12.002C15 11.451 14.551 11.002 14 11.002V9.00195Z" aria-hidden="true"></path></svg>`;
avatarWrapper.appendChild(this.image);
sub.appendChild(avatarWrapper);
nametagSub.appendChild(this.title);
nametag.appendChild(nametagSub);
nametag.appendChild(this.artist);
sub.appendChild(nametag);
sub.appendChild(muteContainer);
this.container.appendChild(sub);
this.image.setAttribute("width", "32");
this.image.setAttribute("height", "32");
this.image.setAttribute("style", "border-radius: 50%");
//#endregion
}
onMuteChanged(callback) {
this.muteCallback = callback;
}
setImg(src) {
this.image.src = src;
}
setTitle(title) {
this.title.innerText = title;
}
setArtist(artist) {
this.artist.innerText = artist;
}
inject() {
let parent = document.querySelector(`section.panels-j1Uci_`);
parent.insertBefore(this.container, parent.lastChild)
// verify injection
let injectionValid = () => document.querySelector(`div#pradio-modal`) != null;
let handle = () => {
if (!injectionValid()) {
try { this.inject(); } catch (e) { console.log(e); }
console.log(`%c[PRadio]`, `color:yellow;`, `Injecting cover...`);
}
let svg = document.querySelector(`svg#pradio-mute-button`);
if (!this.muted) {
svg.classList.remove("colorDanger-2qLCe1");
} else {
svg.classList.add("colorDanger-2qLCe1");
}
// mute button event
this.muteButton.onclick = () => {
this.muted = !this.muted;
let svg = document.querySelector(`svg#pradio-mute-button`);
if (!this.muted) {
svg.classList.remove("colorDanger-2qLCe1");
} else {
svg.classList.add("colorDanger-2qLCe1");
}
if (this.muteCallback) this.muteCallback(this.muted);
this.plugin.settings.set('muted', this.muted);
};
};
handle();
document.addEventListener("readystatechange", () => {
if (document.readyState == "complete") handle();
});
}
uninject() {
let parent = document.querySelector(`section.panels-j1Uci_`);
let container = document.querySelector(`div#pradio-modal`);
try { parent.removeChild(container); } catch (e) { console.log(`%c[PRadio/Warn]`, `color:orange;`, `Failed to remove child! This error might be okay.`); }
//this.container.remove();
}
}
|
H5.merge(new System.Globalization.CultureInfo("eo-001", true), {
englishName: "Esperanto (World)",
nativeName: "esperanto (World)",
numberFormat: H5.merge(new System.Globalization.NumberFormatInfo(), {
nanSymbol: "NaN",
negativeSign: "-",
positiveSign: "+",
negativeInfinitySymbol: "-∞",
positiveInfinitySymbol: "∞",
percentSymbol: "%",
percentGroupSizes: [3],
percentDecimalDigits: 2,
percentDecimalSeparator: ",",
percentGroupSeparator: " ",
percentPositivePattern: 1,
percentNegativePattern: 1,
currencySymbol: "XDR",
currencyGroupSizes: [3],
currencyDecimalDigits: 2,
currencyDecimalSeparator: ",",
currencyGroupSeparator: " ",
currencyNegativePattern: 9,
currencyPositivePattern: 2,
numberGroupSizes: [3],
numberDecimalDigits: 2,
numberDecimalSeparator: ",",
numberGroupSeparator: " ",
numberNegativePattern: 1
}),
dateTimeFormat: H5.merge(new System.Globalization.DateTimeFormatInfo(), {
abbreviatedDayNames: ["di","lu","ma","me","ĵa","ve","sa"],
abbreviatedMonthGenitiveNames: ["jan","feb","mar","apr","maj","jun","jul","aŭg","sep","okt","nov","dec",""],
abbreviatedMonthNames: ["jan","feb","mar","apr","maj","jun","jul","aŭg","sep","okt","nov","dec",""],
amDesignator: "atm",
dateSeparator: "-",
dayNames: ["dimanĉo","lundo","mardo","merkredo","ĵaŭdo","vendredo","sabato"],
firstDayOfWeek: 1,
fullDateTimePattern: "dddd, d-'a' 'de' MMMM yyyy HH:mm:ss",
longDatePattern: "dddd, d-'a' 'de' MMMM yyyy",
longTimePattern: "HH:mm:ss",
monthDayPattern: "MMMM d",
monthGenitiveNames: ["januaro","februaro","marto","aprilo","majo","junio","julio","aŭgusto","septembro","oktobro","novembro","decembro",""],
monthNames: ["januaro","februaro","marto","aprilo","majo","junio","julio","aŭgusto","septembro","oktobro","novembro","decembro",""],
pmDesignator: "ptm",
rfc1123: "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
shortDatePattern: "yyyy-MM-dd",
shortestDayNames: ["di","lu","ma","me","ĵa","ve","sa"],
shortTimePattern: "HH:mm",
sortableDateTimePattern: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
sortableDateTimePattern1: "yyyy'-'MM'-'dd",
timeSeparator: ":",
universalSortableDateTimePattern: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
yearMonthPattern: "yyyy MMMM",
roundtripFormat: "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffzzz"
}),
TextInfo: H5.merge(new System.Globalization.TextInfo(), {
ANSICodePage: 0,
CultureName: "eo-001",
EBCDICCodePage: 500,
IsRightToLeft: false,
LCID: 4096,
listSeparator: ";",
MacCodePage: 2,
OEMCodePage: 1,
IsReadOnly: true
})
});
|
import { createView, createRoute } from '../frame/index';
import { formatFilename } from '../../utils/formatFilename';
import { createElement } from '../../utils/createElement';
import { text } from '../../utils/text';
import { file } from './file';
import { applyFilters } from '../../filter';
/**
* Creates the file view
*/
const create = ({ root, props }) => {
// filename
root.ref.fileName = createElement('legend');
root.appendChild(root.ref.fileName);
// file appended
root.ref.file = root.appendChildView(
root.createChildView(file, { id: props.id })
);
// create data container
const dataContainer = createElement('input');
dataContainer.type = 'hidden';
dataContainer.name = root.query('GET_NAME');
dataContainer.disabled = root.query('GET_DISABLED');
root.ref.data = dataContainer;
root.appendChild(dataContainer);
};
const didSetDisabled = ({ root }) => {
root.ref.data.disabled = root.query('GET_DISABLED');
}
/**
* Data storage
*/
const didLoadItem = ({ root, action, props }) => {
root.ref.data.value = action.serverFileReference;
// updates the legend of the fieldset so screenreaders can better group buttons
text(
root.ref.fileName,
formatFilename(root.query('GET_ITEM_NAME', props.id))
);
};
const didRemoveItem = ({ root }) => {
root.ref.data.removeAttribute('value');
};
const didCompleteItemProcessing = ({ root, action }) => {
root.ref.data.value = action.serverFileReference;
};
const didRevertItemProcessing = ({ root }) => {
root.ref.data.removeAttribute('value');
};
export const fileWrapper = createView({
create,
ignoreRect: true,
write: createRoute({
DID_SET_DISABLED: didSetDisabled,
DID_LOAD_ITEM: didLoadItem,
DID_REMOVE_ITEM: didRemoveItem,
DID_COMPLETE_ITEM_PROCESSING: didCompleteItemProcessing,
DID_REVERT_ITEM_PROCESSING: didRevertItemProcessing
}),
didCreateView: root => {
applyFilters('CREATE_VIEW', { ...root, view: root });
},
tag: 'fieldset',
name: 'file-wrapper'
});
|
import { matcherHint, printExpected, printReceived } from 'jest-matcher-utils';
import predicate from './predicate';
const passMessage = received => () =>
matcherHint('.not.toBeDidCoreDatetime', 'received', '') +
'\n\n' +
'Expected value to not be of a valid DID Core Datetime received:\n' +
` ${printReceived(received)}`;
const failMessage = received => () =>
matcherHint('.toBeDidCoreDatetime', 'received', '') +
'\n\n' +
'Expected value to be of a valid DID Core Datetime, but received:\n' +
` ${printReceived(received)}`;
export default {
toBeDidCoreDatetime: expected => {
const pass = predicate(expected);
if (pass) {
return { pass: true, message: passMessage(expected) };
}
return { pass: false, message: failMessage(expected) };
},
isDidCoreDatetime: obj => {
return predicate(obj);
}
};
|
// Copyright (c) 2009-2017 SAP SE, All Rights Reserved
/**
* @fileOverview QUnit tests for sap.ushell.components.HeaderManager
*/
sap.ui.require([
"jquery.sap.global",
"sap/ui/core/IconPool",
"sap/ushell/ui/ShellHeader",
"sap/ushell/ui/shell/ShellAppTitle",
"sap/ushell/ui/shell/ShellHeadItem"
], function (jQuery, IconPool, ShellHeader, ShellAppTitle, ShellHeadItem) {
"use strict";
/* global QUnit, sinon */
// for the AppTitle control
sap.ushell.Container = {
getService: function () {
return {
isEnabled: function () {
return true;
}
};
}
};
var oShellHeader;
QUnit.module("basic test", {
beforeEach: function (assert) {
var done = assert.async();
var delegate = {
onAfterRendering: function () {
oShellHeader.removeDelegate(delegate);
done();
}
};
if (oShellHeader) {
oShellHeader.destroy();
}
oShellHeader = new ShellHeader("shell-header", {
logo: jQuery.sap.getModulePath("sap.ushell") + '/themes/base/img/sap_55x27.png',
showLogo: true,
visible: true,
headItems: [
new ShellHeadItem("backBtn", {icon: IconPool.getIconURI("back"), ariaLabel: "Back"})
],
headEndItems: [
new ShellHeadItem("sf", {icon: IconPool.getIconURI("search"), ariaLabel: "Search"})
],
title: "Subtitle with a long text",
appTitle: new ShellAppTitle("shellAppTitle", { text: "AppTitle with a long text" }),
search: new sap.m.Input()
});
oShellHeader.createUIArea("canvas");
oShellHeader.addDelegate(delegate);
},
afterEach: {
}
});
QUnit.test("Logo linked if not on homepage, navigate home", function (assert) {
var done = assert.async();
var oDelegate = {
onAfterRendering: function () {
oShellHeader.removeDelegate(oDelegate);
assert.equal(jQuery(".sapUshellShellIco").attr("href"), "#Shell-home", "Logo is linked");
assert.equal(jQuery(".sapUshellShellIco").attr("tabindex"), 0, "Tabindex is set correct for logo");
assert.equal(jQuery(".sapUshellShellIco").attr("aria-label"), "Home", "Aria-label is set correct for logo");
// Navigate home
var oLogo = oShellHeader.$("logo")[0];
oShellHeader.onsapspace({
target: oLogo
});
assert.strictEqual(oLogo.href, window.location.href, "Navigate home by space on the logo");
done();
}
};
if (oShellHeader) {
oShellHeader.destroy();
}
window.hasher = { getHash: sinon.stub().returns('aaa-bbb-ccc') };
oShellHeader = new ShellHeader("shell-header", {
homeUri: "#Shell-home"
});
oShellHeader.createUIArea("canvas");
oShellHeader.addDelegate(oDelegate);
});
QUnit.test("Logo not linked on homepage", function (assert) {
var done = assert.async();
var oDelegate = {
onAfterRendering: function () {
assert.notOk(jQuery(".sapUshellShellIco").attr("tabindex"), "tabindex is not set");
assert.notOk(jQuery(".sapUshellShellIco").attr("title"), "title is not set");
oShellHeader.removeDelegate(oDelegate);
done();
}
};
if (oShellHeader) {
oShellHeader.destroy();
}
window.hasher = { getHash: sinon.stub().returns("Shell-home") };
oShellHeader = new ShellHeader("shell-header", {
visible: true,
homeUri: "#Shell-home"
});
oShellHeader.createUIArea("canvas");
oShellHeader.addDelegate(oDelegate);
});
QUnit.test("Rendering", function (assert) {
assert.ok(oShellHeader.getId() === "shell-header", "Shell Header is rendered");
assert.ok(jQuery("#shellAppTitle .sapUshellHeadTitle").text() === oShellHeader.getAppTitle().getText(), "Apptitle is rendered");
assert.ok(jQuery(".sapUshellShellHeadSubtitle .sapUshellHeadTitle").text() === oShellHeader.getTitle(), "Title is rendered");
assert.ok(jQuery(".sapUshellShellIco").length === 1, "Logo is rendered");
assert.ok(jQuery(".sapUshellShellIco").attr("id") === "shell-header-logo", "Logo has an ID");
assert.ok(jQuery("#sf").length === 1, "Search button is rendered");
});
QUnit.test("Test that accessibility property is set correctly", function (assert) {
var aHeadItems = oShellHeader.getHeadItems(),
aHeadEndItems = oShellHeader.getHeadEndItems();
function assertShellHeaderItem(oItem) {
if (!oItem.getDomRef()) {
return;
}
var jQueryItem = jQuery(oItem.getDomRef()),
sId = oItem.getId();
assert.equal(jQueryItem.attr("tabindex"), 0, "tabindex is set correctly for ShellHeaderItem: " + sId);
assert.equal(jQueryItem.attr("role"), "button", "role is set correctly for ShellHeaderItem: " + sId);
assert.ok(!!jQueryItem.attr("aria-label"), "aria-label is not empty for ShellHeaderItem: " + sId);
}
aHeadItems.forEach(assertShellHeaderItem);
aHeadEndItems.forEach(assertShellHeaderItem);
});
QUnit.test("_handleFocus:", function (assert) {
[
{
sTestDescription: "navigation from outside and navigation direction forward, no HeadItems",
bFromOutside: true,
bForwardNavigation: true,
bExpectedFocusOnShell: true,
bExpectedFocusOnShellHeadItem: false,
bExpectedFocusOnAppTitle: true,
bExpectedFocusOnShellHeadEndItem: false,
bExpectedHandleEventUsingExternalKeysHandlerCalled: false
},
{
sTestDescription: "navigation from outside and navigation direction forward, with HeadItems",
bFromOutside: true,
bForwardNavigation: true,
bShellHeadItems: true,
bExpectedFocusOnShell: true,
bExpectedFocusOnShellHeadItem: true,
bExpectedFocusOnAppTitle: false,
bExpectedFocusOnShellHeadEndItem: false,
bExpectedHandleEventUsingExternalKeysHandlerCalled: false
},
{
sTestDescription: "navigation from outside and navigation direction backwards, no HeadEndItems",
bFromOutside: true,
bForwardNavigation: false,
bExpectedFocusOnShell: true,
bExpectedFocusOnShellHeadItem: false,
bExpectedFocusOnAppTitle: true,
bExpectedFocusOnShellHeadEndItem: false,
bExpectedHandleEventUsingExternalKeysHandlerCalled: false
},
{
sTestDescription: "navigation from outside and navigation direction backwards, with HeadEndItems",
bFromOutside: true,
bForwardNavigation: false,
bShellHeadEndItems: true,
bExpectedFocusOnShell: true,
bExpectedFocusOnShellHeadItem: false,
bExpectedFocusOnAppTitle: false,
bExpectedFocusOnShellHeadEndItem: true,
bExpectedHandleEventUsingExternalKeysHandlerCalled: false
},
{
sTestDescription: "navigation from inside and navigation direction backwards",
bFromOutside: false,
bForwardNavigation: false,
bExpectedFocusOnShell: false,
bExpectedFocusOnShellHeadItem: false,
bExpectedFocusOnAppTitle: false,
bExpectedFocusOnShellHeadEndItem: false,
bExpectedHandleEventUsingExternalKeysHandlerCalled: true
}
].forEach(function (oFixture) {
// Arrange
var bHandleEventUsingExternalKeysHandlerCalled = false;
var oAccessKeyHandler = {
fromOutside: oFixture.bFromOutside,
bForwardNavigation: oFixture.bForwardNavigation,
bFocusOnShell: true,
_handleEventUsingExternalKeysHandler: function () {
bHandleEventUsingExternalKeysHandlerCalled = true;
}
};
var oFocusResult = {
bShellHeadItem: false,
bAppTitle: false,
bShellHeadEndItem: false
};
var fnGetHeadItemsStub = sinon.stub(oShellHeader, "getHeadItems",
function () {
return oFixture.bShellHeadItems ? [{
focus: function () {
oFocusResult.bShellHeadItem = true;
}
}] : [];
}
),
fnGetAppTitleStub = sinon.stub(oShellHeader, "getAppTitle").returns({
focus: function () {
oFocusResult.bAppTitle = true;
}
}),
fnGetHeadEndItemsStub = sinon.stub(oShellHeader, "getHeadEndItems",
function () {
return oFixture.bShellHeadEndItems ? [{
focus: function () {
oFocusResult.bShellHeadEndItem = true;
}
}] : [];
}
);
oShellHeader.setAccessKeyHandler(oAccessKeyHandler);
// Act
oShellHeader._handleFocus();
// Assert
assert.strictEqual(
oAccessKeyHandler.bFocusOnShell,
oFixture.bExpectedFocusOnShell,
"Focus was (not) set on the shell when " + oFixture.sTestDescription);
assert.strictEqual(
oFocusResult.bShellHeadItem,
oFixture.bExpectedFocusOnShellHeadItem,
"Focus was (not) set on the first shellHeadItem when " + oFixture.sTestDescription);
assert.strictEqual(
oFocusResult.bAppTitle,
oFixture.bExpectedFocusOnAppTitle,
"Focus was (not) set on the appTitle when " + oFixture.sTestDescription);
assert.strictEqual(
oFocusResult.bShellHeadEndItem,
oFixture.bExpectedFocusOnShellHeadEndItem,
"Focus was (not) set on the last shellHeadEndItem when " + oFixture.sTestDescription);
assert.strictEqual(
bHandleEventUsingExternalKeysHandlerCalled,
oFixture.bExpectedHandleEventUsingExternalKeysHandlerCalled,
"_handleEventUsingExternalKeysHandler was (not) called when " + oFixture.sTestDescription);
fnGetAppTitleStub.restore();
fnGetHeadItemsStub.restore();
fnGetHeadEndItemsStub.restore();
});
});
QUnit.test("Search State", function (assert) {
var done = assert.async();
var _afterOpen = {
onAfterRendering: function () { // after search open
oShellHeader.removeDelegate(_afterOpen);
var searchContainer = jQuery("#shell-header-hdr-search");
var maxWidth = searchContainer[0].style.maxWidth;
assert.strictEqual(maxWidth, "10rem", "Search field width is correctly set");
assert.strictEqual(searchContainer.width() > 0, true, "Search Field container is visible");
// close search
oShellHeader.setSearchState("COL", 10, true);
oShellHeader.addDelegate(_afterClose);
}
};
var _afterClose = {
onAfterRendering: function () { // after search close
oShellHeader.removeDelegate(_afterClose);
var searchContainer = jQuery("#shell-header-hdr-search");
var maxWidth = searchContainer[0].style.maxWidth;
assert.strictEqual(maxWidth, "0rem", "Search field width is correctly set");
assert.strictEqual(searchContainer.width(), 0, "Search Field container is invisible");
done();
}
};
// open search
oShellHeader.setSearchState("EXP", 10, true);
oShellHeader.addDelegate(_afterOpen);
});
});
|
import { csv } from 'd3-fetch';
import { group, groups } from 'd3-array';
import countyDict from '../data/county_dict.json';
import fipsExceptions from '../util/fipsExceptions';
//this function calculates the number of new cases/deaths for each place
//d is datum, is index of datum in values array, measure is either "totalCases" or "totalDeaths"
const calculateNew = (d, i, arr, measure) => {
if (i === 0) {
//if the first entry for the location, new cases are simply the number of cases
return d[measure];
} else {
//current day's figure minus previous day's figure
const differenceFromPrevious = d[measure] - arr[i - 1][measure];
//if there are more or the same, return new cases/deaths
if (Math.sign(differenceFromPrevious) !== -1) {
return differenceFromPrevious;
//if there are less cases/deaths than the day before, return 0 new cases/deaths
} else if (Math.sign(differenceFromPrevious) === -1) {
return 0;
}
}
}
//add newCases and newDeaths and push to a new array
const createGroupedMap = (oldEntriesMap) => {
//creating new map which will be returned at the end
const groupedMap = new Map();
oldEntriesMap.forEach((municipalityData, municipality) => {
//data which will contain previous data, plus newCases and newDeaths
const newData = [];
municipalityData.forEach((d, i) => {
const newCases = calculateNew(d, i, municipalityData, 'totalCases');
const newDeaths = calculateNew(d, i, municipalityData, 'totalDeaths');
const newEntry = {
...d,
newCases,
newDeaths,
};
//push the new entry to the newData array
newData.push(newEntry);
});
//set the current municipality (key) to the newData array (value)
groupedMap.set(municipality, newData);
});
//return the final grouped map
return groupedMap;
}
export const fetchCountryNyt = async () => {
try {
const url = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us.csv';
const countryRes = await csv(url, d => {
//renaming and removing old keys
const entry = {
...d,
totalCases: +d.cases,
totalDeaths: +d.deaths
};
const { cases, deaths, ...formatted } = entry;
return formatted;
});
const withNew = countryRes.map((d, i) => {
const newCases = calculateNew(d, i, countryRes, 'totalCases');
const newDeaths = calculateNew(d, i, countryRes, 'totalDeaths');
return {
...d,
newCases,
newDeaths,
};
});
return withNew;
} catch (e) {
console.error(e);
}
}
export const fetchStateNyt = async () => {
try {
const url = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv';
const stateRes = await csv(url, d => {
//renaming and removing old keys
const entry = {
...d,
totalCases: +d.cases,
totalDeaths: +d.deaths
};
const { cases, deaths, ...formatted } = entry;
return formatted;
});
const groupByState = group(stateRes, d => d.state);
return createGroupedMap(groupByState);
} catch (e) {
console.error(e);
}
}
export const fetchCountyNyt = async () => {
const url = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv';
try {
const countyRes = await csv(url, d => {
//renaming and removing old keys, adding coordinates
const entry = {
...d,
totalCases: +d.cases,
totalDeaths: +d.deaths,
coordinates: countyDict[d.fips]
};
const { cases, deaths, ...formatted } = entry;
//return custom coordinates and fips code
const returnCoordinates = (coordinates, fipsException ) => {
return {
...formatted,
fips: fipsException,
coordinates
}
}
//localities with no fips code but are included in data
if (d.county === 'New York City') {
return returnCoordinates([-74.006, 40.713], fipsExceptions.nyc);
} else if (d.county === 'Kansas City' && d.state === 'Missouri') {
return returnCoordinates([-94.579, 39.100], fipsExceptions.kc)
} else if (d.state === 'Puerto Rico') {
return returnCoordinates([-66.430, 18.222], fipsExceptions.pr);
} else if (d.state === 'Guam') {
return returnCoordinates([144.794, 13.444], fipsExceptions.guam);
} else if (d.state === 'Virgin Islands') {
return returnCoordinates([-64.896, 18.336], fipsExceptions.vi);
} else if (d.state === 'Northern Mariana Islands') {
return returnCoordinates([145.674, 15.098], fipsExceptions.nmi);
}
else {
return formatted;
}
});
const haveFips = countyRes.filter(d => d.fips);
const groupByFips = group(haveFips, d => d.fips);
return createGroupedMap(groupByFips);
} catch (e) {
console.error(e);
}
}
|
import React from 'react';
import { Spinner } from 'reactstrap';
export default () => <div className="py-5 my-1 text-center">
<Spinner color="yellow" style={{ width: '15rem', height: '15rem' }} type="grow" className="my-2" />
</div>;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.