text
stringlengths 7
3.69M
|
|---|
"use strict";
exports.restoreLocation = restoreLocation;
var _type = require("../../../../core/utils/type");
var _common = require("../../../../core/utils/common");
var _scroll_direction = require("./scroll_direction");
function restoreLocation(location, direction) {
if ((0, _type.isPlainObject)(location)) {
var left = (0, _common.ensureDefined)(location.left, location.x);
var top = (0, _common.ensureDefined)(location.top, location.y);
return {
left: (0, _type.isDefined)(left) ? -left : undefined,
top: (0, _type.isDefined)(top) ? -top : undefined
};
}
var _ScrollDirection = new _scroll_direction.ScrollDirection(direction),
isHorizontal = _ScrollDirection.isHorizontal,
isVertical = _ScrollDirection.isVertical;
return {
left: isHorizontal ? -location : undefined,
top: isVertical ? -location : undefined
};
}
|
"use strict";
/// <reference path="../../scene/componentEditors/ComponentEditorPlugin.d.ts" />
/// <reference path="../../scene/componentEditors/ImportIntoScenePlugin.d.ts" />
Object.defineProperty(exports, "__esModule", { value: true });
const ModelRendererEditor_1 = require("./ModelRendererEditor");
const importModelIntoScene = require("./importModelIntoScene");
SupClient.registerPlugin("componentEditors", "ModelRenderer", ModelRendererEditor_1.default);
SupClient.registerPlugin("importIntoScene", "model", importModelIntoScene);
|
/**
* LINKURIOUS CONFIDENTIAL
* Copyright Linkurious SAS 2012 - 2018
*
* - Created on 2016-02-18.
*/
'use strict';
const EventEmitter = require('events');
class GremlinStream extends EventEmitter {
/**
* @param {any} gremlinDriver
* @param {string} pageQuery
* @param {string} type 'node' or 'edge'
*/
constructor(gremlinDriver, pageQuery, type) {
super();
this.gremlinDriver = gremlinDriver;
this.pageQuery = pageQuery;
this.buffer = [];
this.paused = true;
this.type = type;
this.resume();
}
pause() {
this.paused = true;
}
resume() {
if (!this.paused) { return; }
this.paused = false;
this._loop();
}
abort() {
// not implemented
}
_loop() {
let data;
while (!this.paused && this.buffer.length) {
data = this.buffer.pop();
data = this.type === 'node'
? this.gremlinDriver.rawNodeToLkNode(data)
: this.gremlinDriver.rawEdgeToLkEdge(data);
this.emit('data', data);
}
if (!this.paused && !this.buffer.length) {
this.gremlinDriver.connector.$doGremlinQuery(this.pageQuery).then(results => {
if (results.length === 0) {
this.emit('end');
} else {
this.buffer = results;
process.nextTick(() => this._loop());
}
}, error => {
this.emit('error', error);
});
}
}
}
module.exports = GremlinStream;
|
/*******************************************************************************
* Licensed Materials - Property of IBM
* (c) Copyright IBM Corporation 2019. All Rights Reserved.
*
* Note to U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule
* Contract with IBM Corp.
*******************************************************************************/
/* Copyright (c) 2020 Red Hat, Inc. */
'use strict'
const ReactDOMServer = require('react-dom/server'),
thunkMiddleware = require('redux-thunk').default,
redux = require('redux'),
React = require('react'),
express = require('express'),
StaticRouter = require('react-router-dom').StaticRouter,
context = require('../../lib/shared/context'),
msgs = require('../../nls/platform.properties'),
config = require('../../config'),
appUtil = require('../../lib/server/app-util'),
Provider = require('react-redux').Provider,
router = express.Router({ mergeParams: true }),
lodash = require('lodash'),
request = require('../../lib/server/request'),
i18n = require('node-i18n-util')
const log4js = require('log4js'),
logger = log4js.getLogger('app')
const targetAPIGroups = [
'policy.open-cluster-management.io',
'apps.open-cluster-management.io',
]
let App, Login, reducers, access //laziy initialize to reduce startup time seen on k8s
router.get('*', (req, res) => {
reducers = reducers === undefined ? require('../../src-web/reducers') : reducers
const store = redux.createStore(redux.combineReducers(reducers), redux.applyMiddleware(
thunkMiddleware, // lets us dispatch() functions
))
Login = Login === undefined ? require('../../src-web/actions/login') : Login
store.dispatch(Login.receiveLoginSuccess(req.user))
App = App === undefined ? require('../../src-web/containers/App').default : App
const fetchHeaderContext = getContext(req)
fetchHeader(req, res, store, fetchHeaderContext)
})
function fetchHeader(req, res, store, fetchHeaderContext) {
const optionsUrlPrefix = `${config.get('headerUrl')}${config.get('headerContextPath')}/api/v1/header`
const optionsUrlQuery = `serviceId=grc-ui&dev=${process.env.NODE_ENV === 'development'}&targetAPIGroups=${JSON.stringify(targetAPIGroups)}`
const options = {
method: 'GET',
url: `${optionsUrlPrefix}?${optionsUrlQuery}`,
json: true,
headers: {
Cookie: req.headers.cookie,
Authorization: req.headers.Authorization || req.headers.authorization || `Bearer ${req.cookies['acm-access-token-cookie']}`,
'Accept-Language': i18n.locale(req)
}
}
request(options, null, [200], (err, headerRes) => {
if (err) {
return res.status(500).send(err)
}
const { headerHtml: header, props: propsH, state: stateH, files: filesH, userAccess } = headerRes.body
if (!header || !propsH || !stateH || !filesH) {
logger.err(headerRes.body)
return res.status(500).send(headerRes.body)
}
access = access === undefined ? require('../../src-web/actions/access') : access
if (userAccess) {
// logger.info(`userAccess is : ${JSON.stringify(userAccess)}`)
store.dispatch(access.userAccessSuccess(userAccess))
}
if(process.env.NODE_ENV === 'development') {
lodash.forOwn(filesH, value => {
value.path = `${config.get('contextPath')}/api/proxy${value.path}` //preprend with proxy route
})
}
try {
res.render('home', Object.assign({
manifest: appUtil.app().locals.manifest,
content: ReactDOMServer.renderToString(
<Provider store={store}>
<StaticRouter
location={req.originalUrl}
context={fetchHeaderContext}>
<App />
</StaticRouter>
</Provider>
),
contextPath: config.get('contextPath'),
headerContextPath: config.get('headerContextPath'),
state: store.getState(),
props: fetchHeaderContext,
header: header,
propsH: propsH,
stateH: stateH,
filesH: filesH
}, fetchHeaderContext))
} catch(e) {
//eslint-disable-next-line no-console
console.error(e)
}
return undefined
})
}
function getContext(req) {
const reqContext = context(req)
return {
title: msgs.get('common.app.name', reqContext.locale),
context: reqContext,
xsrfToken: req.csrfToken()
}
}
module.exports = router
|
/*
* Copyright (c) 2012,2013 DeNA Co., Ltd. et al.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
import "./type.jsx";
import "./analysis.jsx";
import "./classdef.jsx";
import "./statement.jsx";
import "./expression.jsx";
import "./doc.jsx";
import "./util.jsx";
import "./completion.jsx";
import _CompletionCandidatesWithLocal, _CompletionCandidatesOfProperty, _CompletionCandidatesOfNamespace from "completion.jsx";
class Token {
var _value : string;
var _isIdentifier : boolean;
var _filename : Nullable.<string>;
var _lineNumber : number;
var _columnNumber : number;
function constructor (value : string, isIdentifier : boolean = false, filename : Nullable.<string> = null, lineNumber : number = NaN, columnNumber : number = NaN) {
this._value = value;
this._isIdentifier = isIdentifier;
this._filename = filename;
this._lineNumber = lineNumber;
this._columnNumber = columnNumber;
}
function getValue () : string {
return this._value;
}
function isIdentifier () : boolean {
return this._isIdentifier;
}
function getFilename () : Nullable.<string> {
return this._filename;
}
function getLineNumber () : number {
return this._lineNumber;
}
function getColumnNumber () : number {
return this._columnNumber;
}
function serialize () : variant {
return [
this._value,
this._isIdentifier,
this._filename,
this._lineNumber,
this._columnNumber
] : variant[];
}
// "'x' at filename:linenumber" for debugging purpose
function getNotation() : string {
return "'" + this._value + "'"
+ " at " + (this._filename ?: "<<unknown>>") + ":" + this._lineNumber as string + ":" + this._columnNumber as string;
}
}
class _Lexer {
static const ident = " [a-zA-Z_] [a-zA-Z0-9_]* ";
static const doubleQuoted = ' " [^"\\\\]* (?: \\\\. [^"\\\\]* )* " ';
static const singleQuoted = " ' [^'\\\\]* (?: \\\\. [^'\\\\]* )* ' ";
static const stringLiteral = _Lexer.makeAlt([_Lexer.singleQuoted, _Lexer.doubleQuoted]);
static const regexpLiteral = _Lexer.doubleQuoted.replace(/"/g, "/") + "[mgi]*";
static const heredocStartDoubleQuoted = '"""';
static const heredocStartSingleQuoted = "'''";
static const heredocStart = _Lexer.makeAlt([ _Lexer.heredocStartDoubleQuoted, _Lexer.heredocStartSingleQuoted ]);
static const heredocEndDoubleQuoted = ' (?:^|.*?[^\\\\]) (?:\\\\\\\\)* """ ';
static const heredocEndSingleQuoted = " (?:^|.*?[^\\\\]) (?:\\\\\\\\)* ''' ";
// ECMA 262 compatible,
// see also ECMA 262 5th (7.8.3) Numeric Literals
static const decimalIntegerLiteral = "(?: 0 | [1-9][0-9]* )";
static const exponentPart = "(?: [eE] [+-]? [0-9]+ )";
static const numberLiteral = _Lexer.makeAlt([
"(?: " + _Lexer.decimalIntegerLiteral + " \\. " +
"[0-9]* " + _Lexer.exponentPart + "? )",
"(?: \\. [0-9]+ " + _Lexer.exponentPart + "? )",
"(?: " + _Lexer.decimalIntegerLiteral + _Lexer.exponentPart + " )",
"NaN",
"Infinity"
]) + "\\b";
static const integerLiteral = _Lexer.makeAlt([
"(?: 0 [xX] [0-9a-fA-F]+ )", // hex
_Lexer.decimalIntegerLiteral
]) + "(?![\\.0-9eE])\\b";
// regular expressions
static const rxIdent = _Lexer.rx("^" + _Lexer.ident);
static const rxStringLiteral = _Lexer.rx("^" + _Lexer.stringLiteral);
static const rxNumberLiteral = _Lexer.rx("^" + _Lexer.numberLiteral);
static const rxIntegerLiteral = _Lexer.rx("^" + _Lexer.integerLiteral);
static const rxRegExpLiteral = _Lexer.rx("^" + _Lexer.regexpLiteral);
static const rxHeredocStart = _Lexer.rx("^" + _Lexer.heredocStart);
static const rxHeredocEndDoubleQuoted = _Lexer.rx(_Lexer.heredocEndDoubleQuoted);
static const rxHeredocEndSingleQuoted = _Lexer.rx(_Lexer.heredocEndSingleQuoted);
static const rxNewline = /(?:\r\n?|\n)/;
// blacklists of identifiers
static const keywords = Util.asSet([
// literals shared with ECMA 262
"null", "true", "false",
"NaN", "Infinity",
// keywords shared with ECMA 262
"break", "do", "instanceof", "typeof",
"case", "else", "new", "var",
/*"catch",*/ // contextual
"finally", "return", "void",
"const",
/*"continue",*/ // contextual
"for", "switch", "while",
"function", "this",
/* "default", */ // contextual keywords
"if", "throw",
/* "assert", "log", // contextual keywords */
/*"delete",*/ // contextual
"in", "try",
// keywords of JSX
"class", "extends", "super",
"import", "implements",
// "interface", // contextual keywords
"static",
"__FILE__", "__LINE__",
"undefined"
]);
static const reserved = Util.asSet([
// literals of ECMA 262 but not used by JSX
"debugger", "with",
// future reserved words of ECMA 262
"export",
// future reserved words within strict mode of ECMA 262
"let", "private", "public", "yield",
"protected",
// JSX specific reserved words
"extern", "native", "as", "operator"
]);
static function makeAlt (patterns : string[]) : string {
return "(?: \n" + patterns.join("\n | \n") + "\n)\n";
}
static function quoteMeta (pattern : string) : string {
return pattern.replace(/([^0-9A-Za-z_])/g, '\\$1');
}
/// compile a regular expression
static function rx (pat : string) : RegExp {
return new RegExp(pat.replace(/[ \t\r\n]/g, ""));
}
}
class Import {
var _filenameToken : Token;
var _aliasToken : Token;
var _classNames : Token[];
var _sourceParsers : Parser[];
function constructor(parser : Parser) {
// for built-in classes
this._filenameToken = null;
this._aliasToken = null;
this._classNames = null;
this._sourceParsers = [ parser ];
}
function constructor (filenameToken : Token, aliasToken : Token, classNames : Token[]) {
this._filenameToken = filenameToken;
this._aliasToken = aliasToken;
this._classNames = classNames;
this._sourceParsers = [] : Parser[];
}
function getFilenameToken () : Token {
return this._filenameToken;
}
function getAlias () : Nullable.<string> {
if (this._aliasToken) {
return this._aliasToken.getValue();
}
else {
return null;
}
}
function getClassNames () : string[] {
if (this._classNames == null)
return null;
var names = new string[];
for (var i = 0; i < this._classNames.length; ++i)
names[i] = this._classNames[i].getValue();
return names;
}
function serialize () : variant {
return [
"Import",
Util.serializeNullable(this._filenameToken),
Util.serializeNullable(this._aliasToken),
Util.serializeArray(this._classNames)
] : variant[];
}
function checkNameConflict (errors : CompileError[], nameToken : Token) : boolean {
if (this._aliasToken != null) {
if (this._aliasToken.getValue() == nameToken.getValue()) {
errors.push(new CompileError(nameToken, "an alias with the same name is already declared"));
return false;
}
} else {
if (this._classNames != null) {
for (var i = 0; i < this._classNames.length; ++i) {
if (this._classNames[i].getValue() == nameToken.getValue()) {
errors.push(new CompileError(nameToken, "a class with the same name has already been explicitely imported"));
return false;
}
}
}
}
return true;
}
function addSource (parser : Parser) : void {
this._sourceParsers.push(parser);
}
function getSources () : Parser[] {
return this._sourceParsers;
}
function assertExistenceOfNamedClasses (errors : CompileError[]) : void {
if (this._classNames == null) {
// no named classes
return;
}
// list all classses
var allClassNames = new string[];
for (var i = 0; i < this._sourceParsers.length; ++i) {
allClassNames = allClassNames.concat(this._sourceParsers[i].getClassDefs().map.<string>(function (classDef) {
return classDef.className();
}));
allClassNames = allClassNames.concat(this._sourceParsers[i].getTemplateClassDefs().map.<string>(function (classDef) {
return classDef.className();
}));
}
function countNumberOfClassesByName(className : string) : number {
var num = 0;
for (var i = 0; i < allClassNames.length; ++i) {
if (allClassNames[i] == className) {
++num;
}
}
return num;
}
for (var i = 0; i < this._classNames.length; ++i) {
switch (countNumberOfClassesByName(this._classNames[i].getValue())) {
case 0:
errors.push(new CompileError(this._classNames[i], "no definition for class '" + this._classNames[i].getValue() + "'"));
break;
case 1:
// ok
break;
default:
errors.push(new CompileError(this._classNames[i], "multiple candidates for class '" + this._classNames[i].getValue() + "'"));
break;
}
}
}
function getClasses (name : string) : ClassDefinition[] {
if (! this._classIsImportable(name)) {
return [] : ClassDefinition[];
}
var found = [] : ClassDefinition[];
for (var i = 0; i < this._sourceParsers.length; ++i) {
var classDefs = this._sourceParsers[i].getClassDefs();
for (var j = 0; j < classDefs.length; ++j) {
var classDef = classDefs[j];
if (classDef.className() == name) {
found.push(classDef);
break;
}
}
}
return found;
}
function createGetTemplateClassCallbacks (errors : CompileError[], request : TemplateInstantiationRequest, postInstantiationCallback : function(:Parser,:ClassDefinition):ClassDefinition) : Array.<function(:CompileError[],:TemplateInstantiationRequest,:function(:Parser,:ClassDefinition):ClassDefinition):ClassDefinition> {
if (! this._classIsImportable(request.getClassName())) {
return new Array.<function(:CompileError[],:TemplateInstantiationRequest,:function(:Parser,:ClassDefinition):ClassDefinition):ClassDefinition>;
}
var callbacks = new Array.<function(:CompileError[],:TemplateInstantiationRequest,:function(:Parser,:ClassDefinition):ClassDefinition):ClassDefinition>;
for (var i = 0; i < this._sourceParsers.length; ++i) {
var callback = this._sourceParsers[i].createGetTemplateClassCallback(errors, request, postInstantiationCallback);
if (callback != null) {
callbacks.push(callback);
}
}
return callbacks;
}
function _classIsImportable (name : string) : boolean {
if (this._classNames != null) {
for (var i = 0; i < this._classNames.length; ++i)
if (this._classNames[i].getValue() == name)
break;
if (i == this._classNames.length)
return false;
} else {
if (name.charAt(0) == '_')
return false;
}
return true;
}
static function create (errors : CompileError[], filenameToken : Token, aliasToken : Token, classNames : Token[]) : Import {
var filename = Util.decodeStringLiteral(filenameToken.getValue());
if (filename.indexOf("*") != -1) {
// read the files from a directory
var match = filename.match(/^([^\*]*)\/\*(\.[^\/\*]*)$/);
if (match == null) {
errors.push(new CompileError(filenameToken, "invalid use of wildcard"));
return null;
}
return new WildcardImport(filenameToken, aliasToken, classNames, match[1], match[2]);
}
return new Import(filenameToken, aliasToken, classNames);
}
}
class WildcardImport extends Import {
var _directory : string;
var _suffix : string;
function constructor (filenameToken : Token, aliasToken : Token, classNames : Token[], directory : string, suffix : string) {
super(filenameToken, aliasToken, classNames);
this._directory = directory;
this._suffix = suffix;
}
function getDirectory () : string {
return this._directory;
}
function getSuffix () : string {
return this._suffix;
}
}
class QualifiedName {
var _token : Token;
// _import and _enclosingType are exclusive
var _import : Import;
var _enclosingType : ParsedObjectType;
function constructor (token : Token) {
this._token = token;
this._import = null;
this._enclosingType = null;
}
function constructor (token : Token, imprt : Import) {
this._token = token;
this._import = imprt;
this._enclosingType = null;
}
function constructor (token : Token, enclosingType : ParsedObjectType) {
this._token = token;
this._import = null;
this._enclosingType = enclosingType;
}
function getToken () : Token {
return this._token;
}
function getImport () : Import {
return this._import;
}
function getEnclosingType () : ParsedObjectType {
return this._enclosingType;
}
function serialize () : variant {
return [
"QualifiedName",
this._token.serialize(),
Util.serializeNullable(this._import),
Util.serializeNullable(this._enclosingType)
] : variant[];
}
function equals (x : QualifiedName) : boolean {
if (x == null)
return false;
if (this._token.getValue() != x._token.getValue())
return false;
if (this._import != x._import)
return false;
if (this._enclosingType == null) {
if (x._enclosingType != null)
return false;
} else {
if (! this._enclosingType.equals(x._enclosingType))
return false;
}
return true;
}
function getClass (context : AnalysisContext, typeArguments : Type[]) : ClassDefinition {
var classDef = null : ClassDefinition;
if (this._import != null) { // && this._enclosingType == null
if (typeArguments.length == 0) {
var classDefs = this._import.getClasses(this._token.getValue());
switch (classDefs.length) {
case 1:
classDef = classDefs[0];
break;
case 0:
context.errors.push(new CompileError(this._token, "no definition for class '" + this.toString() + "' in file '" + this._import.getFilenameToken().getValue() + "'"));
return null;
default:
context.errors.push(new CompileError(this._token, "multiple candidates"));
return null;
}
} else {
var callbacks = this._import.createGetTemplateClassCallbacks(context.errors, new TemplateInstantiationRequest(this._token, this._token.getValue(), typeArguments), function (parser : Parser, classDef : ClassDefinition) : ClassDefinition { return null; });
switch (callbacks.length) {
case 1:
return callbacks[0](null, null, null);
case 0:
context.errors.push(new CompileError(this._token, "no definition for template class '" + this.toString() + "' in file '" + this._import.getFilenameToken().getValue() + "'"));
return null;
default:
context.errors.push(new CompileError(this._token, "multiple canditates"));
return null;
}
}
} else if (this._enclosingType != null) {
this._enclosingType.resolveType(context);
var enclosingClassDef;
if ((enclosingClassDef = this._enclosingType.getClassDef()) == null)
return null;
if (typeArguments.length == 0) {
if ((classDef = enclosingClassDef.lookupInnerClass(this._token.getValue())) == null) {
context.errors.push(new CompileError(this._token, "no class definition or variable for '" + this.toString() + "'"));
return null;
}
} else {
if ((classDef = enclosingClassDef.lookupTemplateInnerClass(context.errors, new TemplateInstantiationRequest(this._token, this._token.getValue(), typeArguments), (parser, classDef) -> { return null; })) == null) {
context.errors.push(new CompileError(this._token, "failed to instantiate class"));
return null;
}
}
} else {
if (typeArguments.length == 0) {
if ((classDef = context.parser.lookup(context.errors, this._token, this._token.getValue())) == null) {
if ((classDef = context.parser.lookupTemplate(context.errors, new TemplateInstantiationRequest(this._token, this._token.getValue(), typeArguments), function (parser : Parser, classDef : ClassDefinition) : ClassDefinition { return null; })) == null) {
context.errors.push(new CompileError(this._token, "no class definition or variable for '" + this.toString() + "'"));
return null;
}
}
} else {
if ((classDef = context.parser.lookupTemplate(context.errors, new TemplateInstantiationRequest(this._token, this._token.getValue(), typeArguments), function (parser : Parser, classDef : ClassDefinition) : ClassDefinition { return null; })) == null) {
context.errors.push(new CompileError(this._token, "failed to instantiate class"));
return null;
}
}
}
return classDef;
}
function getTemplateClass (parser : Parser) : TemplateClassDefinition {
var foundClassDefs = new TemplateClassDefinition[];
var checkClassDef = function (classDef : TemplateClassDefinition) : void {
if (classDef.className() == this._token.getValue()) {
foundClassDefs.push(classDef);
}
};
if (this._import != null) {
this._import.getSources().forEach(function (parser) {
parser.getTemplateClassDefs().forEach(checkClassDef);
});
} else {
parser.getTemplateClassDefs().forEach(checkClassDef);
if (foundClassDefs.length == 0) {
parser.getImports().forEach(function (imprt) {
imprt.getSources().forEach(function (parser) {
parser.getTemplateClassDefs().forEach(checkClassDef);
});
});
}
}
return foundClassDefs.length == 1 ? foundClassDefs[0] : null;
}
override function toString () : string {
return this._enclosingType != null ? this._enclosingType.toString() + "." + this._token.getValue() : this._token.getValue();
}
}
class ParserState {
var lineNumber : number;
var columnOffset : number;
var docComment : DocComment;
var tokenLength : number;
var isGenerator : boolean;
var numErrors : number;
var numClosures : number;
var numObjectTypesUsed : number;
var numTemplateInstantiationRequests : number;
function constructor (lineNumber : number, columnNumber : number, docComment : DocComment, tokenLength : number, isGenerator : boolean, numErrors : number, numClosures : number, numObjectTypesUsed : number, numTemplateInstantiationRequests : number) {
this.lineNumber = lineNumber;
this.columnOffset = columnNumber;
this.docComment = docComment;
this.tokenLength = tokenLength;
this.isGenerator = isGenerator;
this.numErrors = numErrors;
this.numClosures = numClosures;
this.numObjectTypesUsed = numObjectTypesUsed;
this.numTemplateInstantiationRequests = numTemplateInstantiationRequests;
}
}
class ClassState {
var outer : ClassState;
var classType : ParsedObjectType;
var typeArgs : Token[];
var extendType : ParsedObjectType;
var implementTypes : ParsedObjectType[];
var objectTypesUsed : ParsedObjectType[];
var classFlags : number;
var inners : ClassDefinition[];
var templateInners : TemplateClassDefinition[];
function constructor (outer : ClassState, classType : ParsedObjectType, typeArgs : Token[], extendType : ParsedObjectType, implementTypes : ParsedObjectType[], objectTypesUsed : ParsedObjectType[], classFlags : number, inners : ClassDefinition[], templateInners : TemplateClassDefinition[]) {
this.outer = outer;
this.classType = classType;
this.typeArgs = typeArgs;
this.extendType = extendType;
this.implementTypes = implementTypes;
this.objectTypesUsed = objectTypesUsed;
this.classFlags = classFlags;
this.inners = inners;
this.templateInners = templateInners;
}
}
class Scope {
var prev : Scope;
var locals : LocalVariable[];
var funcLocal : LocalVariable; // the name of current closure, can be null
var arguments : ArgumentDeclaration[];
var statements : Statement[];
var closures : MemberFunctionDefinition[];
var isGenerator : boolean;
function constructor (prev : Scope, locals : LocalVariable[], funcLocal : LocalVariable, args : ArgumentDeclaration[], statements : Statement[], closures : MemberFunctionDefinition[], isGenerator : boolean) {
this.prev = prev;
this.locals = locals;
this.funcLocal = funcLocal;
this.arguments = args;
this.statements = statements;
this.closures = closures;
this.isGenerator = isGenerator;
}
}
class Parser {
var _sourceToken : Token;
var _filename : string;
var _completionRequest : CompletionRequest;
var _content : Nullable.<string>;
var _lines : string[];
var _tokenLength : number;
var _lineNumber : number; // one origin
var _columnOffset : number; // zero origin
var _fileLevelDocComment : DocComment;
var _docComment : DocComment;
var _errors : CompileError[];
var _templateClassDefs : TemplateClassDefinition[];
var _classDefs : ClassDefinition[];
var _imports : Import[];
var _isGenerator : boolean;
var _locals : LocalVariable[];
var _statements : Statement[];
var _closures : MemberFunctionDefinition[];
var _outerClass : ClassState;
var _classType : ParsedObjectType;
var _extendType : ParsedObjectType;
var _implementTypes : ParsedObjectType[];
var _objectTypesUsed : ParsedObjectType[];
var _inners : ClassDefinition[];
var _templateInners : TemplateClassDefinition[];
var _templateInstantiationRequests : TemplateInstantiationRequest[];
var _prevScope : Scope = null;
var _funcLocal : LocalVariable = null;
var _arguments : ArgumentDeclaration[] = null;
var _classFlags : number;
var _typeArgs : Token[];
function constructor (sourceToken : Token, filename : string, completionRequest : CompletionRequest) {
this._sourceToken = sourceToken;
this._filename = filename;
this._completionRequest = completionRequest;
}
function parse (content : string, errors : CompileError[]) : boolean {
// lexer properties
this._content = content;
this._lines = this._content.split(_Lexer.rxNewline);
this._tokenLength = 0;
this._lineNumber = 1; // one origin
this._columnOffset = 0; // zero origin
this._fileLevelDocComment = null;
this._docComment = null;
// insert a marker so that at the completion location we would always get _expectIdentifierOpt called, whenever possible
if (this._completionRequest != null) {
var compLineNumber = Math.min(this._completionRequest.getLineNumber(), this._lines.length + 1);
var line = this._lines[compLineNumber - 1] ?: '';
this._lines[compLineNumber - 1] =
line.substring(0, this._completionRequest.getColumnOffset())
+ "Q," + // use a character that is permitted within an identifier, but never appears in keywords
line.substring(this._completionRequest.getColumnOffset());
}
// output
this._errors = errors;
this._templateClassDefs = new TemplateClassDefinition[];
this._classDefs = new ClassDefinition[];
this._imports = new Import[];
// use for function parsing
this._isGenerator = false;
this._locals = null;
this._statements = null;
this._closures = null;
this._classType = null;
this._extendType = null;
this._implementTypes = null;
this._objectTypesUsed = new ParsedObjectType[];
this._inners = new ClassDefinition[];
this._templateInners = new TemplateClassDefinition[];
this._templateInstantiationRequests = new TemplateInstantiationRequest[];
// doit
while (! this._isEOF()) {
var importToken = this._expectOpt("import");
if (importToken == null)
break;
this._importStatement(importToken);
}
while (! this._isEOF()) {
if (this._classDefinition() == null)
return false;
}
if (this._errors.length != 0)
return false;
return true;
}
function getContent() : string {
return this._content;
}
function _getInput () : string {
return this._lines[this._lineNumber - 1].substring(this._columnOffset);
}
function _getInputByLength (length : number) : string {
return this._lines[this._lineNumber - 1].substring(this._columnOffset, this._columnOffset + length);
}
function _forwardPos (len : number) : void {
this._columnOffset += len;
}
function getSourceToken () : Token {
return this._sourceToken;
}
function getPath () : string {
return this._filename;
}
function getDocComment () : DocComment {
return this._fileLevelDocComment;
}
function getClassDefs () : ClassDefinition[] {
return this._classDefs;
}
function getTemplateClassDefs () : TemplateClassDefinition[] {
return this._templateClassDefs;
}
function getTemplateInstantiationRequests () : TemplateInstantiationRequest[] {
return this._templateInstantiationRequests;
}
function getImports () : Import[] {
return this._imports;
}
function registerBuiltinImports (parsers : Parser[]) : void {
for (var i = parsers.length - 1; i >= 0; --i)
this._imports.unshift(new Import(parsers[i]));
}
function lookupImportAlias (name : string) : Import {
for (var i = 0; i < this._imports.length; ++i) {
var alias = this._imports[i].getAlias();
if (alias != null && alias == name)
return this._imports[i];
}
return null;
}
function lookup (errors : CompileError[], contextToken : Token, className : string) : ClassDefinition {
// class within the file is preferred
for (var i = 0; i < this._classDefs.length; ++i) {
var classDef = this._classDefs[i];
if (classDef.className() == className)
return classDef;
}
// classnames within the imported files may conflict
var found = new ClassDefinition[];
for (var i = 0; i < this._imports.length; ++i) {
if (this._imports[i].getAlias() == null)
found = found.concat(this._imports[i].getClasses(className));
}
if (found.length == 1)
return found[0];
if (found.length >= 2)
errors.push(new CompileError(contextToken, "multiple candidates exist for class name '" + className + "'"));
return null;
}
function lookupTemplate (errors : CompileError[], request : TemplateInstantiationRequest, postInstantiationCallback : function(:Parser,:ClassDefinition):ClassDefinition) : ClassDefinition {
// lookup within the source file
var instantiateCallback = this.createGetTemplateClassCallback(errors, request, postInstantiationCallback);
if (instantiateCallback != null) {
return instantiateCallback(errors, request, postInstantiationCallback);
}
// lookup within the imported files
var candidateCallbacks = new Array.<function(:CompileError[],:TemplateInstantiationRequest,:function(:Parser,:ClassDefinition):ClassDefinition):ClassDefinition>;
for (var i = 0; i < this._imports.length; ++i) {
candidateCallbacks = candidateCallbacks.concat(this._imports[i].createGetTemplateClassCallbacks(errors, request, postInstantiationCallback));
}
if (candidateCallbacks.length == 0) {
errors.push(new CompileError(request.getToken(), "could not find definition for template class: '" + request.getClassName() + "'"));
return null;
} else if (candidateCallbacks.length >= 2) {
errors.push(new CompileError(request.getToken(), "multiple candidates exist for template class name '" + request.getClassName() + "'"));
return null;
}
return candidateCallbacks[0](null,null,null);
}
function createGetTemplateClassCallback (errors : CompileError[], request : TemplateInstantiationRequest, postInstantiationCallback : function(:Parser,:ClassDefinition):ClassDefinition) : function(:CompileError[],:TemplateInstantiationRequest,:function(:Parser,:ClassDefinition):ClassDefinition):ClassDefinition {
// lookup the already-instantiated class
for (var i = 0; i < this._classDefs.length; ++i) {
var classDef = this._classDefs[i];
if (classDef instanceof InstantiatedClassDefinition
&& (classDef as InstantiatedClassDefinition).getTemplateClassName() == request.getClassName()
&& Util.typesAreEqual((classDef as InstantiatedClassDefinition).getTypeArguments(), request.getTypeArguments())) {
return function (_ : CompileError[], __ : TemplateInstantiationRequest, ___ : function(:Parser,:ClassDefinition):ClassDefinition) : ClassDefinition {
return classDef;
};
}
}
// create instantiation callback
for (var i = 0; i < this._templateClassDefs.length; ++i) {
var templateDef = this._templateClassDefs[i];
if (templateDef.className() == request.getClassName()) {
return function (_ : CompileError[], __ : TemplateInstantiationRequest, ___ : function(:Parser,:ClassDefinition):ClassDefinition) : ClassDefinition {
var classDef = templateDef.instantiateTemplateClass(errors, request);
if (classDef == null) {
return null;
}
this._classDefs.push(classDef);
classDef.setParser(this);
classDef.resolveTypes(new AnalysisContext(errors, this, null));
postInstantiationCallback(this, classDef);
return classDef;
};
}
}
return null;
}
function _pushClassState () : void {
this._outerClass = new ClassState (
this._outerClass,
this._classType,
this._typeArgs,
this._extendType,
this._implementTypes,
this._objectTypesUsed,
this._classFlags,
this._inners,
this._templateInners
);
}
function _popClassState () : void {
this._classType = this._outerClass.classType;
this._typeArgs = this._outerClass.typeArgs;
this._extendType = this._outerClass.extendType;
this._implementTypes = this._outerClass.implementTypes;
this._objectTypesUsed = this._outerClass.objectTypesUsed;
this._classFlags = this._outerClass.classFlags;
this._inners = this._outerClass.inners;
this._templateInners = this._outerClass.templateInners;
this._outerClass = this._outerClass.outer;
}
function _pushScope (funcLocal : LocalVariable, args : ArgumentDeclaration[]) : void {
this._prevScope = new Scope (
this._prevScope,
this._locals,
this._funcLocal,
this._arguments,
this._statements,
this._closures,
this._isGenerator
);
this._locals = new LocalVariable[];
this._funcLocal = funcLocal;
this._arguments = args;
this._statements = new Statement[];
this._closures = new MemberFunctionDefinition[];
this._isGenerator = false;
}
function _popScope () : void {
this._locals = this._prevScope.locals;
this._funcLocal = this._prevScope.funcLocal;
this._arguments = this._prevScope.arguments;
this._statements = this._prevScope.statements;
this._closures = this._prevScope.closures;
this._isGenerator = this._prevScope.isGenerator;
this._prevScope = this._prevScope.prev;
}
function _registerLocal (identifierToken : Token, type : Type, isConst : boolean, isFunctionStmt : boolean = false) : LocalVariable {
function isEqualTo (local : LocalVariable) : boolean {
if (local.getName().getValue() == identifierToken.getValue()) {
if ((type != null && local.getType() != null && ! local.getType().equals(type)) || isFunctionStmt)
this._newError("conflicting types for variable " + identifierToken.getValue(), identifierToken);
if (local.isConstant() != isConst)
this._newError("const attribute conflict for variable " + identifierToken.getValue(), identifierToken);
return true;
}
return false;
}
if (this._arguments == null) {
this._newError(Util.format("cannot declare variable %1 outside of a function", [identifierToken.getValue()])); // FIXME should we allow this?
return null;
}
if (this._funcLocal != null) {
if (isEqualTo(this._funcLocal)) {
return this._funcLocal;
}
}
for (var i = 0; i < this._arguments.length; ++i) {
if (isEqualTo(this._arguments[i])) {
return this._arguments[i];
}
}
for (var i = 0; i < this._locals.length; i++) {
if (isEqualTo(this._locals[i])) {
return this._locals[i];
}
}
var newLocal = new LocalVariable(identifierToken, type, isConst);
this._locals.push(newLocal);
return newLocal;
}
function _preserveState () : ParserState {
return new ParserState(
// lexer properties
this._lineNumber,
this._columnOffset,
this._docComment,
this._tokenLength,
this._isGenerator,
// errors
this._errors.length,
// closures
this._closures != null ? this._closures.length : 0,
// objectTypesUsed
this._objectTypesUsed.length,
// templateInstantiationrequests
this._templateInstantiationRequests.length
);
}
function _restoreState (state : ParserState) : void {
this._lineNumber = state.lineNumber;
this._columnOffset = state.columnOffset;
this._docComment = state.docComment;
this._tokenLength = state.tokenLength;
this._isGenerator = state.isGenerator;
this._errors.length = state.numErrors;
if (this._closures != null)
this._closures.splice(state.numClosures, this._closures.length - state.numClosures);
this._objectTypesUsed.splice(state.numObjectTypesUsed, this._objectTypesUsed.length - state.numObjectTypesUsed);
this._templateInstantiationRequests.splice(state.numTemplateInstantiationRequests, this._templateInstantiationRequests.length - state.numTemplateInstantiationRequests);
}
// this is column offset, and is thus zero-origin
function _getColumn () : number {
return this._columnOffset;
}
function _newError (message : string) : void {
this._errors.push(new CompileError(this._filename, this._lineNumber, this._getColumn(), message));
}
function _newError (message : string, lineNumber : number, columnOffset : number) : void {
this._errors.push(new CompileError(this._filename, lineNumber, columnOffset, message));
}
function _newError (message : string, token : Token) : void {
this._errors.push(new CompileError(token, message));
}
function _newDeprecatedWarning (message : string) : void {
this._errors.push(new DeprecatedWarning(this._filename, this._lineNumber, this._getColumn(), message));
}
function _newExperimentalWarning(feature : Token) : void {
this._errors.push(new ExperimentalWarning(feature, feature.getValue()));
}
function _advanceToken () : void {
if (this._tokenLength != 0) {
this._forwardPos(this._tokenLength);
this._tokenLength = 0;
this._docComment = null;
}
while (true) {
// skip espaces and comments in-line
while (true) {
var matched = this._getInput().match(/^[ \t]+/);
if (matched != null)
this._forwardPos(matched[0].length);
if (this._columnOffset != this._lines[this._lineNumber - 1].length)
break;
if (this._lineNumber == this._lines.length)
break;
this._lineNumber++;
this._columnOffset = 0;
}
switch (this._getInputByLength(2)) {
case "/*":
if (this._getInputByLength(4) == "/***") {
this._forwardPos(3); // skip to the last *, since the input might be: /***/
var fileLevelDocComment = this._parseDocComment();
if (fileLevelDocComment == null) {
return;
}
// the first "/***" comment is the file-level doc comment
if (this._fileLevelDocComment == null) {
this._fileLevelDocComment = fileLevelDocComment;
}
} else if (this._getInputByLength(3) == "/**") {
this._forwardPos(2); // skip to the last *, the input might be: /**/
if ((this._docComment = this._parseDocComment()) == null) {
return;
}
} else {
this._forwardPos(2); // skip "/*"
this._docComment = null;
if (! this._skipMultilineComment()) {
return;
}
}
break;
case "//":
this._docComment = null;
if (this._lineNumber == this._lines.length) {
this._columnOffset = this._lines[this._lineNumber - 1].length;
} else {
this._lineNumber++;
this._columnOffset = 0;
}
break;
default:
return;
}
}
}
function _skipMultilineComment () : boolean {
var startLineNumber = this._lineNumber;
var startColumnOffset = this._columnOffset;
while (true) {
var endAt = this._getInput().indexOf("*/");
if (endAt != -1) {
this._forwardPos(endAt + 2);
return true;
}
if (this._lineNumber == this._lines.length) {
this._columnOffset = this._lines[this._lineNumber - 1].length;
this._errors.push(new CompileError(this._filename, startLineNumber, startColumnOffset, "could not find the end of the comment"));
return false;
}
++this._lineNumber;
this._columnOffset = 0;
}
return false; // dummy
}
// parse jsxdoc comments
function _parseDocComment () : DocComment {
var docComment = new DocComment();
var node : DocCommentNode = docComment;
while (true) {
// skip " * ", or return if "*/"
var count = this._parseDocCommentAdvanceWhiteSpace();
if (this._getInputByLength(2) == "*/") {
this._forwardPos(2);
break;
} else if (this._getInputByLength(1) == "*") {
this._forwardPos(1);
this._parseDocCommentAdvanceWhiteSpace();
}
else {
this._forwardPos(-count); // to keep indent
}
// fetch tag (and paramName), and setup the target node to push content into
var tagMatch = this._getInput().match(/^\@([0-9A-Za-z_]+)[ \t]*/);
if (tagMatch != null) {
this._forwardPos(tagMatch[0].length);
var tag = tagMatch[1];
switch (tag) {
case "param":
var nameMatch = this._getInput().match(/[0-9A-Za-z_]+/);
if (nameMatch != null) {
var token = new Token(nameMatch[0], false, this._filename, this._lineNumber, this._getColumn());
this._forwardPos(nameMatch[0].length);
node = new DocCommentParameter(token);
docComment.getParams().push(node as DocCommentParameter);
} else {
this._newError("name of the parameter not found after @param");
node = null;
}
break;
default:
node = new DocCommentTag(tag);
docComment.getTags().push(node as DocCommentTag);
break;
}
}
var endAt = this._getInput().indexOf("*/");
if (endAt != -1) {
if (node != null) {
node.appendDescription(this._getInput().substring(0, endAt) + "\n");
}
this._forwardPos(endAt + 2);
break;
}
if (node != null) {
node.appendDescription(this._getInput() + "\n");
}
if (this._lineNumber == this._lines.length) {
this._columnOffset = this._lines[this._lineNumber - 1].length;
this._newError("could not find the end of the doccomment");
return null;
}
++this._lineNumber;
this._columnOffset = 0;
}
return docComment;
}
function _parseDocCommentAdvanceWhiteSpace () : number {
var count = 0;
while (true) {
var ch = this._getInputByLength(1);
if (ch == " " || ch == "\t") {
this._forwardPos(1);
count++;
} else {
break;
}
}
return count;
}
function _isEOF () : boolean {
this._advanceToken();
return this._lineNumber == this._lines.length && this._columnOffset == this._lines[this._lines.length - 1].length;
}
function _expectIsNotEOF () : boolean {
if (this._isEOF()) {
this._newError("unexpected EOF");
return false;
}
return true;
}
function _expectOpt (expected : string, excludePattern : RegExp = null) : Token {
return this._expectOpt([ expected ], excludePattern);
}
function _expectOpt (expected : string[], excludePattern : RegExp = null) : Token {
this._advanceToken();
for (var i = 0; i < expected.length; ++i) {
if (this._completionRequest != null) {
var offset = this._completionRequest.isInRange(this._lineNumber, this._columnOffset, expected[i].length);
if (offset != -1) { // && expected[i].match(/[A-Za-z]/) != null) {
this._completionRequest.pushCandidates(new KeywordCompletionCandidate(expected[i]).setPrefix(this._getInputByLength(offset)));
}
}
if (this._getInputByLength(expected[i].length) == expected[i]) {
if (expected[i].match(_Lexer.rxIdent) != null
&& this._getInput().match(_Lexer.rxIdent)[0].length != expected[i].length) {
// part of a longer token
} else if (excludePattern != null && this._getInput().match(excludePattern) != null) {
// skip if the token matches the exclude pattern
} else {
// found
this._tokenLength = expected[i].length;
return new Token(expected[i], false, this._filename, this._lineNumber, this._getColumn());
}
}
}
return null;
}
function _expect (expected : string, excludePattern : RegExp = null) : Token {
return this._expect([ expected ], excludePattern);
}
function _expect (expected : string[], excludePattern : RegExp = null) : Token {
var token = this._expectOpt(expected, excludePattern);
if (token == null) {
// move to the point where expect
// see t/compile_error/178
var lineOffset = this._lineNumber - 1;
var columnOffset = this._columnOffset - 1;
while (lineOffset >= 0 && columnOffset >= 0) {
if (! /[ \t\r\n]/.test(this._lines[lineOffset].charAt(columnOffset) ?: " ")) {
break;
}
if (columnOffset != 0) {
columnOffset--;
}
else {
do {
columnOffset = this._lines[--lineOffset].length - 1;
} while (this._lines[lineOffset].length == 0 && lineOffset >= 0);
}
}
this._newError("expected keyword: " + expected.join(" "), lineOffset + 1, columnOffset + 1);
return null;
}
return token;
}
function _expectIdentifierOpt (completionCb : function(:Parser):CompletionCandidates = null) : Token {
this._advanceToken();
var matched = this._getInput().match(_Lexer.rxIdent);
if (completionCb != null && this._completionRequest != null) {
var offset = this._completionRequest.isInRange(this._lineNumber, this._columnOffset, matched != null ? matched[0].length : 0);
if (offset != -1) {
this._completionRequest.pushCandidates(completionCb(this).setPrefix(matched[0].substring(0, offset)));
}
}
if (matched == null)
return null;
this._tokenLength = matched[0].length;
var token = new Token(matched[0], true, this._filename, this._lineNumber, this._getColumn());
if (_Lexer.keywords.hasOwnProperty(matched[0])) {
this._newError("expected an identifier but found a keyword", token);
return null;
}
if (_Lexer.reserved.hasOwnProperty(matched[0])) {
this._newError("expected an identifier but found a reserved word", token);
return null;
}
return token;
}
function _expectIdentifier (completionCb : function(:Parser):CompletionCandidates = null) : Token {
var token = this._expectIdentifierOpt(completionCb);
if (token != null)
return token;
this._newError("expected an identifier");
return null;
}
function _expectStringLiteralOpt () : Token {
this._advanceToken();
var heredocStartMatch = this._getInput().match(_Lexer.rxHeredocStart);
if (heredocStartMatch) {
var preservedState = this._preserveState();
var value = heredocStartMatch[0];
this._forwardPos(value.length);
var endRe = value.charAt(0) == '"' ? _Lexer.rxHeredocEndDoubleQuoted : _Lexer.rxHeredocEndSingleQuoted;
while (true) {
var input = this._getInput();
var endMatch = input.match(endRe);
if (endMatch) {
value += endMatch[0];
this._forwardPos(endMatch[0].length);
break;
}
value += input + "\n";
this._lineNumber++;
this._columnOffset = 0;
if (this._lineNumber > this._lines.length) {
// EOF
this._restoreState(preservedState);
this._newError("unterminated multi-line string literal");
break;
}
}
return new Token(value, false, this._filename, preservedState.lineNumber, preservedState.columnOffset);
}
var matched = this._getInput().match(_Lexer.rxStringLiteral);
if (matched == null)
return null;
this._tokenLength = matched[0].length;
return new Token(matched[0], false, this._filename, this._lineNumber, this._getColumn());
}
function _expectStringLiteral () : Token {
var token = this._expectStringLiteralOpt();
if (token != null)
return token;
this._newError("expected a string literal");
return null;
}
function _expectNumberLiteralOpt () : Token {
this._advanceToken();
var matched = this._getInput().match(_Lexer.rxIntegerLiteral);
if (matched == null)
matched = this._getInput().match(_Lexer.rxNumberLiteral);
if (matched == null)
return null;
this._tokenLength = matched[0].length;
return new Token(matched[0], false, this._filename, this._lineNumber, this._getColumn());
}
function _expectRegExpLiteralOpt () : Token {
this._advanceToken();
var matched = this._getInput().match(_Lexer.rxRegExpLiteral);
if (matched == null)
return null;
this._tokenLength = matched[0].length;
return new Token(matched[0], false, this._filename, this._lineNumber, this._getColumn());
}
function _skipStatement () : void {
var advanced = false;
while (! this._isEOF()) {
switch (this._getInputByLength(1)) {
case ";":
// return after the semicolon
this._tokenLength = 1;
this._advanceToken();
return;
case "{":
if (! advanced) {
this._tokenLength = 1;
this._advanceToken();
}
return;
case "}":
// return before the block token
return;
}
this._tokenLength = 1;
this._advanceToken();
advanced = true;
}
}
function _importStatement (importToken : Token) : boolean {
// parse
var classes = null : Token[];
var token = this._expectIdentifierOpt();
if (token != null) {
classes = [ token ];
while (true) {
if ((token = this._expect([ ",", "from" ])) == null)
return false;
if (token.getValue() == "from")
break;
if ((token = this._expectIdentifier()) == null)
return false;
classes.push(token);
}
}
var filenameToken = this._expectStringLiteral();
if (filenameToken == null)
return false;
var alias = null : Token;
if (this._expectOpt("into") != null) {
if ((alias = this._expectIdentifier()) == null)
return false;
}
if (this._expect(";") == null)
return false;
// check conflict
if (alias != null && Util.isBuiltInClass(alias.getValue())) {
this._errors.push(new CompileError(alias, "cannot use name of a built-in class as an alias"));
return false;
}
if (classes != null) {
var success = true;
for (var i = 0; i < this._imports.length; ++i)
for (var j = 0; j < classes.length; ++j)
if (! this._imports[i].checkNameConflict(this._errors, classes[j]))
success = false;
if (! success)
return false;
} else {
for (var i = 0; i < this._imports.length; ++i) {
if (alias == null) {
if (this._imports[i].getAlias() == null && this._imports[i].getFilenameToken().getValue() == filenameToken.getValue()) {
this._errors.push(new CompileError(filenameToken, "cannot import the same file more than once (unless using an alias)"));
return false;
}
} else {
if (! this._imports[i].checkNameConflict(this._errors, alias))
return false;
}
}
}
// push
var imprt = Import.create(this._errors, filenameToken, alias, classes);
if (imprt == null)
return false;
this._imports.push(imprt);
return true;
}
function _expectClassDefOpt () : boolean {
var state = this._preserveState();
try {
while (true) {
var token = this._expectOpt([ "class", "interface", "mixin", "abstract", "final" ]);
if (token == null)
return false;
if (token.getValue() == "class" || token.getValue() == "interface" || token.getValue() == "mixin")
return true;
}
} finally {
this._restoreState(state);
}
return true; // dummy
}
function _classDefinition () : ClassDefinition {
this._classType = null;
this._extendType = null;
this._implementTypes = new ParsedObjectType[];
this._objectTypesUsed = new ParsedObjectType[];
this._inners = new ClassDefinition[];
this._templateInners = new TemplateClassDefinition[];
// attributes* class
this._classFlags = 0;
if (this._outerClass) {
// inherits flags from the outer classe
this._classFlags |= this._outerClass.classFlags & (ClassDefinition.IS_NATIVE);
}
var nativeSource = null : Token;
var docComment = null : DocComment;
while (true) {
var token = this._expect([ "class", "interface", "mixin", "abstract", "final", "native", "__fake__", "__export__" ]);
if (token == null)
return null;
if (this._classFlags == 0)
docComment = this._docComment;
// "class", "interface", or "mixin"
if (token.getValue() == "class") {
break;
}
else if (token.getValue() == "interface") {
if ((this._classFlags & (ClassDefinition.IS_FINAL | ClassDefinition.IS_NATIVE)) != 0) {
this._newError("interface cannot have final or native attribute set");
return null;
}
this._classFlags |= ClassDefinition.IS_INTERFACE;
break;
}
else if (token.getValue() == "mixin") {
if ((this._classFlags & (ClassDefinition.IS_FINAL | ClassDefinition.IS_NATIVE | ClassDefinition.IS_EXPORT)) != 0) {
this._newError("mixin cannot have final, native, or __export__ attribute set");
return null;
}
this._classFlags |= ClassDefinition.IS_MIXIN;
break;
}
// class attributes
var newFlag = 0;
switch (token.getValue()) {
case "abstract":
newFlag = ClassDefinition.IS_ABSTRACT;
break;
case "final":
newFlag = ClassDefinition.IS_FINAL;
break;
case "native":
if (this._expectOpt("(") != null) { // native("...")
this._newDeprecatedWarning("use of native(\"...\") is deprecated, use class N { ... } = \"...\"; instead");
nativeSource = this._expectStringLiteral();
this._expect(")");
}
newFlag = ClassDefinition.IS_NATIVE;
break;
case "__fake__":
newFlag = ClassDefinition.IS_FAKE;
break;
case "__export__":
newFlag = ClassDefinition.IS_EXPORT;
break;
default:
throw new Error("logic flaw");
}
if ((this._classFlags & newFlag) != 0) {
this._newError("same attribute cannot be specified more than once");
return null;
}
this._classFlags |= newFlag;
}
var className = this._expectIdentifier();
if (className == null)
return null;
// template
if ((this._typeArgs = this._formalTypeArguments()) == null) {
return null;
}
this._classType = new ParsedObjectType(
new QualifiedName(className, (this._outerClass != null) ? this._outerClass.classType : null),
this._typeArgs.map.<Type>(function (token : Token) : Type {
// convert formal typearg (Token) to actual typearg (Type)
return new ParsedObjectType(new QualifiedName(token), new Type[]);
}));
this._objectTypesUsed.push(this._classType);
// extends
if ((this._classFlags & (ClassDefinition.IS_INTERFACE | ClassDefinition.IS_MIXIN)) == 0) {
if (this._expectOpt("extends") != null) {
this._extendType = this._objectTypeDeclaration(
null,
true,
function (classDef) {
return (classDef.flags() & (ClassDefinition.IS_MIXIN | ClassDefinition.IS_INTERFACE | ClassDefinition.IS_FINAL)) == 0;
});
}
if (this._extendType == null && className.getValue() != "Object") {
this._extendType = new ParsedObjectType(new QualifiedName(new Token("Object", true)), new Type[]);
this._objectTypesUsed.push(this._extendType);
}
} else {
if ((this._classFlags & (ClassDefinition.IS_ABSTRACT | ClassDefinition.IS_FINAL | ClassDefinition.IS_NATIVE)) != 0) {
this._newError("interface or mixin cannot have attributes: 'abstract', 'final', 'native");
this._classFlags &= ~ (ClassDefinition.IS_ABSTRACT | ClassDefinition.IS_FINAL | ClassDefinition.IS_NATIVE); // erase the flags and continue
}
}
// implements
if (this._expectOpt("implements") != null) {
do {
var implementType = this._objectTypeDeclaration(
null,
true,
function (classDef) {
return (classDef.flags() & (ClassDefinition.IS_MIXIN | ClassDefinition.IS_INTERFACE)) != 0;
});
if (implementType != null) {
this._implementTypes.push(implementType);
}
} while (this._expectOpt(",") != null);
}
// body
if (this._expect("{") == null)
return null;
var members = new MemberDefinition[];
var success = true;
while (this._expectOpt("}") == null) {
if (! this._expectIsNotEOF())
break;
if (this._expectClassDefOpt()) {
this._pushClassState();
// parse inner class
if (this._classDefinition() == null)
this._skipStatement();
this._popClassState();
continue;
}
var member = this._memberDefinition();
if (member != null) {
members.push(member);
} else {
this._skipStatement();
}
}
// in-line native definition
var assignToken = this._expectOpt("=");
if (assignToken != null) {
nativeSource = this._expectStringLiteral();
if (this._expect(";") == null) {
return null;
}
if ((this._classFlags & ClassDefinition.IS_NATIVE) == 0) {
this._errors.push(new CompileError(assignToken, "in-line native definition requires native attribute"));
return null;
}
}
// check name conflicts
if ((this._classFlags & ClassDefinition.IS_NATIVE) == 0 && Util.isBuiltInClass(className.getValue())) {
// any better way to check that we are parsing a built-in file?
this._errors.push(new CompileError(className, "cannot re-define a built-in class"));
success = false;
} else if (this._outerClass != null) {
for (var i = 0; i < this._outerClass.inners.length; ++i) {
if (this._outerClass.inners[i].className() == className.getValue()) {
this._errors.push(new CompileError(className, "a non-template inner class with the same name has been already declared"));
success = false;
break;
}
}
for (var i = 0; i < this._outerClass.templateInners.length; ++i) {
if (this._outerClass.templateInners[i].className() == className.getValue()) {
this._errors.push(new CompileError(className, "a template inner class with the same name has been already declared"));
success = false;
break;
}
}
} else {
for (var i = 0; i < this._imports.length; ++i)
if (! this._imports[i].checkNameConflict(this._errors, className))
success = false;
for (var i = 0; i < this._classDefs.length; ++i) {
if (this._classDefs[i].className() == className.getValue()) {
this._errors.push(new CompileError(className, "a non-template class with the same name has been already declared"));
success = false;
break;
}
}
for (var i = 0; i < this._templateClassDefs.length; ++i) {
if (this._templateClassDefs[i].className() == className.getValue()) {
this._errors.push(new CompileError(className, "a template class with the name same has been already declared"));
success = false;
break;
}
}
}
if (! success)
return null;
// done
var classDef : ClassDefinition;
if (this._typeArgs.length != 0) {
var templateClassDef = new TemplateClassDefinition(className, className.getValue(), this._classFlags, this._typeArgs, this._extendType, this._implementTypes, members, this._inners, this._templateInners, this._objectTypesUsed, docComment);
if (this._outerClass != null) {
this._outerClass.templateInners.push(templateClassDef);
} else {
this._templateClassDefs.push(templateClassDef);
}
classDef = templateClassDef;
} else {
classDef = new ClassDefinition(className, className.getValue(), this._classFlags, this._extendType, this._implementTypes, members, this._inners, this._templateInners, this._objectTypesUsed, docComment);
if (this._outerClass != null) {
this._outerClass.inners.push(classDef);
} else {
this._classDefs.push(classDef);
}
}
if (nativeSource != null) {
classDef.setNativeSource(nativeSource);
}
classDef.setParser(this);
return classDef;
}
function _memberDefinition () : MemberDefinition {
var flags = 0;
var isNoExport = false;
var docComment = null : DocComment;
while (true) {
var token = this._expect([ "function", "var", "static", "abstract", "override", "final", "const", "native", "__readonly__", "inline", "__pure__", "delete", "__export__", "__noexport__" ]);
if (token == null)
return null;
if (flags == 0)
docComment = this._docComment;
if (token.getValue() == "const") {
if ((flags & ClassDefinition.IS_STATIC) == 0) {
this._newError("constants must be static");
return null;
}
flags |= ClassDefinition.IS_CONST;
break;
} else if (token.getValue() == "function" || token.getValue() == "var") {
break;
} else if (token.getValue() == "__noexport__") {
if (isNoExport) {
this._newError("same attribute cannot be specified more than once");
return null;
} else if ((flags & ClassDefinition.IS_EXPORT) != 0) {
this._newError("cannot set the attribute, already declared as __export__");
return null;
}
isNoExport = true;
} else {
var newFlag = 0;
switch (token.getValue()) {
case "static":
if ((this._classFlags & (ClassDefinition.IS_INTERFACE | ClassDefinition.IS_MIXIN)) != 0) {
this._newError("interfaces and mixins cannot have static members");
return null;
}
newFlag = ClassDefinition.IS_STATIC;
break;
case "abstract":
newFlag = ClassDefinition.IS_ABSTRACT;
break;
case "override":
if ((this._classFlags & ClassDefinition.IS_INTERFACE) != 0) {
this._newError("functions of an interface cannot have 'override' attribute set");
return null;
}
newFlag = ClassDefinition.IS_OVERRIDE;
break;
case "final":
if ((this._classFlags & ClassDefinition.IS_INTERFACE) != 0) {
this._newError("functions of an interface cannot have 'final' attribute set");
return null;
}
newFlag = ClassDefinition.IS_FINAL;
break;
case "native":
newFlag = ClassDefinition.IS_NATIVE;
break;
case "__readonly__":
newFlag = ClassDefinition.IS_READONLY;
break;
case "inline":
newFlag = ClassDefinition.IS_INLINE;
break;
case "__pure__":
newFlag = ClassDefinition.IS_PURE;
break;
case "delete":
newFlag = ClassDefinition.IS_DELETE;
break;
case "__export__":
if (isNoExport) {
this._newError("cannot set the attribute, already declared as __noexport__");
return null;
}
newFlag = ClassDefinition.IS_EXPORT;
break;
default:
throw new Error("logic flaw");
}
if ((flags & newFlag) != 0) {
this._newError("same attribute cannot be specified more than once");
return null;
}
flags |= newFlag;
}
}
function shouldExport(name : string) : boolean {
if (isNoExport)
return false;
if ((this._classFlags & ClassDefinition.IS_EXPORT) == 0)
return false;
if (name.charAt(0) == "_")
return false;
return true;
}
if ((this._classFlags & ClassDefinition.IS_INTERFACE) != 0)
flags |= ClassDefinition.IS_ABSTRACT;
if (token.getValue() == "function") {
return this._functionDefinition(token, flags, docComment, shouldExport);
}
// member variable decl.
if ((flags & ~(ClassDefinition.IS_STATIC | ClassDefinition.IS_ABSTRACT | ClassDefinition.IS_CONST | ClassDefinition.IS_READONLY | ClassDefinition.IS_EXPORT)) != 0) {
this._newError("variables may only have attributes: static, abstract, const");
return null;
}
if ((flags & ClassDefinition.IS_READONLY) != 0 && (this._classFlags & ClassDefinition.IS_NATIVE) == 0) {
this._newError("only native classes may use the __readonly__ attribute");
return null;
}
var name = this._expectIdentifier();
if (name == null)
return null;
if (shouldExport(name.getValue()))
flags |= ClassDefinition.IS_EXPORT;
var type = null : Type;
if (this._expectOpt(":") != null)
if ((type = this._typeDeclaration(false)) == null)
return null;
var initialValue = null : Expression;
var closures = new MemberFunctionDefinition[];
if (this._expectOpt("=") != null) {
if ((flags & ClassDefinition.IS_ABSTRACT) != 0) {
this._newError("abstract variable cannot have default value");
return null;
}
this._closures = closures;
initialValue = this._assignExpr(false);
this._closures = null;
if (initialValue == null)
return null;
}
if (type == null && initialValue == null) {
this._newError("variable declaration should either have type declaration or initial value");
return null;
}
if (! this._expect(";"))
return null;
// all non-native, non-template values have initial value
if (this._typeArgs.length == 0 && initialValue == null && (this._classFlags & ClassDefinition.IS_NATIVE) == 0)
initialValue = Expression.getDefaultValueExpressionOf(type);
return new MemberVariableDefinition(token, name, flags, type, initialValue, closures, docComment);
}
function _functionDefinition (token : Token, flags : number, docComment : DocComment, shouldExport : function (name : string) : boolean) : MemberFunctionDefinition {
// name
var name = this._expectIdentifier();
if (name == null)
return null;
if (shouldExport(name.getValue()))
flags |= ClassDefinition.IS_EXPORT;
if (name.getValue() == "constructor") {
if ((this._classFlags & ClassDefinition.IS_INTERFACE) != 0) {
this._newError("interface cannot have a constructor");
return null;
}
if ((flags & (ClassDefinition.IS_ABSTRACT | ClassDefinition.IS_FINAL)) != 0) {
this._newError("constructor cannot be declared as 'abstract' or 'final'");
return null;
}
flags |= ClassDefinition.IS_FINAL;
}
flags |= this._classFlags & (ClassDefinition.IS_NATIVE | ClassDefinition.IS_FINAL);
// parse type args and add to the current typearg list
var typeArgs = this._formalTypeArguments();
if (typeArgs == null) {
return null;
}
this._typeArgs = this._typeArgs.concat(typeArgs);
var numObjectTypesUsed = this._objectTypesUsed.length;
this._pushScope(null, null);
try {
if (this._expect("(") == null)
return null;
// arguments
var args = this._functionArgumentsExpr((this._classFlags & ClassDefinition.IS_NATIVE) != 0, true, true);
if (args == null)
return null;
// return type
var returnType = null : Type;
if (name.getValue() == "constructor") {
// no return type
returnType = Type.voidType;
} else {
if (this._expect(":") == null)
return null;
returnType = this._typeDeclaration(true);
if (returnType == null)
return null;
}
// take care of: "delete function constructor();"
if ((flags & ClassDefinition.IS_DELETE) != 0) {
if (name.getValue() != "constructor" || (flags & ClassDefinition.IS_STATIC) != 0) {
this._newError("only constructors may have the \"delete\" attribute set");
return null;
}
if (args.length != 0) {
this._newError("cannot \"delete\" a constructor with one or more arguments");
return null;
}
}
function createDefinition(locals : LocalVariable[], statements : Statement[], closures : MemberFunctionDefinition[], lastToken : Token) : MemberFunctionDefinition {
return typeArgs.length != 0
? new TemplateFunctionDefinition(token, name, flags, typeArgs, returnType, args, locals, statements, closures, lastToken, docComment) as MemberFunctionDefinition
: new MemberFunctionDefinition(token, name, flags, returnType, args, locals, statements, closures, lastToken, docComment);
}
// take care of abstract function
if ((this._classFlags & ClassDefinition.IS_INTERFACE) != 0) {
if (this._expect(";") == null)
return null;
return createDefinition(null, null, new MemberFunctionDefinition[], null);
} else if ((flags & (ClassDefinition.IS_ABSTRACT | ClassDefinition.IS_NATIVE | ClassDefinition.IS_DELETE)) != 0) {
// "delete function constructor() {} is permitted for backwards compatibility
var endDeclToken = this._expect([ ";", "{" ]);
if (endDeclToken == null)
return null;
if (endDeclToken.getValue() == ";")
return createDefinition(null, null, new MemberFunctionDefinition[], null);
} else {
if (this._expect("{") == null)
return null;
}
// body
this._arguments = args;
if (name.getValue() == "constructor")
var lastToken = this._initializeBlock();
else
lastToken = this._block();
var funcDef = createDefinition(this._locals, this._statements, this._closures, lastToken);
return funcDef;
} finally {
this._popScope();
this._typeArgs.splice(this._typeArgs.length - typeArgs.length, this._typeArgs.length);
if (typeArgs.length != 0) {
this._objectTypesUsed.splice(numObjectTypesUsed, this._objectTypesUsed.length - numObjectTypesUsed);
}
}
}
function _formalTypeArguments () : Token[] {
if (this._expectOpt(".") == null) {
return new Token[];
}
if (this._expect("<") == null) {
return null;
}
var typeArgs = new Token[];
do {
var typeArg = this._expectIdentifier();
if (typeArg == null)
return null;
typeArgs.push(typeArg);
var token = this._expectOpt([ ",", ">" ]);
if (token == null)
return null;
} while (token.getValue() == ",");
return typeArgs;
}
function _actualTypeArguments () : Type[] {
var types = new Type[];
var state = this._preserveState();
if (this._expectOpt(".") == null) {
return types;
}
if (this._expect("<") == null) {
this._restoreState(state);
return types;
}
// in type argument
do {
var type = this._typeDeclaration(true);
if (type == null)
return null;
types.push(type);
var token = this._expect([ ">", "," ]);
if (token == null)
return null;
} while (token.getValue() == ",");
return types;
}
function _typeDeclaration (allowVoid : boolean) : Type {
var token;
var typeDecl : Type;
if ((token = this._expectOpt("void")) != null) {
typeDecl = Type.voidType;
} else {
typeDecl = this._typeDeclarationNoVoidNoYield();
if (typeDecl == null)
return null;
}
// yield
while (this._expectOpt("yield") != null) {
var genType = this._typeDeclaration(true);
if (genType == null) {
return null;
}
typeDecl = this._registerGeneratorTypeOf(typeDecl, genType);
}
if (! allowVoid && typeDecl.equals(Type.voidType)) {
this._newError("'void' cannot be used here", token);
return null;
}
return typeDecl;
}
function _typeDeclarationNoVoidNoYield () : Type {
var typeDecl = this._typeDeclarationNoArrayNoVoidNoYield();
if (typeDecl == null)
return null;
// []
while (this._expectOpt("[") != null) {
var token;
if ((token = this._expect("]")) == null)
return null;
if (typeDecl instanceof NullableType) {
this._newError("Nullable.<T> cannot be an array, should be: T[]");
return null;
}
typeDecl = this._registerArrayTypeOf(token, typeDecl);
}
return typeDecl;
}
function _typeDeclarationNoArrayNoVoidNoYield () : Type {
var token = this._expectOpt([ "MayBeUndefined", "Nullable", "variant" ]);
if (token == null) {
return this._primaryTypeDeclaration();
}
switch (token.getValue()) {
case "MayBeUndefined":
this._newDeprecatedWarning("use of 'MayBeUndefined' is deprecated, use 'Nullable' instead");
// falls through
case "Nullable":
return this._nullableTypeDeclaration();
case "variant":
return Type.variantType;
default:
throw new Error("logic flaw");
}
}
function _nullableTypeDeclaration () : Type {
if (this._expect(".") == null || this._expect("<") == null)
return null;
var baseType = this._typeDeclaration(true);
if (baseType == null)
return null;
if (this._expect(">") == null)
return null;
if (baseType.equals(Type.variantType)) {
this._newError("variant cannot be declared as nullable (since it is always nullable)");
return null;
}
if (baseType instanceof NullableType) {
this._newError("nested Nullable.<T> is forbidden");
return null;
}
if (this._typeArgs != null) {
for (var i = 0; i < this._typeArgs.length; ++i) {
if (baseType.equals(new ParsedObjectType(new QualifiedName(this._typeArgs[i]), new Type[]))) {
return baseType.toNullableType(true);
}
}
}
return baseType.toNullableType();
}
function _primaryTypeDeclaration () : Type {
var token = this._expectOpt([ "(", "function", "boolean", "int", "number", "string" ]);
if (token != null) {
switch (token.getValue()) {
case "(":
return this._lightFunctionTypeDeclaration(null);
case "function":
return this._functionTypeDeclaration(null);
case "boolean":
return Type.booleanType;
case "int":
return Type.integerType;
case "number":
return Type.numberType;
case "string":
return Type.stringType;
default:
throw new Error("logic flaw");
}
} else {
return this._objectTypeDeclaration(null, true, null);
}
}
function _objectTypeDeclaration (firstToken : Token, allowInner : boolean, autoCompleteMatchCb : function(:ClassDefinition):boolean) : ParsedObjectType {
var token;
if (firstToken == null) {
if (this._classType != null && (token = this._expectOpt("__CLASS__")) != null) {
// ok
} else if ((token = this._expectIdentifier(function (self) { return self._getCompletionCandidatesOfTopLevel(autoCompleteMatchCb); })) == null)
return null;
} else {
token = firstToken;
}
if (token.getValue() == "variant") {
this._errors.push(new CompileError(token, "cannot use 'variant' as a class name"));
return null;
} else if (token.getValue() == "Nullable" || token.getValue() == "MayBeUndefined") {
this._errors.push(new CompileError(token, "cannot use 'Nullable' (or MayBeUndefined) as a class name"));
return null;
} else if (token.getValue() == "__CLASS__") {
return this._classType;
}
// import part
var imprt = this.lookupImportAlias(token.getValue());
if (imprt != null) {
if (this._expect(".") == null)
return null;
token = this._expectIdentifier(function (self) { return self._getCompletionCandidatesOfNamespace(imprt, autoCompleteMatchCb); });
if (token == null)
return null;
}
if (! allowInner) {
var qualifiedName = new QualifiedName(token, imprt);
var typeArgs = this._actualTypeArguments();
if (typeArgs == null) {
return null;
} else if (typeArgs.length != 0) {
return this._templateTypeDeclaration(qualifiedName, typeArgs);
} else {
// object
var objectType = new ParsedObjectType(qualifiedName, new Type[]);
this._objectTypesUsed.push(objectType);
return objectType;
}
} else {
var enclosingType : ParsedObjectType = null;
while (true) {
qualifiedName = enclosingType != null ? new QualifiedName(token, enclosingType) : new QualifiedName(token, imprt);
var typeArgs = this._actualTypeArguments();
if (typeArgs == null) {
return null;
} else if (typeArgs.length != 0) {
enclosingType = this._templateTypeDeclaration(qualifiedName, typeArgs);
} else {
var objectType = new ParsedObjectType(qualifiedName, new Type[]);
this._objectTypesUsed.push(objectType);
enclosingType = objectType;
}
if (this._expectOpt(".") == null)
break;
token = this._expectIdentifier();
if (token == null)
return null;
}
return enclosingType;
}
}
function _templateTypeDeclaration (qualifiedName : QualifiedName, typeArgs : Type[]) : ParsedObjectType {
var className = qualifiedName.getToken().getValue();
if (className == "Array" || className == "Map") {
if (typeArgs[0] instanceof NullableType) {
this._newError("cannot declare " + className + ".<Nullable.<T>>, should be " + className + ".<T>");
return null;
}
if (typeArgs[0].equals(Type.voidType)) {
this._newError("cannot declare " + className + ".<T> with T=void");
return null;
}
}
// return object type
var objectType = new ParsedObjectType(qualifiedName, typeArgs);
this._objectTypesUsed.push(objectType);
return objectType;
}
function _lightFunctionTypeDeclaration (objectType : Type) : Type {
// parse args
var argTypes = new Type[];
if (this._expectOpt(")") == null) {
do {
var isVarArg = this._expectOpt("...") != null;
var argType = this._typeDeclaration(false);
if (argType == null)
return null;
if (isVarArg) {
argTypes.push(new VariableLengthArgumentType(argType));
if (this._expect(")") == null)
return null;
break;
}
argTypes.push(argType);
var token = this._expect([ ")", "," ]);
if (token == null)
return null;
} while (token.getValue() == ",");
}
// parse return type
if (this._expect(["->", "=>"]) == null)
return null;
var returnType = this._typeDeclaration(true);
if (returnType == null)
return null;
if (objectType != null)
return new MemberFunctionType(null, objectType, returnType, argTypes, true);
else
return new StaticFunctionType(null, returnType, argTypes, true);
}
function _functionTypeDeclaration (objectType : Type) : Type {
// optional function name
this._expectIdentifierOpt();
// parse args
if(this._expect("(") == null)
return null;
var argTypes = new Type[];
if (this._expectOpt(")") == null) {
do {
var isVarArg = this._expectOpt("...") != null;
this._expectIdentifierOpt(); // may have identifiers
if (this._expect(":") == null)
return null;
var argType = this._typeDeclaration(false);
if (argType == null)
return null;
if (isVarArg) {
argTypes.push(new VariableLengthArgumentType(argType));
if (this._expect(")") == null)
return null;
break;
}
argTypes.push(argType);
var token = this._expect([ ")", "," ]);
if (token == null)
return null;
} while (token.getValue() == ",");
}
// parse return type
if (this._expect(":") == null)
return null;
var returnType = this._typeDeclaration(true);
if (returnType == null)
return null;
if (objectType != null)
return new MemberFunctionType(null, objectType, returnType, argTypes, true);
else
return new StaticFunctionType(null, returnType, argTypes, true);
}
function _registerArrayTypeOf (token : Token, elementType : Type) : ParsedObjectType {
// var arrayType = new ParsedObjectType(new QualifiedName(new Token("Array", true), null), [ elementType ], token);
var arrayType = new ParsedObjectType(new QualifiedName(new Token("Array", true)), [ elementType ]);
this._objectTypesUsed.push(arrayType);
return arrayType;
}
function _registerGeneratorTypeOf (seedType : Type, genType : Type) : ParsedObjectType {
var generatorType = new ParsedObjectType(new QualifiedName(new Token("Generator", true)), [ seedType, genType ]);
this._objectTypesUsed.push(generatorType);
return generatorType;
}
function _initializeBlock () : Token {
var token;
while ((token = this._expectOpt("}")) == null) {
var state = this._preserveState();
if (! this._constructorInvocationStatement()) {
this._restoreState(state);
return this._block();
}
}
return token;
}
function _block () : Token {
var token;
while ((token = this._expectOpt("}")) == null) {
if (! this._expectIsNotEOF())
return null;
if (! this._statement())
this._skipStatement();
}
return token;
}
function _statement () : boolean {
// has a label?
var state = this._preserveState();
var label = this._expectIdentifierOpt();
if (label != null && this._expectOpt(":") != null) {
// within a label
} else {
this._restoreState(state);
label = null;
}
// parse the statement
var token = this._expectOpt([
"{", "var", ";", "if", "do", "while", "for", "continue", "break", "return", "switch", "throw", "try", "assert", "log", "delete", "debugger", "function", "void", "const"
]);
if (label != null) {
if (! (token != null && token.getValue().match(/^(?:do|while|for|switch)$/) != null)) {
this._newError("only blocks, iteration statements, and switch statements are allowed after a label");
return false;
}
}
if (token != null) {
switch (token.getValue()) {
case "{":
return this._block() != null;
case "var":
return this._variableStatement(false);
case "const":
return this._variableStatement(true);
case ";":
return true;
case "if":
return this._ifStatement(token);
case "do":
return this._doWhileStatement(token, label);
case "while":
return this._whileStatement(token, label);
case "for":
return this._forStatement(token, label);
case "continue":
return this._continueStatement(token);
case "break":
return this._breakStatement(token);
case "return":
return this._returnStatement(token);
case "switch":
return this._switchStatement(token, label);
case "throw":
return this._throwStatement(token);
case "try":
return this._tryStatement(token);
case "assert":
return this._assertStatement(token);
case "log":
return this._logStatement(token);
case "delete":
return this._deleteStatement(token);
case "debugger":
return this._debuggerStatement(token);
case "function":
return this._functionStatement(token);
case "void":
// void is simply skipped
break;
default:
throw new Error("logic flaw, got " + token.getValue());
}
}
// expression statement
var expr = this._expr(false);
if (expr == null)
return false;
this._statements.push(new ExpressionStatement(expr));
if (this._expect(";") == null)
return false;
return true;
}
function _constructorInvocationStatement () : boolean {
// get class
var token : Token;
if ((token = this._expectOpt("super")) != null) {
var classType = this._extendType;
} else if ((token = this._expectOpt("this")) != null) {
classType = this._classType;
} else {
if ((classType = this._objectTypeDeclaration(null, true, null)) == null)
return false;
token = classType.getToken();
if (this._classType.equals(classType)) {
// ok is calling the alternate constructor
} else if (this._extendType != null && this._extendType.equals(classType)) {
// ok is calling base class
} else {
for (var i = 0; i < this._implementTypes.length; ++i) {
if (this._implementTypes[i].equals(classType)) {
break;
}
}
if (i == this._implementTypes.length) {
// not found (and thus is not treated as a constructor invocation statement)
return false;
}
}
}
// get args
if (this._expect("(") == null)
return false;
var args = this._argsExpr();
if (args == null)
return false;
if (this._expect(";") == null)
return false;
// success
this._statements.push(new ConstructorInvocationStatement(token, classType, args));
return true;
}
function _variableStatement (isConst : boolean) : boolean {
var succeeded = [ false ];
var expr = this._variableDeclarations(false, isConst, succeeded);
if (! succeeded[0])
return false;
if (this._expect(";") == null)
return false;
if (expr != null)
this._statements.push(new ExpressionStatement(expr));
return true;
}
function _functionStatement (token : Token) : boolean {
var isGenerator = false;
if (this._expectOpt("*") != null)
isGenerator = true;
var name = this._expectIdentifier();
if (name == null)
return false;
if (this._expect("(") == null)
return false;
var args = this._functionArgumentsExpr(false, true, false);
if (args == null)
return false;
if (this._expect(":") == null)
return false;
var returnType = this._typeDeclaration(true);
if (returnType == null) {
return false;
}
if (this._expect("{") == null)
return false;
var funcLocal = this._registerLocal(name, new StaticFunctionType(token, returnType, args.map.<Type>((arg) -> arg.getType()), false), false, true);
var funcDef = this._functionBody(token, name, funcLocal, args, returnType, true, isGenerator);
if (funcDef == null) {
return false;
}
this._closures.push(funcDef);
funcDef.setFuncLocal(funcLocal);
this._statements.push(new FunctionStatement(token, funcDef));
return true;
}
function _ifStatement (token : Token) : boolean {
if (this._expect("(") == null)
return false;
var expr = this._expr(false);
if (expr == null)
return false;
if (this._expect(")") == null)
return false;
var onTrueStatements = this._subStatements();
var onFalseStatements = new Statement[];
if (this._expectOpt("else") != null) {
onFalseStatements = this._subStatements();
}
this._statements.push(new IfStatement(token, expr, onTrueStatements, onFalseStatements));
return true;
}
function _doWhileStatement (token : Token, label : Token) : boolean {
var statements = this._subStatements();
if (this._expect("while") == null)
return false;
if (this._expect("(") == null)
return false;
var expr = this._expr(false);
if (expr == null)
return false;
if (this._expect(")") == null)
return false;
this._statements.push(new DoWhileStatement(token, label, expr, statements));
return true;
}
function _whileStatement (token : Token, label : Token) : boolean {
if (this._expect("(") == null)
return false;
var expr = this._expr(false);
if (expr == null)
return false;
if (this._expect(")") == null)
return false;
var statements = this._subStatements();
this._statements.push(new WhileStatement(token, label, expr, statements));
return true;
}
function _forStatement (token : Token, label : Token) : boolean {
var state = this._preserveState();
// first try to parse as for .. in, and fallback to the other
switch (this._forInStatement(token, label)) {
case -1: // try for (;;)
break;
case 0: // error
return false;
case 1:
return true;
}
this._restoreState(state);
if (this._expect("(") == null)
return false;
// parse initialization expression
var initExpr = null : Expression;
if (this._expectOpt(";") != null) {
// empty expression
} else if (this._expectOpt("var") != null) {
var succeeded = [ false ];
initExpr = this._variableDeclarations(true, false, succeeded);
if (! succeeded[0])
return false;
if (this._expect(";") == null)
return false;
} else {
if ((initExpr = this._expr(true)) == null)
return false;
if (this._expect(";") == null)
return false;
}
// parse conditional expression
var condExpr = null : Expression;
if (this._expectOpt(";") != null) {
// empty expression
} else {
if ((condExpr = this._expr(false)) == null)
return false;
if (this._expect(";") == null)
return false;
}
// parse post expression
var postExpr = null : Expression;
if (this._expectOpt(")") != null) {
// empty expression
} else {
if ((postExpr = this._expr(false)) == null)
return false;
if (this._expect(")") == null)
return false;
}
// statements
var statements = this._subStatements();
this._statements.push(new ForStatement(token, label, initExpr, condExpr, postExpr, statements));
return true;
}
function _forInStatement (token : Token, label : Token) : number {
if (this._expect("(") == null)
return 0; // failure
var lhsExpr;
if (this._expectOpt("var") != null) {
if ((lhsExpr = this._variableDeclaration(true, false)) == null)
return -1; // retry the other
} else {
if ((lhsExpr = this._lhsExpr()) == null)
return -1; // retry the other
}
if (this._expect("in") == null)
return -1; // retry the other
var listExpr = this._expr(false);
if (listExpr == null)
return 0;
if (this._expect(")") == null)
return 0;
var statements = this._subStatements();
this._statements.push(new ForInStatement(token, label, lhsExpr, listExpr, statements));
return 1;
}
function _continueStatement (token : Token) : boolean {
var label = this._expectIdentifierOpt();
if (this._expect(";") == null)
return false;
this._statements.push(new ContinueStatement(token, label));
return true;
}
function _breakStatement (token : Token) : boolean {
var label = this._expectIdentifierOpt();
if (this._expect(";") == null)
return false;
this._statements.push(new BreakStatement(token, label));
return true;
}
function _returnStatement (token : Token) : boolean {
if (this._expectOpt(";") != null) {
this._statements.push(new ReturnStatement(token, null));
return true;
}
var expr = this._expr(false);
if (expr == null)
return false;
this._statements.push(new ReturnStatement(token, expr));
if (this._expect(";") == null)
return false;
return true;
}
function _switchStatement (token : Token, label : Token) : Nullable.<boolean> {
if (this._expect("(") == null)
return false;
var expr = this._expr(false);
if (expr == null)
return false;
if (this._expect(")") == null
|| this._expect("{") == null)
return null;
var foundCaseLabel = false;
var foundDefaultLabel = false;
// caseblock
var startStatementIndex = this._statements.length;
while (this._expectOpt("}") == null) {
if (! this._expectIsNotEOF())
return false;
var caseOrDefaultToken;
if (! foundCaseLabel && ! foundDefaultLabel) {
// first statement within the block should start with a label
if ((caseOrDefaultToken = this._expect([ "case", "default" ])) == null) {
this._skipStatement();
continue;
}
} else {
caseOrDefaultToken = this._expectOpt([ "case", "default" ]);
}
if (caseOrDefaultToken != null) {
if (caseOrDefaultToken.getValue() == "case") {
var labelExpr = this._expr();
if (labelExpr == null) {
this._skipStatement();
continue;
}
if (this._expect(":") == null) {
this._skipStatement();
continue;
}
this._statements.push(new CaseStatement(caseOrDefaultToken, labelExpr));
foundCaseLabel = true;
} else { // "default"
if (this._expect(":") == null) {
this._skipStatement();
continue;
}
if (foundDefaultLabel) {
this._newError("cannot have more than one default statement within one switch block");
this._skipStatement();
continue;
}
this._statements.push(new DefaultStatement(caseOrDefaultToken));
foundDefaultLabel = true;
}
} else {
if (! this._statement())
this._skipStatement();
}
}
// done
this._statements.push(new SwitchStatement(token, label, expr, (this._statements.splice(startStatementIndex, this._statements.length - startStatementIndex))));
return true;
}
function _throwStatement (token : Token) : boolean {
var expr = this._expr();
if (expr == null)
return false;
if (this._expect(";") == null)
return false;
this._statements.push(new ThrowStatement(token, expr));
return true;
}
function _tryStatement (tryToken : Token) : boolean {
if (this._expect("{") == null)
return false;
var startIndex = this._statements.length;
if (this._block() == null)
return false;
var tryStatements = this._statements.splice(startIndex, this._statements.length - startIndex);
var catchStatements = new CatchStatement[];
var catchOrFinallyToken = this._expect([ "catch", "finally" ]);
if (catchOrFinallyToken == null)
return false;
for (;
catchOrFinallyToken != null && catchOrFinallyToken.getValue() == "catch";
catchOrFinallyToken = this._expectOpt([ "catch", "finally" ])) {
var catchIdentifier;
var catchType;
if (this._expect("(") == null
|| (catchIdentifier = this._expectIdentifier()) == null
|| this._expect(":") == null
|| (catchType = this._typeDeclaration(false)) == null
|| this._expect(")") == null
|| this._expect("{") == null)
return false;
var caughtVariable = new CaughtVariable(catchIdentifier, catchType);
this._locals.push(caughtVariable);
try {
if (this._block() == null) {
return false;
}
} finally {
this._locals.splice(this._locals.indexOf(caughtVariable), 1);
}
catchStatements.push(new CatchStatement(catchOrFinallyToken, caughtVariable, this._statements.splice(startIndex, this._statements.length - startIndex)));
}
if (catchOrFinallyToken != null) {
// finally
if (this._expect("{") == null)
return false;
if (this._block() == null)
return false;
var finallyStatements = this._statements.splice(startIndex, this._statements.length - startIndex);
} else {
finallyStatements = new Statement[];
}
this._statements.push(new TryStatement(tryToken, tryStatements, catchStatements, finallyStatements));
return true;
}
function _assertStatement (token : Token) : boolean {
var expr = this._assignExpr(false);
if (expr == null)
return false;
var msgExpr : Expression = null;
if (this._expectOpt(",") != null) {
msgExpr = this._assignExpr(false);
if (msgExpr == null)
return false;
}
if (this._expect(";") == null)
return false;
this._statements.push(new AssertStatement(token, expr, msgExpr));
return true;
}
function _logStatement (token : Token) : boolean {
var exprs = new Expression[];
do {
var expr = this._assignExpr(false);
if (expr == null)
return false;
exprs.push(expr);
} while (this._expectOpt(",") != null);
if (this._expect(";") == null)
return false;
if (exprs.length == 0) {
this._newError("no arguments");
return false;
}
this._statements.push(new LogStatement(token, exprs));
return true;
}
function _deleteStatement (token : Token) : boolean {
var expr = this._expr();
if (expr == null)
return false;
if (this._expect(";") == null)
return false;
this._statements.push(new DeleteStatement(token, expr));
return true;
}
function _debuggerStatement (token : Token) : boolean {
this._statements.push(new DebuggerStatement(token));
return true;
}
function _subStatements () : Statement[] {
var statementIndex = this._statements.length;
if (! this._statement())
this._skipStatement();
return this._statements.splice(statementIndex, this._statements.length - statementIndex);
}
function _variableDeclarations (noIn : boolean, isConst : boolean, isSuccess : boolean[]) : Expression {
isSuccess[0] = false;
var expr = null : Expression;
var commaToken = null : Token;
do {
var declExpr = this._variableDeclaration(noIn, isConst);
if (declExpr == null)
return null;
// do not push variable declarations wo. assignment
if (! (declExpr instanceof LocalExpression))
expr = expr != null ? (new CommaExpression(commaToken, expr, declExpr) as Expression) : declExpr;
} while ((commaToken = this._expectOpt(",")) != null);
isSuccess[0] = true;
return expr;
}
function _variableDeclaration (noIn : boolean, isConst : boolean) : Expression {
var identifier = this._expectIdentifier();
if (identifier == null)
return null;
var type = null : Type;
if (this._expectOpt(":"))
if ((type = this._typeDeclaration(false)) == null)
return null;
// FIXME value should be registered after parsing the initialization expression, but that prevents: var f = function () : void { f(); };
var local = this._registerLocal(identifier, type, isConst);
// parse initial value (optional)
var initialValue = null : Expression;
var assignToken;
if ((assignToken = this._expectOpt("=")) == null) {
if (isConst) {
this._newError("initializer expression is mandatory for constant declaration");
return null;
}
} else {
if ((initialValue = this._assignExpr(noIn)) == null)
return null;
}
var expr : Expression = new LocalExpression(identifier, local);
if (initialValue != null)
expr = new AssignmentExpression(assignToken, expr, initialValue);
return expr;
}
function _expr () : Expression {
return this._expr(false);
}
function _expr (noIn : boolean) : Expression {
var expr = this._assignExpr(noIn);
if (expr == null)
return null;
var commaToken;
while ((commaToken = this._expectOpt(",")) != null) {
var assignExpr = this._assignExpr(noIn);
if (assignExpr == null)
break;
expr = new CommaExpression(commaToken, expr, assignExpr);
}
return expr;
}
function _assignExpr () : Expression {
return this._assignExpr(false);
}
function _assignExpr (noIn : boolean) : Expression {
var state = this._preserveState();
// FIXME contrary to ECMA 262, we first try lhs op assignExpr, and then condExpr; does this have any problem?
// lhs
var lhsExpr = this._lhsExpr();
if (lhsExpr != null) {
var op = this._expect([ "=", "*=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=" ], /^==/);
if (op != null) {
var assignExpr = this._assignExpr(noIn);
if (assignExpr == null)
return null;
if (op.getValue() == "=") {
return new AssignmentExpression(op, lhsExpr, assignExpr);
}
else {
return new FusedAssignmentExpression(op, lhsExpr, assignExpr);
}
}
}
// failed to parse as lhs op assignExpr, try condExpr
this._restoreState(state);
return this._yieldExpr(noIn);
}
function _yieldExpr (noIn : boolean) : Expression {
var operatorToken;
if ((operatorToken = this._expectOpt("yield")) != null) {
this._newExperimentalWarning(operatorToken);
if (! this._isGenerator) {
this._newError("invalid use of 'yield' keyword in non-generator function");
return null;
}
var condExpr = this._condExpr(noIn);
if (condExpr == null)
return null;
return new YieldExpression(operatorToken, condExpr);
}
return this._condExpr(noIn);
}
function _condExpr (noIn : boolean) : Expression {
var lorExpr = this._lorExpr(noIn);
if (lorExpr == null)
return null;
var operatorToken;
if ((operatorToken = this._expectOpt("?")) == null)
return lorExpr;
var ifTrueExpr = null : Expression;
var ifFalseExpr = null : Expression;
if (this._expectOpt(":") == null) {
ifTrueExpr = this._assignExpr(noIn);
if (ifTrueExpr == null)
return null;
if (this._expect(":") == null)
return null;
}
ifFalseExpr = this._assignExpr(noIn);
if (ifFalseExpr == null)
return null;
return new ConditionalExpression(operatorToken, lorExpr, ifTrueExpr, ifFalseExpr);
}
function _binaryOpExpr (ops : string[], excludePattern : RegExp, parseFunc : function(:boolean):Expression, noIn : boolean, builderFunc : function(:Token,:Expression,:Expression):Expression) : Expression {
var expr = parseFunc(noIn);
if (expr == null)
return null;
while (true) {
var op = this._expectOpt(ops, excludePattern);
if (op == null)
break;
var rightExpr = parseFunc(false);
if (rightExpr == null)
return null;
expr = builderFunc(op, expr, rightExpr);
}
return expr;
}
function _lorExpr (noIn : boolean) : Expression {
return this._binaryOpExpr([ "||" ], null, function (noIn) {
return this._landExpr(noIn);
}, noIn, function (op, e1, e2) {
return new LogicalExpression(op, e1, e2);
});
}
function _landExpr (noIn : boolean) : Expression {
return this._binaryOpExpr([ "&&" ], null, function (noIn) {
return this._borExpr(noIn);
}, noIn, function (op, e1, e2) {
return new LogicalExpression(op, e1, e2);
});
}
function _borExpr (noIn : boolean) : Expression {
return this._binaryOpExpr([ "|" ], /^\|\|/, function (noIn) {
return this._bxorExpr(noIn);
}, noIn, function (op, e1, e2) {
return new BinaryNumberExpression(op, e1, e2);
});
}
function _bxorExpr (noIn : boolean) : Expression {
return this._binaryOpExpr([ "^" ], null, function (noIn) {
return this._bandExpr(noIn);
}, noIn, function (op, e1, e2) {
return new BinaryNumberExpression(op, e1, e2);
});
}
function _bandExpr (noIn : boolean) : Expression {
return this._binaryOpExpr([ "&" ], /^&&/, function (noIn) {
return this._eqExpr(noIn);
}, noIn, function (op, e1, e2) {
return new BinaryNumberExpression(op, e1, e2);
});
}
function _eqExpr (noIn : boolean) : Expression {
return this._binaryOpExpr([ "==", "!=" ], null, function (noIn) {
return this._relExpr(noIn);
}, noIn, function (op, e1, e2) {
return new EqualityExpression(op, e1, e2);
});
}
function _relExpr (noIn : boolean) : Expression {
var ops = [ "<=", ">=", "<", ">" ];
if (! noIn)
ops.push("in");
return this._binaryOpExpr(ops, null, function (noIn) {
return this._shiftExpr();
}, noIn, function (op, e1, e2) {
if (op.getValue() == "in")
return new InExpression(op, e1, e2);
else
return new BinaryNumberExpression(op, e1, e2);
});
}
function _shiftExpr () : Expression {
var expr = this._binaryOpExpr([ ">>>", "<<", ">>" ], null, function (noIn) {
return this._addExpr();
}, false, function (op, e1, e2) {
return new ShiftExpression(op, e1, e2);
});
return expr;
}
function _addExpr () : Expression {
return this._binaryOpExpr([ "+", "-" ], /^[+-]{2}/, function (noIn) {
return this._mulExpr();
}, false, function (op, e1, e2) {
if (op.getValue() == "+")
return new AdditiveExpression(op, e1, e2);
else
return new BinaryNumberExpression(op, e1, e2);
});
}
function _mulExpr () : Expression {
return this._binaryOpExpr([ "*", "/", "%" ], null, function (noIn) {
return this._unaryExpr();
}, false, function (op, e1, e2) {
return new BinaryNumberExpression(op, e1, e2);
});
}
function _unaryExpr () : Expression {
// read other unary operators
var op = this._expectOpt([ "++", "--", "+", "-", "~", "!", "typeof" ]);
if (op == null)
return this._asExpr();
var expr = this._unaryExpr();
if (expr == null)
return null;
switch (op.getValue()) {
case "++":
case "--":
return new PreIncrementExpression(op, expr);
case "+":
case "-":
return new SignExpression(op, expr);
case "~":
return new BitwiseNotExpression(op, expr);
case "!":
return new LogicalNotExpression(op, expr);
case "typeof":
return new TypeofExpression(op, expr);
default:
throw new Error("logic flaw");
}
}
function _asExpr () : Expression {
var expr = this._postfixExpr();
if (expr == null)
return null;
var token;
while ((token = this._expectOpt("as")) != null) {
var noConvert = this._expectOpt("__noconvert__");
var type = this._typeDeclaration(false);
if (type == null)
return null;
expr = noConvert ? (new AsNoConvertExpression(token, expr, type) as Expression) : (new AsExpression(token, expr, type) as Expression);
}
return expr;
}
function _postfixExpr () : Expression {
var expr = this._lhsExpr();
var op = this._expectOpt([ "++", "--", "instanceof" ]);
if (op == null)
return expr;
switch (op.getValue()) {
case "instanceof":
var type = this._typeDeclaration(false);
if (type == null)
return null;
return new InstanceofExpression(op, expr, type);
default:
return new PostIncrementExpression(op, expr);
}
}
function _lhsExpr () : Expression {
var expr;
var token = this._expectOpt([ "new", "super", "function" ]);
if (token != null) {
switch (token.getValue()) {
case "super":
return this._superExpr();
case "function":
expr = this._functionExpr(token);
break;
case "new":
expr = this._newExpr(token);
break;
default:
throw new Error("logic flaw");
}
} else {
expr = this._arrowFunctionOpt();
if (expr == null)
expr = this._primaryExpr();
}
if (expr == null)
return null;
while ((token = this._expectOpt([ "(", "[", "." ])) != null) {
switch (token.getValue()) {
case "(":
var args;
if ((args = this._argsExpr()) == null)
return null;
expr = new CallExpression(token, expr, args);
break;
case "[":
var index = this._expr(false);
if (index == null)
return null;
if (this._expect("]") == null)
return null;
expr = new ArrayExpression(token, expr, index);
break;
case ".":
var identifier = this._expectIdentifier(function (self) { return self._getCompletionCandidatesOfProperty(expr); });
if (identifier == null)
return null;
var typeArgs = this._actualTypeArguments();
if (typeArgs == null)
return null;
expr = new PropertyExpression(token, expr, identifier, typeArgs);
break;
}
}
return expr;
}
function _newExpr (newToken : Token) : Expression {
var type = this._typeDeclarationNoArrayNoVoidNoYield();
if (type == null)
return null;
// handle [] (if it has an length parameter, that's the last)
while (this._expectOpt("[") != null) {
if (type instanceof NullableType) {
this._newError("cannot instantiate an array of an Nullable type");
return null;
}
type = this._registerArrayTypeOf(newToken, type);
if (this._expectOpt("]") == null) {
var lengthExpr = this._assignExpr(false);
if (lengthExpr == null)
return null;
if (this._expect("]") == null)
return null;
return new NewExpression(newToken, type, [ lengthExpr ]);
}
}
if (! (type instanceof ParsedObjectType)) {
this._newError("cannot instantiate a primitive type '" + type.toString() + "' using 'new'");
return null;
}
if (this._expectOpt("(") != null) {
var args = this._argsExpr();
if (args == null)
return null;
} else {
args = new Expression[];
}
return new NewExpression(newToken, type, args);
}
function _superExpr () : Expression {
if (this._expect(".") == null)
return null;
var identifier = this._expectIdentifier(null /* FIXME */);
if (identifier == null)
return null;
// token of the super expression is set to "(" to mimize the differences bet.compile error messages generated by CallExpression
var token = this._expect("(");
if (token == null)
return null;
var args = this._argsExpr();
if (args == null)
return null;
return new SuperExpression(token, identifier, args);
}
function _arrowFunctionOpt () : FunctionExpression {
var state = this._preserveState();
var expr;
if ((expr = this._arrowFunction()) == null) {
this._restoreState(state);
return null;
}
return expr;
}
function _arrowFunction () : FunctionExpression {
if (this._expectOpt("(") != null) {
var args = this._functionArgumentsExpr(false, false, false);
if (args == null)
return null;
}
else {
var argName = this._expectIdentifier();
if (argName == null)
return null;
var argType : Type = null;
if (this._expectOpt(":") != null) {
if ((argType = this._typeDeclaration(false)) == null)
return null;
}
args = [ new ArgumentDeclaration(argName, argType, null) ];
}
var returnType = null : Type;
if (this._expectOpt(":") != null) {
if ((returnType = this._typeDeclaration(true)) == null)
return null;
}
var token = this._expect(["->", "=>"]);
if (token == null)
return null;
var funcDef = this._functionBody(token, null, null, args, returnType, this._expectOpt("{") != null, false);
if (funcDef == null)
return null;
this._closures.push(funcDef);
return new FunctionExpression(token, funcDef);
}
function _functionBody(token : Token, name : Token, funcLocal : LocalVariable, args : ArgumentDeclaration[], returnType : Type, withBlock : boolean, isGenerator : boolean) : MemberFunctionDefinition {
this._pushScope(funcLocal, args);
try {
// parse lambda body
var flags = ClassDefinition.IS_STATIC;
if (isGenerator) {
this._isGenerator = isGenerator;
flags |= ClassDefinition.IS_GENERATOR;
}
var lastToken : Token;
if (! withBlock) {
lastToken = null;
var expr = this._assignExpr();
this._statements.push(new ReturnStatement(token, expr));
} else {
var lastToken = this._block();
if (lastToken == null)
return null;
}
var funcDef = new MemberFunctionDefinition(
token, name , flags, returnType, args, this._locals, this._statements, this._closures, lastToken, null);
if (funcLocal != null) {
funcDef.setFuncLocal(funcLocal);
}
return funcDef;
} finally {
this._popScope();
}
}
function _functionExpr (token : Token) : Expression {
var isGenerator = false;
if (this._expectOpt("*") != null)
isGenerator = true;
var name = this._expectIdentifierOpt();
if (this._expect("(") == null)
return null;
var args = this._functionArgumentsExpr(false, false, false);
if (args == null)
return null;
if (this._expectOpt(":") != null) {
var returnType = this._typeDeclaration(true);
if (returnType == null) {
return null;
}
} else {
returnType = null;
}
if (this._expect("{") == null)
return null;
var type : Type = null;
if (returnType != null) {
var argTypes = args.map.<Type>((arg) -> arg.getType());
type = new StaticFunctionType(token, returnType, argTypes, false);
}
var funcLocal : LocalVariable = null;
if (name != null) {
funcLocal = new LocalVariable(name, type, true);
}
var funcDef = this._functionBody(token, name, funcLocal, args, returnType, true, isGenerator);
if (funcDef == null) {
return null;
}
this._closures.push(funcDef);
return new FunctionExpression(token, funcDef);
}
function _forEachScope (cb : function(:LocalVariable,:LocalVariable[],:ArgumentDeclaration[]):boolean) : boolean {
if (this._locals != null) {
if (! cb(this._funcLocal, this._locals, this._arguments)) {
return false;
}
for (var scope = this._prevScope; scope != null; scope = scope.prev) {
if (scope.locals && ! cb(scope.funcLocal, scope.locals, scope.arguments)) {
return false;
}
}
}
return true;
}
function _findLocal (name : string) : LocalVariable {
var found = null : LocalVariable;
this._forEachScope(function (funcLocal, locals, args) {
if (funcLocal != null && funcLocal.getName().getValue() == name) {
found = funcLocal;
return false;
}
for (var i = 0; i < locals.length; ++i) {
if (locals[i].getName().getValue() == name) {
found = locals[i];
return false;
}
}
if (args != null) {
for (var i = 0; i < args.length; ++i) {
if (args[i].getName().getValue() == name) {
found = args[i];
return false;
}
}
}
return true;
});
return found;
}
function _primaryExpr () : Expression {
var token;
if ((token = this._expectOpt([ "this", "undefined", "null", "false", "true", "[", "{", "(", "__FILE__", "__LINE__", "__CLASS__" ])) != null) {
switch (token.getValue()) {
case "this":
return new ThisExpression(token, null);
case "undefined":
this._newDeprecatedWarning("use of 'undefined' is deprerated, use 'null' instead");
// falls through
case "null":
return this._nullLiteral(token);
case "false":
return new BooleanLiteralExpression(token);
case "true":
return new BooleanLiteralExpression(token);
case "[":
return this._arrayLiteral(token);
case "{":
return this._mapLiteral(token);
case "(":
var expr = this._expr(false);
if (this._expect(")") == null)
return null;
return expr;
case "__FILE__":
return new FileMacroExpression(token);
case "__LINE__":
return new LineMacroExpression(token);
case "__CLASS__":
return new ClassExpression(token, this._classType);
default:
throw new Error("logic flaw");
}
} else if ((token = this._expectNumberLiteralOpt()) != null) {
return new NumberLiteralExpression(token);
} else if ((token = this._expectIdentifierOpt(function (self) { return self._getCompletionCandidatesWithLocal(); })) != null) {
var local = this._findLocal(token.getValue());
if (local != null) {
return new LocalExpression(token, local);
} else {
var parsedType = this._objectTypeDeclaration(token, false, null);
if (parsedType == null)
return null;
return new ClassExpression(parsedType.getToken(), parsedType);
}
} else if ((token = this._expectStringLiteralOpt()) != null) {
return new StringLiteralExpression(token);
} else if ((token = this._expectRegExpLiteralOpt()) != null) {
return new RegExpLiteralExpression(token);
} else {
this._newError("expected primary expression");
return null;
}
}
function _nullLiteral (token : Token) : NullExpression {
var type = Type.nullType as Type;
if (this._expectOpt(":") != null) {
if ((type = this._typeDeclaration(false)) == null)
return null;
if (type instanceof PrimitiveType) {
this._newError("type '" + type.toString() + "' is not nullable");
return null;
}
}
return new NullExpression(token, type);
}
function _arrayLiteral (token : Token) : ArrayLiteralExpression {
var exprs = new Expression[];
while (this._expectOpt("]") == null) {
var expr = this._assignExpr();
if (expr == null)
return null;
exprs.push(expr);
// separator
var separator = this._expect([",", "]"]);
if (separator == null) {
return null;
}
else if (separator.getValue() == "]") {
break;
}
}
var type = null : Type;
if (this._expectOpt(":") != null)
if ((type = this._typeDeclaration(false)) == null)
return null;
return new ArrayLiteralExpression(token, exprs, type);
}
function _mapLiteral (token : Token) : MapLiteralExpression {
var elements = new MapLiteralElement[];
while (this._expectOpt("}") == null) {
// obtain key
var keyToken;
if ((keyToken = this._expectIdentifierOpt()) != null
|| (keyToken = this._expectNumberLiteralOpt()) != null
|| (keyToken = this._expectStringLiteralOpt()) != null) {
// ok
} else {
this._newError("expected identifier, number or string");
return null;
}
// separator
if (this._expect(":") == null)
return null;
// obtain value
var expr = this._assignExpr();
if (expr == null)
return null;
elements.push(new MapLiteralElement(keyToken, expr));
// separator
var separator = this._expect([",", "}"]);
if (separator == null) {
return null;
}
else if (separator.getValue() == "}") {
break;
}
}
var type = null : Type;
if (this._expectOpt(":") != null)
if ((type = this._typeDeclaration(false)) == null)
return null;
return new MapLiteralExpression(token, elements, type);
}
function _functionArgumentsExpr (allowVarArgs : boolean, requireTypeDeclaration : boolean, allowDefaultValues : boolean) : ArgumentDeclaration[] {
var args = new ArgumentDeclaration[];
if (this._expectOpt(")") == null) {
var token = null : Token;
do {
var isVarArg = allowVarArgs && (this._expectOpt("...") != null);
var argName = this._expectIdentifier();
if (argName == null)
return null;
var argType : Type = null;
if (requireTypeDeclaration) {
if (this._expect(":") == null) {
this._newError("type declarations are mandatory for non-expression function definition");
return null;
}
if ((argType = this._typeDeclaration(false)) == null)
return null;
} else if (this._expectOpt(":") != null) {
if ((argType = this._typeDeclaration(false)) == null)
return null;
}
for (var i = 0; i < args.length; ++i) {
if (args[i].getName().getValue() == argName.getValue()) {
this._errors.push(new CompileError(argName, "cannot declare an argument with the same name twice"));
return null;
}
}
if (isVarArg) {
// vararg is the last argument
if (argType == null && isVarArg)
throw new Error("not yet implemented!");
args.push(new ArgumentDeclaration(argName, new VariableLengthArgumentType(argType)));
if (this._expect(")") == null)
return null;
break;
}
var defaultValue : Expression = null;
var assignToken = this._expectOpt("=");
if (assignToken != null) {
var state = this._preserveState();
this._pushScope(null, args);
try {
if ((defaultValue = this._assignExpr(true)) == null) {
return null;
}
} finally {
// do not create a between the parent method and the children funcDefs stored in defVal
if (this._closures != null) {
this._closures.splice(state.numClosures, this._closures.length - state.numClosures);
}
this._popScope();
}
if (! allowDefaultValues) {
this._errors.push(new CompileError(assignToken, "default parameters are only allowed for member functions"));
return null;
}
} else {
if (args.length != 0 && args[args.length - 1].getDefaultValue() != null) {
this._errors.push(new CompileError(argName, "required argument cannot be declared after an optional argument"));
return null;
}
}
args.push(new ArgumentDeclaration(argName, argType, defaultValue));
token = this._expect([ ")", "," ]);
if (token == null)
return null;
} while (token.getValue() == ",");
}
return args;
}
function _argsExpr () : Expression[] {
var args = new Expression[];
if (this._expectOpt(")") == null) {
var token = null : Token;
do {
var arg = this._assignExpr(false);
if (arg == null)
return null;
args.push(arg);
token = this._expect([ ")", "," ]);
if (token == null)
return null;
} while (token.getValue() == ",");
}
return args;
}
function _getCompletionCandidatesOfTopLevel (autoCompleteMatchCb : function(:ClassDefinition):boolean) : CompletionCandidatesOfTopLevel {
return new CompletionCandidatesOfTopLevel(this, autoCompleteMatchCb);
}
function _getCompletionCandidatesWithLocal () : _CompletionCandidatesWithLocal {
return new _CompletionCandidatesWithLocal(this);
}
function _getCompletionCandidatesOfNamespace (imprt : Import, autoCompleteMatchCb : function(:ClassDefinition):boolean) : _CompletionCandidatesOfNamespace {
return new _CompletionCandidatesOfNamespace(imprt, autoCompleteMatchCb);
}
function _getCompletionCandidatesOfProperty (expr : Expression) : _CompletionCandidatesOfProperty {
return new _CompletionCandidatesOfProperty(expr);
}
}
|
import styled from "styled-components";
export let TourDetailContainer = styled.main`
min-height: 100vh;
`;
|
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
// See https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom
// Slightly modified version of the official solution, because of a known
// incompatibility with Antd: https://github.com/ant-design/ant-design/issues/21096
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: (query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
}),
});
|
import React, { useState, useEffect } from 'react';
import { Link, useHistory } from 'react-router-dom';
import Form from './Form';
import authorization from '../authorization';
import Message from './Message';
const SignupPage = () => {
const [errorMessage, setErrorMessage] = useState('');
const [infoMessage, setInfoMessage] = useState('');
const history = useHistory();
useEffect(() => {
document.querySelector('form').reset();
}, [infoMessage]);
const onSignUp = async (email, password) => {
const user = {
email: `${email}`,
password: `${password}`,
};
try {
const signUpInfo = await authorization.createUser(user);
if (typeof signUpInfo === 'object') {
setErrorMessage('');
setInfoMessage(
`The user with e-mail ${email} was signed up. You are navigating to sign in page.`
);
} else {
setErrorMessage(signUpInfo);
}
} catch (e) {
setErrorMessage(
'Incorrect e-mail or password. Password should contain at least one upper and lower case symbol, numeric and special symbols.'
);
}
};
const onFormError = (text) => {
setErrorMessage(text);
};
useEffect(() => {
if (infoMessage) {
setTimeout(() => {
history.push('/');
}, 2500);
}
}, [infoMessage, history]);
return (
<div className="signup-page">
<h1>EnglishPuzzle</h1>
<div className="link-to-sign-up">
<div>Have an acount?</div>
<Link to="/" className="sign-in">
Sign in
</Link>
</div>
<Form
className="login-form"
emailClassName="login"
passwordClassName="password-for-sign-in"
submitClassName="submit"
submitText="Sign up"
onSubmit={onSignUp}
onError={onFormError}
/>
{infoMessage && <Message className="info" text={infoMessage} />}
{errorMessage && <Message className="error" text={errorMessage} />}
</div>
);
};
SignupPage.propTypes = {};
export default SignupPage;
|
var randomTeam = ["Panthers", "Falcons", "Bears", "Packers", "Saints", "Chiefs", "Seahawks", "Cowboys", "Patriots", "Browns" ]
var randomWord = randomTeam[Math.floor(Math.random() * randomTeam.length)];
var s;
var g;
var count = 0;
var answerArr = [];
var userArr = [];
var remainingLetters = randomWord.length;
var output = "";
var loseAmt = 10;
var winNumber = document.getElementById("winNumber");
var currentWord = document.getElementById("currentWord");
var guessRemain = document.getElementById("guessRemain");
var alreadyUsed = document.getElementById("alreadyUsed");
function startup() {
console.log(randomWord)
for (i = 0; i < randomWord.length; i++) {
answerArr[i] = "_ ";
output = output + answerArr[i];
}
document.getElementById("guess-string").innerHTML = output;
output = "";
loseAmt = 10;
document.getElementById("remain").textContent = loseAmt;
}
document.onkeyup = function play() {
userGuess = event.key;
if (loseAmt === 0) {
alert("Game over!");
loseAmt === 10;
}
for (i = 0; i < userArr.length; i++);
if (userGuess === userArr[i]) {
alert("you can't do that");
}
else {
for (i = 0; i < randomWord.length; i++);
userArr.push(userGuess);
if (userGuess === randomWord[i]) {
(answerArr[i] = userGuess);
remainingLetters--;
};
loseAmt--;
document.getElementById("remain").innerHTML = loseAmt;
document.getElementById("used").innerHTML = userArr;
document.getElementById("used").innerHTML = userArr;
console.log(userGuess)
}
//Put "else" logic here if loseAmt is 0
}
|
let contador = 1
// Versão WHILE
while(contador <= 10) {
console.log(`O numero do contador é ${contador}`)
contador++
}
// Versão FOR
for( let i = 1; i<=10; i++){
console.log(`O numero do contador é ${i}`)
}
// O i vai pegar a posição no array, fazer notas[i], quer dizer que você está pegando a nota a partir do i da vez
const notas = [6.4, 7.3, 9.8, 8.1, 7.7]
for (i=0;i < notas.length;i++){
console.log(`notas = ${notas[i]}`)
}
|
const test = require('tape');
const bottomVisible = require('./bottomVisible.js');
test('Testing bottomVisible', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof bottomVisible === 'function', 'bottomVisible is a Function');
t.pass('Tested on 09/02/2018 by @chalarangelo');
//t.deepEqual(bottomVisible(args..), 'Expected');
//t.equal(bottomVisible(args..), 'Expected');
//t.false(bottomVisible(args..), 'Expected');
//t.throws(bottomVisible(args..), 'Expected');
t.end();
});
|
import _ from 'lodash'
Graffiti.prototype = new window.google.maps.OverlayView()
function Graffiti (parent) {
this.content_ = null
this.text_ = null
this.parent_ = parent
this.setMap(parent.streetView)
}
Graffiti.prototype.onAdd = function () {
var form = document.createElement('div')
var content = document.createElement('div')
var button = document.createElement('button')
form.appendChild(content)
form.appendChild(button)
this.button_ = button
content.setAttribute('contenteditable', true)
content.className = 'floating-text'
this.content_ = content
var parent = this.parent_
content.addEventListener('keydown', function (e) {
e.stopPropagation()
})
content.addEventListener('keypress', function (e) {
e.stopPropagation()
if (e.keyCode === 13) {
if (!_.isEmpty(this.textContent)) {
parent.props.closePopups()
}
e.preventDefault()
return false
}
})
content.addEventListener('mousedown', function (e) {
e.stopPropagation()
})
content.addEventListener('keyup', function (e) {
e.stopPropagation()
parent.props.titleChanged(e)
})
button.innerHTML = 'save'
button.className = 'save-text'
if (_.isEmpty(this.text_)) {
button.disabled = true
}
button.addEventListener('click', function (e) {
parent.props.closePopups()
})
var panes = this.getPanes()
panes.overlayLayer.appendChild(form)
this.content_.innerHTML = this.text_
this.focusCaret()
}
Graffiti.prototype.updateText = function (text) {
this.text_ = text
if (this.button_) {
if (_.isEmpty(text)) {
this.button_.disabled = true
} else {
this.button_.disabled = false
}
}
}
Graffiti.prototype.focusCaret = function () {
if (this.content_) {
this.content_.focus()
if (typeof window.getSelection !== 'undefined' && typeof document.createRange !== 'undefined') {
const range = document.createRange()
range.selectNodeContents(this.content_)
range.collapse(false)
const sel = window.getSelection()
sel.removeAllRanges()
sel.addRange(range)
} else if (typeof document.body.createTextRange !== 'undefined') {
const textRange = document.body.createTextRange()
textRange.moveToElementText(this.content_)
textRange.collapse(false)
textRange.select()
}
}
}
Graffiti.prototype.draw = function () {
this.content_.innerHTML = this.text_
this.focusCaret()
}
Graffiti.prototype.onRemove = function () {
this.content_.parentNode.removeChild(this.content_)
this.content_ = null
}
module.exports = Graffiti
|
const express = require('express');
const router = express.Router();
var agregarCuentaController = require('../controller/agregarCuenta.js');
var datosCuenta = require('../controller/datosCuenta.js');
var csv = require('../controller/csv.js');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
router.get('/cuentas', datosCuenta.cuentas);
router.get('/cuentas/delete', datosCuenta.borrarCuenta);
router.get('/iniciarConML', agregarCuentaController.iniciarMl);
router.get('/auth_ml', agregarCuentaController.authMl);
router.get('/csv/preguntas', csv.get);
router.post('/csv/preguntas', multipartMiddleware, csv.post);
router.get('/csv/create', csv.create );
router.get('/csv/status', csv.status );
module.exports = router;
|
( function () {
var component = {
name: 'calendar', // texthighlight
version: [1,0,0],
ccm: 'https://ccmjs.github.io/ccm/versions/ccm-24.0.1.js',
config: {
html: {
calendar: {
class: 'calendar',
id: 'calendar-container',
inner: [
{
tag: 'div',
class: 'month',
inner: [
{
tag: 'ul',
inner: [
{
tag: 'li',
class: 'prev',
id: 'prev-btn',
inner: '❮',
onclick: '%prevMonth%'
},
{
tag: 'li',
class: 'next',
id: 'next-btn',
inner: '❯',
onclick: '%nextMonth%'
},
{
tag: 'li',
class: 'month-value',
id: 'month-value'
}
]
}
]
},
{
tag: 'ul',
class: 'weekdays',
id: 'weekdays'
},
{
tag: 'ul',
class: 'days',
id: 'days'
}
]
},
modal: {
id: 'modal',
class: 'todo-modal',
inner: [
{
class: 'modal-content',
inner: [
{
id: 'todo',
class: 'todo-header',
inner:[
{
tag: 'h2',
class: 'title',
id: 'title'
},
{
tag: 'input',
type: 'text',
id: 'todo-text',
placeholder: 'Enter todo...'
},
{
tag: 'span',
class: 'addBtn',
id: 'add-btn',
onclick: '%createTodo%'
}
]
},
{
id: 'todo-container',
inner: [
{
tag: 'ul',
id: 'todo-items'
}
]
}
]
}
]
}
},
css: [ "ccm.load", "https://niroGH.github.io/pages/calendar.css", "https://niroGH.github.io/pages/todo.css" ]
},
Instance: function () {
/**
* own reference for inner functions
* @type {Instance}
*/
const self = this;
/**
* shortcut to help functions
* @type {Object.<string,function>}
*/
let $;
/**
* init is called once after all dependencies are solved and is then deleted
*/
this.init = async () => {
// set shortcut to help functions
$ = this.ccm.helper;
};
this.start = async () => {
const calendar = $.html( self.html.calendar, {
nextMonth: (e) => {
month++;
if(month > 11){
month = 0;
year++;
}
span.innerText = year;
calendar.querySelector('#month-value').innerHTML = getMonthValue(month) + '<br>' + span.outerHTML;
printDaysOfMonth(daysContainer, month, year);
},
prevMonth: (e) => {
month--;
if(month < 0){
month = 11;
year--;
}
span.innerText = year;
calendar.querySelector('#month-value').innerHTML = getMonthValue(month) + '<br>' + span.outerHTML;
printDaysOfMonth(daysContainer, month, year);
}
} );
let month = getCurrentMonth();
let year = new Date().getFullYear();
let span = document.createElement('span');
span.style.fontSize = '18px';
span.innerText = year;
calendar.querySelector('#month-value').innerHTML = getMonthValue(month) + '<br>' + span.outerHTML;
//calendar.querySelector('#year-value').innerText = year;
const weekdaysContainer = calendar.querySelector('#weekdays');
const weekdays = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'];
weekdays.forEach(weekday => {
let li = document.createElement('li');
li.innerText = weekday;
weekdaysContainer.appendChild(li);
});
const daysContainer = calendar.querySelector('#days');
printDaysOfMonth(daysContainer, month, year);
self.element.appendChild(calendar);
self.element.childNodes[0].style.display = 'none';
function printDaysOfMonth(dayContainer, month, year) {
dayContainer.innerHTML = '';
let date = new Date();
let currentDay = date.getDate();
let isCurrent = false;
if(date.getMonth() === month && date.getFullYear() === year){
isCurrent = true;
}
let firstDayOfMonth = new Date(year, month, 1).getDay();
for(let i = 1; i < firstDayOfMonth; ++i){
let day = document.createElement('li');
dayContainer.appendChild(day);
}
const numberOfDays = new Date(year, month + 1, 0).getDate();
for(let i = 0; i < numberOfDays; ++i){
let day = document.createElement('li');
day.onclick = (e)=> {
const key = (i+1) + ' ' + getMonthValue(month) + ' ' + year;
const todos = localStorage.getItem(key);
const todoItems = todoContainer.querySelector('#todo-items');
todoItems.innerHTML = '';
if(todos){
for(let todo of JSON.parse(todos)){
const li = document.createElement('li');
li.innerText = todo;
const span = document.createElement('span');
span.classList.add('close');
span.innerText = '\u00D7';
li.appendChild(span);
todoItems.appendChild(li);
}
}
modal.querySelector('#date-span').innerHTML = key;
modal.style.display = 'block';
}
const key = (i+1) + ' ' + getMonthValue(month) + ' ' + year;
const idParts = key.split(' ');
day.id = idParts[1] + idParts[0] + idParts[2];
const todos = localStorage.getItem(key);
let span = document.createElement('span');
span.innerText = (i+1);
if(isCurrent && currentDay === (i+1)){
span.classList.add('active');
}
if(todos){
span.classList.add('todo-mark');
}
day.appendChild(span);
day.style.cursor = 'pointer';
dayContainer.appendChild(day);
}
}
function getCurrentMonth() {
const date = new Date();
return date.getMonth();
}
function getMonthValue(month) {
switch (month) {
case 0:
return 'Januar';
case 1:
return 'Februar';
case 2:
return 'März';
case 3:
return 'April';
case 4:
return 'Mai';
case 5:
return 'Juni';
case 6:
return 'Juli';
case 7:
return 'August';
case 8:
return 'September';
case 9:
return 'Oktober';
case 10:
return 'November';
case 11:
return 'Dezember';
default:
return 'Januar';
}
}
//const modal = $.html(self.html.modal);
const modal = $.html( self.html.modal, {
createTodo: (e) => {
const li = document.createElement('li');
const todoTextInput = modal.querySelector('#todo-text');
const value = todoTextInput.value;
if(value === ''){
return;
}
li.innerText = value;
const span = document.createElement('span');
span.classList.add('close');
span.innerText = '\u00D7';
li.appendChild(span);
const todoItems = todoContainer.querySelector('#todo-items');
todoItems.appendChild(li);
todoTextInput.value = '';
const key = modal.querySelector('#date-span').innerText;
const list = localStorage.getItem(key);
const todos = [];
if(list){
const todos = JSON.parse(list);
todos.push(value);
localStorage.setItem(key, JSON.stringify(todos));
}else {
const todos = [];
todos.push(value);
localStorage.setItem(key, JSON.stringify(todos));
}
const idParts = key.split(' ');
const id = idParts[1] + idParts[0] + idParts[2];
const day = calendar.querySelector('#' + id);
const markSpan = day.querySelector('span');
markSpan.classList.add('todo-mark');
}
});
const todoContainer = modal.querySelector('#todo-container');
const dateSpan = document.createElement('span');
dateSpan.id = 'date-span';
modal.querySelector('#title').innerHTML = 'TODO List' + '<br>' + dateSpan.outerHTML;
modal.querySelector('#add-btn').innerText = 'Add';
//self.element.appendChild(todo);
calendar.appendChild(modal);
calendar.onclick = function(event) {
if (event.target === modal) {
modal.style.display = "none";
}
}
};
}
};
function p(){window.ccm[v].component(component)}var f="ccm."+component.name+(component.version?"-"+component.version.join("."):"")+".js";if(window.ccm&&null===window.ccm.files[f])window.ccm.files[f]=component;else{var n=window.ccm&&window.ccm.components[component.name];n&&n.ccm&&(component.ccm=n.ccm),"string"==typeof component.ccm&&(component.ccm={url:component.ccm});var v=component.ccm.url.split("/").pop().split("-");if(v.length>1?(v=v[1].split("."),v.pop(),"min"===v[v.length-1]&&v.pop(),v=v.join(".")):v="latest",window.ccm&&window.ccm[v])p();else{var e=document.createElement("script");document.head.appendChild(e),component.ccm.integrity&&e.setAttribute("integrity",component.ccm.integrity),component.ccm.crossorigin&&e.setAttribute("crossorigin",component.ccm.crossorigin),e.onload=function(){p(),document.head.removeChild(e)},e.src=component.ccm.url}}
}() );
|
import React, { PropTypes } from 'react';
const AboutUI = ({bios}) => (
<div>
{bios.map((bio) => <p><img src={bio.avatar} height="200px" width="200px"/>{bio.bio}</p>)}
</div>
);
AboutUI.propTypes = {
bios : PropTypes.array.isRequired
};
export default AboutUI;
|
import { find, map, range } from "lodash";
import handleError from "./handleError";
import { processResponse } from "../helpers";
export default async function bet({ betAmount, user }) {
try {
const appInfo = JSON.parse(localStorage.getItem("appInfo"));
const game = find(appInfo.games, { metaName: "plinko_variation_1" });
const gameResultSpaceLength = game.resultSpace.length;
const result = new Array(gameResultSpaceLength).fill(0).map( (value, index) => {
return {
place: index,
value: parseFloat(parseFloat(betAmount/gameResultSpaceLength))
};
});
const response = await user.createBet({
amount: betAmount,
result,
gameId: game._id
});
await processResponse(response);
const { winAmount, betAmount : amountBetted, _id : id, nonce, isWon, user_delta, totalBetAmount } = response.data.message;
const { index } = response.data.message.outcomeResultSpace;
return {
result : index,
winAmount,
isWon,
nonce,
betAmount : amountBetted,
id,
userDelta : user_delta,
totalBetAmount
};
} catch (error) {
throw error;
}
}
|
const { router } = require('../../../config/expressconfig')
const User = require('../../models/user')
let getAllUsers = router.get("/get-all-users-for-editing", async (req, res) => {
// console.log(status)
const result = await User.find()
if (result && result.length != 0) {
return res.json({ message: "USERS FOUND", responseCode: 200, users: result })
}
else {
return res.json({ message: "USERS NOT FOUND", responseCode: 404, user: result })
}
});
module.exports = { getAllUsers }
|
const GameSound = `
<audio class="correct-sound" src="audio/correct.mp3" type="audio/mpeg"></audio>
<audio class="incorrect-sound" src="audio/error.mp3" type="audio/mpeg"></audio>
<audio class="success-sound" src="audio/success.mp3" type="audio/mpeg"></audio>
<audio class="failure-sound" src="audio/failure.mp3" type="audio/mpeg"></audio>
`;
export default GameSound;
|
// Creates a new audio element object that contains all audio properties
export function createAudioElement(audioElement, numSamples) {
let ctx = new(window.AudioContext || window.webkitAudioContext);
let audioHolder = {
element: audioElement,
ctx: ctx,
source: ctx.createMediaElementSource(audioElement),
analyser: ctx.createAnalyser(),
gain: ctx.createGain(),
highShelfBiquadFilter: ctx.createBiquadFilter(),
lowShelfBiquadFilter: ctx.createBiquadFilter(),
distortionFilter: ctx.createWaveShaper(),
data: new Uint8Array(numSamples / 2),
};
audioHolder.analyser.fftSize = numSamples;
audioHolder.highShelfBiquadFilter.type = "highshelf";
audioHolder.lowShelfBiquadFilter.type = "lowshelf";
audioHolder.gain.gain.value = 1;
audioHolder.source.connect(audioHolder.highShelfBiquadFilter);
audioHolder.highShelfBiquadFilter.connect(audioHolder.lowShelfBiquadFilter);
audioHolder.lowShelfBiquadFilter.connect(audioHolder.distortionFilter);
audioHolder.distortionFilter.connect(audioHolder.analyser);
audioHolder.analyser.connect(audioHolder.gain);
audioHolder.gain.connect(audioHolder.ctx.destination);
return Object.freeze(audioHolder);
}
|
const express = require('express');
const router = express.Router();
const verifyToken = require("../middleware/authorization");
const authRouter = require('./auth');
const userRouter = require('./user.controller');
const likeRouter = require('./like.controller');
const commentRouter = require('./comment.controller');
const imageRouter = require('./image.controller');
const keyRouter = require('./key.controller.js');
router.use('/auth', authRouter);
router.use('/user', userRouter);
router.use('/image', imageRouter);
router.use('/comment', commentRouter);
router.use('/like', verifyToken, likeRouter);
router.use('/key', verifyToken, keyRouter);
// router.use(verifyToken);
module.exports = router;
|
// @flow
import * as React from 'react';
import { View } from 'react-native';
import { Translation, Alert } from '@kiwicom/mobile-localization';
import {
TextInput,
StyleSheet,
TextIcon,
type StylePropType,
TouchableWithoutFeedback,
} from '@kiwicom/mobile-shared';
import { defaultTokens } from '@kiwicom/mobile-orbit';
type Props = {|
+onSecurityCodeChange: (securityCode: string) => void,
+inputWrapperStyle?: StylePropType,
+placeholder?: React.Element<typeof Translation>,
+placeholderStyle?: StylePropType,
+displayLabel: boolean,
|};
export default class SecurityCodeInput extends React.Component<Props> {
static defaultProps = {
displayLabel: true,
};
onPress = () => {
Alert.translatedAlert(
{ id: 'mmb.trip_services.insurance.payment.security_code' },
{
id: 'mmb.trip_services.insurance.payment.security_code.alert_message',
},
);
};
render() {
let label;
let helpIconOffset;
if (this.props.displayLabel) {
label = (
<Translation id="mmb.trip_services.insurance.payment.security_code" />
);
helpIconOffset = styles.helpIconOffset;
}
let placeholderProps;
if (this.props.placeholder != null) {
placeholderProps = {
placeholder: this.props.placeholder,
placeholderStyle: this.props.placeholderStyle,
};
}
return (
<React.Fragment>
<TextInput
label={label}
onChangeText={this.props.onSecurityCodeChange}
keyboardType="numeric"
maxLength={4}
inputWrapperStyle={this.props.inputWrapperStyle}
{...placeholderProps}
/>
<TouchableWithoutFeedback onPress={this.onPress}>
<View style={[styles.helpIcon, helpIconOffset]}>
<TextIcon code="F" style={styles.icon} />
</View>
</TouchableWithoutFeedback>
</React.Fragment>
);
}
}
const styles = StyleSheet.create({
helpIcon: {
position: 'absolute',
end: 0,
padding: 10,
},
helpIconOffset: {
end: 15,
bottom: 2.5,
},
icon: {
color: defaultTokens.paletteProductNormal,
fontSize: 16,
},
});
|
/* *****************************************************************************
* Name: Una Rúnarsdóttir
*
* Description: Define the format of Show Cover
*
* Written: 9/12/2020
* Last updated: 3/1/2021
*
*
**************************************************************************** */
module.exports = (sequelize, Sequelize) => {
const Showcover = sequelize.define('showcover', {
type: {
type: Sequelize.STRING
},
name: {
type: Sequelize.STRING
},
data: {
type: Sequelize.BLOB('long')
}
});
return Showcover;
}
|
module.exports = {
run: function(args) {
`
fdgfdg
dfgdfs
dfgdfsgdfsg
dsfgde
`
}
}
|
module.exports = {
// Options
options: {
limit: 3
},
// development tasks
devFirst: [
'typescript:dev',
'coffee:dev',
'clean'
],
devSecond: [
'sass:dev',
'uglify',
'jade'
],
//watcher tasks
tsw: [
'typescript:watcher'
],
// Production tasks
prodFirst: [
'typescript:prod',
'coffee:prod',
'clean',
'jshint'
],
prodSecond: [
'sass:prod',
'uglify',
'jade'
],
prodThird: [
'clean:js'
],
// Image's tasks
imgFirst: [
'imagemin:prod'
],
imgDev: [
'imagemin:dev'
]
};
|
/**
* Created by forli on 2017/4/6.
*/
|
<?xml version="1.0" encoding="UTF-8"?>
<Values version="2.0">
<value name="name">toJson</value>
<value name="encodeutf8">true</value>
<value name="body">Ly8gcGlwZWxpbmUNCklEYXRhQ3Vyc29yIHBpcGVsaW5lQ3Vyc29yID0gcGlwZWxpbmUuZ2V0Q3Vy
c29yKCk7DQpPYmplY3QJb2JqZWN0ID0gSURhdGFVdGlsLmdldCggcGlwZWxpbmVDdXJzb3IsICJv
YmplY3QiICk7DQoNCmlmKCB1c2VXeEpzb24gPT0gbnVsbCApIHsNCgl1c2VXeEpzb24gPSB1c2VX
eEpzb24oKTsNCn0NCg0KU3RyaW5nCWpzb24gPSBudWxsOwkJDQppZiggdXNlV3hKc29uICkgew0K
CWpzb24gPSBpbnZva2VXeEpzb24ob2JqZWN0KTsNCn0gZWxzZSB7DQoJanNvbiA9IGludm9rZU5h
dGl2ZUlzSnNvbihvYmplY3QpOw0KfQ0KDQpJRGF0YVV0aWwucHV0KCBwaXBlbGluZUN1cnNvciwg
Impzb24iLCBqc29uICk7DQpwaXBlbGluZUN1cnNvci5kZXN0cm95KCk7DQoNCgk=</value>
</Values>
|
export const CD_TYPE = 'cds';
export const RECORED_TYPE = 'vinyl_records';
|
function periodicLimit (n, nlow, nhigh) {
pl = false;
while (n >= nhigh) {
n -= (nhigh - nlow);
pl = true;
}
while (n < nlow) {
n += (nhigh - nlow);
pl = true;
}
return [pl, n];
}
|
celebinoApp.controller('gardenController', function (GardenService, UserService, $scope, $state, $mdToast) {
$scope.gardens = [];
$scope.insertGarden = function () {
console.log(UserService.getCurrentUser());
$scope.garden.user = UserService.getCurrentUser();
GardenService.insertGarden($scope.garden)
.then(function (response) {
// Chamado quando a resposta contém status de sucesso.
// Exibir toas com mensagem de sucesso ou erro.
var toast = $mdToast.simple()
.textContent('Garden(a) cadastrado(a) com sucesso.')
.position('top right')
.action('Ok')
.hideDelay(6000);
$mdToast.show(toast);
})
.catch(function (data) {
// Handle error here
var toast = $mdToast.simple()
.textContent('Problema no cadastro do Garden.')
.position('top right')
.action('Ok')
.hideDelay(6000);
$mdToast.show(toast);
});
};
$scope.getGardens = function () {
GardenService.getAll()
.then(function (response) {
$scope.gardens = response.data;
});
};
$scope.getGardensByUser = function () {
GardenService.getByUser(UserService.getCurrentUserId())
.then(function (response) {
$scope.gardens = response.data;
});
};
$scope.limparFormulario = function () {
// Reinicializa as variáveis nome e alunos.
$scope.nome = "";
angular.copy({}, $scope.gardens);
// Reinicializa o estado do campo para os eventos e validação.
// É necessário indicar o atributo name no formulário <form>
$scope.formPesquisa.$setPristine();
$scope.formPesquisa.$setValidity();
}
$scope.redirecionar = function () {
$state.transitionTo('home');
};
});
|
var mobileUser = AV.Object.extend("_User");
//function newMobileUser(){
// var MobileU = new mobileUser();
// MobileU.save({username: "13855555555", phone: "13855555555", password: encryptPwd("123456"), groupCode: "1", userType: 1}, {
// success: function(savePro) {
// alert("OK");
// },
// error: function(savePro, error) {
// alert("错误:" + error.message);
// }
// });
//}
var array;
var num = 0;
var $btn = $("#uploadUserButton").button('loading');
var mobileUsers={
MobileUser: AV.Object.extend("_User"),
pageNo: 1,
pageSize: 10,
pageCount: 1,
cql_baselist: "select count(*),* from _User where userType=1 order by createdAt desc",
cql_list: "",
//初始化
init:function(page){
mobileUsers.pageNo = page;
mobileUsers.cql_list = mobileUsers.cql_baselist + " limit " + (mobileUsers.pageNo - 1) * mobileUsers.pageSize + "," + mobileUsers.pageSize;
},
//分页
goPage:function(type){
var page=mobileUsers.pageNo;
if(type==-1){
page=page-1==0?1:page-1;
}else if(type==1){
page = page+1 > mobileUsers.pageCount ? mobileUsers.pageCount : page+1;
}
mobileUsers.init(page);
mobileUsers.loadData();
},
//加载分页数据
loadData:function(){
AV.Query.doCloudQuery(mobileUsers.cql_list, {
success: function(result){
//results 是查询返回的结果,AV.Object 列表
var obj = result.results;
var count = result.count;
mobileUsers.pageCount = count%mobileUsers.pageSize == 0 ? (count/mobileUsers.pageSize == 0 ? 1 : count/mobileUsers.pageSize):parseInt(count/mobileUsers.pageSize)+1;
if (mobileUsers.pageNo == mobileUsers.pageCount) {
$("#btn1").attr("disabled","disabled");
}else{
$("#btn1").removeAttr("disabled");
}
if(mobileUsers.pageNo == 1){
$("#btn2").attr("disabled","disabled");
}else{
$("#btn2").removeAttr("disabled");
}
//清空选择数据
var tableHtml="";
for (var i = 0; i < obj.length; i++) {
tableHtml+="<tr>" +
"<td>"+obj[i].get('nickName')+"</td>" +
"<td>"+obj[i].get('phone')+"</td>" +
"<td>"+obj[i].get('groupCode')+"</td>" +
"<td>" +
'<button onclick="mobileUsers.deleteData(\''+obj[i].id+'\')" class="btn btn-primary">删除</button> ' +
"</td>" +
"</tr>";
}
$("#dataMsg").html(tableHtml);
},
error: function(error){
console.log(error.message);
}
});
},
//删除数据
deleteData:function(objectId){
AV.Cloud.run('deleteMobileUser',{objectId:objectId,}, {
success: function(data){
alert(data);
mobileUsers.reload();
},
error: function(err){
alert(err);
}
});
},
//重新加载页面
reload:function(){
location.reload();
},
selectData: function(phone){
AV.Query.doCloudQuery("select * from _User where userType=1 and phone='"+phone+"' limit 0, 1", {
success: function(result){
var obj = result.results;
isHave = obj.length;
alert(isHave);
return;
},
error: function(error){
console.log(error.message);
}
});
},
validatePhone: function(phone){
if(phone.length!=11)
{
return '请输入有效的手机号码!';
}
var myreg = /^(((1[3,8][0-9]{1})|159|153|156|158)+\d{8})$/;
if(!myreg.test(phone))
{
return '请输入有效的手机号码!';
}
return "";
},
uploadMobileUser:function(){
var user = AV.User.current();
if (!user) {
alert("您尚未登陆");
return;
}
$("#dataFont").html("");
try {
//先删除以前的数据
var data = $("#clientUserdata").val();
if(data == null || data.length < 1){
$("#dataFont").html("<font color='red'>数据不能为空</font>");
$btn.button('reset');
return ;
}
var mobileUserArray = new Array();
array = data.split("\n");
mobileUsers.saveMobileUser(0);
//验证该手机号码(该用户类型下)是否已经存在
// mobileUsers.selectData(itemAttrs[1]);
// if(isHave != 0){
// $("#dataFont").html("<font color='red'>数据格式不对</font>,出错数据在第:" + (i+1) +"行,"+mobileUsers.selectData(itemAttrs[1]));
// $btn.button('reset');
// return ;
// }
// //验证手机号码格式是否正确
// if (mobileUsers.validatePhone(itemAttrs[1]).length > 1) {
// $("#dataFont").html("<font color='red'>数据格式不对</font>,出错数据在第:" + (i+1) +"行,"+mobileUsers.validatePhone(itemAttrs[1]));
// $btn.button('reset');
// return ;
// }
//
// var mobile = new mobileUser();
// mobile.set("nickName", itemAttrs[0]);
// mobile.set("username", itemAttrs[1]);
// mobile.set("phone", itemAttrs[1]);
// mobile.set("groupCode", itemAttrs[2]);
// mobile.set("userType", 1);
// mobile.set("password", encryptPwd("123456"));
//
//// console.log("item:"+jsonObj.username);
//
// mobileUserArray[i] = mobile;
// }
//
// AV.Object.saveAll(mobileUserArray, {
// success: function(list) {
// // All the objects were saved.
//
// $("#dataFont").html("<font color='blue'>数据已保存</font>");
// $("#clientUserdata").val("");
// mobileUsers.loadData();
// $("#uploadUserButton").button('上传数据');
// $btn.button('reset');
// $('#myModal').modal('hide');
// },
// error: function(error) {
// // An error occurred while saving one of the objects.
// $("#dataFont").html("<font color='red'>"+error.message+"</font>");
// $btn.button('reset');
// }
// });
} catch (e) {
// TODO: handle exception
$("#dataFont").html("<font color='red'>数据格式错误</font>");
$btn.button('reset');
}
},
saveMobileUser: function(num){
if (num >= array.length){
$("#dataFont").html("<font color='blue'>数据已保存</font>");
$("#clientUserdata").val("");
$("#uploadUserButton").button('上传数据');
$('#myModal').modal('hide');
$btn.button('reset');
mobileUsers.loadData();
return;
}
var item = array[num];
var itemAttrs = item.split(",");
if(itemAttrs.length != 3 ){
$("#dataFont").html("<font color='red'>数据格式不对</font>,出错数据在第:" + (num+1) +"行,请确保每行只有3个字段");
$btn.button('reset');
return ;
}
//验证该手机号码(该用户类型下)是否已经存在
AV.Query.doCloudQuery("select * from _User where userType=1 and phone='"+itemAttrs[1]+"' limit 0, 1", {
success: function(result){
var obj = result.results;
if (obj.length > 0){
var user=obj[0];
AV.Cloud.run('updateMobileUser',
{nickName: itemAttrs[0],
objectId: user.id,
groupCode: itemAttrs[2]}, {
success: function(data){
num++;
mobileUsers.saveMobileUser(num);
},
error: function(err){
alert(err);
}
});
// $("#dataFont").html("<font color='red'>数据格式不对</font>,出错数据在第:" + (i+1) +"行,该手机号码已存在");
// $btn.button('reset');
// return ;
}else {
//验证手机号码格式是否正确
if (mobileUsers.validatePhone(itemAttrs[1]).length > 1) {
$("#dataFont").html("<font color='red'>数据格式不对</font>,出错数据在第:" + (num+1) +"行,"+mobileUsers.validatePhone(itemAttrs[1]));
$btn.button('reset');
return ;
}
var mobile = new mobileUser();
mobile.set("nickName", itemAttrs[0]);
mobile.set("username", itemAttrs[1]);
mobile.set("phone", itemAttrs[1]);
mobile.set("groupCode", itemAttrs[2]);
mobile.set("userType", 1);
mobile.set("password", encryptPwd("123456"));
// mobileUserArray[i] = mobile;
var MobileU = new mobileUser();
MobileU.save(mobile, {
success: function(savePro) {
num++;
mobileUsers.saveMobileUser(num);
},
error: function(savePro, error) {
$("#dataFont").html("<font color='red'>"+error.message+"</font>");
$btn.button('reset');
}
});
}
},
error: function(error){
console.log(error.message);
}
});
},
queryPhone: function(){
var user = AV.User.current();
if (!user) {
alert("您尚未登陆");
return;
}
$("#mobileUserQueryTbody").html("");
$("#hintinfo3").html("");
$("#queryButton").button('loading');
var phone = $("#phonenumber").val();
var mu = new mobileUser();
mu.set("phone", phone);
AV.Query.doCloudQuery("select * from _User where phone = '" + phone + "' ", {
success: function(data){
var obj = data.results;
if(obj.length > 0){
var user = obj[0];
var groupCode = user.get('groupCode');
AV.Query.doCloudQuery("select * from userGroup where groupCode='"+groupCode+"'", {
success: function(d){
var groupObj = d.results;
if(groupObj.length > 0){
var group = groupObj[0];
mobileUsers.showQueryHtml(user, group);
}else {
mobileUsers.showQueryHtml(user, null);
}
},
error: function(error){
mobileUsers.showQueryHtml(user, null);
}
});
}else {
$("#hintinfo3").html("<font color='red'>暂无数据</font>");
$("#queryButton").button('查询');
$("#queryButton").button('reset');
}
},
error: function(error){
alert("查询失败,请稍候再试");
console.log(error.message);
$("#queryButton").button('查询');
$("#queryButton").button('reset');
}
});
},
showQueryHtml: function(user, group){
var html =
'用户姓名:' + user.get('nickName') + '<br/>' +
'用户电话:' + user.get('phone') + '<br/>' +
'分组编号:' + user.get('groupCode') + '<br/>';
if (group == null) {
}else {
html += '分组名称:' + group.get('groupName') + '<br/>' +
'奖励政策:<font>' + group.get('groupPolicy') + '</font><br/>';
}
$("#mobileUserQueryTbody").html(html);
// var tableHtml =
// "<tr>" +
// "<th class='visible-lg'>用户姓名</th>" +
// "<th class='visible-lg'>用户电话</th>" +
// "<th class='visible-lg'>分组名称</th>" +
// "<th class='visible-lg'>分组编号</th>" +
// "<th class='visible-lg'>奖励政策</th>" +
// "</tr>" +
// "<tr>" +
// "<td>"+user.get('username')+"</td>" +
// "<td>"+user.get('phone')+"</td>";
// if(group == null){
// tableHtml += "<td> </td>" +
// "<td>"+user.get('groupCode')+"</td>" +
// "<td> </td>";
// }else {
// tableHtml += "<td>"+group.get('groupName')+"</td>" +
// "<td>"+user.get('groupCode')+"</td>" +
// "<td>"+group.get('groupPolicy')+"</td>";
// }
// tableHtml += "</tr>";
// $("#mobileUserQueryTbody").html(tableHtml);
$("#queryButton").button('查询');
$("#queryButton").button('reset');
}
}
|
import * as f from './flags'
import { browserify as b, gulp as g } from './plugins'
const entry = 'tgui.js'
import { transform as babel } from 'babel-core'
import { readFileSync as read } from 'fs'
b.componentify.compilers['text/javascript'] = function (source, file) {
const config = { sourceMaps: true }
Object.assign(config, JSON.parse(read(`${f.src}/.babelrc`, 'utf8')))
const compiled = babel(source, config)
return { source: compiled.code, map: compiled.map }
}
import { render as stylus } from 'stylus'
b.componentify.compilers['text/stylus'] = function (source, file) {
const config = { filename: file }
const compiled = stylus(source, config)
return { source: compiled }
}
import browserify from 'browserify'
const bundle = browserify(`${f.src}/${entry}`, {
debug: f.debug,
cache: {},
packageCache: {},
extensions: [ '.js', '.ract' ],
paths: [ f.src ]
})
if (f.min) bundle.plugin(b.collapse)
bundle
.transform(b.babelify)
.plugin(b.helpers)
.transform(b.componentify)
.transform(b.globify)
.transform(b.es3ify)
import buffer from 'vinyl-buffer'
import gulp from 'gulp'
import source from 'vinyl-source-stream'
export function js () {
return bundle.bundle()
.pipe(source(entry))
.pipe(buffer())
.pipe(g.if(f.debug, g.sourcemaps.init({loadMaps: true})))
.pipe(g.bytediff.start())
.pipe(g.if(f.min, g.uglify({mangle: true, compress: {unsafe: true}})))
.pipe(g.if(f.debug, g.sourcemaps.write()))
.pipe(g.bytediff.stop())
.pipe(gulp.dest(f.dest))
}
import gulplog from 'gulplog'
export function watch_js () {
bundle.plugin(b.watchify)
bundle.on('update', js)
bundle.on('error', err => {
gulplog.error(err.toString())
this.emit('end')
})
return js()
}
|
(function() {
'use strict';
angular.module('users')
.factory('User', ['common', 'DS',
function(common, DS) {
var User = DS.defineResource({
name: 'user',
endpoint: 'users'
});
return User;
/////////////////////
}]);
}());
|
pm_domain_url = null;
sender_guid = "";
popup_onload = false;
object_cnt = null;
// 2015.04.03 hwjang start websock_areaID[index]와 AreaID 관련성 확인
//AreaID = null;
socketIndex_AreaID = null;
// 2015.04.03 hwjang end websock_areaID[index]와 AreaID 관련성 확인
Guid2 = null;
function Bems_postmessage(domain, popup_name, popup_width, popup_height){
this.domain_url = domain;
this.window_popup = null;
this.popup_name = popup_name;
this.popup_width = popup_width;
this.popup_height = popup_height;
this.send_message = null;
this.receive_message = null;
}
function receiveMessage(event)
{
//if(event.origin !== pm_domain_url) return;
console.log('received response: ',event.data);
var strEvent = event.data;
// 2014.12.22 hwjang start
//if(event.data == "|onload|true"){ // 화면 초기시 수행
if(strEvent.indexOf("|onload|true")!=-1){
// 2014.12.22 hwjang end
popup_onload = true;
bems_pm_obj.sender_send_msg(Bems_element_list[object_cnt].guid + "|" + Bems_element_list[object_cnt].animation_enable);
bems_pm_obj.sender_send_msg("Name|" + Bems_element_list[object_cnt].name);
// 2014.11.20 hwjang start description 표시 항목 변경
//bems_pm_obj.sender_send_msg("Description|" + Bems_element_list[object_cnt].name);
bems_pm_obj.sender_send_msg("Description|" + Bems_element_list[object_cnt].description);
// 2014.11.20 hwjang end description 표시 항목 변경
bems_pm_obj.sender_send_msg("Guid|" + Bems_element_list[object_cnt].guid);
bems_pm_obj.sender_send_msg("Guid2|" + Bems_element_list[object_cnt].guid2);
guidNumber = Bems_element_list[object_cnt].guid;
bems_pm_obj.sender_send_msg("PresentValue|" + Bems_element_list[object_cnt].bems_object.present_value);
// 2014.11.20 hwjang start BinaryStatic ==> BinaryObject전체로 변경
// 2016.01.18 hwjang start BinaryStateText객체 추가
//if (Bems_element_list[object_cnt].base_type == "BinaryStatic" || Bems_element_list[object_cnt].base_type == "NewBinaryStatic" ||
// Bems_element_list[object_cnt].base_type == "BinaryDynamic" || Bems_element_list[object_cnt].base_type == "NewBinaryDynamic") {
if (Bems_element_list[object_cnt].base_type == "BinaryStatic" || Bems_element_list[object_cnt].base_type == "NewBinaryStatic" ||
Bems_element_list[object_cnt].base_type == "BinaryDynamic" || Bems_element_list[object_cnt].base_type == "NewBinaryDynamic" ||
Bems_element_list[object_cnt].base_type == "BinaryStateText") {
// 2016.01.18 hwjang end BinaryStateText객체 추가
//if (Bems_element_list[object_cnt].base_type.indexof("Binary") != -1) {
if (Bems_element_list[object_cnt].bems_object.in_active_text != null && Bems_element_list[object_cnt].bems_object.in_active_text != "")
bems_pm_obj.sender_send_msg("InActiveText|" + Bems_element_list[object_cnt].bems_object.in_active_text);
if (Bems_element_list[object_cnt].bems_object.active_text != null && Bems_element_list[object_cnt].bems_object.active_text != "")
bems_pm_obj.sender_send_msg("ActiveText|"+Bems_element_list[object_cnt].bems_object.active_text);
}
// 2014.11.20 hwjang start max_value, min_value, unit추가
// 2015.03.19 hwjang start "General" Type 정보 추가
//if (Bems_element_list[object_cnt].base_type == "AnalogStatic" || Bems_element_list[object_cnt].base_type == "ValueStatic" ||
// Bems_element_list[object_cnt].base_type == "NewAnalogStatic" ) {
if (Bems_element_list[object_cnt].base_type == "AnalogStatic" || Bems_element_list[object_cnt].base_type == "ValueStatic" ||
Bems_element_list[object_cnt].base_type == "NewAnalogStatic" || Bems_element_list[object_cnt].base_type == "General") {
bems_pm_obj.sender_send_msg("MaxValue|" + Bems_element_list[object_cnt].bems_object.max_value);
bems_pm_obj.sender_send_msg("MinValue|" + Bems_element_list[object_cnt].bems_object.min_value);
bems_pm_obj.sender_send_msg("Unit|" + Bems_element_list[object_cnt].bems_object.unit);
}
// 2015.03.19 hwjang end "General" Type 정보 추가
// 2014.11.20 hwjang end max_value, min_value, unit추가
// 2014.12.10 hwjang start stateText, NumberOfStates, StateNo 추가
if (Bems_element_list[object_cnt].base_type == "MultiStateText") {
bems_pm_obj.sender_send_msg("StateText|" + Bems_element_list[object_cnt].bems_object.StateText);
bems_pm_obj.sender_send_msg("NumberOfStates|" + Bems_element_list[object_cnt].bems_object.NumberOfStates);
bems_pm_obj.sender_send_msg("StateNo|" + Bems_element_list[object_cnt].bems_object.present_value);
}
// 2014.12.10 hwjang end stateText, NumberOfStates, StateNo 추가
return;
}
// popup_analog/popup_binary/popup_multistate화면에서 확인_적용 버튼 선택시 수행
// 2014.12.22 hwjang start AreaID추가
//var msg_data = event.data.split('|');
//var strDevicePos = event.data.indexOf(":");
// 2014.12.30 hwjang start 주소쳬계 변경 (WebCCMS와 통일)
//var strDevicePos = n_indexOf(event.data, ":", 2);
var strDevicePos = n_indexOf(event.data, ".", 2);
// 2014.12.30 hwjang endt 주소쳬계 변경 (WebCCMS와 통일)
// 2014.12.22 hwjang end AreaID추가
// 2014.12.17 hwjang start AreaID 추가
// 2015.04.03 hwjang start websock_areaID[index]와 AreaID 관련성 확인
//if (socketFlag[AreaID] == true && socket[AreaID].readyState == WebSocket.OPEN) {
// //socket[AreaID].send("3publish|" + event.data);
// socket[AreaID].send("3publish|" + event.data.substr(strDevicePos + 1));
// console.log("send: ", "AreaID:" + AreaID + " , " + event.data.substr(strDevicePos + 1));
//}
if (socketFlag[socketIndex_AreaID] == true && socket[socketIndex_AreaID].readyState == WebSocket.OPEN) {
//socket[AreaID].send("3publish|" + event.data);
// 2015.12.04 hwjang start 로그인정보 추가
//socket[socketIndex_AreaID].send("3publish|" + event.data.substr(strDevicePos + 1));
socket[socketIndex_AreaID].send("3publish|" + event.data.substr(strDevicePos + 1) + "|" + userId);
// 2015.12.04 hwjang end 로그인정보 추가
console.log("send: ", "AreaID:" + setting.server.websock_areaID[socketIndex_AreaID] + " , " + event.data.substr(strDevicePos + 1) + ",userId="+userId);
}
// 2015.04.03 hwjang end websock_areaID[index]와 AreaID 관련성 확인
// 2014.12.17 hwjang end AreaID 추가
// 2014.12.05 hwjang start // 처리함.
//bems_operation(msg_data[0], msg_data[1]);
// 2014.12.05 hwjang end // 처리함.
window.removeEventListener("message", receiveMessage, false);
}
Bems_postmessage.prototype = {
// 메시지 송신 후처리
// 2014.12.22 hwjang start 메시지에 guid2 추가
//set_sender_postmessage: function (i, areaID) {
set_sender_postmessage: function(i, areaID, guid2){
// 2014.12.22 hwjang end 메시지에 guid2 추가
pm_domain_url = this.domain_url;
object_cnt = i;
// 2014.12.17 hwjang start AreaID 추가
// 2015.04.03 hwjang start websock_areaID[index]와 AreaID 관련성 확인
//AreaID = areaID;
socketIndex_AreaID = -1;
for (var j = 0; j < setting.server.websock_server.length; j++) {
if (areaID == setting.server.websock_areaID[j]) {
socketIndex_AreaID = j;
break;
}
}
// 2015.04.03 hwjang end websock_areaID[index]와 AreaID 관련성 확인
// 2014.12.17 hwjang end AreaID 추가
// 2014.12.22 hwjang start 메시지에 guid2 추가
Guid2 = guid2;
// 2014.12.22 hwjang end 메시지에 guid2 추가
window.addEventListener('message',receiveMessage,false);
},
// 메시지수신 후처리(1. 화면 로드시에 화면정보 갱신용으로 수행)
set_receiver_postmessage: function(){
pm_domain_url = this.domain_url;
window.addEventListener('message',function(event) {
//if(event.origin !== pm_domain_url)
//return;
console.log('message received: ', event.data);
var msg_data = event.data.split('|');
/*
if(msg_data[0] == "Name")
$("#name").html("Name : "+ msg_data[1]);
else if(msg_data[0] == "Description")
$("#description").html("Description : "+ msg_data[1]);
else if (msg_data[0] == "Guid") {
// 2014.12.10 hwjang start guid => Address로 이름 변경
//$("#guid").html("Guid : " + msg_data[1]);
$("#guid").html("Address : " + msg_data[1]);
// 2014.12.10 hwjang end guid => Address로 이름 변경
set_guid(msg_data[1]);
}
*/
if(msg_data[0] == "Name")
$("#name").html(msg_data[1]);
else if(msg_data[0] == "Description")
$("#description").html(msg_data[1]);
else if (msg_data[0] == "Guid") {
// 2014.12.10 hwjang start guid => Address로 이름 변경
//$("#guid").html("Guid : " + msg_data[1]);
$("#guid").html(msg_data[1]);
// 2014.12.10 hwjang end guid => Address로 이름 변경
set_guid(msg_data[1]);
}
else if (msg_data[0] == "Guid2") {
$("#guid2").html(msg_data[1]);
set_guid2(msg_data[1]);
}
else if (msg_data[0] == "PresentValue") {
set_present_value(msg_data[1]);
}
else if (msg_data[0] == "ActiveText") {
$("#notify1").text(msg_data[1]);
}
else if (msg_data[0] == "InActiveText") {
$("#notify2").text(msg_data[1]);
}
// 2014.11.20 hwjang start max_value, min_value, unit추가
else if (msg_data[0] == "MaxValue") {
//$("#max_value").html("Max Value : " + msg_data[1]);
$("#max_value").html(msg_data[1]);
set_max_value(msg_data[1]);
}
else if (msg_data[0] == "MinValue") {
//$("#min_value").html("Min Value : " + msg_data[1]);
$("#min_value").html( msg_data[1]);
set_min_value(msg_data[1]);
}
else if (msg_data[0] == "Unit") {
if (msg_data[1] == "no unit")
$("#unit").html("");
else
$("#unit").html(msg_data[1]);
set_unit(msg_data[1]);
}
// 2014.11.20 hwjang start max_value, min_value, unit추가
// 2014.12.10 hwjang start stateText, NumberOfStates, StateNo 추가
else if (msg_data[0] == "StateText") {
//alert(msg_data[1]);
var strArray = msg_data[1].split(",");
//alert(strArray.length);
var strText = "";
for (var i = 0; i < strArray.length; i++) {
strText += "<option>" + strArray[i] + "</option>";
}
//alert(strText);
$("#stateText").html(strText);
set_state_text(msg_data[1]);
}
else if (msg_data[0] == "NumberOfStates") {
//alert(msg_data[1]);
$("#NumberOfStates").val(msg_data[1]);
set_number_of_states(msg_data[1]);
}
else if (msg_data[0] == "StateNo") {
//alert(msg_data[1]);
$("#StateNo").val(msg_data[1]);
set_state_no(msg_data[1]);
}
// 2014.12.10 hwjang end stateText, NumberOfStates, StateNo 추가
else
sender_guid = msg_data[0];
},false);
},
// 송신측 메시지 송신(개별속성 송신)
sender_send_msg: function (message) {
this.window_popup.postMessage(message, this.domain_url);
},
// 수신측 메시지 송신 (2. 화면 load시, 확인/적용시)
receiver_send_msg: function(message){
console.log('receiver_send_msg ', message);
// 2014.12.05 hwjang start Guid 변경 (Device ID 제외)
//// 2014.12.22 hwjang strat GUID에서 AreaID,Network ID 제외
//window.opener.postMessage(Guid2 + "|" + message, this.domain_url);
//var strDevicePos = n_indexOf(sender_guid, ":", 2);
//window.opener.postMessage(sender_guid.substr(strDevicePos + 1) + "|" + message, this.domain_url);
//var strDevicePos = sender_guid.indexOf(":");
//console.log("receive_send_msg", strDevicePos + ":" + sender_guid.substr(strDevicePos + 1));
window.opener.postMessage(sender_guid + "|" + message, this.domain_url);
//window.opener.postMessage(sender_guid.substr(strDevicePos + 1) + "|" + message, this.domain_url);
//// 2014.12.22 hwjang end GUID에서 AreaID,Network ID 제외
// 2014.12.05 hwjang end Guid 변경 (Device ID 제외)
},
create_popup: function(obj_type, url){
//var popX = (420 * document.body.clientWidth) / 1920;
//var popY = (280 * document.body.clientHeight) / 1080;
var popX = (1920 / document.body.clientWidth) * 390;
var popY = (1080 / document.body.clientHeight) * 200;
// 2014.11.20 hwjang start analog.html 화면 크기 변경
popX = 410;
popY = 280; //popY = 220;
// 2014.11.20 hwjang end
// 2014.11.04 hwjang start
var popX2 = 1280;
var popY2 = 1080;
// 2016.01.04 hwjang start 제어창 시작위치을 중간으로 변경 설정
LeftPosition = (screen.width - popX) / 2;
TopPosition = (screen.height - popY) / 2;
// 2016.01.04 hwjang end 제어창 시작위치을 중간으로 변경 설정
//alert(popX);
//alert(popY);
// 2016.01.18 hwjang start BinaryStateText객체 추가
//if (obj_type == "BinaryStatic" || obj_type == "BinaryAnalog" || obj_type == "BinaryDynamic" || obj_type == "NewBinaryDynamic" || obj_type == "NewBinaryStatic" )
if (obj_type == "BinaryStatic" || obj_type == "BinaryAnalog" || obj_type == "BinaryDynamic" || obj_type == "NewBinaryDynamic" || obj_type == "NewBinaryStatic" || obj_type == "BinaryStateText")
// 2016.01.18 hwjang end BinaryStateText객체 추가
//this.window_popup = window.open(this.domain_url + "/popup_binary.html", this.popup_name, "width="+this.popup_width*0.7+",height="+this.popup_height*0.7,'resizable=yes');
//this.window_popup = window.open(setting.server.host_server + "/popup_binary.html", this.popup_name, "width="+popX+",height="+popY,'resizable=yes');
//this.window_popup = window.open(this.domain_url, this.popup_name, "width="+popX+",height="+popY,'resizable=yes');
// 2014.12.24 hwjang start 웹브라우저 주소를 자체적으로 읽어들이기
//this.window_popup = window.open(setting.server.host_server + "/popup_binary.html", this.popup_name, "width=" + popX + ",height=" + popY + ", resizable=yes,location=no,titlebar=no");
this.window_popup = window.open(this.domain_url + "/popup_binary.html", this.popup_name, "width=" + popX + ",height=" + popY + ", resizable=yes,location=no,titlebar=no"+",left="+LeftPosition+ ", top="+TopPosition);
// 2014.12.24 hwjang end 웹브라우저 주소를 자체적으로 읽어들이기
// 2015.03.19 hwjang start "General" Type 정보 추가
//else if (obj_type == "AnalogStatic" || obj_type == "ValueStatic" || obj_type == "NewAnalogStatic" || obj_type == "General")
else if (obj_type == "AnalogStatic" || obj_type == "ValueStatic" || obj_type == "NewAnalogStatic" )
// 2015.03.19 hwjang end "General" Type 정보 추가
//this.window_popup = window.open(this.domain_url + "/popup_analog.html", this.popup_name, "width=" + this.popup_width * 0.7 + ",height=" + this.popup_height * 0.7,'resizable=yes');
// 2014.12.24 hwjang start 웹브라우저 주소를 자체적으로 읽어들이기
//this.window_popup = window.open(setting.server.host_server + "/popup_analog.html", this.popup_name, "width=" + popX + ",height=" + popY + ", resizable=yes,location=no,titlebar=no");
this.window_popup = window.open(this.domain_url + "/popup_analog.html", this.popup_name, "width=" + popX + ",height=" + popY + ", resizable=yes,location=no,titlebar=no" + ",left=" + LeftPosition + ", top=" + TopPosition);
// 2014.12.24 hwjang end 웹브라우저 주소를 자체적으로 읽어들이기
else if (obj_type == "MultiStateText")
// 2014.12.24 hwjang start 웹브라우저 주소를 자체적으로 읽어들이기
//this.window_popup = window.open(setting.server.host_server + "/popup_multistate.html", this.popup_name, "width=" + popX + ",height=" + popY + ", resizable=yes,location=no,titlebar=no");
this.window_popup = window.open(this.domain_url + "/popup_multistate.html", this.popup_name, "width=" + popX + ",height=" + popY + ", resizable=yes,location=no,titlebar=no" + ",left=" + LeftPosition + ", top=" + TopPosition);
// 2014.12.24 hwjang end 웹브라우저 주소를 자체적으로 읽어들이기
else if (obj_type == "General")
// 2014.12.24 hwjang start 웹브라우저 주소를 자체적으로 읽어들이기
//this.window_popup = window.open(setting.server.host_server + "/popup_multistate.html", this.popup_name, "width=" + popX + ",height=" + popY + ", resizable=yes,location=no,titlebar=no");
this.window_popup = window.open(this.domain_url + "/popup_general.html", this.popup_name, "width=" + popX + ",height=" + popY + ", resizable=yes,location=no,titlebar=no" + ",left=" + LeftPosition + ", top=" + TopPosition);
// 2014.12.24 hwjang end 웹브라우저 주소를 자체적으로 읽어들이기
else if (obj_type == "LabelLink") {
// 2016.01.12 hwjang start LabelLink관련 로그인정보 포함
//url += "?GUID=" + strGUID + "&GraphicControl=" + GraphicControl + "&GraphicAuth=" + GraphicAuth + "&userId=" + userId;
// 2016.01.12 hwjang end LabelLink관련 로그인정보 포함
this.window_popup = window.open(url, this.popup_name, "width=" + popX2 + ",height=" + popY2, 'resizable=yes');
}
//this.window_popup.focus();
}
}
|
import Model from "~/models/Model"
export default class Product extends Model {
resource() {
return "v1/products"
}
}
|
var arr1 = ["a","b","c","d","e","f"];
var arr2 = [1,2,3,4];
var alt_join = function(arr1,arr2){
var len = max(arr1.length,arr2.length);
var array = [];
for(i=0;i<len;i++){
if(arr1[i] != undefined) array.push(arr1[i]);
if(arr2[i] != undefined) array.push(arr2[i]);
}
return array;
}
var max = function(num1,num2){
if(num1>num2) return num1;
return num2;
}
console.log(alt_join(arr1,arr2));
|
// packages
import React from 'react'
// components
import Text from './Text'
export default function Heading() {
return (
<div className='heading' style={{textAlign: 'center'}}>
<Text tag='h1' text='Darlington Congregational Chruch' />
</div>
)
}
|
/*Function for AJAX requests*/
function AJAX(method, link, data, callback){
var req = new XMLHttpRequest();
req.open(method, link, true);
if (method === 'POST')
req.setRequestHeader('Content-Type', 'application/json');
req.addEventListener('load', function(){
if (req.status >= 200 && req.status < 400){
callback(req.responseText);
}
else{
console.log("Error: " + req.statusText);
}
});
req.send(data);
}
function makeTable(data){
var table = document.getElementById('tableRows');
table.innerHTML = "";
var tableData = JSON.parse(data);
tableData.forEach(function(r){
var row = document.createElement('tr');
Object.keys(r).forEach(function(c){
if (c =='name'){
var cell = document.createElement('td');
cell.setAttribute("id", "product-" + r.name);
cell.setAttribute("class", "col-md-8");
cell.textContent = r[c];
row.appendChild(cell);
}
else if (c == 'product_qty'){
var editCell = document.createElement('td');
editCell.setAttribute("class", "col-md-3");
var editField = document.createElement('span');
editField.innerHTML = "<div>" +
"<input type='text' class='form-control' id='item-" + r.name +"' placeholder=" + r[c] +" ></div>";
editCell.appendChild(editField);
editCell.setAttribute("style", "float: right;");
row.appendChild(editCell);
}
});
var updateCell = document.createElement('td');
var updateButton = document.createElement('input');
updateButton.setAttribute("type", "submit");
updateButton.setAttribute("class", "btn btn-warning btn-block");
updateButton.setAttribute("style", "float: right;");
updateButton.setAttribute("value", "Update");
updateCell.appendChild(updateButton);
updateRow(updateButton, r.id, r.name);
row.appendChild(updateCell);
/*appends row to the table*/
table.appendChild(row);
});
}
function updateRow(btn, id, name){
btn.addEventListener('click', function(e) {
e.preventDefault();
var data = {};
//data.cart_id = 1;
data.product_id = id;
data.product_qty = document.getElementById("item-" + name).value;
data = JSON.stringify(data);
AJAX('POST', '/update-cart', data, function(response){
makeTable(response);
});
window.location.reload();
});
}
function addIndiaWater(qty){
var data = {};
data.action = 'insert-water';
//data.cart_id = 1;
data.product_id = 1;
data.product_qty = qty;
data = JSON.stringify(data);
AJAX('POST', '/update-cart', data, function(response){
});
window.location.reload();
}
function addItem(qty, product){
var data = {};
data.product_id = product;
data.product_qty = qty;
data = JSON.stringify(data);
AJAX('POST', '/update-cart', data, function(response){
});
}
|
var app = new Vue(
{
el: '#app',
data: {
images:[
{
source:"https://mole24.it/wp-content/uploads/2019/11/space_adventure_torino.jpg",
alt:"",
},
{
source:"https://images3.alphacoders.com/905/905078.jpg",
alt:"",
},
{
source:"https://images6.alphacoders.com/923/thumb-1920-923687.jpg",
alt:"",
},
],
imageIndex: 0, //questa è la chiave dell'oggetto.
},
methods: {
//FUNZIONE PER SCORRERE LE IMG SIA QUELLA PRIMA CHE QUELLA DOPO, IMAGEINDEX VA MOTIFICATO ANCHE SU HTML PER DARE UN INDICE ALL'IMG.
previousImage: function(){ //questa funzione permette di scorrere l'array di uno aumentando di uno l'indice
this.imageIndex--; //
console.log(this.imageIndex);
if(this.imageIndex < 0){
this.imageIndex = this.images.length - 1;
}
},
nextImage: function(){ //questa funzione permette di scorrere l'array di uno sottraendo di uno l'indice
this.imageIndex++;
console.log(this.imageIndex);
if(this.imageIndex >= this.images.length){
this.imageIndex = 0;
}
},
}
});
|
angular
.module('app')
.controller('blogCtrl', ['$scope', '$http', function ($scope, $http) {
'use strict';
$scope.progressIndicator = true;
$scope.error = false;
$http({method: 'GET', url: 'https://aweilf1bak.execute-api.us-east-1.amazonaws.com/medium/'})
.then(function (response) {
const data = Object.keys(response.data.payload.references.Post).map(function (key) {
return response.data.payload.references.Post[key];
});
$scope.mediumArticles = data;
$scope.progressIndicator = false;
}, function (error) {
let errorText;
$scope.progressIndicator = false;
if (error.xhrStatus === 'complete') {
errorText = error.status + error.statusText;
} else {
errorText = error.xhrStatus;
}
$scope.errorText = 'Error occurred getting data: ' + errorText;
});
$scope.getArticleDate = function (value) {
const monthNames = [
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'
];
const date = new Date(value);
return monthNames[date.getMonth()] + ' ' + date.getDate() + ' ' + date.getFullYear();
};
$scope.getReadingTime = function (value) {
return Math.ceil(value);
};
}]);
|
import { AsyncStorage } from 'react-native';
import { call, put } from 'redux-saga/effects';
import { appActions } from 'state/app';
import { isNil } from 'lodash';
function* loadHackatonVote() {
const hackathonVote = yield call(AsyncStorage.getItem, 'isVotedForHackathon');
if (isNil(hackathonVote)) return false;
return true;
}
export default function* hackathonVoteInitSaga() {
const isVotedForHackathon = yield call(loadHackatonVote);
if (isVotedForHackathon) {
yield put(appActions.setHackathonVote());
}
}
|
import { createSelector } from 'reselect'
export const UserOfCommentSelector = (state, comment) => {
if (comment && comment.user && state && state.profiles)
return state.profiles[comment.user]
}
export const SellerOfProductSelector = (state, product) => {
if (product && product.seller && state && state.profiles)
return state.profiles[product.seller]
}
|
import { Col, Row, Container } from "react-bootstrap"
import DailySummariesList from "./DailySummariesList"
import SummaryDetailPane from "./SummaryDetailPane"
const Summaries = () => {
return (
<Container>
<Row>
<Col xs={6} sm={5} md={4} lg={3}>
<DailySummariesList />
</Col>
<Col>
<SummaryDetailPane /></Col>
</Row>
</Container>
)
}
export default Summaries
|
'use strict'
/** @typedef { import('./types').Deployment } Deployment */
/** @typedef { import('./types').CreateDeploymentOptions } CreateDeploymentOptions */
/** @typedef { import('./types').CreateDeploymentResult } CreateDeploymentResult */
/** @typedef { import('./types').GetDeploymentOptions } GetDeploymentOptions */
/** @typedef { import('./types').GetDeploymentResult } GetDeploymentResult */
/** @typedef { import('./types').GetDeploymentTemplateOptions } GetDeploymentTemplateOptions */
/** @typedef { import('./types').GetDeploymentTemplateResult } GetDeploymentTemplateResult */
/** @typedef { import('./types').DeleteDeploymentOptions } DeleteDeploymentOptions */
/** @typedef { import('./types').DeploymentCreatePayload } DeploymentCreatePayload */
const { writeFileSync, unlinkSync } = require('fs')
const { execFile } = require('child_process')
const tempy = require('tempy')
const pkg = require('../package.json')
const logger = require('./logger')
const { resolveable } = require('./utils')
module.exports = {
createDeployment,
deleteDeployment,
getDeployment,
getDeploymentTemplate,
listDeployments,
listStacks,
listTemplates,
}
/** @type { (options: CreateDeploymentOptions) => Promise<CreateDeploymentResult> } */
async function createDeployment({ config, template, stack, name, deploymentName, esSize, kbSize, tmMaxWorkers, tmPollInterval }) {
let args = ['deployment', 'create']
args.push('--config', config)
if (template) args.push('--deployment-template', template)
if (stack) args.push('--version', stack)
args.push('--message', `${pkg.name}: creating deployment ${name}`)
args.push('--output', 'json')
args.push('--name', deploymentName)
args.push('--generate-payload')
// generate the payload to create the deployment
const payload = await ecctlRun(args)
// console.log(JSON.stringify(payload, null, 4))
await fixDeploymentCreatePayload(payload, config, {
esSize,
kbSize,
tmMaxWorkers,
tmPollInterval
})
// console.log(JSON.stringify(payload, null, 4))
// write the create deployment payload to a file and deploy it
const tmpFile = tempy.file({ extension: 'json' })
writeFileSync(tmpFile, JSON.stringify(payload, null, 4))
args = ['deployment', 'create']
args.push('--config', config)
args.push('--file', tmpFile)
args.push('--name', deploymentName)
const result = asCreateDeploymentResult(await ecctlRun(args))
unlinkSync(tmpFile)
return result
}
/** @type { (options: GetDeploymentOptions) => Promise<GetDeploymentResult> } */
async function getDeployment({ config, name, id }) {
const args = ['deployment', 'show', id]
args.push('--config', config)
args.push('--message', `${pkg.name}: getting deployment ${id} ${name}`)
args.push('--output', 'json')
return asGetDeploymentResult(await ecctlRun(args))
}
/** @type { (options: GetDeploymentTemplateOptions) => Promise<GetDeploymentTemplateResult> } */
async function getDeploymentTemplate({ config, id }) {
const args = ['deployment', 'template', 'show', '--template-id', id]
args.push('--config', config)
args.push('--message', `${pkg.name}: getting deployment template ${id}`)
args.push('--output', 'json')
return await ecctlRun(args)
}
/** @type { (options: DeleteDeploymentOptions) => Promise<any> } */
async function deleteDeployment({ config, id, name }) {
const args = ['deployment', 'shutdown', id]
args.push('--config', config)
args.push('--message', `${pkg.name}: deleting deployment ${id} ${name}`)
args.push('--output', 'json')
args.push('--force')
args.push('--skip-snapshot')
return await ecctlRun(args)
}
/** @type { ({ config }: { config: string }) => Promise<any> } */
async function listDeployments({ config }) {
const args = ['deployment', 'list']
args.push('--config', config)
args.push('--message', `${pkg.name}: listing deployments`)
args.push('--output', 'json')
return await ecctlRun(args)
}
/** @type { ({ config }: { config: string }) => Promise<any> } */
async function listStacks({ config }) {
const args = ['stack', 'list']
args.push('--config', config)
args.push('--message', `${pkg.name}: listing stacks`)
args.push('--output', 'json')
return await ecctlRun(args)
}
// used to get list of possible memory configurations
/** @type { (options: { config: string }) => Promise<any> } */
async function listTemplates({ config }) {
const args = ['deployment', 'template', 'list']
args.push('--config', config)
args.push('--message', `${pkg.name}: listing template`)
args.push('--output', 'json')
return await ecctlRun(args)
}
/** @type { (args: string[]) => Promise<any> } */
async function ecctlRun(args) {
const file = 'ecctl'
const result = resolveable()
const execOptions = {
maxBuffer: 20 * 1000 * 1000,
encoding: 'utf8'
}
const errMessagePrefix = `error running "${file} ${args.join(' ')}"`
try {
execFile(file, args, execOptions, (err, stdout, stderr) => {
if (err) {
logger.debug(`${errMessagePrefix}: stderr:\n${stderr}`)
return result.reject(`${errMessagePrefix}: ${err}}`)
}
try {
return result.resolve(JSON.parse(stdout))
} catch (err) {
logger.debug(`${errMessagePrefix}: error parsing JSON: ${err}:\n${stdout}`)
return result.reject(`${errMessagePrefix}: error parsing JSON: ${err}}`)
}
})
} catch (err) {
result.reject(`${errMessagePrefix}: ${err}}`)
}
return result.promise
}
/** @type { (result: any) => CreateDeploymentResult } */
function asCreateDeploymentResult(result) {
if (result == null) throw new Error('unexpected null from create deployment')
if (result.id == null) throw new Error('id null from create deployment')
const id = `${result.id}`
/** @type { any[] } */
const resources = result.resources || []
const esResource = resources.find(resource => resource.kind === 'elasticsearch')
if (esResource == null) throw new Error('no elasticsearch resource from create deployment')
const credentials = esResource.credentials || {}
const username = credentials.username
const password = credentials.password
if (username == null) throw new Error('username not set from create deploymeent')
if (password == null) throw new Error('password not set from create deployment')
return { id, username, password }
}
/** @type { (result: any) => GetDeploymentResult } */
function asGetDeploymentResult(result) {
if (result == null) throw new Error('unexpected null from get deployment')
if (result.resources == null) throw new Error('unexpected null resources from get deployment')
// return a deep copy
const esInfo = getResourceInfo('elasticsearch', result)
const kbInfo = getResourceInfo('kibana', result)
const healthy = esInfo.healthy && esInfo.status === 'started' && kbInfo.healthy && kbInfo.status === 'started'
const status = [
`es: ${esInfo.healthy ? 'healthy' : 'unhealthy'}: ${esInfo.status}`,
`kb: ${esInfo.healthy ? 'healthy' : 'unhealthy'}: ${kbInfo.status}`,
].join('; ')
return {
healthy,
status,
esEndpoint: esInfo.endpoint,
esPort: esInfo.port,
kbEndpoint: kbInfo.endpoint,
kbPort: kbInfo.port,
version: esInfo.version,
zone: esInfo.zone,
}
}
/** @type { (key: string, result: any) => { endpoint: string, port: number, healthy: boolean, status: string, version: string, zone: string } } */
function getResourceInfo(key, showDeployment) {
const allResources = (showDeployment || {}).resources || {}
const resource = (allResources[key] || [])[0] || {}
const info = resource.info || {}
const healthy = !!(info.healthy || false)
const status = `${info.status || 'unknown'}`
const metadata = info.metadata || {}
const endpoint = `${metadata.endpoint}`
const port = parseInt(metadata.ports.https, 10)
const topology = info.topology || {}
const instance = (topology.instances || [])[0] || {}
const version = instance.service_version || 'unknown'
const zone = instance.zone || 'unknown'
return { endpoint, port, healthy, status, version, zone }
}
/** @type { (payload: DeploymentCreatePayload, config: string, opts: {esSize: number, kbSize: number, tmMaxWorkers: number, tmPollInterval: number }) => Promise<void> } */
async function fixDeploymentCreatePayload(payload, config, { esSize, kbSize, tmMaxWorkers, tmPollInterval }){
// just use the first element of the elasticsearch and kibana arrays
const elasticsearch = payload.resources.elasticsearch[0]
const kibana = payload.resources.kibana[0]
payload.resources.elasticsearch = [ elasticsearch ]
payload.resources.kibana = [ kibana ]
const deploymentTemplateId = elasticsearch.plan?.deployment_template?.id
if (deploymentTemplateId == null) throw new Error('unable to find deployment template id')
const deploymentTemplate = await getDeploymentTemplate({ config, id: deploymentTemplateId })
// elasticsearch: set memory for "hot_content"
for (const elasticsearch of payload.resources.elasticsearch) {
elasticsearch.plan.cluster_topology = elasticsearch.plan.cluster_topology.map((node) => {
if (node.size?.value) {
node.size.value = getClosestSizeFromTemplate(node.instance_configuration_id, esSize * 1024, deploymentTemplate)
}
return node
})
}
// Kibana fix ups
for (const kibana of payload.resources.kibana) {
// set Kibana config overrides
let configOverridesYaml = ''
if (tmMaxWorkers !== 10) configOverridesYaml += `\nxpack.task_manager.max_workers: ${tmMaxWorkers}`
if (tmPollInterval !== 3000) configOverridesYaml += `\nxpack.task_manager.poll_interval: ${tmPollInterval}`
if (configOverridesYaml.length > 0) {
payload.resources.kibana.forEach(kibana => {
kibana.plan.kibana.user_settings_yaml = configOverridesYaml
})
}
// set Kibana memory
kibana.plan.cluster_topology = kibana.plan.cluster_topology.map((node) => {
if (node.size?.value) {
node.size.value = getClosestSizeFromTemplate(node.instance_configuration_id, kbSize * 1024, deploymentTemplate)
}
return node
})
}
}
/** @type { (instanceConfigId: string, requestedSize: number, template: GetDeploymentTemplateResult) => number } */
function getClosestSizeFromTemplate(instanceConfigId, requestedSize, template) {
for (const instanceConfig of template.instance_configurations) {
if (instanceConfig.id != instanceConfigId) continue
const sizes = instanceConfig.discrete_sizes?.sizes ?? []
if (sizes.length === 0) continue
// extend the sizes to account for multiple nodes, all using max memory
const last = sizes[sizes.length - 1]
for (let i = 2; i <= 100; i++) {
sizes.push(last * i)
}
// find the value in sizes closest to requestedSize
let closest = sizes[0]
let closestDiff = Number.MAX_SAFE_INTEGER
for (const size of sizes) {
const diff = Math.abs(size - requestedSize)
if (diff < closestDiff) {
closest = size
closestDiff = diff
}
}
if (closestDiff !== 0) {
logger.debug(`changing memory of ${requestedSize} to ${closest} for ${instanceConfigId}`)
}
return closest
}
}
|
const admin = require("firebase-admin");
const serviceAccount = require("./serviceAccountKey.json");
const config = {
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://-------.firebaseio.com"
}
!admin.apps.length ? admin.initializeApp(config) : admin.app();
const db = admin.database();
const sourcesRef = db.ref('sources');
const favoritesRef = db.ref('favorites');
const savedRef = db.ref('saved');
const getSources = () => {
return new Promise((resolve, reject) => {
sourcesRef.on('value', (data) => {
const sourcesObj = data.val();
if (!sourcesObj)
return resolve([]);
const keys = Object.keys(sourcesObj);
const sources = [];
for (let i = 0; i < keys.length; i++) {
const obj = sourcesObj[keys[i]];
sources.push({
id: keys[i],
title: obj.title,
link: obj.link,
description: obj.description,
url: obj.url
})
}
resolve(sources);
}, (error) => reject())
});
}
const getSourceFromId = (sourceId) => {
return new Promise((resolve, reject) => {
sourcesRef.child(sourceId).on('value', (snap) => {
const value = snap.val();
resolve({title: value.title, url: value.url});
}, (error) => reject())
})
}
const addNewSource = (source) => {
return new Promise((resolve, reject) => {
sourcesRef.push(source, (error) => error ? reject() : resolve());
})
}
const deleteSource = (sourceId) => {
return new Promise((resolve, reject) => {
sourcesRef.child(sourceId).remove((error) => error ? reject() : resolve());
})
}
const getFavorites = () => {
return new Promise((resolve, reject) => {
favoritesRef.on('value', (data) => {
const favoritesObj = data.val();
if (!favoritesObj)
return resolve([]);
const keys = Object.keys(favoritesObj);
const favorites = [];
for (let i = 0; i < keys.length; i++) {
const obj = favoritesObj[keys[i]];
const {content, date, link, title} = obj;
favorites.push({
id: keys[i],
content,
date,
link,
title
});
}
resolve(favorites);
}, (error) => reject())
})
}
const addNewFavorite = (favorite) => {
return new Promise((resolve, reject) => {
favoritesRef.push(favorite, (error) => error ? reject() : resolve());
})
}
const deleteFavorite = (favoriteId) => {
return new Promise((resolve, reject) => {
favoritesRef.child(favoriteId).remove((error) => error ? reject() : resolve());
})
}
const getSaved = () => {
return new Promise((resolve, reject) => {
savedRef.on('value', (data) => {
const savedObj = data.val();
if (!savedObj)
return resolve([]);
const keys = Object.keys(savedObj);
const saved = [];
for (let i = 0; i < keys.length; i++) {
const obj = savedObj[keys[i]];
const {content, date, link, title} = obj;
saved.push({
id: keys[i],
content,
date,
link,
title
});
}
resolve(saved);
}, (error) => reject())
})
}
const addNewSaved = (saved) => {
return new Promise((resolve, reject) => {
savedRef.push(saved, (error) => error ? reject() : resolve());
})
}
const deleteSaved = (savedId) => {
return new Promise((resolve, reject) => {
savedRef.child(savedId).remove((error) => error ? reject() : resolve());
})
}
module.exports.getSources = getSources;
module.exports.getSourceFromId = getSourceFromId;
module.exports.addNewSource = addNewSource;
module.exports.deleteSource = deleteSource;
module.exports.getFavorites = getFavorites;
module.exports.addNewFavorite = addNewFavorite;
module.exports.deleteFavorite = deleteFavorite;
module.exports.getSaved = getSaved;
module.exports.addNewSaved = addNewSaved;
module.exports.deleteSaved = deleteSaved;
|
const routes = Object.freeze({
home: '/',
root: '/',
posts: '/posts/',
})
export default routes
export const postWithId = (id = ':id') => `${routes.posts}${id}`
|
import React, { Component } from 'react';
import InsereUsuario from './Insere';
class Usuario extends Component {
render() {
return (
<section>
<InsereUsuario />
</section>
);
}
}
export default Usuario;
|
//全局变量
var inputFocus;//该变量记录当前焦点的input
var bKeyDown=false;//记录键盘被按下的状态,当有键盘按下时其值为true
function setRowClass(obj,className){
obj.className=className;
var oldClass,toClass;
if(className=="tableData") {oldClass="inputTableDataHit";toClass="inputTableData";}
if(className=="tableDataHit") {oldClass="inputTableData";toClass="inputTableDataHit";}
var objsInput=obj.all;
for(var i=0;i<objsInput.length;i++)
if(objsInput[i].tagName=="INPUT")if(objsInput[i].className==oldClass)objsInput[i].className=toClass;
}
function lightonRow(obj){
if(obj.tagName!="TR")return;
//将所有未被选中的行取消高亮度现实
var tableOnlineEdit=obj.parentElement;
while(tableOnlineEdit.tagName!="TABLE")tableOnlineEdit=tableOnlineEdit.parentElement;
var objsCheckBox=tableOnlineEdit.all("checkLine");
for(var iCheckBox=1;iCheckBox<objsCheckBox.length;iCheckBox++)
if(objsCheckBox[iCheckBox].checked==false) setRowClass(tableOnlineEdit.rows[iCheckBox+1],"tableData");
//当前点击行高亮度显示
setRowClass(obj,"tableDataHit");
}
//得到obj的上级元素TagName
function getUpperObj(obj,TagName){
var strTagName=TagName.toUpperCase();
var objUpper=obj.parentElement;
while(objUpper){
if(objUpper.tagName==strTagName) break;
objUpper=objUpper.parentElement;
}
return objUpper;
}
function getPosition(obj,pos){
var t=eval("obj."+pos);
while(obj=obj.offsetParent){
t+=eval("obj."+pos);
}
return t;
}
function showInputSelect(obj,objShow){
inputFocus=obj;//记录当前焦点input至全局变量
objShow.style.top =getPosition(obj,"offsetTop")+obj.offsetHeight+2;
objShow.style.left=getPosition(obj,"offsetLeft");
objShow.style.width=obj.offsetWidth;
objShow.value=obj.value;
objShow.style.display="block";
}
function setInputFromSelect(objTo,objShow){
objTo.value=objShow.options[objShow.selectedIndex].value;
//objShow.style.display="none";
}
function hideInput(obj){
obj.style.display="none";
}
function clearRow(objTable){
var tbodyOnlineEdit=objTable.getElementsByTagName("TBODY")[0];
for (var i=tbodyOnlineEdit.children.length-1;i>=0;i--)
tbodyOnlineEdit.deleteRow(i);
}
function deleteRow(objTable){
var tbodyOnlineEdit=objTable.getElementsByTagName("TBODY")[0];
for (var i=tbodyOnlineEdit.children.length-1; i>=0 ; i-- )
if (tbodyOnlineEdit.children[i].firstChild.firstChild.checked)
tbodyOnlineEdit.deleteRow(i);
}
function addRow(objTable){
var tbodyOnlineEdit=objTable.getElementsByTagName("TBODY")[0];
var theadOnlineEdit=objTable.getElementsByTagName("THEAD")[0];
var elm = theadOnlineEdit.lastChild.cloneNode(true);
elm.style.display="";
tbodyOnlineEdit.insertBefore(elm);
}
//将指定数据行的objRow的输入域strName设置为strValue
function setInputValue(objRow,strName,strValue){
var objs=objRow.all;
for(var i=0;i<objs.length;i++){
if(objs[i].name==strName)objs[i].value=strValue;
}
}
//添加一个实例数据行
function addInstanceRow(objTable,Names,Values){
var tbodyOnlineEdit=objTable.getElementsByTagName("TBODY")[0];
var theadOnlineEdit=objTable.getElementsByTagName("THEAD")[0];
var elm = theadOnlineEdit.lastChild.cloneNode(true)
elm.style.display="";
for(var i=0;i<Names.length;i++)
setInputValue(elm,Names[i],Values[i]);
tbodyOnlineEdit.insertBefore(elm);
}
//将全部复选框设为指定值
function setOnlineEditCheckBox(obj,value){
var tbodyOnlineEdit=obj.getElementsByTagName("TBODY")[0];
for (var i=tbodyOnlineEdit.children.length-1; i>=0 ; i-- )
tbodyOnlineEdit.children[i].firstChild.firstChild.checked=value;
}
//为动态表格增加键盘导航功能,要使用该功能请在表格定义中增加事件处理onKeyDown="navigateKeys()" onKeyUp="setKeyDown(false)"
//有一点点问题,当按下"->"跳转到下一输入域时,光标显示在第一个字符之后
//建议仍然使用Tab键跳转
function navigateKeys(){
if(bKeyDown) return;
bKeyDown=true;
var elm=event.srcElement;
if(elm.tagName!="INPUT") return;//默认只对INPUT进行导航,可自行设定
var objTD=elm.parentElement;
var objTR=objTD.parentElement;
var objTBODY=objTR.parentElement.parentElement;
var objTable=objTBODY.parentElement;
var nRow=objTR.rowIndex;
var nCell=objTD.cellIndex;
var nKeyCode=event.keyCode;
switch(nKeyCode){
case 37://<-
if(getCursorPosition(elm)>0)return;
nCell--;
if(nCell==0){
nRow--;//跳转到上一行
nCell=objTR.cells.length-1;//最后一列
}
break;
case 38://^
nRow--;
break;
case 39://->
if(getCursorPosition(elm)<elm.value.length)return;
nCell++;
if(nCell==objTR.cells.length){
nRow++;//跳转到下一行首位置
nCell=1;//第一列
}
break;
case 40://\|/
nRow++;
if(nRow==objTBODY.rows.length){
addRow(objTable);//增加一个空行
nCell=1;//跳转到第一列
}
break;
case 13://Enter
nCell++;
if(nCell==objTR.cells.length){
nRow++;//跳转到下一行首位置
nCell=1;//第一列
}
if(nRow==objTBODY.rows.length){
addRow(objTable);//增加一个空行
nCell=1;//跳转到第一列
}
break;
default://do nothing
return;
}
if(nRow<2 || nRow>=objTBODY.rows.length || nCell<1 ||nCell>=objTR.cells.length) return;
objTR=objTBODY.rows[nRow];
objTD=objTR.cells[nCell];
var objs=objTD.all;
for(var i=0;i<objs.length;i++){
//此处使用ojbs[0],实际使用时可能需要加以修改,或加入其他条件
try{
lightonRow(objTR);
objs[i].focus();//setCursorPosition(objs[i],-1);
return;
}catch(e){
continue;
//if error occur,continue to next element
}
}//end for objs.length
}
//设置键盘状态,即bKeyDown的值
function setKeyDown(status){
bKeyDown=status;
}
//得到光标的位置
function getCursorPosition(obj){
var qswh="@#%#^&#*$"
obj.focus();
rng=document.selection.createRange();
rng.text=qswh;
var nPosition=obj.value.indexOf(qswh)
rng.moveStart("character", -qswh.length)
rng.text="";
return nPosition;
}
//设置光标位置
function setCursorPosition(obj,position){
range=obj.createTextRange();
range.collapse(true);
range.moveStart('character',position);
range.select();
}
|
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return this.store.createRecord('category');
},
afterModel: function(model){
/* model.set('status','I');
console.log('after model: ');
console.log(model.get('status'));*/
},
/* setupController: function (controller, model) {
this._super(controller, model);
controller.set('title', 'Create a new category');
controller.set('buttonLabel', 'Save category');
},
renderTemplate() {
this.render('libraries/form');
},*/
actions: {
saveCategory(newCategory) {
console.log('Get-data: ');
console.log(newCategory);
newCategory.save().then(() => this.transitionTo('admin.categories'));
},
willTransition() {
let model = this.controller.get('model');
if (model.get('isNew')) {
model.destroyRecord();
}
}
}
});
|
import Vue from 'vue';
import VeeValidate from 'vee-validate';
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
Vue.use(VeeValidate);
Vue.component('app-form', require('./components/Form.vue'));
const app = new Vue({
el: '#app'
});
/**
* We'll load jQuery and the Foundation framework which provides support
* for JavaScript based foundation features such as modals and tabs. This
* code may be modified to fit the specific needs of your application.
*/
try {
window.$ = window.jQuery = require('jquery');
require('foundation-sites/dist/js/plugins/foundation.core.js');
require('foundation-sites/dist/js/plugins/foundation.util.mediaQuery.js');
} catch (e) {}
/**
* Init foundation
*/
$(document).foundation();
/**
* We'll load custom fonts with web font loader to improve page speed
*/
import WebFont from 'webfontloader';
WebFont.load({
google: {
families: ['Open Sans:300,400,700']
}
});
|
import React, { Component } from 'react'
import { createPortal } from 'react-dom'
import PropTypes from 'prop-types'
import Editor from './Editor'
class EditorPortal extends Component {
constructor(props) {
super(props)
if (props.el) {
props.el.innerHTML = ''
}
}
render() {
const { el, ...editorProps } = this.props
editorProps.className = 'postrchild-editor'
return createPortal(<Editor {...editorProps} />, el)
}
}
EditorPortal.propTypes = {
el: PropTypes.node.isRequired,
}
export default EditorPortal
|
import createConfigurations from './config'
const configurations = createConfigurations()
function featureDetector(configurations) {
for (let i in configurations) {
const configuration = configurations[i]
let { features, fallback, breaking = true } = configuration
const unsupportedFeatures = features.filter(checkFeature => !checkFeature())
const supported = unsupportedFeatures.length === 0
fallback(supported)
if (!supported && breaking) {
break
}
}
}
featureDetector(configurations)
|
require('../../config/babel.register')
const path = require('path')
const express = require('express')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const app = express()
const port = 3001
setGlobalScope('window')
const routes = require('./server.routes')
app.set('views', path.join(__dirname, '../..','views'))
app.set('view engine', 'pug')
app.use(bodyParser.json())
app.use(cookieParser())
app.use('/', routes)
app.listen(port, error => {
error
? console.error(error)
: console.info(`==> 🌎 Proxy server listen on port ${port}.`)
})
function setGlobalScope(scope) {
global[scope] = {}
}
|
import React, { Component } from 'react';
import { ActivityIndicator, Alert, View, Text, StyleSheet, TextInput, KeyboardAvoidingView, TouchableWithoutFeedback, Keyboard, DeviceEventEmitter, Dimensions, StatusBar, TouchableOpacity, Platform } from 'react-native';
import styles from '../styles/Style_LoginScreen';
import layout from '../constants/Layout'
import colors from '../constants/Colors'
import { Asset } from 'expo-asset';
import { AppLoading } from 'expo';
import { TapGestureHandler, State } from 'react-native-gesture-handler';
import Svg, { Image, Circle, ClipPath } from 'react-native-svg';
import Animated, {
Value,
event,
block,
cond,
eq,
set,
Clock,
startClock,
stopClock,
debug,
timing,
clockRunning,
Easing,
interpolate,
Extrapolate,
concat
} from 'react-native-reanimated';
import { Feather } from '@expo/vector-icons';
import * as Animatable from 'react-native-animatable';
import * as Facebook from 'expo-facebook';
import * as Google from 'expo-google-app-auth';
import * as firebase from 'firebase';
import * as Actions_User from '../redux/actions/Actions_User';
import * as Actions_Customer from '../redux/actions/Actions_Customer';
import { connect } from 'react-redux';
// import firebaseApp from '../firebaseConfig';
require('../firebaseConfig');
import route from '../routeConfig';
class LoginScreen extends Component {
constructor(props) {
super(props);
this.state = {
screenStatus: 'sign-in',
// isReady: false,
visibleHeight: layout.window.height,
isKeyboardOpen: false,
email: '',
emailValidationColor: colors.gray02,
password: '',
passwordValidationColor: colors.gray02,
hidePassword: true,
logoSize: {width: 100, height: 70},
signed: false,
// shouldRender: false
};
this.buttonOpacity = new Value(1);
this.onStateChange = event([
{
nativeEvent: ({state}) => block([cond(eq(state, State.END), set(this.buttonOpacity, runTiming(new Clock(), 1, 0)))])
}
]);
this.onCloseState = event([
{
nativeEvent: ({state}) => block([cond(eq(state, State.END), set(this.buttonOpacity, runTiming(new Clock(), 0, 1)))])
}
]);
this.buttonY = interpolate(this.buttonOpacity, {
inputRange: [0, 1],
outputRange: [300, 0],
extrapolate: Extrapolate.CLAMP
});
this.bgY = interpolate(this.buttonOpacity, {
inputRange: [0, 1],
outputRange: this.state.isKeyboardOpen === true ? [-layout.window.height / 3 - this.state.visibleHeight, 0] : [-layout.window.height / 3 - 50, 0],
extrapolate: Extrapolate.CLAMP
});
this.textInputZIndex = interpolate(this.buttonOpacity, {
inputRange: [0, 1],
outputRange: [1, -1],
extrapolate: Extrapolate.CLAMP
});
this.textInputY = interpolate(this.buttonOpacity, {
inputRange: [0, 1],
outputRange: [0, 300],
extrapolate: Extrapolate.CLAMP
});
this.textInputOpacity = interpolate(this.buttonOpacity, {
inputRange: [0, 1],
outputRange: [1, 0],
extrapolate: Extrapolate.CLAMP
});
this.rotateCross = interpolate(this.buttonOpacity, {
inputRange: [0, 1],
outputRange: [180, 360],
extrapolate: Extrapolate.CLAMP
});
this.validateEmail = this.validateEmail.bind(this);
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
this.renderPasswordIcon = this.renderPasswordIcon.bind(this);
this.renderSignIn = this.renderSignIn.bind(this);
this.renderSignUp = this.renderSignUp.bind(this);
this.createNewUser = this.createNewUser.bind(this);
this.validateUser = this.validateUser.bind(this);
this.logInViaFacebook = this.logInViaFacebook.bind(this);
this.logInViaGoogle = this.logInViaGoogle.bind(this);
this.isUserEqual = this.isUserEqual.bind(this);
this.onSignIn = this.onSignIn.bind(this);
}
componentDidMount() {
}
componentWillMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this.keyboardDidShow.bind(this));
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this.keyboardDidHide.bind(this));
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
keyboardDidShow(e) {
let newSize = layout.window.height - e.endCoordinates.height
this.setState({
isKeyboardOpen: true,
visibleHeight: newSize,
logoSize: {width: 100, height: 70}
})
}
keyboardDidHide(e) {
this.setState({
isKeyboardOpen: false,
visibleHeight: layout.window.height,
logoSize: {width: Dimensions.get('window').width}
})
}
validateEmail(email) {
const expression = /(?!.*\.{2})^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([\t]*\r\n)?[\t]+)?([\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]))*(([\t]*\r\n)?[\t]+)?")@(([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;
return expression.test(String(email).toLowerCase());
}
handleEmailChange(text) {
let validation = this.validateEmail(text);
this.setState({
email: text,
emailValidationColor: validation === true ? 'green' : colors.gray02
});
}
handlePasswordChange(text) {
this.setState({ password: text });
}
handleHidePassword() {
this.setState({ hidePassword: !this.state.hidePassword });
}
renderPasswordIcon() {
if (this.state.password.length > 0) {
return(
<Animatable.View animation="flipInX">
<TouchableOpacity onPress={() => this.handleHidePassword()}>
{
this.state.hidePassword === true ?
<Feather name="eye-off" color={colors.gray02} size={20} style={styles.inputIconRight}/>
:
<Feather name="eye" color={colors.gray02} size={20} style={styles.inputIconRight}/>
}
</TouchableOpacity>
</Animatable.View>
);
} else return null;
}
renderSignIn() {
const { email, password } = this.state;
return(
<View>
<TouchableOpacity style={styles.forgotPasswordContainer}>
<Text style={styles.textForgotPassword}>Forgot Password?</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.logInViaEmail(email, password)}>
<Animated.View style={{...styles.button}}>
<Text style={{fontSize: 20, fontWeight: 'bold'}}>SIGN IN</Text>
</Animated.View>
</TouchableOpacity>
</View>
);
}
renderSignUp() {
const { email, password } = this.state;
return(
<TouchableOpacity onPress={() => this.signUpViaEmail(email, password)}>
<TapGestureHandler onHandlerStateChange={this.onCloseState}>
<Animated.View style={{...styles.button}}>
<Text style={{fontSize: 20, fontWeight: 'bold'}} >SIGN UP</Text>
</Animated.View>
</TapGestureHandler>
</TouchableOpacity>
);
}
validateUser() {
if(this.state.password.length > 0 && this.validateEmail(this.state.email)) return true
else return false
}
async createNewUser(user) {
if(this.validateUser()) {
const url = `${route}/register`;
const options = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
};
const request = new Request(url, options);
await fetch(request)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Something went wrong ...');
}
})
.then(data => {
console.log(data);
})
.catch(error => console.log(error))
} else {
Alert.alert(
'Try again',
'Incorrect email or password',
[
{text: 'OK'},
],
{ cancelable: false }
)
}
}
async loginUser(user) {
if(this.validateUser()) {
const url = `${route}/login`;
const options = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
};
const request = new Request(url, options);
await fetch(request)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Something went wrong ...');
}
})
.then(data => console.log(data.status))
.catch(error => console.log(error))
} else {
Alert.alert(
'Try again',
'Incorrect email or password',
[
{text: 'OK'},
],
{ cancelable: false }
)
}
}
signUpViaEmail = (email, password) => {
try {
if (password.length < 6) {
alert("Please enter at least 6 characters");
return;
}
firebase.auth().createUserWithEmailAndPassword(email, password);
this.setState({ signed: true });
} catch (error) {
console.log(error);
}
}
logInViaEmail = (email, password) => {
try {
if (password.length < 6) {
alert("Please enter at least 6 characters");
return;
}
firebase.auth().signInWithEmailAndPassword(email, password)
.then((result) => {
// console.log(result.user.email);
this.props.navigation.navigate('Profile');
})
} catch (error) {
console.log(error);
}
}
async logInViaFacebook() {
try {
await Facebook.initializeAsync('786955858495098');
const { type, token } = await Facebook.logInWithReadPermissionsAsync({permissions: ['public_profile', 'email']});
if (type === 'success') {
const FBcredential = firebase.auth.FacebookAuthProvider.credential(token);
firebase.auth().signInWithCredential(FBcredential)
.then(async (result) => {
// result.additionalUserInfo
// mg {
// "isNewUser": false,
// "profile": Object {
// "birthday": "11/29/1992",
// "email": "makmel.miki@gmail.com",
// "first_name": "Miki",
// "gender": "male",
// "id": "10221659860226854",
// "last_name": "Makmel",
// "name": "Miki Makmel",
// "picture": Object {
// "data": Object {
// "height": 100,
// "is_silhouette": false,
// "url": "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=10221659860226854&height=100&width=100&ext=1592054652&hash=AeSKzSG-bOMykG4Q",
// "width": 100,
// },
// },
// },
// "providerId": "facebook.com",
// }
this.props.navigation.navigate('SplashScreen', {socialLogin: true, email: result.user.email, profilePic: `${result.user.photoURL}?height=500`});
console.log("Facebook Login Success");
})
.catch((error) => { console.log(`Facebook Login Error: ${error}`) });
} else {
// type === 'cancel'
console.log("cancel");
}
} catch ({ message }) {
alert(`Facebook Login Error: ${message}`);
console.log(`Facebook Login Error: ${message}`);
}
}
isUserEqual(googleUser, firebaseUser) {
if (firebaseUser) {
var providerData = firebaseUser.providerData;
for (var i = 0; i < providerData.length; i++) {
if (providerData[i].providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
providerData[i].uid === googleUser.getBasicProfile().getId()) {
// We don't need to reauth the Firebase connection.
return true;
}
}
}
return false;
}
onSignIn(googleUser) {
// console.log('Google Auth Response', googleUser);
// We need to register an Observer on Firebase Auth to make sure auth is initialized.
var unsubscribe = firebase.auth().onAuthStateChanged(function(firebaseUser) {
unsubscribe();
// Check if we are already signed-in Firebase with the correct user.
if (!isUserEqual(googleUser, firebaseUser)) {
// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
} else {
console.log('User already signed-in Firebase.');
}
});
}
async logInViaGoogle() {
try {
const result = await Google.logInAsync({
behavior: 'web',
// androidClientId: YOUR_CLIENT_ID_HERE,
iosClientId: '1068271769932-ro1oeq9koi558n60h5v3urc6tftakj0i.apps.googleusercontent.com',
scopes: ['profile', 'email'],
});
if (result.type === 'success') {
// console.log(result.user)
this.onSignIn(result);
this.props.navigation.navigate('SplashScreen', {
shouldRefresh: false,
socialLogin: true,
email: result.user.email,
firstName: result.user.givenName,
lastName: result.user.familyName,
profilePic: `${result.user.photoUrl}?height=500`
});
console.log("Google Login Success");
return result.accessToken;
} else {
console.log("cancel");
return { cancelled: true };
}
} catch (e) {
console.log("error");
return { error: true };
}
}
render() {
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
<KeyboardAvoidingView style={{ flex: 1, justifyContent: 'flex-end'}} behavior="padding">
<View style={{ width: layout.window.width, height: layout.window.height}}>
<StatusBar barStyle="light-content" />
<View style={{flex: 1, backgroundColor: 'white', justifyContent: 'flex-end', height: this.state.visibleHeight}}>
<Animated.View style={{ ...StyleSheet.absoluteFill, transform: [{ translateY: this.bgY }]}} >
<Svg height={layout.window.height + 50} width={layout.window.width}>
<ClipPath id="clip">
<Circle r={layout.window.height + 50} cx={layout.window.width / 2} />
</ClipPath>
<Image
href={require('../assets/images/loginGradient.png')}
height={layout.window.height + 50}
width={layout.window.width}
preserveAspectRatio={'xMidYMid slice'}
clipPath="url(#clip)"
/>
<View style={styles.overlay} />
</Svg>
</Animated.View>
<Animatable.View style={{ position: 'absolute', top: layout.window.height/4, alignSelf: 'center'}} >
<Animated.Image style={{}} source={require('../assets/images/logo.png')} />
</Animatable.View>
<View style={{height: layout.window.height/3 + 40, justifyContent: 'center' }} >
<Animatable.View animation="fadeIn">
<TouchableOpacity onPress={() => this.setState({screenStatus: 'sign-in'})}>
<TapGestureHandler onHandlerStateChange={this.onStateChange}>
<Animated.View style={{...styles.button, opacity: this.buttonOpacity,
transform: [{ translateY: this.buttonY }]
}}>
<Text style={{fontSize: 16, fontWeight: '600', color: colors.green03, opacity: 0.9}}>SIGN IN</Text>
</Animated.View>
</TapGestureHandler>
</TouchableOpacity>
</Animatable.View>
<TapGestureHandler onHandlerStateChange={this.onStateChange}>
<Animated.View style={{padding: 10, justifyContent: 'center', alignItems: 'center', transform: [{ translateY: this.buttonY }] }}>
<TouchableOpacity onPress={() => this.setState({screenStatus: 'sign-up'})}>
<Text>
<Text style={{...styles.textForgotPassword, color: colors.white}} >Don't have an account?</Text>
<Text style={{...styles.textForgotPassword, color: colors.white, fontWeight: '700'}}> Sign Up Now</Text>
</Text>
</TouchableOpacity>
<Text style={{...styles.textForgotPassword, color: colors.white, fontWeight: '200', marginTop: 30}}>- OR -</Text>
</Animated.View>
</TapGestureHandler>
<Animated.View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', height: 70, transform: [{ translateY: this.buttonY }] }}>
<TouchableOpacity style={styles.socialIcon} onPress={this.logInViaFacebook}>
<Animated.Image style={{ width: 55, height: 55, transform: [{ translateY: this.buttonY }] }} source={require('../assets/images/facebook-logo.png')} />
</TouchableOpacity>
<TouchableOpacity style={styles.socialIcon} onPress={this.logInViaGoogle}>
<Animated.Image style={{ width: 55, height: 55, transform: [{ translateY: this.buttonY }] }} source={require('../assets/images/google-logo.png')} />
</TouchableOpacity>
</Animated.View>
<Animated.View style={{
height: layout.window.height/3,
...StyleSheet.absoluteFill,
top: null,
justifyContent: 'center',
zIndex: this.textInputZIndex,
opacity: this.textInputOpacity,
transform: [{translateY: this.textInputY}],
}}
>
<TapGestureHandler onHandlerStateChange={this.onCloseState}>
<Animated.View style={styles.closeButton} >
<Animated.Text style={{ fontSize: 16, fontWeight: '400', transform: [{rotate: concat(this.rotateCross, 'deg')}] }} >
X
</Animated.Text>
</Animated.View>
</TapGestureHandler>
<View style={styles.inputContainer}>
<Feather name="mail" color={colors.blue} size={24} style={styles.inputIconLeft} />
<TextInput
placeholder={'E-MAIL'}
style={styles.textInput}
placeholderTextColor={colors.gray04}
onChangeText={(text) => this.handleEmailChange(text)}
autoCompleteType="email"
keyboardType="email-address"
/>
{
this.state.email.length > 0 ?
<Animatable.View animation="flipInX">
<Feather name="check-circle" color={this.state.emailValidationColor} size={20} style={styles.inputIconRight} />
</Animatable.View>
:
null
}
</View>
<View style={styles.inputContainer}>
<Feather name="lock" color={colors.blue} size={20} style={styles.inputIconLeft} />
<TextInput
placeholder={'PASSWORD'}
style={styles.textInput}
placeholderTextColor={colors.gray04}
secureTextEntry={this.state.hidePassword}
keyboardType={Platform.OS === 'ios' ? "ascii-capable" : "visible-password"}
onChangeText={(text) => this.handlePasswordChange(text)}
/>
{this.renderPasswordIcon()}
</View>
{this.state.screenStatus === 'sign-in' ?
this.renderSignIn()
:
this.renderSignUp()
}
</Animated.View>
</View>
</View>
</View>
</KeyboardAvoidingView>
</TouchableWithoutFeedback>
);
}
}
const mapStateToProps = ({ User, Customer }) => {
return {
hasBusiness: User.hasBusiness,
currentUser: User.currentUser,
favoritesList: Customer.favoritesList
}
}
export default connect(mapStateToProps)(LoginScreen);
function runTiming(clock, value, dest) {
const state = {
finished: new Value(0),
position: new Value(0),
time: new Value(0),
frameTime: new Value(0)
};
const config = {
duration: 1000,
toValue: new Value(0),
easing: Easing.inOut(Easing.ease)
};
return block([
cond(clockRunning(clock), 0, [
set(state.finished, 0),
set(state.time, 0),
set(state.position, value),
set(state.frameTime, 0),
set(config.toValue, dest),
startClock(clock)
]),
timing(clock, state, config),
cond(state.finished, debug('stop clock', stopClock(clock))),
state.position
]);
}
|
import React, {useState, useEffect} from 'react';
import { Container, Row, Col, Form} from 'react-bootstrap'
import DataSource from '../data/mattressses'
import ProductCard from '../Components/ProductCard';
const Main = (props) =>{
const [filterObj, setFilterObj] = useState({thickness:0, priceSort:"", priceHigh:"", priceLow:"",hasLatex:false})
const [data, setData] = useState([]);
useEffect(()=>{
const filteredData = DataSource(filterObj);
setData(filteredData);
console.log(filterObj);
},[filterObj]);
const handleThicknessChange = (e)=>{
e.persist();
setFilterObj((prevState)=>{
return {...prevState, thickness:e.target.value}
})
}
const handlePriceSortChange = (e) => {
e.persist();
console.log(e.target.value)
setFilterObj((prevState)=>{
return {...prevState, priceSort:e.target.value}
})
console.log(filterObj)
}
const handlePriceHighChange = (e) => {
e.persist()
setFilterObj((prevState)=>{
return {...prevState, priceHigh:e.target.value}
})
}
const handlePriceLowChange = (e) => {
e.persist()
setFilterObj((prevState)=>{
return {...prevState, priceLow:e.target.value}
})
}
return(
<>
<div className="full-width-background">
<Container>
<Row>
<Col>
<div className="text-center">
<h1>Mattresses in Market</h1>
<p>Use the options below to sort anf filter</p>
</div>
</Col>
</Row>
<Row>
<Col>
<Form>
<Form.Row>
<Form.Group as={Col}>
<Form.Label>Filter by Thickness</Form.Label>
<Form.Control
id="thickness"
name="thickness"
value={filterObj.thickness}
onChange = {handleThicknessChange}
as="select"
type="Number"
>
<option value="0">Show all</option>
<option>6</option>
<option>8</option>
</Form.Control>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>SortBy Price</Form.Label>
<Form.Control
id="priceSort"
name="priceSort"
value={filterObj.priceSort}
onChange = {handlePriceSortChange}
as="select"
type="Number"
>
<option>select one</option>
<option>Ascending</option>
<option>Descending</option>
</Form.Control>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Price Low</Form.Label>
<Form.Control
id="priceLow"
name="priceLow"
value={filterObj.priceLow}
onChange = {handlePriceLowChange}
type="Number"
/>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Price High</Form.Label>
<Form.Control
id="priceHigh"
name="priceHigh"
value={filterObj.priceHigh}
onChange = {handlePriceHighChange}
type="Number"
/>
</Form.Group>
</Form.Row>
</Form>
</Col>
</Row>
</Container>
</div>
<Container>
<Row>
<Col>displaying {data.length} products.</Col>
</Row>
<Row>
{data.map(item =>{
return(
<ProductCard key={item.id} data={item}/>
)
})}
</Row>
</Container>
</>
)
}
export default Main
|
/*jslint white:true, this:true*/
"use strict";
var customModel = angular.module('Model', ["ngRoute",'aStatusBar'])
//var wizard = angular.module('wizard', ["ngRoute"])
.controller('CustomModels', ['$scope', function ($scope) {
// Declare a variable to store the current ProjectID
var c_projectID;
// .controller('Navigation', ['$scope', '$http', '$rootScope','$window', function ($scope, $http, $rootScope,$window) {
// declare an internal variable to store the current right value for each customer model row
var Rows = []; // Todo - Update Rows data structure to store the leftmost and rightmost value for the current row
var topBaseline = 50;
// Declare a variable to define the vertical offset between rows
var activityOffset = 25;
var waterfalTopBaseline = 50;
var leftBaseline = 50;
var workDay = 8;
var scalingFactor = 20;
var displayWidth = 875;
//Declare a variable to adjust the week bar height for the top div header and the bottom calendar div row
var weekBarAdjustment = 100;
// Declare a variable to store the hiehgt of themodel display portion of the screen
$scope.displayHeight = '950px';
// Declare a variable to indicate whether the waterfall display should be visible
$scope.waterfallVisible = true;
// Declare a variable to indicate whether the custom model display should be visible
$scope.customVisible = true;
// Declare a variable to indicate whether the concurrent display should be visible
$scope.concurrentVisible = true;
// Declare a vraiable to indicate the class for the pre-conditin input panel
$scope.preConditionBorder = "solid 0px black";
// Declare a vraiable to indicate the class for the pre-conditin input panel
$scope.postConditionBorder = "solid 0px black";
// Declare a vraiable to indicate the border settings for the staffing Panel
$scope.staffingBorder = "solid 0px black";
// Declare an object to store the staffing data
$scope.staffingDemandData = [];
// Declare an object to store the calendar data (i.e. an array of days for the staffing chart
$scope.calendarData = [];
// Declare a variable to track the total waterfall width
var totalWaterfallWidth = 0;
// Declare a local object to store the graph color array
$scope.Colors = new Array("orange", "yellowgreen", "#80C1DD", "#639e4b", "#4b9e5c", "#4b9e85", "#4b8d9e", "#4b639e", "#5c4b9e", "#854b9e", "#9e488d", "#9e4b63");
// Declare a smooting factor. This will expand the resolutin of the graph data to minimize rounding effects and yield a more continuous appearing data set
var smooth = 10;
$scope.width = '125px';
$scope.left = '50px';
$scope.top = '350px';
// Declare a variable for the post condition toggle button label
$scope.postConditionToggleButton = { Displayed: false, Name: 'Edit Postconditions', Top: 50, TopPos: '50px', Left: 1300, LeftPos: '1300px' };
// Declre a data structure for the post condition input panel
$scope.postConditionPanel = { Height: 0, HeightPos: '0px', Top: 80, TopPos: '80px' };
// Declare a variable for the pre condition toggle button label
$scope.preConditionToggleButton = { Displayed: false, Name: 'Edit Preconditions', Top: 50, TopPos: '50px', Left: 1300, LeftPos: '1300px' };
// Declre a data structure for the pre condition input panel
$scope.preConditionPanel = { Height: 0, HeightPos: '0px' };
// Declare a variable for the staffing toggle button label
$scope.staffingToggleButton = { Displayed: false, Name: 'Edit Staffing', Top: 80, TopPos: '80px', Left: 1300, LeftPos: '1300px' };
// Declre a data structure for the staffing input panel
$scope.staffingPanel = { Left: 925, LeftPos: '925px', Height: 0, HeightPos: '0px', Top: 110, TopPos: '110px' };
// Declare an array of objects to store the screen position for the model displays
$scope.displayPositions = [{ Name: 'Waterfall Display', Height: 125, Top: '25px', Visible: true },
{ Name: 'Custom Display', Height: 250, Top: '150px', Visible: true },
{ Name: 'Staffing Display', Height: 300, Top: '400px', Visible: true },
{ Name: 'Concurrent Display', Height: 250, Top: '700px', Visible: true },
{ Name: 'Calendar Display', Height: 100, Top: '950px', Visible: true }
]
// Declare an array of objects to store the screen position for the edit panels
$scope.editPanelPositions = [{ Name: 'Precondition', Height: 500, Top: '50', TopPos: '50px', Visible: false },
{ Name: 'Postcondition', Height: 500, Top: '550', TopPos: '550px', Visible: false },
{ Name: 'Staffing', Height: 350, Top: '900', TopPos: '900px', Visible: false }
]
// Declare a data structure to store the staffing information
$scope.Staff = [];
$scope.Activities = [];
$scope.Activities2 = [];
$scope.customActivityGraphics = [
{ Left: 0, LeftPos: '0px', Top: 50, TopPos: '50px', Width: '120', WidthPos: '120px', Color: 'yellowgreen', Delayed: false, BaseWidth: '0', DelayWidth: '0', BaseStaffRatio: 1, Row: 0 }, // Functional Design
{ Left: 0, LeftPos: '0px', Top: 75, TopPos: '75px', Width: '200', WidthPos: '200px', Color: 'orange', Delayed: false, BaseWidth: '0', DelayWidth: '0', BaseStaffRatio: 1, Row: 0 }, // Development
{ Left: 0, LeftPos: '0px', Top: 100, TopPos: '100px', Width: '200', WidthPos: '200px', Color: 'orange', Delayed: false, BaseWidth: '0', DelayWidth: '0', BaseStaffRatio: 1, Row: 0 }, // Validation
{ Left: 0, LeftPos: '0px', Top: 125, TopPos: '125px', Width: '60', WidthPos: '60px', Color: 'orange', Delayed: false, BaseWidth: '0', DelayWidth: '0', BaseStaffRatio: 1, Row: 0 }, // Graphical Design
{ Left: 0, LeftPos: '0px', Top: 125, TopPos: '125px', Width: '50', WidthPos: '50px', Color: 'orange', Delayed: false, BaseWidth: '0', DelayWidth: '0', BaseStaffRatio: 1, Row: 0 }, // Documentation
{ Left: 0, LeftPos: '0px', Top: 100, TopPos: '100px', Width: '80', WidthPos: '80px', Color: 'orange', Delayed: false, BaseWidth: '0', DelayWidth: '0', BaseStaffRatio: 1, Row: 0 }, // Acceptance
];
$scope.waterfallActivityGraphics = [];
$scope.concurrentActivityGraphics = [];
$scope.preConditions = [];
$scope.Postconditions = [[]];
// $scope.Postconditions = [[], [], [], [], [], []];
// Declre a data structure to store the preconditions for the current set of activities
$scope.testConditions = [{ ActivityID: 15, Name: 'Functional Design', DependentID: 12, CompletionPercentage: 75 },
{ ActivityID: 17, Name: 'Functional Design', DependentID: 12, CompletionPercentage: 75 },
{ ActivityID: 17, Name: 'Development', DependentID: 15, CompletionPercentage: 25 },
{ ActivityID: 14, Name: 'Functional Design', DependentID: 12, CompletionPercentage: 50 },
{ ActivityID: 18, Name: 'Functional Design', DependentID: 12, CompletionPercentage: 100 },
{ ActivityID: 18, Name: 'Development', DependentID: 15, CompletionPercentage: 100 },
{ ActivityID: 22, Name: 'Documentation', DependentID: 18, CompletionPercentage: 100 }];
// $scope.testConditions2 = [];
$scope.newRecord = [];
$scope.newPostCondition = [];
// $scope.ActivityList = [{ ID: 0, Name: 'Functional Design' },
// { ID: 1, Name: 'Development' },
// { ID: 2, Name: ' Validation' },
// { ID: 3, Name: 'Graphical Design' },
// { ID: 4, Name: 'Documentation' },
// { ID: 5, Name: 'Acceptance' }];
$scope.Calendar = [{ ID: 1, Left: 50, LeftPos: '50px', Width: 50, WidthPos: '50px', Top: 50, TopPos: '50px' },
{ ID: 2, Left: 101, LeftPos: '101px', Width: 50, WidthPos: '50px', Top: 50, TopPos: '50px' },
{ ID: 3, Left: 152, LeftPos: '152px', Width: 50, WidthPos: '50px', Top: 50, TopPos: '50px' },
{ ID: 4, Left: 203, LeftPos: '203px', Width: 50, WidthPos: '50px', Top: 50, TopPos: '50px' }]
$scope.updateConditionHandler = function (activityIndex, index) {
var dummy = "text";
// Update the CompletionPercentage for the current precondition
updateCondition(c_projectID, $scope.preConditions[activityIndex][index], 1)
}
$scope.updatePostConditionHandler = function (activityIndex, index) {
var dummy = "text";
// Update the CompletionPercentage for the current precondition
updateCondition(c_projectID, $scope.Postconditions[activityIndex][index], 2)
}
var updateCondition = function (projectID, item, conditionType) {
// Declare a Deferred construct to return from this method
var promise;
var targetUrl;
// Declare a resonse structure to return from this object
var response = new Response();
var condition = new Object();
condition.ProjectID = projectID;
condition.ActivityID = item.ActivityID;
condition.Name = item.Name;
condition.DependencyID = item.DependentID;
condition.CompletionPercentage = item.CompletionPercentage;
condition.ConditionTypeID = conditionType;
var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
headers.Authorization = 'Bearer ' + token;
}
targetUrl = ConditionUrl + '?projectID=' + c_projectID;
promise = $.ajax({
url: targetUrl,
type: 'PUT',
dataType: 'json',
data: condition,
headers: headers,
success: function (data, txtStatus, xhr) {
},
error: function (xhr, textStatus, errorThrown) {
response.Status = xhr.status;
errorHandler(response, 901);
}
});
return (promise);
}
// Declare a function to initialize the activity and staffing data
$scope.InitializeRefferenceData = function () {
var ProjectSummaryUrl = "/api/ProjectSummary";
var targetUrl;
// declre an array to store staffing data
var c_staffing = [];
// var projectID;
var orgID;
var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
headers.Authorization = 'Bearer ' + token;
}
// Get the current project ID
c_projectID = getCookieProjectID();
// Get the current Org ID from the cookie
orgID = getCookieOrgID();
// Initialize the web service address
targetUrl = ProjectSummaryUrl + "?ProjectID=" + c_projectID + "&OrgID=" + orgID
// Declare a Deferred construct to return from this method
var activityResponse = new Response();
// Call the target web service
activityResponse.Promise = $.ajax({
url: targetUrl,
type: 'GET',
dataType: 'json',
}).done(function (data, txtStatus, jqXHR) {
renderActivityData(data);
}).fail(function (xhr, textStatus, errorThrown) {
alert("Insert Error");
});
// Declare a Deferred construct to return from this method
var staffingResponse = new Response();
// Initilaize the target URL for the next web service all
targetUrl = StaffUrl + "/" + c_projectID;
staffingResponse.Promise = $.ajax({
url: targetUrl,
type: 'GET',
dataType: 'json',
headers: headers,
}).done(function (data, txtStatus, jqXHR) {
// alert("Insert Success");
renderStaffingData(data);
}).fail(function (xhr, textStatus, errorThrown) {
errorHandler(xhr, 1303);
});
activityResponse.Promise.done(function () {
// Load the condition data once the activity data is populated
// Declare a Deferred construct to return from this method
var conditionResponse = new Response();
// Initilaize the target URL for the next web service all
targetUrl = ConditionUrl + "?ProjectID=" + c_projectID;
conditionResponse.Promise = $.ajax({
url: targetUrl,
type: 'GET',
dataType: 'json',
headers: headers,
}).done(function (data, txtStatus, jqXHR) {
// alert("Insert Success");
renderConditionData(data);
}).fail(function (xhr, textStatus, errorThrown) {
errorHandler(xhr, 1303);
});
staffingResponse.Promise.done(function () {
conditionResponse.Promise.done(function () {
mergeSetupData();
});
});
});
};
var renderConditionData = function (data) {
var index = 0;
// declare a local object to store the activity index
var activityIndex = -1;
var dummy = 'text';
$scope.testConditions.length = 0;
// $scope.Postconditions.length = 0;
// loop over the data and copy the pre-conditions into the Test Conditionss collection
while (index < data.length) {
{
// Create a new condition object
var condition = new Object();
condition.ActivityID = data[index].ActivityID;
condition.Name = data[index].DependencyName;
condition.DependentID = data[index].DependencyID;
condition.CompletionPercentage = data[index].CompletionPercentage;
// get the Activity index for the current activity and make sure the Postcondition array is initialized
activityIndex = getActivityIndex(condition.ActivityID);
// filter for preconditions
if (data[index].ConditionTypeID == 1) {
$scope.testConditions.push(condition);
}
else {
// Load the post condition data
if (activityIndex >= 0) {
$scope.Postconditions[activityIndex].push(condition);
}
}
index++;
}
}
}
var renderActivityData = function (data) {
var index = 0;
var dummy = "text";
// reset the ACtivities collection
$scope.Activities.length = 0;
// reset the post condition collection
$scope.Postconditions.lenght = 0;
// Loop over the returned data set
while (index < data.ActivitySummary.length) {
var newActivity = {};
// filter inactive records
newActivity.ID = data.ActivitySummary[index].ActivityID; //ActivityID
newActivity.Name = data.ActivitySummary[index].ActivityName;
newActivity.Effort = data.ActivitySummary[index].effort;
newActivity.MasterRoleID = data.ActivitySummary[index].MasterRoleID;
// Temporarily assign a fixed value to overhead
newActivity.Overhead = .25;
$scope.Activities.push(newActivity);
// initialize the post condition data structure
$scope.Postconditions[index] = [];
index++;
}
};
var renderStaffingData = function (data) {
var index = 0;
var dummy = "text";
// reset the staffing data
$scope.Staff.length = 0;
// loop over the staffing data
while (index < data.length) {
var newStaff = {};
newStaff.MasterRoleID = data[index].MasterRoleID;
newStaff.RoleName = data[index].RoleName;
newStaff.Count = data[index].Count;
$scope.Staff.push(newStaff);
index++;
}
}
var mergeSetupData = function () {
var index = 0;
var index2;
var dummy = "text";
// Loop over the activities and merge the data
while (index < $scope.Activities.length) {
// Get the staffing record for the current role
index2 = 0;
while (index2 < $scope.Staff.length) {
if ($scope.Activities[index].MasterRoleID == $scope.Staff[index2].MasterRoleID) {
$scope.Activities[index].StaffCount = $scope.Staff[index2].Count;
$scope.Activities[index].RoleName = $scope.Staff[index2].RoleName;
break;
}
index2++;
}
index++;
}
$scope.refreshScreen();
}
$scope.InitializeRefferenceData();
// declare a function to toggle visibility of the waterfall display
$scope.toggleWaterfall = function () {
var control = document.getElementById("waterfallArray");
if ($scope.waterfallVisible) {
$scope.waterfallVisible = false;
control.src = "../images/down arrow.png";
$scope.displayPositions[0].Visible = false;
}
else {
$scope.waterfallVisible = true;
control.src = "../images/up arrow.png";
$scope.displayPositions[0].Visible = true;
}
updatePositions();
}
// Declare a function to update the display position data based on which displays are visible
var updatePositions = function () {
var index = 0;
var currentTop = 25;
while (index < $scope.displayPositions.length) {
$scope.displayPositions[index].Top = currentTop + 'px';
if ($scope.displayPositions[index].Visible) {
currentTop += $scope.displayPositions[index].Height;
}
else {
// Don't add a div allowance for the Staffing display
if (index != 2) {
currentTop += 30;
}
}
index++;
}
$scope.displayHeight = currentTop - weekBarAdjustment;
}
// Declare a function to update the display position data based on which displays are visible
$scope.updateEditPanelPositions = function () {
var index = 0;
var currentTop = 60;
while (index < $scope.editPanelPositions.length) {
$scope.editPanelPositions[index].Top = currentTop;
$scope.editPanelPositions[index].TopPos = currentTop + 'px';
if ($scope.editPanelPositions[index].Visible) {
currentTop += $scope.editPanelPositions[index].Height + 35;
}
else {
currentTop += 30;
}
// UPdate the toggle button also
switch (index) {
case 0:
$scope.preConditionToggleButton.Top = $scope.editPanelPositions[index].Top - 35;
$scope.preConditionToggleButton.TopPos = $scope.preConditionToggleButton.Top + 'px';
break;
case 1:
$scope.postConditionToggleButton.Top = $scope.editPanelPositions[index].Top - 40;
$scope.postConditionToggleButton.TopPos = $scope.postConditionToggleButton.Top + 'px';
break;
case 2:
$scope.staffingToggleButton.Top = $scope.editPanelPositions[index].Top - 35;
$scope.staffingToggleButton.TopPos = $scope.staffingToggleButton.Top + 'px';
break;
}
index++;
}
// $scope.displayHeight = currentTop - weekBarAdjustment;
}
// declare a function to toggle visibility of the waterfall display
$scope.toggleCustom = function () {
var control = document.getElementById("customVisibleArrow");
if ($scope.customVisible) {
$scope.customVisible = false;
control.src = "../images/down arrow.png";
$scope.displayPositions[1].Visible = false;
$scope.displayPositions[2].Visible = false;
}
else {
$scope.customVisible = true;
control.src = "../images/up arrow.png";
$scope.displayPositions[1].Visible = true;
$scope.displayPositions[2].Visible = true;
}
updatePositions();
}
// declare a function to toggle visibility of the concurrent display
$scope.toggleConcurrent = function () {
var control = document.getElementById("concurrentVisibleArrow");
if ($scope.concurrentVisible) {
$scope.concurrentVisible = false;
control.src = "../images/down arrow.png";
$scope.displayPositions[3].Visible = false;
}
else {
$scope.concurrentVisible = true;
control.src = "../images/up arrow.png";
$scope.displayPositions[3].Visible = true;
}
updatePositions();
}
// Declare a function to remove the specified dependency from the preconditions collection
$scope.deleteDependency = function (activityID, dependencyIndex) {
var index;
// Find the test Condition record corresponding to the supplied Activy and Dependency index
index = getActivityIndex(activityID);
if (index != undefined) {
var DependencyID = $scope.preConditions[index][dependencyIndex].DependentID;
removeCondition(activityID, DependencyID);
$scope.refreshScreen();
}
}
// Declare a function to remove the specified post condition from the post condition collection
$scope.deletePostCondition = function (activityID, dependencyIndex) {
var index;
// Find the test Condition record corresponding to the supplied Activy and Dependency index
index = getActivityIndex(activityID);
if (index != undefined) {
// Get the dependency ID for the current record
var DependencyID = $scope.Postconditions[index][dependencyIndex].DependentID;
$scope.Postconditions[index].splice(dependencyIndex, 1);
// remove the selected condition from the DB
deleteCondition(c_projectID, activityID, DependencyID, 2)
// removePostCondition(activityID, DependencyID);
$scope.refreshScreen();
}
}
var getActivityIndex = function (ID) {
var index = 0;
var result = undefined;
//loop over the Activities collection and return he index of the corresponding ID
while (index < $scope.Activities.length) {
if ($scope.Activities[index].ID == ID) {
result = index;
break;
}
index++;
}
return (result);
}
var removePostCondition = function (activityID, dependencyID) {
var index = 0;
var index2 = 0;
while (index < $scope.Postconditions.length) {
if ($scope.Postconditions[index].ActivityID == activityID) {
// Check for matching dependency record now
// loop over the number of dependency records
while (index2 < $scope.Postconditions[index].length) {
if ($scope.Postconditions[index][index2].DependentID = dependencyID) {
$scope.Postconditions[index].splice(index2, 1);
}
index2++;
}
}
index++;
}
}
var removeCondition = function (activityID, dependencyID) {
var index = 0;
while (index < $scope.testConditions.length) {
if ($scope.testConditions[index].ActivityID == activityID && $scope.testConditions[index].DependentID == dependencyID) {
$scope.testConditions.splice(index, 1);
}
index++;
}
// remove the selected condition from the DB
deleteCondition(c_projectID, activityID, dependencyID,1)
}
// Declare a function to add a newly defined pre-coondition on the specified activity
$scope.addDependency = function (index) {
// declare a locla object to store teh preconditions for the current activity
var preconditions = [];
var status = true;
// validate the input range for the Compoletion Percentage
if ($scope.newRecord[index].CompletionPercentage < 0) {
alert("The entered value for Completion Percentage is less than the allowed minimum (0). No record will be saved.");
status = false;
$scope.newRecord[index].CompletionPercentage = 0;
}
else if ($scope.newRecord[index].CompletionPercentage > 100) {
alert("The entered value for Completion Percentage is greater than the allowed maximum (1). No record will be saved.");
status = false;
$scope.newRecord[index].CompletionPercentage = 100;
}
// Make sure that the user does not add a dependency on itself
if ($scope.newRecord[index].Dependency.ID == $scope.Activities[index].ID) {
alert("You cannot create a dependency between an activity and itself. No record will be saved.");
status = false;
}
// Make sure no dependent activity is included twice
preconditions = $scope.testConditions.filter(filterConditions, $scope.Activities[index].ID);
// Loop over the preconditions and make sure the supplied dependentID is not already present
var condIndex = 0;
while (condIndex < preconditions.length) {
if (preconditions[condIndex].DependentID == $scope.newRecord[index].Dependency.ID) {
alert("The entered dependency already exists for this activity. No record will be saved.");
$scope.newRecord[index] = undefined;
status = false;
break;
}
condIndex++;
}
if (status) {
// check for circular dependencies
status = checkDependency($scope.Activities[index].ID, $scope.Activities[index].ID, $scope.newRecord[index].Dependency.ID);
if (!status) {
alert("The requested dependency would create a circular dependency. No record will be saved.");
$scope.newRecord[index] = undefined;
}
}
// If there are no data issues with the current selection apply the change
if (status) {
var newDependency = { ActivityID: $scope.Activities[index].ID, Name: $scope.newRecord[index].Dependency.Name, DependentID: $scope.newRecord[index].Dependency.ID, CompletionPercentage: $scope.newRecord[index].CompletionPercentage };
$scope.testConditions.push(newDependency);
// Write the new record to the database
saveNewCondition(newDependency, 1);
$scope.newRecord[index] = undefined;
var index1 = 0;
$scope.refreshScreen();
}
}
// Declre a method to save a new condition to the database
var saveNewCondition = function (item, conditionType) {
// Declare a Deferred construct to return from this method
var promise;
var targetUrl;
// Declare a resonse structure to return from this object
var response = new Response();
var condition = new Object();
condition.ProjectID = c_projectID;
condition.ActivityID = item.ActivityID;
condition.Name = item.Name;
condition.DependencyID = item.DependentID;
condition.CompletionPercentage = item.CompletionPercentage;
condition.ConditionTypeID = conditionType;
var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
headers.Authorization = 'Bearer ' + token;
}
targetUrl = ConditionUrl;
promise = $.ajax({
url: targetUrl,
type: 'POST',
dataType: 'json',
data: condition,
headers: headers,
success: function (data, txtStatus, xhr) {
},
error: function (xhr, textStatus, errorThrown) {
response.Sttus = xhr.status;
errorHandler(resposne, 901);
}
});
return (promise);
}
// Declre a method to save a new condition to the database
var deleteCondition = function (projectID,ActivityID,DependencyID, conditionType) {
// Declare a Deferred construct to return from this method
var promise;
var targetUrl;
// Declare a resonse structure to return from this object
var response = new Response();
var condition = new Object();
condition.ProjectID = projectID;
condition.ActivityID = ActivityID;
condition.DependencyID = DependencyID;
condition.ConditionTypeID = conditionType;
var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
headers.Authorization = 'Bearer ' + token;
}
targetUrl = ConditionUrl +'?projectID=' + projectID;
promise = $.ajax({
url: targetUrl,
type: 'DELETE',
dataType: 'json',
data: condition,
headers: headers,
success: function (data, txtStatus, xhr) {
},
error: function (xhr, textStatus, errorThrown) {
response.Status = xhr.status;
errorHandler(response, 901);
}
});
return (promise);
}
var errorHandler = function (response, value) {
alert("error encountered: " + response.Status);
}
// Declare a function to check for circular dependencies in the preconditions
var checkDependency = function (rootID, activityID, dependencyID) {
// declare a locla object to store teh preconditions for the current activity
var preconditions = [];
// Declare a variable to use looping over depdencies
var index = 0;
var status = true;
// Get the set of dependencies for the current activity
preconditions = $scope.testConditions.filter(filterConditions, dependencyID);
// loop over the dependencies
while (index < preconditions.length) {
// Check to see if the current depenency is a reference to the original activity
if (preconditions[index].DependentID == activityID) {
status = false;
break;
}
else if (preconditions[index].DependentID == rootID) {
status = false;
break;
}
else {
// check dependencies for the remaining dependencies and make sure they don't eventually reference back to this activity
status = checkDependency(rootID, rootID, preconditions[index].DependentID);
if (!status) {
// a circular dependency was found
break;
}
}
index++;
}
return (status);
}
// Declare a function to add a newly defined post-coondition on the specified activity
$scope.addPostCondition = function (index) {
var status = true;
// declare a local array to use for postconditions
var postconditions = [];
// validate the input range for the Compoletion Percentage
if ($scope.newPostCondition[index].CompletionPercentage < 0) {
alert("The entered value for Completion Percentage is less than the allowed minimum (0). No record will be saved.");
status = false;
$scope.newPostCondition[index].CompletionPercentage = 0;
}
else if ($scope.newPostCondition[index].CompletionPercentage > 100) {
alert("The entered value for Completion Percentage is greater than the allowed maximum (1). No record will be saved.");
status = false;
$scope.newPostCondition[index].CompletionPercentage = 100;
}
// Make sure that the user does not add a dependency on itself
if ($scope.newPostCondition[index].Dependency.ID == $scope.Activities[index].ID) {
alert("You cannot create a dependency between an activity and itself. No record will be saved.");
status = false;
}
// Make sure no dependent activity is included twice
if (!status) {
postconditions = getPostConditionsByActivity($scope.Activities[index].ID);
// Loop over the preconditions and make sure the supplied dependentID is not already present
var condIndex = 0;
while (condIndex < postconditions.length) {
if (postconditions[condIndex].DependentID == $scope.newPostCondition[index].Dependency.ID) {
alert("The entered dependency already exists for this activity. No record will be saved.");
$scope.newPostCondition[index] = undefined;
status = false;
break;
}
condIndex++;
}
}
// check for circular dependencies
if (!status) {
status = checkPostConditionDependency($scope.Activities[index].ID, $scope.Activities[index].ID, $scope.newPostCondition[index].Dependency.ID);
if (!status) {
alert("The requested dependency would create a circular dependency. No record will be saved.");
$scope.newPostCondition[index] = undefined;
}
}
// If there are not data issues with the current selection apply the change
if (status) {
var newDependency = { ActivityID: $scope.Activities[index].ID, Name: $scope.newPostCondition[index].Dependency.Name, DependentID: $scope.newPostCondition[index].Dependency.ID, CompletionPercentage: $scope.newPostCondition[index].CompletionPercentage };
$scope.Postconditions[index].push(newDependency)
// $scope.testConditions.push(newDependency);
saveNewCondition(newDependency, 2);
$scope.newPostCondition[index] = undefined;
var index1 = 0;
$scope.refreshScreen();
}
}
// Declare a function to check for circular dependencies in the post conditions
var checkPostConditionDependency = function (rootID, activityID, dependencyID) {
// declare a locla object to store teh preconditions for the current activity
var postconditions = [];
// Declare a variable to use looping over depdencies
var index = 0;
var status = true;
// Get the set of dependencies for the current activity
postconditions = getPostConditionsByActivity(dependencyID);
// loop over the dependencies
while (index < postconditions.length) {
// Check to see if the current depenency is a reference to the original activity
if (postconditions[index].DependentID == activityID) {
status = false;
break;
}
else if (postconditions[index].DependentID == rootID) {
status = false;
break;
}
else {
// check dependencies for the remaining dependencies and make sure they don't eventually reference back to this activity
status = checkDependency(rootID, rootID, postconditions[index].DependentID);
if (!status) {
// a circular dependency was found
break;
}
}
index++;
}
return (status);
}
$scope.updatePage = function () {
$scope.topBaseline = 250;
$scope.refreshScreen();
}
// Declare a function to refresh the screen content to include all data changes
$scope.refreshScreen = function () {
var index = 0;
$scope.Activities2.length = 0;
$scope.sortDependency();
// Sort the post conditions to match the Activities
$scope.sortPostConditions();
// render teh waterfall view
$scope.renderWaterfallModel();
$scope.renderConcurrentModel();
$scope.refreshCalendar();
// Initialize the row settings to 0 for all records
Rows.length = 0;
while (index < $scope.customActivityGraphics.length) {
$scope.customActivityGraphics[index].Row = 0;
// initialize the left position
$scope.customActivityGraphics[index].Left = leftBaseline;
$scope.customActivityGraphics[index].LeftPos = leftBaseline + 'px';
index++;
}
// reset the customActivityGraphics collection
$scope.customActivityGraphics.length = 0;
index = 0;
// loop over the number of defined activiities
while (index < $scope.Activities.length) {
$scope.getLeft(index);
$scope.getWidth(index, $scope.Activities[index].ID);
index++;
}
index = 0;
// loop over the number of defined activities
while (index < $scope.Activities.length) {
$scope.getTop(index);
index++;
}
$scope.renderStaffingGraph();
$scope.updateEditPanelPositions();
$scope.$apply();
};
// Declare a function that will regenerate the staffing demand collection based on the current work distribution
var refreshstaffingDemandData = function () {
var index = 0;
// declare a variable to track the start date for the current activity
var startDate;
// Declare a variable to track the impacted staffing level
var deratedStaffing = 0;
// Declare a variable to track the date when an activity is unblocked
var unblockedDate;
// Declare a variable to track the base duration of the current activity. This is the part unaffected by any post conditions
var baseDuration;
// Declare a variable to track the delayed duration due to any post conditions
var delayDuration;
var days = 0;
// declare an array to store the activity specific data
var activityCalendar = [];
// Declare a local variable to hold the index specific staff count
var staff;
// loop over the current activities
while (index < $scope.Activities.length) {
// calculate the start date in days after project kickoff
startDate = (($scope.customActivityGraphics[index].Left - leftBaseline) / scalingFactor) * smooth;
startDate = Math.round(startDate);
// calculate the activity duration
if ($scope.customActivityGraphics[index].Delayed) {
baseDuration = ($scope.customActivityGraphics[index].BaseWidth / scalingFactor) * smooth;
baseDuration = Math.round(baseDuration);
delayDuration = ($scope.customActivityGraphics[index].DelayWidth / scalingFactor) * smooth;
delayDuration = Math.round(delayDuration);
}
else {
baseDuration = ($scope.customActivityGraphics[index].Width / scalingFactor) * smooth;
baseDuration = Math.round(baseDuration);
}
// Build the array
activityCalendar.length = 0;
days = 0;
// Get the staff count for the current activity
staff = $scope.Staff[getStaffCount($scope.Activities[index].MasterRoleID)].Count;
// Loop over the days in the calendar
while (days < totalWaterfallWidth * smooth) {
// build the x-axis data array on the first iteration
if (index == 0) {
$scope.calendarData.push(days);
}
// check to see if this activity was delayed by a post condition
if ($scope.customActivityGraphics[index].Delayed) {
if (days < startDate) {
activityCalendar.push(0);
}
else if (days >= startDate && days <= startDate + baseDuration) {
activityCalendar.push(staff * $scope.customActivityGraphics[index].BaseStaffRatio);
}
else if (days >= startDate + baseDuration && days <= startDate + baseDuration + delayDuration) {
activityCalendar.push(staff);
}
else {
activityCalendar.push(0);
}
}
else {
if (days < startDate) {
activityCalendar.push(0);
}
else if (days >= startDate && days <= startDate + baseDuration) {
activityCalendar.push(staff);
}
else {
activityCalendar.push(0);
}
}
days++;
}
$scope.staffingDemandData[index] = [];
$scope.staffingDemandData[index] = activityCalendar.slice();
index++;
}
}
$scope.renderStaffingGraph = function () {
var canvas;
var index = 0;
refreshstaffingDemandData();
canvas = document.getElementById("lineChartCanvas");
var chart = new StaffingChart(canvas, 0, 0, 890, 300, scalingFactor / 10);
// initialize the axis data
chart.AxisData = $scope.calendarData;
index = 0;
// loop over activities and add teh activity data
while (index < $scope.Activities.length) {
chart.AddData($scope.staffingDemandData[index]);
index++;
}
// Draw teh current data on the chart
chart.Draw();
};
// Declare a function to sort the PostConditions in the same activity order as the Activities
$scope.sortPostConditions = function () {
// Declare a local array to store the sorted post conditions
var sortedPostConditions = [];
var tempArray = [];
// Declare an index to loop over activities
var index = 0;
while (index < $scope.Activities.length) {
sortedPostConditions[index] = [];
tempArray.length = 0;
tempArray = getPostConditionsByActivity($scope.Activities[index].ID);
if (tempArray.length > 0) {
sortedPostConditions[index] = tempArray.slice();
}
index++;
}
// reassign the temp array to the Pastconditions array
$scope.Postconditions.length = 0;
$scope.Postconditions = sortedPostConditions.slice();
}
// Declare a function to return the post conditions corresonding to the passed in activity ID
var getPostConditionsByActivity = function (activityID) {
var index = 0;
var condIndex;
var results = [];
// loop over activiites
while (index < $scope.Postconditions.length) {
// Loop over conditions
condIndex = 0;
while (condIndex < $scope.Postconditions[index].length) {
if ($scope.Postconditions[index][condIndex].ActivityID == activityID) {
results.push($scope.Postconditions[index][condIndex]);
}
condIndex++;
}
index++;
}
return (results);
}
// Declare a function to find any dependencies on the current activity
$scope.findDependencies = function (ActivityID) {
var index1 = 0;
var index2;
var result = new Array();
// Loop over the test conditions
while (index1 < $scope.testConditions.length) {
//Check to see if the passed in record is dependent on the current activity
if ($scope.testConditions[index1].ActivityID == ActivityID) {
result.push($scope.testConditions[index1]);
}
// }
index1++;
}
return (result)
}
// Declare a function to sort activities based on dependency sequence
$scope.sortDependency = function () {
var index1 = 0;
var index2;
var index3;
var copy = false;
var dependencies;
var results;
// Loop over the Activities
while (index1 < $scope.Activities.length) {
// Get the list of activities this activity is depenend on
results = $scope.findDependencies($scope.Activities[index1].ID);
if (results.length == 0) {
// Add the current activity to the new collection
$scope.Activities2.push($scope.Activities[index1]);
index1++;
continue;
}
else {
// Loop over the activities in the results collection
index2 = 0;
while (index2 < results.length) {
// Check the current activity and see if it is included in the results list. If it is then add this
// activity new activity list
// Loop over the remaining activities and see if the the current dependency is later in the collection
index3 = index1;
while (index3 < $scope.Activities.length) {
if (results[index2].DependentID == $scope.Activities[index3].ID) {
$scope.activityPush($scope.Activities[index3]);
break;
}
index3++
}
index2++;
}
// Add the current activity to the resorted collection TODO - This needs to be modified to use the activiytPush method to avoid duplicates
$scope.activityPush($scope.Activities[index1]);
// $scope.Activities2.push($scope.Activities[index1]);
}
index1++;
}
$scope.Activities = $scope.Activities2.slice();
// Generate the pre conditions array for the ng-repeat option
index1 = 0;
// reset the preconditions
$scope.preConditions.length = 0;
while (index1 < $scope.Activities.length) {
$scope.preConditions[index1] = $scope.testConditions.filter(filterConditions, $scope.Activities[index1].ID)
index1++;
}
}
// Declare a function to filter preconditions based on the current activityID
var filterConditions = function (value, index, data) {
// var index = 0;
return data[index].ActivityID == this;
}
/// Declare a function to insert an activity record into the final record set. This function prevents duplicates
$scope.activityPush = function (activity, index) {
var index1 = 0;
var found = false;
var newValue;
var oldValue;
// Loop over the current records and make sure this one is not already there
while (index1 < $scope.Activities2.length) {
if ($scope.Activities2[index1].ID == activity.ID) {
found = true;
}
index1++;
}
// Only insert the new record if it is not already there
if (!found) {
newValue = activity;
// reset index1 for the insert operation
if (index != undefined) {
index1 = index;
while (index1 <= $scope.Activities2.length) {
// if(newValue != undefined)
oldValue = $scope.Activities2[index1];
$scope.Activities2[index1] = newValue;
newValue = oldValue;
index1++;
}
}
else {
$scope.Activities2.push(newValue);
}
}
}
// Update to reflect the modified testConditions structure
$scope.getLeft = function (index) {
var maxLeft = 0;
var counter = 0;
var left = 0;
var currentDependencyID;
var prevWidth = 0;
var refActivity = undefined;
// Declare a local object to store the new ActivityGraphic
var newGraphic;
// Initialize the new graphic record
newGraphic = { ActivityID: $scope.Activities[index].ID, Left: leftBaseline, LeftPos: leftBaseline + 'px', Top: topBaseline, TopPos: topBaseline + 'px', Width: 0, Color: 'yellowgreen', Delayed: false, Row: 0 };
// loop over the preconditions and check those applicable to the current object
while (counter < $scope.testConditions.length) {
// check to see if the current condition applies to the current activity
if ($scope.testConditions[counter].ActivityID == $scope.Activities[index].ID) {
currentDependencyID = $scope.testConditions[counter].DependentID;
refActivity = getActivityGraphic(currentDependencyID);
if (refActivity != undefined) {
prevWidth = refActivity.Width
left = refActivity.Left +
prevWidth * ($scope.testConditions[counter].CompletionPercentage / 100) + 1;
if (left > maxLeft) {
newGraphic.Left = left;
newGraphic.LeftPos = left + 'px';
maxLeft = left;
}
}
}
counter++;
}
$scope.customActivityGraphics.push(newGraphic);
// return ($scope.customActivityGraphics[index].Left + 'px');
}
var getActivityGraphic = function (ID) {
var index = 0;
var result = undefined;
// Loop over the Activity graphics and return the record that matches the current ID
while (index < $scope.customActivityGraphics.length) {
if ($scope.customActivityGraphics[index].ActivityID == ID) {
result = $scope.customActivityGraphics[index];
break;
}
index++;
}
return (result);
}
var getStaffCount = function (masterRoleID) {
var index = 0;
var selectedIndex = -1;
while (index < $scope.Staff.length) {
if ($scope.Staff[index].MasterRoleID == masterRoleID) {
selectedIndex = index;
break;
}
index++;
}
return (selectedIndex);
}
$scope.getWidth = function (index, currentID) {
var counter = 0;
var width;
// declare a variable to store the dependent ID
var dependentID;
var right = 0;
var maxRight = 0;
var refActivity;
// declare a variable to store the base width of the overlapping activity region
var baseWidth;
// declare a variable to store the delay offset due to a ost condition
var delayOffset = 0;
// Declare a variable to store teh derated staff count for the overlapping portion of delayed activities
var staffRatio = 0;
//declare an object to store the post conditions for the current activity
var postConditions = [];
var staff;
// Get the staff count for the current activity
staff = $scope.Staff[getStaffCount($scope.Activities[index].MasterRoleID)].Count;
// Calculate the activity width based on the total effort and the current staffing count
width = ($scope.Activities[index].Effort / ((1 - $scope.Activities[index].Overhead) * staff * workDay)) * scalingFactor;
// get the post conditions for the current activity
postConditions = $scope.Postconditions[index];
// loop over the applicable post conditions
var condIndex = 0;
$scope.customActivityGraphics[index].Delayed = false;;
while (condIndex < postConditions.length) {
// Check to see if this condition would length the task duration
// Calculate the target end date
refActivity = getActivityGraphic(postConditions[condIndex].DependentID);
// delayOffset = width * (postConditions[condIndex].CompletionPercentage / 100);
right = refActivity.Left + refActivity.Width + width * (postConditions[condIndex].CompletionPercentage / 100);
if (right > $scope.customActivityGraphics[index].Left + width) {
if (right > maxRight) {
maxRight = right;
delayOffset = right - (refActivity.Left + refActivity.Width);
// delayOffset = right - ($scope.customActivityGraphics[index].Left + width);
baseWidth = (refActivity.Left + refActivity.Width) - $scope.customActivityGraphics[index].Left;
staffRatio = (width / baseWidth) * (1 - postConditions[condIndex].CompletionPercentage / 100);
// staffRatio = (1 - delayOffset / baseWidth);
// baseWidth = width;
width = right - $scope.customActivityGraphics[index].Left;
// set the delayed flag to indicate that resource are probably underutilized for this activity
$scope.customActivityGraphics[index].Delayed = true;
$scope.customActivityGraphics[index].BaseWidth = baseWidth;
$scope.customActivityGraphics[index].DelayWidth = delayOffset;
$scope.customActivityGraphics[index].BaseStaffRatio = staffRatio;
}
else {
$scope.customActivityGraphics[index].Delayed = false;;
}
}
condIndex++;
}
// Assign this activity to a row
// Check to see if the rows array is empty
if (Rows.length == 0) {
Rows.push($scope.customActivityGraphics[index].Left + width);
$scope.customActivityGraphics[index].Row = 0;
}
else {
// Loop over the current rows and find the first one which will hold this activity
var rowCounter = 0;
var rowFound = false;
while (rowCounter < Rows.length) {
if ($scope.customActivityGraphics[index].Left > Rows[rowCounter]) { // Todo - Update to check to see if the current activity will fit to he left in this row
Rows[rowCounter] = $scope.customActivityGraphics[index].Left + width;
$scope.customActivityGraphics[index].Row = rowCounter;
rowFound = true;
break;
}
rowCounter++;
}
// Check to see if a row was found
if (!rowFound) {
Rows.push($scope.customActivityGraphics[index].Left + width);
$scope.customActivityGraphics[index].Row = Rows.length - 1;
}
}
$scope.customActivityGraphics[index].Width = width;
$scope.customActivityGraphics[index].WidthPos = width + 'px';
// return ($scope.customActivityGraphics[index].Width + 'px');
}
// Declare a function to calculate the top position of the current activity
$scope.getTop = function (index) {
$scope.customActivityGraphics[index].Top = (($scope.customActivityGraphics[index].Row * 25) + topBaseline + 1);
$scope.customActivityGraphics[index].TopPos = (($scope.customActivityGraphics[index].Row * 25) + topBaseline + 1) + 'px';
}
// $scope.getDelayedStatus = function (index) {
// return ($scope.customActivityGraphics[index].Delayed);
// }
// Declare a function to render the waterfall view of the current activities
$scope.renderWaterfallModel = function () {
// Declare a variable to iterate over Activiites
var index = 0;
var width = 0;
// Declare a local object to store the new ActivityGraphic
var newGraphic;
// Declrae a local variable to hold the current staff count
var staff;
totalWaterfallWidth = 0;
$scope.waterfallActivityGraphics.length = 0;
// loop over the activities
while (index < $scope.Activities.length) {
// Initialize the new graphic record
newGraphic = { ActivityID: $scope.Activities[index].ID, Left: 0, LeftPos: 0 + 'px', Top: waterfalTopBaseline, TopPos: waterfalTopBaseline + 'px', Width: 0 };
// calculate the left position of the current graphic
if (index == 0) {
newGraphic.Left = leftBaseline;
newGraphic.LeftPos = leftBaseline + 'px';
}
else {
newGraphic.Left = $scope.waterfallActivityGraphics[index - 1].Left + $scope.waterfallActivityGraphics[index - 1].Width;
newGraphic.LeftPos = newGraphic.Left + 'px';
}
// Get the staff count for the current activity
staff = $scope.Staff[getStaffCount($scope.Activities[index].MasterRoleID)].Count;
// Calculate the current width
width = ($scope.Activities[index].Effort / ((1 - $scope.Activities[index].Overhead) * staff * workDay));
newGraphic.Width = width;
newGraphic.WidthPos = width + 'px';
totalWaterfallWidth += width;
// insert the new record
$scope.waterfallActivityGraphics.push(newGraphic);
index++;
}
// round the total width to an integer number of days
totalWaterfallWidth = Math.round(totalWaterfallWidth);
// update the scaling factor based on the total width;
scalingFactor = (displayWidth - leftBaseline) / totalWaterfallWidth;
// refresh the current date based on the new scaling factor
index = 0;
while (index < $scope.Activities.length) {
if (index > 0) {
$scope.waterfallActivityGraphics[index].Left = $scope.waterfallActivityGraphics[index - 1].Left + $scope.waterfallActivityGraphics[index - 1].Width + 1;
$scope.waterfallActivityGraphics[index].LeftPos = $scope.waterfallActivityGraphics[index].Left + 'px';
}
$scope.waterfallActivityGraphics[index].Width = $scope.waterfallActivityGraphics[index].Width * scalingFactor;
$scope.waterfallActivityGraphics[index].WidthPos = $scope.waterfallActivityGraphics[index].Width + 'px';
index++;
}
}
// Declare a method to render the concurrent model
$scope.renderConcurrentModel = function () {
// Declare a variable to iterate over Activiites
var index = 0;
var width = 0;
// Declare a local object to store the new ActivityGraphic
var newGraphic;
var staff;
$scope.concurrentActivityGraphics.length = 0;
// loop over the activities
while (index < $scope.Activities.length) {
// Initialize the new graphic record
newGraphic = { ActivityID: $scope.Activities[index].ID, Left: 0, LeftPos: 0 + 'px', Top: waterfalTopBaseline, TopPos: waterfalTopBaseline + 'px', Width: 0 };
// calculate the left position of the current graphic
newGraphic.Left = leftBaseline;
newGraphic.LeftPos = leftBaseline + 'px';
// Get the staff count for the current activity
staff = $scope.Staff[getStaffCount($scope.Activities[index].MasterRoleID)].Count;
// Calculate the current width
width = ($scope.Activities[index].Effort / ((1 - $scope.Activities[index].Overhead) * staff * workDay)) * scalingFactor;
newGraphic.Width = width;
newGraphic.WidthPos = width + 'px';
// calculate the top position of the current graphic
newGraphic.Top = topBaseline + index * (activityOffset + 1);
newGraphic.TopPos = newGraphic.Top + 'px';
$scope.concurrentActivityGraphics.push(newGraphic);
index++;
}
};
// Declare a function to refresh the calendar scale based on the scaling factor
$scope.refreshCalendar = function () {
var index = 0;
var width = 0;
var calendarWidth = 0;
var newWeek = undefined;
// Set the week width to 5 times the Scaling factor since that represents the pixels per day for the current display
width = 5 * scalingFactor;
$scope.Calendar.length = 0;
while (calendarWidth < (totalWaterfallWidth * scalingFactor)) {
newWeek = { ID: 0, Left: 0, LeftPos: '0px', Width: 0, WidthPos: '0px', Top: 0, TopPos: '0px' };
newWeek.ID = index + 1;
newWeek.Left = (leftBaseline + index * width);
newWeek.LeftPos = newWeek.Left + 'px';
newWeek.Width = width;
newWeek.WidthPos = newWeek.Width + 'px';
newWeek.Top = topBaseline;
newWeek.TopPos = newWeek.Top + 'px';
$scope.Calendar.push(newWeek);
calendarWidth += width;
index++;
}
}
}])
.filter('percentage', ['$filter', function ($filter) {
return function (input, decimals) {
return $filter('number')(input * 100, decimals) + '%';
};
}])
.directive("postConditionToggle", function ($location) {
return {
restrict: "A",
controller: function ($scope) {
$scope.togglePostconditionPanel = function (element) {
var element;
// hide post condition control
if ($scope.postConditionToggleButton.Displayed) {
$scope.postConditionBorder = "solid 0px black";
$scope.postConditionToggleButton.Name = 'Edit Postconditions';
$scope.postConditionToggleButton.Displayed = false;
$scope.postConditionPanel.Height = 0;
$scope.postConditionPanel.HeightPos = $scope.postConditionPanel.Height + 'px';
$scope.editPanelPositions[1].Visible = false;
}
// show post condition control
else {
$scope.postConditionBorder = "solid 1px black";
$scope.postConditionToggleButton.Name = 'Hide Postconditions';
$scope.postConditionToggleButton.Displayed = true;
$scope.postConditionPanel.Height = 500;
$scope.postConditionPanel.HeightPos = $scope.postConditionPanel.Height + 'px';
$scope.editPanelPositions[1].Visible = true;
}
$scope.updateEditPanelPositions();
};
$scope.togglePreconditionPanel = function (element) {
var element;
// Hide the precondition panel
if ($scope.preConditionToggleButton.Displayed) {
$scope.preConditionBorder = "solid 0px black";
$scope.preConditionToggleButton.Name = 'Edit Preconditions';
$scope.preConditionToggleButton.Displayed = false;
$scope.preConditionPanel.Height = 0;
$scope.preConditionPanel.HeightPos = $scope.preConditionPanel.Height + 'px';
// update the top attributes for the post condition panel
$scope.postConditionPanel.Top = 80;
$scope.postConditionPanel.TopPos = $scope.postConditionPanel.Top + 'px';
// Update the pot condition button style data
$scope.postConditionToggleButton.Top = 50;
$scope.postConditionToggleButton.TopPos = $scope.postConditionToggleButton.Top + 'px';
$scope.editPanelPositions[0].Visible = false;
}
// show the precondition panel
else {
$scope.preConditionBorder = "solid 1px black";
$scope.preConditionToggleButton.Name = 'Hide Preconditions';
$scope.preConditionToggleButton.Displayed = true;
$scope.preConditionPanel.Height = 500;
$scope.preConditionPanel.HeightPos = $scope.preConditionPanel.Height + 'px';
// update the top attributes for the post condition panel
$scope.postConditionPanel.Top = 585;
$scope.postConditionPanel.TopPos = $scope.postConditionPanel.Top + 'px';
// Update the pot condition button style data
$scope.postConditionToggleButton.Top = 555;
$scope.postConditionToggleButton.TopPos = $scope.postConditionToggleButton.Top + 'px';
$scope.editPanelPositions[0].Visible = true;
}
$scope.updateEditPanelPositions();
};
$scope.toggleStaffingPanel = function (element) {
var element;
$scope.staffingToggleButton.Top = $scope.editPanelPositions[2].Top - 35;
$scope.staffingToggleButton.TopPos = $scope.staffingToggleButton.Top + 'px';
// hide post condition control
if ($scope.staffingToggleButton.Displayed) {
$scope.staffingBorder = "solid 0px black";
$scope.staffingToggleButton.Name = 'Edit Staffing';
$scope.staffingToggleButton.Displayed = false;
$scope.staffingPanel.Height = 0;
$scope.staffingPanel.HeightPos = $scope.staffingPanel.Height + 'px';
$scope.editPanelPositions[2].Visible = false;
}
// show post condition control
else {
$scope.staffingBorder = "solid 1px black";
$scope.staffingToggleButton.Name = 'Hide Staffing';
$scope.staffingToggleButton.Displayed = true;
$scope.staffingPanel.Height = 350;
$scope.staffingPanel.HeightPos = $scope.staffingPanel.Height + 'px';
$scope.editPanelPositions[2].Visible = false;
}
$scope.updateEditPanelPositions();
};
},
};
})
|
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var navClass = "navbar fixed-top navbar-expand-sm navbar-light bg-light pl-3 pr-3 pb-0 pt-0";
var navID = "navbar_b";
function NavBrand(props) {
'use strict';
var root = props.root;
var home = root + "/index.php";
return React.createElement(
"div",
null,
React.createElement(
"a",
{ className: "navbar-brand", href: home },
"Portals"
),
React.createElement(
"button",
{
"aria-controls": "navbarText",
"aria-expanded": "false",
"aria-label": "Toggle navigation",
className: "navbar-toggler",
"data-target": "#navbarText",
"data-toggle": "collapse",
type: "button"
},
React.createElement("span", { className: "navbar-toggler-icon" })
)
);
}
function ListItem(props) {
'use strict';
var href = props.href;
var content = props.content;
var isActive = props.isActive;
var liClass = "nav-item";
if (isActive && isActive === true) liClass += " active";
return React.createElement(
"li",
{ className: liClass },
React.createElement(
"a",
{ className: "nav-link", href: href },
content
)
);
}
function NavText(props) {
'use strict';
var isLoggedIn = props.isLoggedIn;
//const shoppingCart = props.shoppingCart;
var logout = props.root + '/u/actions/logout/index.php';
var login = props.root + '/u/actions/login/index.php';
var register = props.root + '/u/actions/register/index.php';
if (isLoggedIn && isLoggedIn === "1") {
//TODO: get shopping cart count here to keep out of nav-collapse;
//cartCount = props.cartCount;
return React.createElement(
"span",
{ className: "navbar-text" },
"Welcome, ",
props.fname,
".",
React.createElement("br", null),
React.createElement(
"a",
{ className: "mute", href: logout },
"Logout"
)
);
} else {
return React.createElement(
"span",
{ className: "navbar-text" },
React.createElement(
"a",
{ className: "", href: login },
"Sign In"
),
"\xA0or\xA0",
React.createElement(
"a",
{ className: "", href: register },
"Register Now"
)
);
}
}
function ShoppingCart(props) {
'use strict';
if (props.isLoggedIn && props.isLoggedIn === "1") {
return React.createElement(
"li",
{ className: "nav-item" },
React.createElement(
"a",
{
className: "nav-link",
title: "Shopping Cart",
href: props.href
},
React.createElement(
"span",
{ className: "fa-stack " },
React.createElement("i", { className: "fa-stack-2x backdrop-usd fas fa-circle" }),
React.createElement("i", { className: "fa-stack-1x fas fa-tw fa-shopping-cart" })
),
React.createElement(
"span",
{ className: "badge badge-primary" },
props.cartCount
)
)
);
} else {
return React.createElement("li", null);
}
}
var MainNav = function (_React$Component) {
_inherits(MainNav, _React$Component);
function MainNav(props) {
_classCallCheck(this, MainNav);
var _this = _possibleConstructorReturn(this, (MainNav.__proto__ || Object.getPrototypeOf(MainNav)).call(this, props));
//TODO: Probably read the paths from a json file;
//TODO: Pull over shopping cart from nav-test and data-*
_this.state = {
collapseIsOpen: false,
home: "#",
features: "#",
pricing: "#",
blog: "#",
userDash: "#",
adminDash: "#"
};
var PATHS = fetch(_this.props.root + '/config/paths.json').then(function (response) {
return response.json();
}).then(function (resData) {
_this.setState({ home: resData['NAV_HOME'] });
_this.setState({ features: resData['NAV_ITEM2'] });
_this.setState({ pricing: resData['NAV_ITEM3'] });
_this.setState({ blog: resData['NAV_ITEM4'] });
_this.setState({ userDash: resData['NAV_CART'] });
_this.setState({ adminDash: resData['ADMIN_DASH'] });
});
_this.PATHS = PATHS;
_this.isAdmin = _this.props.is_admin; //DataSet
_this.isLoggedIn = _this.props.is_logged_in; //DataSet
_this.fname = _this.props.fname; //DataSet
_this.cartCount = _this.props.cart_count; //DataSet
return _this;
}
_createClass(MainNav, [{
key: "render",
value: function render() {
return React.createElement(
"nav",
{
className: navClass,
id: navID
},
React.createElement(
"div",
{ className: "collapse navbar-collapse", id: "navbarText" },
React.createElement(NavBrand, { root: this.props.root }),
React.createElement(
"ul",
{ className: "navbar-nav mr-auto" },
React.createElement(ListItem, { href: this.state.home, content: "Home" }),
React.createElement(ListItem, { href: this.state.features, content: "Features" }),
React.createElement(ListItem, { href: this.state.pricing, content: "Pricing" }),
React.createElement(ListItem, { href: this.state.blog, content: "Blog" }),
React.createElement(ShoppingCart, {
href: this.userDash,
cartCount: this.cartCount,
isLoggedIn: this.isLoggedIn
}),
this.isAdmin && this.isAdmin === "1" ? React.createElement(ListItem, { href: this.state.adminDash, content: "Admin" }) : React.createElement("div", null)
),
React.createElement(NavText, {
isLoggedIn: this.isLoggedIn,
cartCount: this.cartCount,
fname: this.fname,
root: this.props.root
})
)
);
}
}]);
return MainNav;
}(React.Component);
ReactDOM.render(React.createElement(MainNav, main_nav.dataset), document.getElementById('main_nav') //Main nav bar
);
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { StyleSheet } from 'quantum'
import { buy } from '../actions/cart'
import { Modal, Header, Body, Footer } from 'bypass/ui/modal'
import { ColumnLayout, RowLayout, Layout } from 'bypass/ui/layout'
import { Checkbox } from 'bypass/ui/checkbox'
import { Button } from 'bypass/ui/button'
import { Text } from 'bypass/ui/text'
const styles = StyleSheet.create({
self: {
padding: '15px 20px',
background: 'transparent',
outline: 'none',
'& span:first-child': {
fontSize: '18px',
color: '#8bc34a',
margin: '0 0 15px 0',
display: 'block',
},
},
})
class FastBuy extends Component {
static defaultProps = {
options: {},
}
constructor(props, context) {
super(props, context)
this.state = props.options
}
onChangeCheck = ({ target }) => {
this.setState({ check: target.checked })
}
onChangeOpen = ({ target }) => {
this.setState({ open: target.checked })
}
onChangeRedirect = ({ target }) => {
this.setState({ redirect: target.checked })
}
onChangeCsv = ({ target }) => {
this.setState({ csv: target.checked })
}
onBuy = () => {
const { cards, onBuy } = this.props
const { check, open, redirect, csv } = this.state
if (onBuy) {
onBuy(cards, { check, open, redirect, csv })
}
}
renderPurchase() {
const { count, price } = this.props
return (
<div>
<div>
<Text size={14}>
{__i18n('SEARCH.FAST_BUY.CARD_SELECTED')}: {count}
</Text>
</div>
<div>
<Text size={14}>
{__i18n('SEARCH.FAST_BUY.TOTAL_COAST')}: ${price}
</Text>
</div>
</div>
)
}
renderOptions() {
const { check, open, redirect, csv } = this.state
return (
<div className={styles()}>
<span>
{__i18n('SEARCH.FAST_BUY.AFTER_BUY')}
</span>
<div>
<ColumnLayout justify='space-around'>
<Layout>
<RowLayout>
<Layout>
<Checkbox checked={check} onChange={this.onChangeCheck} /> {__i18n('SEARCH.FAST_BUY.SET_CHECK')}
</Layout>
<Layout basis='5px' />
<Layout>
<Checkbox checked={open} onChange={this.onChangeOpen} /> {__i18n('LANG.BUTTONS.OPEN')}
</Layout>
</RowLayout>
</Layout>
<Layout>
<RowLayout>
<Layout>
<Checkbox checked={redirect} onChange={this.onChangeRedirect} /> {__i18n('SEARCH.FAST_BUY.GO_ORDER')}
</Layout>
<Layout basis='5px' />
<Layout>
<Checkbox checked={csv} onChange={this.onChangeCsv} /> {__i18n('SEARCH.FAST_BUY.SHOW_CVS')}
</Layout>
</RowLayout>
</Layout>
</ColumnLayout>
</div>
</div>
)
}
render() {
const { onClose } = this.props
return (
<Modal onClose={onClose}>
<Header>
<Text size={19}>
{__i18n('PROFILE.FAST_BUY.TEXT')}
</Text>
</Header>
<Body alignCenter>
{this.renderPurchase()}
{this.renderOptions()}
</Body>
<Footer alignCenter>
<Button onClick={this.onBuy}>
{__i18n('LANG.BUTTONS.BUY')}
</Button>
</Footer>
</Modal>
)
}
}
export default connect(
null,
dispatch => ({
onBuy: (cards, options) => dispatch(buy(cards, options)),
}),
)(FastBuy)
|
/*
* Copyright (C) 2021 Radix IoT LLC. All rights reserved.
*/
import angular from 'angular';
import EventTarget from '../classes/EventTarget';
/**
* @ngdoc service
* @name ngMangoServices.maEventManager
*
* @description
* REPLACE
*
* # Usage
*
* <pre prettyprint-mode="javascript">
REPLACE
* </pre>
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maEventManager
* @name openSocket
*
* @description
* REPLACE
*
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maEventManager
* @name closeSocket
*
* @description
* REPLACE
*
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maEventManager
* @name messageReceived
*
* @description
* REPLACE
*
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maEventManager
* @name subscribe
*
* @description
* REPLACE
*
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maEventManager
* @name unsubscribe
*
* @description
* REPLACE
*
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maEventManager
* @name smartSubscribe
*
* @description
* REPLACE
*
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maEventManager
* @name updateSubscriptions
*
* @description
* REPLACE
*
*/
EventManagerFactory.$inject = ['MA_BASE_URL', '$rootScope', 'MA_TIMEOUTS', 'maUser', '$window', '$injector', 'maEventBus', 'maWatchdog'];
function EventManagerFactory(mangoBaseUrl, $rootScope, MA_TIMEOUTS, maUser, $window, $injector, maEventBus, maWatchdog) {
const $state = $injector.has('$state') && $injector.get('$state');
//const READY_STATE_CONNECTING = 0;
const READY_STATE_OPEN = 1;
//const READY_STATE_CLOSING = 2;
//const READY_STATE_CLOSED = 3;
function arraysEqual(a, b) {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
class PayloadEvent extends CustomEvent {
constructor(type, payload) {
super(type);
this.payload = payload;
}
}
class EventManager {
constructor(options) {
// keys are xid, value is object where key is event type and value is the number of subscriptions
this.subscriptionsByXid = {};
// keys are xid, value is array of event types
this.activeEventTypesByXid = {};
// subscriptions to all xids
this.allSubscriptions = {};
// array of event types active for all xids
this.activeAllEventTypes = [];
Object.assign(this, options);
// used for subscriptions to all XIDs
this.eventEmitter = new EventTarget();
let unloadPending = false;
$window.addEventListener('beforeunload', event => {
// if a beforeunload event occurs on the login page do not try and open the WebSocket
if ($state && $state.includes('login')) {
unloadPending = true;
}
});
this.loggedIn = maWatchdog.status === 'LOGGED_IN';
maEventBus.subscribe('maWatchdog/#', (event, watchdog) => {
this.loggedIn = watchdog.status === 'LOGGED_IN';
if (watchdog.status === 'LOGGED_IN') {
// API is up and we are logged in
// prevent opening WS connections which are closed immediately when maLoginRedirector sets window.location
if (!unloadPending) {
this.openSocket();
}
} else if (watchdog.status === 'API_UP') {
// API is up but we aren't logged in
this.closeSocket();
}
// all other states we dont do anything
});
this.openSocket();
}
openSocket() {
// dont attempt to connect if we are already connected or not logged in
if (this.socket || !this.loggedIn) return;
if (!('WebSocket' in window)) {
throw new Error('WebSocket not supported');
}
let host = document.location.host;
let protocol = document.location.protocol;
const baseUrl = mangoBaseUrl;
if (baseUrl) {
const i = baseUrl.indexOf('//');
if (i >= 0) {
protocol = baseUrl.substring(0, i);
host = baseUrl.substring(i+2);
}
else {
host = baseUrl;
}
}
protocol = protocol === 'https:' ? 'wss:' : 'ws:';
const socket = this.socket = new WebSocket(protocol + '//' + host + this.url);
this.connectTimer = setTimeout(() => {
this.closeSocket();
}, MA_TIMEOUTS.websocket);
socket.onclose = event => {
this.closeSocket(event);
};
socket.onerror = event => {
this.closeSocket(event);
};
socket.onopen = () => {
clearTimeout(this.connectTimer);
delete this.connectTimer;
// update subscriptions for individual xids
for (const xidKey in this.subscriptionsByXid) {
this.updateSubscriptions(xidKey);
}
// update subscriptions to all xids
this.updateSubscriptions();
};
socket.onmessage = (event) => {
const message = JSON.parse(event.data);
this.messageReceived(message);
};
return socket;
}
closeSocket(event) {
if (this.connectTimer) {
clearTimeout(this.connectTimer);
delete this.connectTimer;
}
if (this.socket) {
this.socket.onclose = angular.noop;
this.socket.onerror = angular.noop;
this.socket.onopen = angular.noop;
this.socket.onmessage = angular.noop;
this.socket.close();
delete this.socket;
}
this.activeEventTypesByXid = {};
this.activeAllEventTypes = [];
if (event) {
// websocket closed by server, check if Mango is still up
maWatchdog.checkStatus();
}
}
messageReceived(message) {
if (message.status === 'OK') {
const payload = this.transformPayload(message.payload);
const eventType = payload.event || payload.action;
const xid = payload.xid || payload.object.xid;
const event = new PayloadEvent(eventType, payload);
this.eventEmitter.dispatchEvent(event);
const xidSubscriptions = this.subscriptionsByXid[xid];
if (xidSubscriptions) {
xidSubscriptions.lastPayload = event;
xidSubscriptions.eventEmitter.dispatchEvent(event);
}
}
}
transformPayload(payload) {
return payload;
}
subscribe(xid, eventTypes, eventHandler) {
let xidSubscriptions;
if (xid) {
if (!this.subscriptionsByXid[xid])
this.subscriptionsByXid[xid] = {eventEmitter: new EventTarget()};
xidSubscriptions = this.subscriptionsByXid[xid];
}
if (!Array.isArray(eventTypes)) eventTypes = [eventTypes];
if (this.replayLastPayload && xidSubscriptions && xidSubscriptions.lastPayload && typeof eventHandler === 'function') {
eventHandler(xidSubscriptions.lastPayload);
}
for (let i = 0; i < eventTypes.length; i++) {
const eventType = eventTypes[i];
if (xidSubscriptions) {
if (typeof eventHandler === 'function') {
xidSubscriptions.eventEmitter.addEventListener(eventType, eventHandler);
}
if (!xidSubscriptions[eventType]) {
xidSubscriptions[eventType] = 1;
}
else {
xidSubscriptions[eventType]++;
}
} else {
if (typeof eventHandler === 'function') {
this.eventEmitter.addEventListener(eventType, eventHandler);
}
if (!this.allSubscriptions[eventType]) {
this.allSubscriptions[eventType] = 1;
}
else {
this.allSubscriptions[eventType]++;
}
}
}
this.updateSubscriptions(xid);
}
unsubscribe(xid, eventTypes, eventHandler) {
let xidSubscriptions;
if (xid) {
xidSubscriptions = this.subscriptionsByXid[xid];
}
if (!Array.isArray(eventTypes)) eventTypes = [eventTypes];
for (let i = 0; i < eventTypes.length; i++) {
const eventType = eventTypes[i];
if (xidSubscriptions) {
if (typeof eventHandler === 'function') {
xidSubscriptions.eventEmitter.removeEventListener(eventType, eventHandler);
}
if (xidSubscriptions[eventType] > 0) {
xidSubscriptions[eventType]--;
}
} else {
if (typeof eventHandler === 'function') {
this.eventEmitter.removeEventListener(eventType, eventHandler);
}
if (this.allSubscriptions[eventType] > 0) {
this.allSubscriptions[eventType]--;
}
}
}
this.updateSubscriptions(xid);
}
/**
* Subscribes to the event type for the XID but also unsubscribes automatically when the given $scope
* is destroyed and does scope apply for the eventHandler function
*/
smartSubscribe($scope, xid, eventTypes, eventHandler) {
const appliedHandler = scopeApply.bind(null, $scope, eventHandler);
this.subscribe(xid, eventTypes, appliedHandler);
const unsubscribe = () => {
this.unsubscribe(xid, eventTypes, appliedHandler);
};
const deregister = $scope.$on('$destroy', unsubscribe);
// manual unsubscribe function
return () => {
deregister();
unsubscribe();
};
function scopeApply($scope, fn) {
const args = Array.prototype.slice.call(arguments, 2);
const boundFn = fn.bind.apply(fn, [null].concat(args));
$scope.$applyAsync(boundFn);
}
}
updateSubscriptions(xid) {
if (!this.socket || this.socket.readyState !== READY_STATE_OPEN) return;
const subscriptions = xid ? this.subscriptionsByXid[xid] : this.allSubscriptions;
const eventTypes = [];
for (const key in subscriptions) {
if (key === 'eventEmitter' || key === 'lastPayload')
continue;
if (subscriptions[key] === 0) {
delete subscriptions[key];
} else {
eventTypes.push(key);
}
}
eventTypes.sort();
const activeSubs = xid ? this.activeEventTypesByXid[xid] : this.activeAllEventTypes;
// there are no subscriptions for any event types for this xid
if (xid && eventTypes.length === 0) {
delete this.subscriptionsByXid[xid];
delete this.activeEventTypesByXid[xid];
}
if (!activeSubs || !arraysEqual(activeSubs, eventTypes)) {
if (eventTypes.length) {
if (xid) {
this.activeEventTypesByXid[xid] = eventTypes;
} else {
this.activeAllEventTypes = eventTypes;
}
}
const message = {};
if (xid)
message.xid = xid;
message.eventTypes = eventTypes;
this.socket.send(JSON.stringify(message));
}
}
isConnected() {
return this.socket && this.socket.readyState === READY_STATE_OPEN;
}
}
return EventManager;
}
export default EventManagerFactory;
|
function addme(e1,e2,e3,e4,c1){
var res = document.createElement("div")
res.setAttribute("class","row")
res.innerHTML = `<div class="col-3"><p>${e1}</p></div>
<div class="col-3"><p>${e2}</p></div>
<div class="col-3"><p>${e3}</p></div>
<div class="col-3 ${c1}"><p>${e4}</p></div>`;
return res
}
var root = document.getElementById("root")
var container = document.createElement("div")
container.setAttribute("class","container-fluid")
var row1 = document.createElement("div")
row1.setAttribute("class","row")
var calcol = document.createElement("div")
calcol.setAttribute("id","calcol")
calcol.setAttribute("class","col-12")
var rowt=document.createElement("div")
rowt.setAttribute("class","row")
rowt.setAttribute("id","dispbox")
calcol.appendChild(rowt)
var row2 = document.createElement("div")
row2.setAttribute("class","row")
row2.setAttribute("id","calc")
var col12 = document.createElement("div")
col12.setAttribute("class","col-12")
col12.appendChild(addme('AC','C','%','/','c'))
col12.appendChild(addme('7','8','9','*','c'))
col12.appendChild(addme('4','5','6','-','c'))
col12.appendChild(addme('1','2','3','+','c'))
col12.appendChild(addme('.','0','( )','=','c1'))
row2.appendChild(col12)
calcol.appendChild(row2)
row1.appendChild(calcol)
container.appendChild(row1)
root.appendChild(container)
|
const logger = require('../../logger');
const productService = require('../../services/product');
async function add(req, res, next) {
logger.log("GET ADD PRODUCT");
var result = {};
try {
result.payload = await productService.add(req.body);
result.status = true;
result.message = 'ok';
} catch (e) {
result.status = false;
result.message = `exceptiom occured! - ${e.message}`;
}
res.json(result);
}
module.exports = add
|
(function () {
if (typeof Snake === "undefined") {
window.Snake = {};
}
var View = window.Snake.View = function (board, $el) {
this.board = board;
this.bindListeners();
var that = this;
setInterval(function () {
that.step();
}, 500);
};
View.prototype.step = function () {
this.board.snake.move();
var boardText = this.board.render();
$el.text(boardText);
};
View.prototype.bindListeners = function () {
var that = this;
$(document).on("keydown", function (event) {
that.handleKeyEvent(event);
});
};
View.KEYCODES = {
87: "N",
65: "W",
83: "S",
68: "E"
};
View.prototype.handleKeyEvent = function (event) {
var dir = event.keyCode;
this.board.snake.turn(View.KEYCODES[dir]);
};
})();
|
import {
FETCH_USER_PENDING,
FETCH_USER_FUFILLED,
FETCH_USER_REJECTED,
CLEAR_LOGIN_ERROR,
VERIFY_JWT_TOKEN_SUCCESS,
VERIFY_JWT_TOKEN_FAIL
} from "../types";
const defaultState = {
user : {},
loading: false,
disabled: false,
isLoading : true, //hide app content until jwt is verified
error : {
email : {
message : ""
}
}
};
export const authReducer = (state = defaultState, action) => {
switch (action.type) {
case VERIFY_JWT_TOKEN_SUCCESS:
return {...state, isLoading : false, user : action.payload };
case VERIFY_JWT_TOKEN_FAIL:
return {...state, isLoading : false };
case FETCH_USER_PENDING:
return {...state, loading: true, disabled : true};
case FETCH_USER_FUFILLED:
return {...state, user : action.payload, loading: false, disabled : false, isAuthenticated : true};
case FETCH_USER_REJECTED:
return {...state, loading: false, error: action.payload, disabled : false};
case CLEAR_LOGIN_ERROR:
return {...state, error : { ...state.error, email : { ...state.error.email, message : action.payload }}};
default:
return state;
}
}
|
var joinValidate = {
// 결과 메세지 출력시 사용하는 Text
resultCode : {
empty_val : {
code : 1,
desc : '필수입력 정보입니다.'
},
// ID
empty_id : {
code : 2,
desc : '공백 없이 3~15자의 영문/숫자 또는 ,_를 조합하여 입력'
},
invalid_id : {
code : 3,
desc : '3~15자의 영문/숫자 또는 ,_를 조합하여 입력'
},
length_id : {
code : 4,
desc : '3~15자의 영문/숫자 또는 ,_를 조합하여 입력'
},
overlap_id : {
code : 6,
desc : '이미 사용 중인 아이디입니다.'
},
// PW
empty_pw : {
code : 2,
desc : '공백 없이 5~16자의 영문/숫자를 조합하여 입력'
},
invalid_pw : {
code : 3,
desc : '5~16자의 영문/숫자를 조합하여 입력'
},
other_pw : {
code : 5,
desc : '입력하신 비밀번호가 일치하지 않습니다.'
},
// name
empty_name : {
code : 2,
desc : '공백 없이 표준 한글 2~8자까지 가능합니다.'
},
invalid_name : {
code : 3,
desc : '표준 한글 2~8자까지 가능합니다.'
},
// phone
number_phone : {
code : 6,
desc : '숫자만 입력해주세요.'
},
invalid_phone : {
code : 3,
desc : '번호가 유효하지 않습니다.'
},
// email
invalid_email : {
code : 3,
desc : '올바른 이메일을 입력해주세요.'
},
success_id : {
code : 0,
desc : '사용 가능합니다.'
},
success_pw : {
code : 0,
desc : '사용 가능합니다.'
},
success_rpw : {
code : 0,
desc : '사용 가능합니다.'
},
success_name : {
code : 0,
desc : '사용 가능합니다.'
},
success_phone : {
code : 0,
desc : '사용 가능합니다.'
},
success_email : {
code : 0,
desc : '사용 가능합니다.'
}
},
checkId : function(memId){
var regEmpty = /\s/g; // 공백문자
var reg = /[^a-z0-9_.]+/g; // []안과 같으면 false, 다르면 true
// 4. member.jsp에서 전달한 매개변수 memId로 유효성체크 시작
// 1) null값 체크 if
// 2) 값 사이의 공백값 체크 else if
// 3) 유효한 값인지 체크(정규식) else if
// 4) 6자~50자 이내 길이 체크 else if
// 5) 성공: 유효한 값(중복유무X) else
if (memId == '' || memId.length == 0) {
return this.resultCode.empty_val;
} else if (memId.match(regEmpty)) {
return this.resultCode.empty_id;
} else if (reg.test(memId)) {
return this.resultCode.invalid_id;
} else if ((memId.length<3) || (memId.length>15)) {
return this.resultCode.length_id;
} else {
// 5. 입력받은 값의 아이디로 위의 유효성체크 4단계를 통과
// 하지만 중복된 ID인지 검정 필요함
// 6. return 결과값으로 success_id(code, desc)를 호출한 곳으로 전송!
// code: 0, desc: "사용 가능합니다."
return this.resultCode.success_id;
}
// 중복체크(ajax)
// ajaxCheck(id);
},
checkPw:function(memPw, memRpw){
var regEmpty = /\s/g;
var pwReg = RegExp(/^[a-zA-Z0-9]{5,16}$/);
if (memPw == '' || memPw.length == 0) {
return this.resultCode.empty_val;
} else if (memPw.match(regEmpty)) {
return this.resultCode.empty_pw;
} else if (!pwReg.test(memPw)) {
return this.resultCode.invalid_pw;
} else {
return this.resultCode.success_pw;
}
},
checkRpw:function(memPw, memRpw){
var regEmpty = /\s/g;
var pwReg = RegExp(/^[a-zA-Z0-9]{5,16}$/);
if (memRpw == '' || memRpw.length == 0) {
return this.resultCode.empty_val;
} else if (memRpw.match(regEmpty)) {
return this.resultCode.empty_pw;
} else if (!pwReg.test(memRpw)) {
return this.resultCode.invalid_pw;
} else {
return this.resultCode.success_pw;
}
}
}
//ID 중복체크 Ajax
function ajaxCheck(memId) {
// 10. ajax 시작!!!
// 목적지: idCheck.gaon
// 전달데이터: memId 데이터를 id변수에 담아 전달
// 데이터 포장방법: json
// 데이터 전달방법: POST방식
// id에 값이 있는 경우에만 ajax 동작!
var ajaxId = "-1";
$.ajax({
url: "idcheck?id="+memId,
type: "POST", // 보내는 방식(운송역할)
async: false,
contentType: "application/json", // 거의 ajax에서는 json만 쓴다, 데이터 가방의 타입(포장)
success: function(data) { // data: Action에서 return으로 보내준 값을 받음
console.log(data);
// 29. Action단에서 전송한 message, id를 data매개변수로 받음
// 30. data.message의 값이 -1이면 => 중복메세지 출력
// data.message의 값이 1이면 => 사용가능메세지 출력
if (data == 1) {
$('.box_inner').eq(0).css('color', 'tomato')
.css('display', 'block')
.text("이미 사용 중인 아이디입니다.");
ajaxId = "-1";
} else {
$(".box_inner").eq(0).css('display', 'none');
ajaxId = "1";
}
},
// success를 타면 error를 타지 않음
error: function() {
alert("system Error!!");
}
});
return ajaxId;
}
function ajaxPwCheck(nowId, nowPw){
var ajaxPw = false;
$.ajax({
url: "pwcheck?id="+nowId+"&pw="+nowPw,
type: "POST",
async: false,
success: function(data) {
console.log(data);
if (data == "1") {
$('.pwAjax').css('color', 'dodgerblue')
.css('display', 'block')
.text("비밀번호가 일치합니다.");
ajaxPw = true;
} else {
$('.pwAjax').css('color', 'tomato')
.css('display', 'block')
.text("비밀번호가 일치하지 않습니다.");
ajaxPw = false;
}
},
error:function(){
alert("system Error!!!");
}
});
return ajaxPw;
}
var return_val = false;
function idCheck(id) {
var memId = $.trim(id);
var checkResult = joinValidate.checkId(memId);
if(checkResult.code != 0) {
$('.box_inner').eq(0).text(checkResult.desc)
.css('color', 'tomato')
.css('display', 'block');
return_val = false;
} else {
if(ajaxCheck(memId) == "1"){
return_val = true;
} else {
return_val = false;
}
}
return return_val;
}
function pwCheck(pw, rpw) {
var memPw = $.trim(pw);
var memRpw = $.trim(rpw);
var checkResult = joinValidate.checkPw(memPw, memRpw);
if(checkResult.code != 0) {
$('.box_inner').eq(1).text(checkResult.desc)
.css('color', 'tomato')
.css('display', 'block');
return_val = false;
} else {
$('.box_inner').eq(1).css('display', 'none');
if (memRpw != null || memRpw.length != 0) {
if (memPw == memRpw) { // pw, rpw가 같은지 확인
$('.box_inner').eq(2).css('display', 'none');
return_val = true;
} else {
$('.box_inner').eq(2).css('color', 'tomato')
.css('display', 'block')
.text('입력하신 비밀번호가 일치하지 않습니다.');
return_val = false;
}
}
}
return return_val;
}
function rpwCheck(pw, rpw){
var memPw = $.trim(pw);
var memRpw = $.trim(rpw);
var checkResult = joinValidate.checkRpw(memPw, memRpw);
if(checkResult.code != 0) {
$('.box_inner').eq(2).text(checkResult.desc)
.css('color', 'tomato')
.css('display', 'block');
return_val = false;
} else {
$('.box_inner').eq(2).css('display', 'none');
if (memPw != null || memPw.length != 0) {
if (memPw == memRpw) { // pw, rpw가 같은지 확인
$('.box_inner').eq(2).css('display', 'none');
return_val = true;
} else {
$('.box_inner').eq(2).css('color', 'tomato')
.css('display', 'block')
.text('입력하신 비밀번호가 일치하지 않습니다.');
return_val = false;
}
}
}
return return_val;
}
function nameCheck(name) {
var nameReg = RegExp(/^[가-힣]{2,8}$/);
var regEmpty = /\s/g;
if (name == '' || name.length == 0) {
//alert('test');
$('.box_inner').eq(3).css('color', 'tomato')
.css('display', 'block')
.text("필수입력 정보입니다.");
return_val = false;
} else if (name.match(regEmpty)) {
$('.box_inner').eq(3).css('color', 'tomato')
.css('display', 'block')
.text("공백 없이 표준 한글 2~8자까지 가능합니다.");
return_val = false;
} else if (!nameReg.test(name)) {
$('.box_inner').eq(3).css('color', 'tomato')
.css('display', 'block')
.text("표준 한글 2~8자까지 가능합니다.");
return_val = false;
} else {
$('.box_inner').eq(3).css('display', 'none');
return_val = true;
}
return return_val;
}
function phone1Check(phone){
var regEmpty = /\s/g;
if (phone == '' || phone.length == 0) {
$('.box_inner_phone').css('color', 'tomato')
.css('display', 'block')
.text("필수입력 정보입니다.");
return_val = false;
} else if ($.isNumeric(phone) == false) {
$('.box_inner_phone').css('color', 'tomato')
.css('display', 'block')
.text("숫자만 입력해주세요.");
return_val = false;
} else if (phone.indexOf("01") != 0) {
// indexOf("01"): 01로 시작
// lastindexOf
$('.box_inner_phone').css('color', 'tomato')
.css('display', 'block')
.text("번호가 유효하지 않습니다.");
return_val = false;
} else if (phone.length != 3) {
$('.box_inner_phone').css('color', 'tomato')
.css('display', 'block')
.text("번호가 유효하지 않습니다.");
return_val = false;
} else {
$('.box_inner_phone').css('display', 'none');
return_val = true;
}
return return_val;
}
function phone2Check(phone){
var regEmpty = /\s/g;
if (phone == '' || phone.length == 0) {
$('.box_inner_phone').css('color', 'tomato')
.css('display', 'block')
.text("필수입력 정보입니다.");
return_val = false;
} else if ($.isNumeric(phone) == false) {
$('.box_inner_phone').css('color', 'tomato')
.css('display', 'block')
.text("숫자만 입력해주세요.");
return_val = false;
} else if (phone.length != 4) {
$('.box_inner_phone').css('color', 'tomato')
.css('display', 'block')
.text("번호가 유효하지 않습니다.");
return_val = false;
} else {
$('.box_inner_phone').css('display', 'none');
return_val = true;
}
return return_val;
}
function emailCheck(email, url){
var regEmpty = /\s/g;
var emailReg = RegExp(/^[A-Za-z0-9._-]+@[A-Za-z0-9._-]+\.[A-Za-z]{2,4}$/i);
if (email == '' || email.length == 0) {
//alert('test');
$('.box_inner_email').css('color', 'tomato')
.css('display', 'block')
.text("필수입력 정보입니다.");
return_val = false;
} else if (email.match(regEmpty)) {
$('.box_inner_email').css('color', 'tomato')
.css('display', 'block')
.text("올바른 이메일을 입력해주세요.");
return_val = false;
} else if (url != "" || url.length != 0) {
var fullMail = email+"@"+url;
if (!emailReg.test(fullMail)) {
$('.box_inner_email').css('color', 'tomato')
.css('display', 'block')
.text("올바른 이메일을 입력해주세요.");
return_val = false;
} else {
$('.box_inner_email').css('display', 'none');
return_val = true;
}
return return_val;
}
}
function urlCheck(email, url){
var regEmpty = /\s/g;
var emailReg = RegExp(/^[A-Za-z0-9._-]{3,15}+@[A-Za-z0-9._-]+\.[A-Za-z]{2,4}$/i);
if (url == '' || url.length == 0) {
//alert('test');
$('.box_inner_email').css('color', 'tomato')
.css('display', 'block')
.text("필수입력 정보입니다.");
return_val = false;
} else if (url.match(regEmpty)) {
$('.box_inner_email').css('color', 'tomato')
.css('display', 'block')
.text("올바른 이메일을 입력해주세요.");
return_val = false;
} else if (url != "" || url.length != 0) {
var fullMail = email+"@"+url;
if (!emailReg.test(fullMail)) {
$('.box_inner_email').css('color', 'tomato')
.css('display', 'block')
.text("올바른 이메일을 입력해주세요.");
return_val = false;
} else {
$('.box_inner_email').css('display', 'none');
return_val = true;
}
return return_val;
}
}
|
const s = "baabaa";
const solution = (s) => {
const stack = [];
for (let i = 0; i < s.length; i++) {
if (stack.length === 0 || stack[stack.length - 1] !== s[i]) {
stack.push(s[i]);
} else {
stack.pop();
}
}
if (stack.length === 0) {
return 1;
}
return 0;
};
console.log(solution(s));
// 효율성 통과 못한 코드
/*
const solution = (s) => {
let answer = 0;
for (let i = 0; i < s.length - 1; i++) {
if (s[i] === s[i + 1]) {
s = s.substr(0, i) + s.substr(i + 2);
i -= 2;
}
console.log(s);
}
if (s === "") {
return 1;
}
return 0;
};
console.log(solution(s));
*/
|
const blessed = require('blessed');
const HUD = {
screen: null,
objects: {
arbTable: null
},
headers: {
arb: ['Trade', 'Profit', 'AB Age', 'BC Age', 'CA Age', 'Age']
},
initScreen() {
if (HUD.screen) return;
HUD.screen = blessed.screen({
smartCSR: true
});
},
displayArbs(arbs) {
HUD.initScreen();
if (!HUD.objects.arbTable) {
HUD.objects.arbTable = blessed.table({
top: '0',
left: 'center',
width: '50%',
height: '50%',
border: {
type: 'line'
},
style: {
header: {
fg: 'blue',
bold: true
}
}
});
HUD.screen.append(HUD.objects.arbTable);
}
const now = new Date().getTime();
let tableData = [HUD.headers.arb];
arbs.forEach(arb => {
tableData.push([
`${arb.trade.symbol.a}-${arb.trade.symbol.b}-${arb.trade.symbol.c}`,
`${arb.percent.toFixed(4)}%`,
`${((now - arb.depth.ab.eventTime)/1000).toFixed(2)}`,
`${((now - arb.depth.bc.eventTime)/1000).toFixed(2)}`,
`${((now - arb.depth.ca.eventTime)/1000).toFixed(2)}`,
`${((now - Math.min(arb.depth.ab.eventTime, arb.depth.bc.eventTime, arb.depth.ca.eventTime))/1000).toFixed(2)}`
]);
});
HUD.objects.arbTable.setData(tableData);
HUD.screen.render();
}
};
module.exports = HUD;
|
/**
* Authors: Diego Ceresuela, Luis Jesús Pellicer, Raúl Piracés.
* Date: 16-05-2016
* Name file: data.controller.js
* Description: This file contains functions that attends endpoints of the resource "data".
*/
(function () {
'use strict';
var mongoose = require('mongoose');
var http = require('http');
var request = require('request');
var Resource = require('resourcejs');
var _ = require('lodash');
var Data = mongoose.model('data');
var admin_required = require('../../config/policies.config').admin_required;
var user_required = require('../../config/policies.config').user_required;
var jwt = require('jsonwebtoken');
var error = {
status: 500,
item: {
"error": true,
"data": {
"message": "Internal error.",
"url": process.env.CURRENT_DOMAIN + "/data"
}
}
};
module.exports = function (app, route) {
var resource = Resource(app, '', route, app.models.data)
.index(user_required)
.put(user_required);
resource.register(app, 'delete', '/' + route + '/:id', resetData, resource.respond.bind(resource), admin_required);
resource.register(app, 'get', '/' + route + '/:id', getData, resource.respond.bind(resource), admin_required);
/**
* Retrieves data from analytic with id = :id
* @param req
* @param res
* @param next
*/
function getData(req, res, next) {
var _id = req.path.substr(req.path.lastIndexOf('/') + 1);
Data.findById(_id, function (err, data) {
if (err) return resource.setResponse(res, error, next);
else {
switch (data.name) {
case "subunsub":
res.status(200).json({
"error": false,
"data": {
"chart": data,
"url": process.env.CURRENT_DOMAIN + "/data"
}
});
break;
case "lastAccess":
request({
method: 'GET',
url: process.env.CURRENT_DOMAIN + '/users/last',
headers: {
'Content-type': 'application/json',
'Authorization': 'Bearer ' + jwt.sign(req.payload, process.env.MY_SECRET)
}
}, function (error, response, body) {
Data.findById(_id, function (err, data) {
data.chart = JSON.parse(body);
data.save();
});
return resource.setResponse(res, {
"status": 200,
"item": {
"error": false,
"data": {
"chart": JSON.parse(body),
"url": process.env.CURRENT_DOMAIN + "/data"
}
}
}, next);
}).end();
break;
case "tweets":
var tweet_app = 0, tweet_total = 0;
request({
method: 'GET',
url: process.env.CURRENT_DOMAIN + '/users',
headers: {
'Content-type': 'application/json',
'Authorization': 'Bearer ' + jwt.sign(req.payload, process.env.MY_SECRET)
}
}, function (error, response, body) {
JSON.parse(body).forEach(function (user) {
tweet_app += user.tweet_app ? user.tweet_app : 0;
tweet_total += user.tweet_total ? user.tweet_total : 0;
});
data.chart = [tweet_app, tweet_total];
data.save();
return resource.setResponse(res, {
"status": 200,
"item": {
"error": false,
"data": {
"chart": data,
"url": process.env.CURRENT_DOMAIN + "/data"
}
}
}, next);
});
break;
case "tweetsxuser":
request({
method: 'GET',
url: process.env.CURRENT_DOMAIN + '/users/tweets',
headers: {
'Content-type': 'application/json',
'Authorization': 'Bearer ' + jwt.sign(req.payload, process.env.MY_SECRET)
}
}, function (error, response, body) {
return resource.setResponse(res, {
"status": 200,
"item": {
"error": false,
"data": {
"chart": JSON.parse(body),
"url": process.env.CURRENT_DOMAIN + "/data"
}
}
}, next);
});
break;
}
}
})
}
/**
* Resets the analytic with id = _id to 0
* @param req
* @param res
* @param next
*/
function resetData(req, res, next) {
var _id = req.path.substr(req.path.lastIndexOf('/') + 1);
Data.findById(_id, function (err, data) {
if (err) {
return resource.setResponse(res, error, next);
} else {
var my_data = _.cloneDeep(data);
my_data = my_data.toObject();
data.remove();
delete my_data._id;
switch (my_data.name) {
case 'subunsub':
my_data.chart[0] = 0; // Subs
my_data.chart[1] = 0; // Unsubs
break;
case 'lastAccess':
my_data.chart = []; // Users list
break;
case 'tweets':
my_data.chart[0] = 0; // App tweets
my_data.chart[1] = 0; // Total tweets
break;
case 'tweetsxuser':
my_data.chart = []; // Tweets per user
break;
}
new Data(my_data).save(function (err) {
if (err) return resource.setResponse(res, error, next);
else {
return resource.setResponse(res, {
"status": 200,
"item": {
"error": false,
"data": {
"message": "Restarted.",
"url": process.env.CURRENT_DOMAIN + "/data"
}
}
}, next);
}
})
}
});
}
// Return middleware.
return function (req, res, next) {
next();
};
};
})();
|
import { message } from 'antd';
import { find } from '../services/userList';
export default {
namespace: 'userList',
state: {
isLoading: false,
listData: {
list: [],
pagination: {
currentPage: 1,
pageSize: 10,
},
},
formValues: {
nickName: '',
},
},
effects: {
*find({ payload }, { call, put }) {
yield put({
type: 'setLoading',
payload: true,
});
yield put({
type: 'setFormValues',
payload: {
nickName: payload.nickName,
},
});
const response = yield call(find, payload);
if (response.success) {
yield put({
type: 'setListData',
payload: response.data,
});
} else {
message.error(response.data);
}
// console.log(response);
// redirect on client when network broken
// yield put(routerRedux.push(`/exception/${payload.code}`));
// yield put({
// type: 'trigger',
// payload: payload.code,
// });
},
},
reducers: {
setFormValues(state, { payload }) {
return {
...state,
formValues: { ...payload },
};
},
setLoading(state, { payload }) {
return {
...state,
isLoading: !!payload,
};
},
setListData(state, { payload }) {
return {
...state,
listData: { ...payload },
isLoading: false,
};
},
},
};
|
import React, { Component } from 'react';
const style = {
topic : {
paddingTop : 10
},
info : {
paddingBottom : 20,
paddingLeft : 10,
paddingRight : 10
}
}
class Desc extends Component {
render(){
return (
<div className='description'>
<h1 style={style.topic}> React Search </h1>
<h4 style={style.info}>
This is a simple real-time search to practise react :)
</h4>
</div>
);
}
};
export default Desc;
|
define([
"ember",
"text!templates/settings.html.hbs",
"gui/fileselect"
], function( Ember, Template, guiFileselect ) {
return Ember.View.extend({
template: Ember.Handlebars.compile( Template ),
tagName: "main",
classNames: [ "content", "content-settings" ],
didInsertElement: function() {
guiFileselect( this.$() );
}
});
});
|
let audios;
let keys;
const className = 'active';
const allowedKeys = ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'];
window.addEventListener('load', () => {
audios = document.querySelectorAll('.audio');
keys = document.querySelectorAll('.key');
keys.forEach((key, index) => {
key.addEventListener('click', () => {
audios[index].currentTime = 0;
audios[index].play();
});
});
});
document.addEventListener('keydown', e => {
e.preventDefault(); // prevents firing search on firefox when key is being pressed
if (!allowedKeys.includes(e.key.toUpperCase())) return;
const newAudios = Array.from(audios); // converts node list to array
const index = newAudios.findIndex(i => i.parentNode.innerText === e.key.toUpperCase());
handleClass(keys[index]);
audios[index].currentTime = 0;
audios[index].play();
});
const handleClass = el => {
el.classList.add(className);
el.addEventListener('animationend', () => {
el.classList.remove(className);
});
};
|
const Pessoa = require('./Pessoa')
class Arquiteto extends Pessoa
{
constructor(nome,sexo,anoExperiencia)
{
super(nome,sexo)
this.anoExperiencia = anoExperiencia;
}
getAnoExperiencia() { return this.anoExperiencia}
setAnoExperiencia(anoExperiencia) { this.anoExperiencia = anoExperiencia}
}
module.exports = Arquiteto;
|
import mongoose from 'mongoose';
import softDelete from 'mongoose-softdelete'
import mongoosePaginate from 'mongoose-paginate-v2';
import uniqueValidator from 'mongoose-unique-validator';
const Schema = mongoose.Schema
const RoleSchema = new Schema({
name: { type: String, unique : true, required : true, index: true },
permissions: [{ type: String, required: true }],
childRoles: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Role',
required: false,
}]
});
RoleSchema.plugin(uniqueValidator, {message: 'validation.unique'});
RoleSchema.plugin(softDelete);
RoleSchema.plugin(mongoosePaginate);
RoleSchema.set('toJSON', { getters: true });
const RoleModel = mongoose.model('Role', RoleSchema);
module.exports = RoleModel
|
var React = require("react");
var YouTube = require('react-youtube');
var Video = React.createClass({
render: function () {
var opts = {
height: '390',
width: '640',
playerVars: { // https://developers.google.com/youtube/player_parameters
autoplay: 1
}
};
return (
<div>
<YouTube
videoId={this.props.code}
opts={opts}
onReady={this._onReady}
/></div>
);
},
_onReady: function (event) {
// access to player in all event handlers via event.target
event.target.pauseVideo();
}
});
module.exports = Video;
|
import { ref } from 'config/constants'
function saveToDucks (duck) {
// const duckId = ref.database().ref('ducks').push().key()
// const duckPromise = ref.database.ref(`ducks/${duckId}`).set({...duck, duckId})
// return {
// duckId,
// duckPromise,
// }
// var newPostKey = firebase.database().ref().child('posts').push().key;
const duckId = ref.database().ref().child('ducks').push().key
console.log(duck)
const duckPromise = ref.database().ref(`ducks/${duckId}`).set({...duck, duckId})
console.log(duckId)
return {
duckId,
duckPromise,
}
}
function saveToUsersDucks (duck, duckId) {
return ref.database().ref().child(`usersDucks/${duck.uid}/${duckId}`)
.set({...duck, duckId})
}
function saveLikeCount (duckId) {
return ref.database().ref().child(`likeCount/${duckId}`).set(0)
}
export function saveDuck (duck) {
const { duckId, duckPromise } = saveToDucks(duck)
return Promise.all([
duckPromise,
saveToUsersDucks(duck, duckId),
saveLikeCount(duckId),
]).then(() => ({...duck, duckId}))
}
export function listenToFeed (cb, errorCB) {
ref.database().ref().child('ducks').on('value', (snapshot) => {
const feed = snapshot.val() || {}
const sortedIds = Object.keys(feed).sort((a, b) => feed[b].timestamp - feed[a].timestamp)
cb({feed, sortedIds})
}, errorCB)
}
|
console.log('Hola');
Momento = new Date();
dia= document.getElementById('diaS').innerHTML= momento.getMinutes();
|
import React from 'react';
import PropTypes from 'prop-types';
import AddImageComp from './AddImageComp';
import '../styles/flashcard.css';
import Client from './Client';
import done from '../img/buttons/done_FFFFFF.png';
import english from '../img/buttons/english_FFFFFF.png';
import spanish from '../img/buttons/spanish_FFFFFF.png';
import order from '../img/buttons/order_FFFFFF.png';
class EditCardComp extends React.Component {
constructor(props) {
super(props);
this.state = {
currentCard: '',
currentL1: '',
currentL2: '',
currentOrder: 0,
currentImageUrl: 'https://d30y9cdsu7xlg0.cloudfront.net/png/77680-200.png',
currentImageId: 77680,
addImage: false,
styleImage: 'cardContainer',
};
}
componentDidMount = () => {
const { card } = this.props;
this.setState({
currentL1: card.L1_word,
currentL2: card.L2_word,
currentImageUrl: card.img_url,
currentImageId: card.img_id,
currentOrder: card.card_order,
});
}
handleL1Change = (event) => {
this.setState({ currentL1: event.target.value });
};
handleL2Change = (event) => {
this.setState({ currentL2: event.target.value });
};
handleOrderChange = (event) => {
this.setState({ currentOrder: event.target.value });
};
handleEditCardClick = () => {
const { card, onCardEdited } = this.props;
const {
currentL1,
currentL2,
currentOrder,
currentImageUrl,
currentImageId,
} = this.state;
Client.editCard(card.card_id, currentL1, currentL2, currentOrder,
currentImageUrl, currentImageId)
.then((id) => {
onCardEdited(id);
});
};
handleImageAdded = (imageUrl, imageId) => {
console.log(`image url: ${imageUrl} image id: ${imageId}`);
this.setState({
currentImageUrl: imageUrl,
currentImageId: imageId,
addImage: false,
styleImage: 'cardContainer',
});
}
handleImageClick = () => {
this.setState({ addImage: true });
}
render() {
const {
currentL1,
currentL2,
currentOrder,
currentImageId,
currentImageUrl,
addImage,
styleImage,
} = this.state;
return (
<div className="EditCardComp">
{ (addImage !== true)
? (
<div className="AddImage">
<div className="LineContainer">
<button
className={styleImage}
type="button"
onClick={this.handleImageClick}
onKeyPress={this.handleItemClick}
>
<img
className="cardImg"
src={currentImageUrl}
alt={currentImageId}
/>
</button>
</div>
<br />
<div>
<div className="LineContainer">
<img className="btnImg" src={english} alt="English" />
<input className="L1Input DetailText" value={currentL1} onChange={this.handleL1Change} />
<br />
</div>
<div className="LineContainer">
<img className="btnImg" src={spanish} alt="Spanish" />
<input className="L2Input DetailText" value={currentL2} onChange={this.handleL2Change} />
</div>
<div className="LineContainer">
<img className="btnImg" src={order} alt="Order" />
<input className="Order DetailText" type="Number" value={currentOrder} onChange={this.handleOrderChange} />
</div>
<div className="LineContainer">
<button className="DoneBtn AppBtn" type="button" onClick={this.handleEditCardClick}>
<img className="btnImg" src={done} alt="Done" />
</button>
</div>
</div>
<br />
<span className="DetailText">Image:</span>
<p>Url:{currentImageUrl} id:{currentImageId}</p>
<img className="btnImg" src={currentImageUrl} alt={currentImageId} />
</div>
)
: <AddImageComp onImageAdded={this.handleImageAdded} />
}
</div>
);
}
}
EditCardComp.defaultProps = {
onCardEdited: () => { },
card: {
L1_word: '',
L2_word: '',
img_id: 0,
img_url: '',
card_order: 0,
cardtype_id: '',
},
};
EditCardComp.propTypes = {
card: PropTypes.shape({
card_id: PropTypes.string.isRequired,
deck_id: PropTypes.string.isRequired,
L1_word: PropTypes.string,
L2_word: PropTypes.string,
img_id: PropTypes.number,
img_url: PropTypes.string,
card_order: PropTypes.number,
cardtype_id: PropTypes.string,
}),
onCardEdited: PropTypes.func,
};
export default EditCardComp;
|
import React, { useState } from 'react';
import './App.css';
import Person from './Person.js';
const Appl = props => {
const [personState,setPersonState] = useState({
person:[
{"name":"sai","age":34},
{"name":"sudha","age":33},
{"name":"sidhu","age":14}
]
})
const switchNameHandler = () =>{
setPersonState({
person:[
{"name":"ganesan","age":34},
{"name":"muthu","age":33},
{"name":"sidhu","age":14}
]
})
}
return (
<div className="App">
<button onClick={switchNameHandler}>Switch name</button>
<h1>Hi, My name is sai siddharth.</h1>
<Person name={personState.person[0].name} age={personState.person[0].age}/>
<Person name={personState.person[1].name} age={personState.person[1].age}/>
<Person name={personState.person[2].name} age={personState.person[2].age}/>
</div>
);
}
export default Appl;
|
const Styles = () => (
<style jsx="true">{`
.boost-publisher-container {
height: 100%;
width: 100vw;
background: rgba(0, 0, 0, 0.5);
display: flex;
flex-direction: column;
position: fixed;
bottom: 0;
}
.boost-publisher-grow {
flex-grow: 1;
}
.boost-publisher-wrapper {
display: flex;
position: fixed;
bottom: 0;
width: 100%;
}
.boost-publisher {
width: 600px;
max-width: calc(100% - 24px);
background: white;
border-radius: 6px 6px 0 0;
}
.boost-publisher-header {
padding: 16px;
display: flex;
align-items: center;
}
.input-content-container {
padding-bottom: 1em;
}
.input-diff-container {
padding-bottom: 1em;
}
.rank-message {
padding-top: 1em;
}
.label {
font-size: 1.1em;
}
.input-content {
padding: 10px;
border: solid 1px #eee;
border-radius: 6px;
display: block;
width: 100%;
font-size: 1.1em;
}
.input-diff {
padding: 10px;
border: solid 1px #eee;
border-radius: 6px;
display: inline-block;
font-size: 1.1em;
margin: 10px;
}
.boost-publisher-logo {
height: 60px;
}
.boost-logo-text {
display: inline-block;
font-size: 1.4em;
font-weight: bold;
letter-spacing: 1px;
padding-left: 10px;
}
.boost-publisher-close {
font-size: 18px;
line-height: 21px;
color: #bdbdbd;
margin: 0;
padding: 4px 8px;
border: none;
border-radius: 2px;
background-color: transparent;
font-weight: normal;
cursor: pointer;
}
.boost-publisher-close:focus {
outline: none;
}
.boost-publisher-close:hover {
background-color: #eee;
}
.boost-publisher-body {
padding: 16px;
border-top: 2px solid #f2f2f2;
min-height: 90px;
padding-bottom: 0;
}
p.lead {
font-size: 1.1em;
}
.boost-publisher-form-control {
margin-top: 0;
margin-bottom: 0;
}
.pow-help-text {
text-decoration: underline;
color: #696969;
font-size: 0.8em;
}
.boost-publisher-select {
color: #696969;
font-size: 14px;
line-height: 17px;
}
.boost-rank-display {
text-align: center;
}
.boost-rank-display span {
font-weight: 600;
font-size: 1.3em;
letter-spacing: -1px;
}
.boost-publisher-menu-list {
padding: 0;
}
.boost-publisher-menu-item {
font-size: 14px;
line-height: 20px;
color: #696969;
padding: 12px;
}
.boost-publisher-menu-item-selected {
color: #ffffff;
background-color: #085af6 !important;
}
.boost-publisher-select-outlined {
border: 1px solid #f2f2f2 !important;
}
.MuiOutlinedInput-notchedOutline {
border-color: #f2f2f2 !important;
border-width: 1px !important;
}
.MuiSlider-marked {
margin-bottom: 8px;
}
.MuiSlider-root {
margin-top: 3em;
}
.contentPreview {
text-align: center;
}
.contentPreview img {
width: 320px;
margin: 0 auto;
}
.contentPreview textarea {
width: 100%;
max-height: 300px;
overflow-y: scroll;
padding: 1em;
margin: 0 auto;
}
.contentPreview embed {
width: 100%;
padding: 1em;
margin: 0 auto;
}
.markdownPreview {
width: 100%;
padding: 1em;
margin: 0 auto;
max-height: 300px;
height: 300px;
border: 1px solid #ccc;
border-radius: 0.5em;
overflow-y: scroll;
}
media only screen and (min-width: 600px) {
.contentPreview img {
max-height: 200px;
width: auto;
margin: 0 auto;
}
.contentPreview video {
max-height: 200px;
width: auto;
margin: 0 auto;
}
}
@media only screen and (max-width: 600px) {
.pdfPreview {
height: 400;
width: 300;
}
.contentPreview {
padding: 1em;
text-align: center;
}
.contentPreview img {
max-height: 100px;
width: auto;
margin: 0 auto;
}
.contentPreview video {
height: 100px;
width: 300px;
margin: 0 auto;
}
.contentPreview textarea {
width: 100%;
max-height: 100px;
overflow-y: scroll;
padding: 1em;
margin: 0 auto;
}
.contentPreview embed {
width: 100%;
height: 100px;
padding: 1em;
margin: 0 auto;
}
.markdownPreview {
width: 100%;
padding: 1em;
margin: 0 auto;
max-height: 100px;
height: 100px;
border: 1px solid #ccc;
border-radius: 0.5em;
overflow-y: scroll;
}
}
#boostpow-slider {
margin-left: 15px;
margin-right: 30px;
margin-bottom: 0;
padding-bottom: 0;
}
#boostpow-slider .inline-diff-selector {
padding: 4px;
}
#boostpow-slider .slider-message {
margin-bottom: 45px;
}
.display-ranks-toggle {
text-decoration: underline;
cursor: pointer;
}
.display-ranks-toggle:before {
content:'\\25B8'
}
.display-ranks-toggle.opened:before {
content:'\\25BE'
}
#display-ranks-container {
width: 100%;
max-height: 150px;
overflow-y: scroll
}
table.display-ranks {
width: 100%;
font-size: 0.8em;
margin-top: 15px;
}
table.display-ranks th, table.display-ranks td {
text-align: center;
}
table.display-ranks th {
font-weight: 600;
font-size: .9em;
}
table.display-ranks td {
border-bottom: 1px solid #eee;
}
.display-ranks-close {
cursor: pointer;
font-size: 1.4em;
}
.display-ranks-close:hover {
text-decoration: 'underline';
font-weight: 600;
}
#boostpow-topic,
#boostpow-categories,
#boostpow-price {
display: block;
height: 50px;
margin-top: 5px;
}
#boostpow-topic div,
#boostpow-categories div,
#boostpow-price div {
float: left;
}
#boostpow-topic div:first-child,
#boostpow-categories div:first-child,
#boostpow-price div:first-child {
min-width: 100px;
width: 15%;
padding-top: 5px;
font-weight: 500;
}
#boostpow-topic div:last-child,
#boostpow-categories div:last-child,
#boostpow-price div:last-child {
width: 75%;
max-width: 80%;
float: right;
}
#boostpow-price {
margin-top: 1em;
}
.boost-publisher-footer {
margin-top: 1.5em;
margin-bottom: 3.5em;
}
.wallet-selector {
width: 43%;
float: left;
text-align: right;
display: block;
height: 70px;
padding-top: 5px;
}
.wallet-button {
width: 55%;
float: right;
display: block;
height: 70px;
}
.payment-completed-section {
margin-top: 1vh;
width: 100%;
display: block;
clear: both;
}
.boost-publisher-bumper {
height: 2vh;
}
`}</style>
);
export default Styles;
|
import React, { Component } from 'react'
import { func } from 'prop-types'
import { View } from '../Native'
import { Icon, Layout } from 'antd'
import { TabBar } from 'antd-mobile'
import { translate } from 'react-i18next'
import { Shop } from '../../pages/shop'
import { IconButton } from '../IconButton'
import { SettingContainer } from 'Features/setting'
import 'Styles/styles.less'
import styles from './styles'
const { Content } = Layout
class AppMobile extends Component {
static propTypes = {
t: func.isRequired,
}
constructor(props) {
super(props);
this.state = {
selectedTab: 'Home',
hidden: false,
}
}
renderContent = (key) => {
switch(key) {
case 'Shop':
return <Shop.Home />
case 'Setting':
return <SettingContainer />
default:
return <Shop.Create />
}
}
render() {
const { t } = this.props
const tabs = [
{
key: 'Home',
title: t('home'),
icon: 'home',
},
{
key: 'Shop',
title: t('shop'),
icon: 'shopping-cart',
},
{
key: 'Notificaction',
title: t('notification'),
icon: 'bell',
},
{
key: 'Setting',
title: t('setting'),
icon: 'setting',
}
]
return (
<Layout style={styles.height('100vh')} >
<Content>
<div style={styles.containerMobile}>
<TabBar
unselectedTintColor="#949494"
tintColor="#33A3F4"
barTintColor={'white'}
hidden={this.state.hidden}
>
{
tabs.map(item => (
<TabBar.Item
title={item.title}
key={item.key}
icon={<Icon type={item.icon} style={styles.fontSize(22)} />}
selectedIcon={<Icon type={item.icon} style={styles.fontSize(22)} />}
selected={this.state.selectedTab === item.key}
onPress={() => this.setState({ selectedTab: item.key })}
data-seed="logId"
>
{this.renderContent(item.key)}
</TabBar.Item>
))
}
</TabBar>
<View style={styles.btnFloating}>
<IconButton type='primary' color='primary' textColor='white' onPress={() => alert('Test')} />
</View>
</div>
</Content>
</Layout>
)
}
}
export default translate()(AppMobile)
|
import { INIT_STATE } from '../store';
import { countReducer } from './documents';
export default function rootReducer(state = INIT_STATE, action) {
return {
docCount: countReducer(state.docCount, action),
};
}
|
import React, {Component} from 'react';
import {
StyleSheet,
Animated,
View,
Text,
SafeAreaView,
PanResponder,
} from 'react-native';
import Svg, {Path, Circle, Rect, Image} from 'react-native-svg';
import ModelView from 'react-native-gl-model-view';
const AnimatedModelView = Animated.createAnimatedComponent(ModelView);
import ReactGlobe from 'react-globe';
import THREE from 'three';
var RNFS = require('react-native-fs');
import RNFetchBlob from 'rn-fetch-blob';
import {WebView} from 'react-native-webview';
export default class App extends Component {
constructor() {
super();
this.state = {
rotateX: new Animated.Value(-90),
rotateZ: new Animated.Value(0),
fromXY: undefined,
valueXY: undefined,
};
}
onMoveEnd = () => {
this.setState({
fromXY: undefined,
});
};
onMove = (e) => {
let {pageX, pageY} = e.nativeEvent,
{rotateX, rotateZ, fromXY, valueXY} = this.state;
if (!this.state.fromXY) {
this.setState({
fromXY: [pageX, pageY],
valueXY: [rotateZ.__getValue(), rotateX.__getValue()],
});
} else {
rotateZ.setValue(valueXY[0] + (pageX - fromXY[0]) / 2);
rotateX.setValue(valueXY[1] + (pageY - fromXY[1]) / 2);
}
};
renderChildren = () => {
return (
<View style={styles.container} {...this.panResponder.panHandlers}>
<View
ref={(component) => (this.refView = component)}
style={styles.rotateView}>
<Text>sss</Text>
</View>
</View>
);
};
componentWillMount() {
this.panResponder = PanResponder.create({
onMoveShouldSetPanResponder: () => true,
onPanResponderMove: this.handlePanResponderMove.bind(this),
});
}
handlePanResponderMove(e, gestureState) {
const {dx, dy} = gestureState;
const y = `${dx}deg`;
const x = `${-dy}deg`;
this.refView.setNativeProps({
style: {transform: [{perspective: 1000}, {rotateX: x}, {rotateY: y}]},
});
}
SimpleGlobe = () => {
return <ReactGlobe />;
};
render() {
let {rotateZ, rotateX, fromXY} = this.state;
return (
<SafeAreaView style={{flex: 1}}>
<AnimatedModelView
model={{
uri: 'Globe.obj',
}}
texture={{uri: 'albedo_defuse.png'}}
onStartShouldSetResponder={() => true}
onResponderRelease={this.onMoveEnd}
onResponderMove={this.onMove}
animate={!!fromXY}
tint={{r: 1.0, g: 1.0, b: 1.0, a: 1.0}}
scale={0.2}
rotateX={rotateX}
rotateZ={rotateZ}
translateZ={-4}
style={styles.container}
/>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'transparent',
// width: 200,
// height: 200,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
overflow: 'hidden',
},
rotateView: {
width: 100,
height: 100,
backgroundColor: 'white',
shadowOffset: {height: 1, width: 1},
shadowOpacity: 0.2,
},
});
//s
|
import React, { Component } from 'react';
//import logo from './logo.svg';
import Workshops from './components/Workshopsm'
import './App.css';
import Axios from 'axios';
import { withStyles } from '@material-ui/core/styles';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
//import { logoutUser } from '../globalState/actions/authentication';
import PropTypes from 'prop-types';
class WorkshopApp extends Component {
getStyleWork = () => {
return {
backgroundColor : '#000',
color : '#f0f0f0'
}
}
constructor(props){
super(props)
this.state={
workshop:[],
error:false,
loading:true,
clicked:false,//yara amr
}
}
// Choose = (id)=>{
// this.setState(
// { workshop : this.state.workshop.map( current => {
// if(current._id===id ) {
// if(clicked===false){
// clicked==true;
// var s=''
// current.choice=!current.choice
// current.title=s
// for (var key in current) {
// if (current.hasOwnProperty(key)) {
// s+=(key + " : " + current[key]);
// }
// }
// }
// else{
// clicked==false;
// }
// }
// return current
// }) })
// }
// delMasterclass= (id)=> {
// this.setState(
// { workshop:[...this.state.workshop.filter((current)=>current._id!==id)]
// })
// }
componentDidMount() {
Axios
.get('http://localhost:5000/api/workshops')
.then(res=> this.setState({workshop:res.data.data,loading:false}))
.catch(error=> this.ERROR.bind(error))
}
delWorkshops =(_id) => {
Axios.delete(`http://localhost:5000/api/workshops/${_id}`)
window.location.reload()
console.log(_id)
}
updateWorkshops =(_id) => {
this.props.history.push(`workshop/updateWorkshop/${_id}`);
console.log(_id)
}
applyWorkshop=(_id) => {
// const { user} = this.props.auth;
const mem =this.state.id;
const tokenB= localStorage.getItem('jwtToken');
var schema = {};
schema["applicantId"] = mem
Axios.put(`http://localhost:5000/api/workshops/${_id}/apply/`,schema)
.then(res =>alert(res.data.err))
console.log(_id+"mayar")
}
onClick=() =>{
this.props.history.push("/workshop/createWorkshop")
}
render(){
const {user} = this.props.auth;
this.state.id={user}.user.id;
return this.state.error?<h1>process couldnot be complete</h1>:this.state.loading?
<h1>loading please be patient</h1>
:
(<div className='WorkshopApp'>
<h2 style={this.getStyleWork()}>WORKSHOPS</h2>
<p><button onClick={this.onClick} style={btnStyle1}>create workshop</button></p>
<Workshops workshop={this.state.workshop} applyWorkshop={this.applyWorkshop} />
</div>
)
}
ERROR=(error)=>{
console.log(error)
this.setState({error:true})
}
}
WorkshopApp.propTypes = {
logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
}
const mapStateToProps = (state) => ({
auth: state.auth
})
const btnStyle1={
background:'grey',
color:'black',
fontSize: 20,
borderColor: 'black',
borderWidth: 3,
padding:'5px 10px',
}
const btnStyle={
background:'#f4f4f4f4',
color:'#000'
}
//export default WorkshopApp;
export default connect(mapStateToProps)(withRouter(WorkshopApp));
|
(function ( $ ) {
/*
*
*
*/
$.fn.validCpfCnpj = function(options){
//Opções
var settings = $.extend({
cpfOrCnpj: 'all', // cpf , cnpj
removeMask :false
}, options );
var obj = $(this);
obj.focusout(function() {
var value = obj.val().replace(/\-|\.|\/|\(|\)| /g, "");
if(settings.removeMask){
obj.val(value);
obj.inputmask('unmaskedvalue');
}
if(!$.isNumeric(value)){
obj.closest('.form-group').addClass('has-error');
obj.val('');
}
if(value.length <= 10 ){
obj.val('');
}else{
if( value.length == 11 ){
var valida = ValidarCPF(value);
if( valida != true ){
obj.closest('.form-group').addClass('has-error');
obj.val('');
obj.focus();
jsAlertBox('error','CPF Inválido!','Numero do CPF é Inválido!');
}else{
obj.closest('.form-group').removeClass('has-error');
}
}
if( value.length == 14 ){
var valida = ValidarCNPJ(value);
if( valida != true ){
obj.closest('.form-group').addClass('has-error');
obj.val('');
obj.focus();
jsAlertBox('error','CNPJ Inválido!','Numero do CNPJ é Inválido!');
}else{
obj.closest('.form-group').removeClass('has-error');
}
}
if( value.length >= 15 || value.length <= 10 ){
obj.closest('.form-group').addClass('has-error');
obj.val('');
jsAlertBox('error','Inválido!','Numero informado é Inválido!');
}
}
});
}
function ValidarCNPJ(cnpj){
if (cnpj.length != 14 || cnpj == "00000000000000" || cnpj == "11111111111111" || cnpj == "22222222222222" || cnpj == "33333333333333" || cnpj == "44444444444444" || cnpj == "55555555555555" || cnpj == "66666666666666" || cnpj == "77777777777777" || cnpj == "88888888888888" || cnpj == "99999999999999")
return false;
var valida = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2);
var dig1= new Number;
var dig2= new Number;
exp = /\.|\-|\//g
cnpj = cnpj.toString().replace( exp, "" );
var digito = new Number(eval(cnpj.charAt(12)+cnpj.charAt(13)));
for(i = 0; i<valida.length; i++){
dig1 += (i>0? (cnpj.charAt(i-1)*valida[i]):0);
dig2 += cnpj.charAt(i)*valida[i];
}
dig1 = (((dig1%11)<2)? 0:(11-(dig1%11)));
dig2 = (((dig2%11)<2)? 0:(11-(dig2%11)));
if(((dig1*10)+dig2) != digito){
return false;
}
return true
}
function ValidarCPF(cpf) {
cpf = cpf.replace(/[^\d]+/g,'');
if(cpf == '') return false;
// Elimina CPFs invalidos conhecidos
if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999")
return false;
// Valida 1o digito
add = 0;
for (i=0; i < 9; i ++)
add += parseInt(cpf.charAt(i)) * (10 - i);
rev = 11 - (add % 11);
if (rev == 10 || rev == 11)
rev = 0;
if (rev != parseInt(cpf.charAt(9)))
return false;
// Valida 2o digito
add = 0;
for (i = 0; i < 10; i ++)
add += parseInt(cpf.charAt(i)) * (11 - i);
rev = 11 - (add % 11);
if (rev == 10 || rev == 11)
rev = 0;
if (rev != parseInt(cpf.charAt(10)))
return false;
return true;
}
$.fn.validPis = function(options){
var obj = $(this);
obj.focusout(function() {
var ftap="3298765432";
var total=0;
var i;
var resto=0;
var numPIS=0;
var strResto="";
numPIS = obj.val();
if ( numPIS=="" || numPIS == null){
obj.closest('.form-group').addClass('has-error');
obj.val('');
return false;
}
for(i=0;i<=9;i++){
resultado = (numPIS.slice(i,i+1))*(ftap.slice(i,i+1));
total=total+resultado;
}
resto = (total % 11)
if (resto != 0) {
resto=11-resto;
}
if (resto==10 || resto==11) {
strResto=resto+"";
resto = strResto.slice(1,2);
}
if (resto!=(numPIS.slice(10,11))){
obj.closest('.form-group').addClass('has-error');
obj.val('');
jsAlertBox('error','PIS Inválido!','Numero do PIS é Inválido!');
return false;
}
obj.closest('.form-group').removeClass('has-error');
return true;
});
}
}( jQuery ));
|
export const Purpose = [
'Education Expenses',
'EMI Payment',
'Business Loan Or Interest Payment',
'Medical Expenses',
'Professional Services',
'Rent Payment',
'Repai And Maintenance',
'Salary',
'Utility Payments',
'Other',
];
export const Relation = [
'Spouse',
'Mother',
'Father',
'Brother',
'Friend',
'Relatives',
];
|
import Taro, { Component } from '@tarojs/taro'
import dayjs from 'dayjs'
import { connect } from '@tarojs/redux'
import { View, Button, Text, Input, Picker } from '@tarojs/components'
import { AtList, AtListItem, AtIcon, AtButton } from 'taro-ui'
import { OrderCell } from '../../../components/OrderCell'
import './index.scss'
@connect(({ order }) => ({
...order,
}))
export default class Detail extends Component {
config = {
navigationBarTitleText: '销售订单',
}
componentDidMount = () => {
this.props.dispatch({
type: 'order/init'
})
}
handleBillTagsChange(orderTags) {
this.props.dispatch({
type: 'order/save',
payload: {
orderTags
}
})
}
handleCommonChange(type, e) {
let payload, value = e.detail.value
switch (type) {
case 'payment':
payload = {
paymentMethod: this.props.payTypes[value]
}
break;
case 'storekeeper':
payload = {
storekeeper: this.props.storekeeperList[value]
}
break;
case 'remark':
payload = {
remark: value
}
break;
default:
break;
}
this.props.dispatch({
type: 'order/save',
payload
})
}
handleBillDateChange(value) {
this.props.dispatch({
type: 'order/save',
payload: {
billDate: dayjs(value.detail.value).format('YYYY-MM-DD')
}
})
}
handleSave() {
let { dispatch, billDate, orderTags, customer, products, remark, staff, paymentMethod } = this.props
if (!customer.FID) {
Taro.showToast({title: '请选择客户', icon: 'none'})
return
}
if (products.length <= 0) {
Taro.showToast({title: '请选择商品', icon: 'none'})
return
}
// 奇葩需求和奇葩api
billDate = dayjs()
.set('month', billDate.split('-')[1] - 1)
.set('date', billDate.split('-')[2])
.valueOf()
let payload = {
billDate: dayjs(billDate).format('YYYY-MM-DD'),
orderTags,
customer,
products,
remark,
creator: staff.userId,
paymentMethod
}
dispatch({
type: 'order/create',
payload
}).then(isCreated => {
if (isCreated) {
dispatch({
type: 'order/empty'
})
Taro.showToast({ title: '创建成功' })
setTimeout(() => {
Taro.switchTab({ url: '/pages/list/index' })
}, 2000)
} else {
Taro.showToast({ title: '创建失败' })
}
})
}
handleAgain() {
this.props.dispatch({
type: 'order/empty'
})
Taro.showToast({
title: '再开一单'
})
}
handleNavigate(path) {
Taro.navigateTo({
url: path
})
}
handleNavProdSel() {
Taro.navigateTo({ url: '/pages/selections/products/index?prevModel=order' })
}
handleNavCustSel() {
Taro.navigateTo({ url: '/pages/selections/customers/index?prevModel=order' })
}
handleScanCode() {
Taro.scanCode().then((data) => {
console.log(data)
Taro.showToast({
title: '扫描成功'
})
})
}
handleRemoveItem(index) {
const { dispatch } = this.props;
dispatch({
type: 'order/removeProduct',
payload: { index },
})
this.forceUpdate()
}
handleSyncOrder = () => {
Taro.showToast({
icon: 'none',
title: '请先保存再同步'
})
}
render() {
const { products, customer, remark, staff } = this.props
const amountRRR = this.props.products.reduce((sum, item) => sum += item.amount, 0).toFixed(2)
return (
<View className='order-page'>
<View className='order-wrapper'>
<Picker className='date-selector' mode='date' onChange={this.handleBillDateChange}>
<View className='picker'>
{this.props.billDate}
<AtIcon value='chevron-right' size='26' color='#c7c7cc'></AtIcon>
</View>
</Picker>
<AtList>
<AtListItem
title='日期'
iconInfo={{
size: 28,
color: '#999',
value: 'clock',
}}
/>
<AtListItem
onClick={this.handleNavCustSel}
className='custom-listItem'
title='客户'
extraText={customer.CustomerName}
arrow='right'
iconInfo={{
size: 28,
color: '#999',
value: 'user',
}}
/>
</AtList>
</View>
<View className='order-content'>
{/* <View>
<Button onClick={this.handleWaiting} style='background-color: rgba(241, 181, 85, 1);' className='custom-button' size='mini'>调用模板</Button>
<Button onClick={this.handleWaiting} style='background-color: #1fb7a6;' className='custom-button' size='mini'>存为模板</Button>
</View> */}
<View></View>
<View>
<Text>选择货品({products.length || 0})</Text>
<Text>开单金额:¥{products.reduce((sum, item) => sum += item.defaultAmount, 0).toFixed(2)}</Text>
</View>
<View>
{products.map((item, index) => (<OrderCell item={item} key={item.FID} index={index} hasIcon={Boolean(true)} onHanleClick={this.handleRemoveItem.bind(this, index)} />) )}
{/* {products.map((item, index) => (
<View key={item.FID} className='order-item'>
<Image className='m-img' src={item.MaterialUrl}></Image>
<View>
<Text>{item.MaterialName}</Text>
<View className='order-cell'>
<Text>单价:¥{Number(item.MaterialPrice).toFixed(2)}</Text>
<Text>数量:{Number(item.qty).toFixed(2)}公斤</Text>
</View>
<View className='order-cell'>
<Text>规格:{item.MaterialModel}</Text>
<Text>金额:¥{Number(item.amount).toFixed(2)}</Text>
</View>
</View>
<AtIcon onClick={this.handleRemoveItem.bind(this, index)} value='subtract-circle' size='30' color='#F00'></AtIcon>
</View>
))} */}
</View>
<View>
<Button onClick={this.handleNavProdSel} style='background-color: #1fb7a6;' className='custom-button' size='large'>添加商品</Button>
{/* <Image onClick={this.handleScanCode} src='http://cdn.jerryshi.com/picgo/scanAdd.png' />
<Image
onClick={this.handleNavigate.bind(this, 'productSelect')}
src='http://cdn.jerryshi.com/picgo/plusAdd.png'
/> */}
</View>
</View>
<View className='order-wrapper order-footer'>
<View>
<Text>结算金额</Text>
<Input value={amountRRR} disabled type='digit' placeholder='0.00' className='input-amount'></Input>
</View>
<View>
<Text>结算方式</Text>
<Picker mode='selector' range={this.props.payTypes} rangeKey='name' onChange={this.handleCommonChange.bind(this, 'payment')}>
<View className='picker'>
{this.props.paymentMethod.name}
<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
</View>
</Picker>
</View>
<View>
<Text>业务员</Text>
<Text>{staff.userName}</Text>
</View>
{/* <View>
<Text>出库员</Text>
<Picker mode='selector' range={this.props.storekeeperList} rangeKey='name' onChange={this.handleCommonChange.bind(this, 'storekeeper')}>
<View className='picker'>
{this.props.storekeeper.name}
<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
</View>
</Picker>
</View> */}
<View>
{/* <Text>票据影像</Text>
<View onClick={this.handleWaiting} >
<AtIcon value='camera' size='34' color='#fff'></AtIcon>
</View> */}
</View>
</View>
<View style='background-color: transparent;' className='remark'>
<View>
<Input value={remark} onChange={this.handleCommonChange.bind(this, 'remark')} placeholder='备注(最多100字)'></Input>
</View>
</View>
{/* <View>
<AtCheckbox
style='background-color: #aaa;'
options={this.props.tagList}
selectedList={this.props.orderTags}
onChange={this.handleBillTagsChange}
/>
</View> */}
<View className='toolbar'>
{/* <View onClick={this.handleWaiting.bind(this, '请先保存')} style='padding:8rpx;background-color: rgba(114, 192, 116, 1); border-radius: 14rpx;'>
<AtIcon value='iconfont icon-sharem1' size='34' color='#fff'></AtIcon>
</View> */}
<AtButton onClick={this.handleAgain} size='normal' type='secondary'>再开一单</AtButton>
<AtButton onClick={this.handleSave} size='normal' type='primary'>确认保存</AtButton>
{/* <View onClick={this.handleSyncOrder} style='padding:6rpx;background-color: rgba(112, 159, 239, 1); border-radius: 14rpx;'>
<AtIcon value='iconfont icon-shangchuan' size='36' color='#fff'></AtIcon>
</View> */}
</View>
</View>
)
}
}
|
var _api = require("../../../utils/api.js");
var _api2 = _interopRequireDefault(_api);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Component({
/**
* 组件的属性列表
*/
properties: {
sdCollege: {
type: Array,
value: []
},
showCode: {
type: Boolean,
value: false
}
},
data: {
cityId: wx.getStorageSync("cityId").cityId
},
/**
* 组件的方法列表
*/
methods: {
add: function add(e) {
var _this = this;
var index = e.currentTarget.dataset.index;
if (this.data.showCode) {
var list = wx.getStorageSync("addCollegeList") || [];
if (list.length == 0) {
list.unshift({
collegeName: this.data.sdCollege[index].collegeName,
collegeCode: this.data.sdCollege[index].collegeCode,
uCode: this.data.sdCollege[index].uCode
});
} else {
list.map(function(i) {
if (i.collegeName != _this.data.sdCollege[index].collegeName) {
list.unshift({
collegeName: _this.data.sdCollege[index].collegeName,
collegeCode: _this.data.sdCollege[index].collegeCode,
uCode: _this.data.sdCollege[index].uCode
});
}
});
}
wx.setStorageSync("addCollegeList", list);
wx.navigateBack({
detail: 1
});
} else {
var pages = getCurrentPages();
var prevPage = pages[pages.length - 2];
//上一个页面
this.prevPage = prevPage;
this.prevPage.setData({
isShowViewCount: true
});
var college = this.data.sdCollege[index];
var cityId = wx.getStorageSync("cityId").cityId;
var json = {
provinceId: cityId,
uCode: college.uCode,
isBen: college.isBen,
collegeCode: college.collegeCode,
totalScore: prevPage.data.score.totalScore,
rank: prevPage.data.score.rank,
chooseLevel: wx.getStorageSync("userScore").chooseSubjects || []
};
if (cityId == 847) {
json.section = prevPage.data.batch || 1;
} else if (cityId == 843) {
json.section = 0;
}
_api2.default.DoNewGaoKaoCustomV4("TZY/Recommendation/DoNewGaoKaoCustomV4", "POST", json).then(function(res) {
var newArr = [];
var list = wx.getStorageSync("userScore").chooseSubjects;
var chooseSubjects = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = list[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var l = _step.value;
chooseSubjects.push(l.substring(0, 1));
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
res.result[0].professions.map(function(j) {
// j.learnYear = j.learnYear+'年'
// j.cost = "¥"+j.cost;
if (j && j.chooseSubjects == "且") {
if (j.chooseCns.length > 1) {
newArr = j.chooseCns.split("+");
chooseSubjects.map(function(c) {
newArr.map(function(n) {
if (n == c) {
j.chooseCns = j.chooseCns.replace(c, '<span style="color:black">' + c + "</span>");
}
});
});
} else if (j.chooseCns.length == 1) {
newArr = [ j.chooseCns ];
chooseSubjects.map(function(c) {
newArr.map(function(n) {
if (n == c) {
j.chooseCns = j.chooseCns.replace(c, '<span style="color:black">' + c + "</span>");
}
});
});
}
} else {
if (j.chooseCns.length > 1) {
newArr = j.chooseCns.split("/");
chooseSubjects.map(function(c) {
newArr.map(function(n) {
if (n == c) {
j.chooseCns = j.chooseCns.replace(c, '<span style="color:black">' + c + "</span>");
}
});
});
} else if (j.chooseCns.length == 1) {
newArr = [ j.chooseCns ];
chooseSubjects.map(function(c) {
newArr.map(function(n) {
if (n == c) {
j.chooseCns = j.chooseCns.replace(c, '<span style="color:black">' + c + "</span>");
}
});
});
}
}
});
_this.college = res.result[0];
_this.UseFunctionLogsInsert(college.collegeId);
wx.navigateBack({
detail: 1
});
});
}
},
UseFunctionLogsInsert: function UseFunctionLogsInsert(numId) {
var that = this;
var userInfo = wx.getStorageSync("userInfo");
if (userInfo[0].UserType > 1) {
that.addCollege();
} else {
var data = {
userNumId: userInfo[0].UserId,
functionNumId: numId,
functionType: 1,
userPermissionId: userInfo[0].UserType
};
_api2.default.UseFunctionLogsInsert("Users/UseFunctionLogs/Insert", "POST", data).then(function(res) {
if (res.isSuccess) {
that.addCollege();
that.prevPage.setData({
count: res.result.value
});
} else {
wx.showToast({
title: res.message,
icon: "none"
});
}
});
}
},
addCollege: function addCollege() {
var that = this;
that.prevPage.data.ZCollegeList.collegeList.unshift(that.college);
that.prevPage.setData({
"ZCollegeList.collegeList": that.prevPage.data.ZCollegeList.collegeList
});
}
}
});
|
import './shared.js';
import Vue from 'vue';
import Meals from './vue/Meals.vue';
const MealsComponent = Vue.extend(Meals);
import 'select2';
import 'select2/dist/css/select2.css';
console.log($(document));
$(document).ready(function () {
$("#inputGroupName").select2({
data: groupNames,
minimumResultsForSearch: -1
});
$("#inputMealType").select2({
data: mealTypes,
minimumResultsForSearch: -1
});
var mealsVueInstance = new MealsComponent({
el: '#searchResult',
data: {
meals: [ ]
}
});
$("#searchForm").submit(function (e) {
// prevent usual submit of the form, handle with ajax instead
e.preventDefault();
$("#searchResult").empty();
// Always hide warnings (if displayed) on submit, they will be shown again later if needed.
$("#searchWarning").hide();
var mealType = $("#inputMealType").val();
var groupName = $("#inputGroupName").val();
var hideEaten = $('#hideEatenCheckbox').prop("checked");
$("#searchingSpinner").fadeIn();
mealsVueInstance.meals = [];
$("#searchBtn").prop("disabled", true);
$.get("mealcheck/search", {
groupName : groupName,
mealType : mealType,
hideEaten : hideEaten
}).always( function () {
$("#searchingSpinner").hide();
$("#searchBtn").prop("disabled", false);
}).done( function (data) {
if(data.length > 0) {
mealsVueInstance.meals = data;
} else {
// Empty result
$("#searchWarning").html("Keine Ergebnisse gefunden!");
$("#searchWarning").show();
}
}).fail( function (data) {
$("#searchWarning").html(data.responseText);
$("#searchWarning").show();
});
// Stop propagation to avoid bubbling up parsley event
// e.stopImmediatePropagation()
});
$('#saveNotice').click(function() {
var vm = this;
$.get("/mealcheck/save/notice", {
mealId: $("#mealId").val(),
notice: $("#noticeTextarea").val()
}).done(function(controllerResponse) {
if(controllerResponse.success) {
$("#noticeDialogError").hide();
$("#noticeModalDialog").modal('hide');
$("#searchForm").submit();
} else {
console.log(controllerResponse.message);
$("#noticeDialogError").show();
$("#noticeDialogError").html(controllerResponse.message);
}
}).fail(function(controllerResponse) {
$("#noticeDialogError").show();
$("#noticeDialogError").html("Fehler beim Speichern der Notiz: " + controllerResponse.message);
});
});
});
|
var app = angular.module('myApp', []).
controller('eventController', function ($scope) {
var technologies = [
{name : 'C#', like: 0, offsets: 0, dislike: 0},
{name : 'ASP', like: 0, offsets: 0, dislike: 0},
{name : 'JS', like: 0, offsets: 0, dislike: 0},
{name : 'Java', like: 0, offsets: 0, dislike: 0},
] ;
$scope.technologies = technologies;
$scope.increaseLike = function (tech) {
tech.like++;
tech.offsets = tech.like - tech.dislike;
}
$scope.increaseDislike = function (tech) {
tech.dislike++;
tech.offsets = tech.like - tech.dislike;
}
});
|
import React from 'react';
import { Table, Icon } from 'antd';
const columns = [{
title: '序号',
dataIndex: 'id',
key: 'id',
}, {
title: '购买日期',
dataIndex: 'buyTime',
key: 'buyTime',
}, {
title: '有效期至',
dataIndex: 'validEndTime',
key: 'validEndTime',
}, {
title: '剩余次数',
dataIndex: 'lastCount',
key: '1',
},{
title: '价格',
dataIndex: 'price',
key: '2',
},{
title: '属性',
dataIndex: 'attributes',
key: '3',
},{
title: '备注',
dataIndex: 'remarks',
key: '4',
}];
const data = [{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
}, {
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
}, {
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sidney No. 1 Lake Park',
}];
const DetailTable = (props) => (
<Table columns={columns} dataSource={props.data} />
);
export default DetailTable;
|
/**
* Auteur: christopher
* Date: 23/11/2016
*/
$(function () {
// Mise à disposition des villes du formulaire
$('select[name="city_fk"]').select2({
ajax: {
url: '/services/GetCityService.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
};
return query;
},
processResults: function (data) {
var resultat = data.map(function (item) {
return {
id: item.id_city,
text: item.name,
};
});
return {
results: resultat
};
}
},
minimumInputLength: 1,
});
// Sport
$.ajax({
url: '/services/GetSportService.php',
method: 'POST',
complete: function (data) {
var sportData = data.responseJSON;
var options = [];
sportData.forEach(function (sport) {
options.push('<option value="' + sport.id_sport + '">' + sport.name + '</option>')
});
options = options.join('');
$(options).appendTo('select[name="sport_fk"]');
}
});
});
|
const { Model } = require('objection')
var environment = process.env.NODE_ENV || 'development'
var config = require('./../knexfile')[environment]
const Knex = require('knex')(config)
Model.knex(Knex);
class BaseModel extends Model {
static get modelPaths() {
return [__dirname];
}
$parseDatabaseJson(json) {
json = super.$parseDatabaseJson(json);
Object.keys(json).forEach(prop => {
const value = json[prop];
if (value instanceof Date) {
json[prop] = value.toISOString();
}
});
return json;
}
}
module.exports = {
BaseModel, Knex
};
|
import { combineReducers } from 'redux';
import userReducer from './userReducer';
import demoReducer from './demoReducer';
import postPageReducer from './pages/postReducer';
import postModelReducer from './models/postReducer';
export default combineReducers({
user: userReducer,
postPage: postPageReducer,
postModel: postModelReducer,
demo: demoReducer
});
|
import React, { useState, useEffect } from 'react';
import './loader.css';
const HorizontalLoader = ({ loading }) => {
const color = '#FFCC00';
const initial = 0;
const target = 100;
const duration = 2000;
// horizontal loader custom hook
const useProgress = (initial, target, duration) => {
const [progress, setProgress] = useState(initial);
useEffect(() => {
let id;
if (loading) {
setProgress(initial);
const increment = (target - initial) / (duration / 16.67);
id = setInterval(() => {
setProgress((prev) => {
if (prev + increment >= target) {
clearInterval(id);
return target;
}
return prev + increment;
});
}, 16.67);
} else {
setProgress(initial);
}
return () => clearInterval(id);
}, [loading]);
return progress;
};
const progress = useProgress(initial, target, duration);
return (
<div
className="loader-container"
style={{
zIndex: loading ? 9999 : -1,
position: 'fixed',
top: '0',
left: '0',
right: '0',
height: '4px'
}}>
{loading && (
<div
className="loader"
style={{
backgroundColor: color,
width: `${progress}%`,
height: '100%'
}}></div>
)}
</div>
);
};
export default HorizontalLoader;
|
import Vue from 'vue';
import App from '@/App';
import Vuex from 'vuex';
import ElementUI from 'element-ui';
import VueRouter from 'vue-router';
import { mount } from '@vue/test-utils';
Vue.use(ElementUI);
Vue.use(Vuex);
Vue.use(VueRouter);
describe('App.vue', () => {
let store;
const router = new VueRouter();
beforeEach(() => {
store = new Vuex.Store({
state: {},
});
});
it('the page should render(no functionability included)', () => {
const wrapper = mount(App, { store, router, Vue });
expect(wrapper.exists()).toBe(true);
});
});
|
// dup
// two sum
// transpose
var array = [1,2,3];
var dup = function(array) {
var new_array = [];
for (var i=0; i<array.length; i++) {
new_array[i] = array[i];
}
return new_array;
};
var uniq = function(array) {
var new_array = [];
for(var i = 0; i < array.length; i++) {
var found = false;
for(var j = 0; j < new_array.length; j++) {
if (array[i] === new_array[j]) {
found = true;
}
}
if (!found) {
new_array.push(array[i]);
}
}
return new_array;
}
var two_sum = function(array) {
var two_sums = [];
for (var i = 0; i < array.length; i++) {
for (var j = i + 1; j < array.length; j++) {
if (array[i] == (-1*array[j])) {
two_sums.push([i,j]);
}
}
}
return two_sums;
};
var rows = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
var transpose = function(array) {
new_array = [];
for (var i = 0; i < array.length; i++) {
new_array.push([])
for (var j = 0; j < array[i].length; j++) {
new_array[i][j] = array[j][i];
}
}
return new_array;
}
var show = console.log
console.log("Dup:");
console.log(dup(array));
console.log("Two sums:");
console.log(two_sum([-1,0,1]));
console.log(two_sum([0,2,4,65]));
show("transpose");
show(transpose(rows));
show("uniq");
show(uniq([1,1,1,2,2,2,5,7,8]));
|
// 添加合同
import PageConst from './PageConst';
export default {
defaults(props) {
//初始的state
return {
reminderTime_0: '',
reminderTime_1: '',
reminderTime_2: '',
reminderTime_3: '',
reminderTime_4: '',
reminderTime_5: '',
reminderTime_6: '',
reminderTime_7: '',
reminderTime_8: '',
reminderTime_9: '',
reminderTime_10: '',
payTime_0: '',
payTime_1: '',
payTime_2: '',
payTime_3: '',
payTime_4: '',
payTime_5: '',
payTime_6: '',
payTime_7: '',
payTime_8: '',
payTime_9: '',
payTime_10: '',
description_0: '',
description_1: '',
description_2: '',
description_3: '',
description_4: '',
description_5: '',
description_6: '',
description_7: '',
description_8: '',
description_9: '',
description_10: '',
// 动态添加款项内容
addMoneyList: [1],
// 0:标准合同;1:非
contractType: 0,
// 款项状态:无0 收款1 付款2
eventType: 0,
// 收付款时间
payTime: '',
// 提醒时间(2029-04-11 11:00:00)
reminderTime: '',
// 审批人
approver: [],
// 上传文件之后返回的数据数组
enclosure: [],
// 款项设置的内容
paymentSettings: [
{
payTime: new Date(),
reminderTime: new Date(),
payCondition: ''
}
],
// 选取部门
departments: []
}
},
/**
* 修改state
* @param ctx
* @param val
*/
setStateData (ctx,val) {
ctx.setState(val);
}
};
|
import test from "tape"
import { last } from "./last"
test("last", t => {
t.equals(last([1, 2, 3]), 3, "Get last element from n array")
t.equals(last([1]), 1, "Get last element of an 1 array")
t.equals(last("xyz"), "z", "From string should return last char")
t.equals(last([]), undefined, "Get last element of empty array")
t.equals(last({}), undefined, "Get last element of empty object")
t.end()
})
|
// TODO: Include packages needed for this application
const inquirer = require('inquirer');
const fs = require('fs');
const generateMarkdown = require('./utils/generateMarkdown');
// const generateMarkdown = require('./utils/generateMarkdown');
//console.log("Hey")
// TODO: Create an array of questions for user input
const questions = ["What is the project title?","Write a short description of the project","Are there any installation instructions?","What is the usage?","Are there any licenses?","Who are the contributors?","What is your Portfolio URL?","What is your Github URL?","What is your LinkedIn URL?","Are there any acknowledgements you would like to include?","What is the deployed link for your site?","Are there any tests?","What languages did you use to build your project?"];
// TODO: Create a function to write README file
function writeToFile(fileName, data) {
fs.writeFile(fileName, data, (err) =>
err ? console.error(err) : console.log('Success!'));
};
// TODO: Create a function to initialize app
function init() {
inquirer.prompt([
{
type:'input',
message:questions[0],
name:'title'
},
{
type:'input',
message:questions[1],
name:'description'
},
{
type:'input',
message:questions[2],
name:'installation'
},
{
type:'input',
message:questions[3],
name:'usage'
},
{
type:'input',
message:questions[4],
name:'licenses'
},
{
type:'input',
message:questions[5],
name:'author'
},
{
type:'input',
message:questions[6],
name:'portfolio'
}, {
type:'input',
message:questions[7],
name:'github'
},
{
type:'input',
message:questions[8],
name:'linkedIn'
},{
type:'input',
message:questions[9],
name:'acknowledgements'
},{
type:'input',
message:questions[10],
name:'deployLink'
},{
type:'input',
message:questions[11],
name:'tests'
},{
type:'checkbox',
message:questions[12],
name: 'builtWith',
choices: ['HTML', 'Javascript','CSS' ]
}
]).then((response)=>{
// generateMarkdown(response);
console.log(response)
// generateMarkdown(response);
writeToFile('readMe.md',generateMarkdown(response));
}
)
};
// Function call to initialize app
init();
|
/**
* Created by StarkX on 08-Apr-18.
*/
const model = require('./model');
module.exports = {
getAccessToken : model.Token.getAccessToken,
getAuthorizationCode : model.AuthCode.getCode,
getClient : model.AuthClient.getClient,
getRefreshToken : model.Token.getRefreshToken,
getUser : model.User.getUser,
revokeAuthorizationCode : model.AuthCode.revokeCode,
revokeToken : model.Token.revokeToken,
saveToken : model.Token.saveToken,
saveAuthorizationCode : model.AuthCode.saveCode,
validateScope : model.AuthScope.validateScope,
generateRefreshToken : model.Token.generate,
generateAccessToken : model.Token.generate,
generateAuthorizationCode : model.AuthCode.generate,
verifyScope : model.AuthScope.verifyScope
};
|
var { defaultVal, getType } = require("./TypeUtils");
test("defaultVal", () => {
expect(() => defaultVal(1)).toThrow("Type must be a string.");
expect(defaultVal("boolean")).toBe(false);
let defFun = defaultVal("function");
expect(defFun).toBeInstanceOf(Function);
expect(defFun).not.toThrow();
expect(defaultVal("null")).toBe(null);
expect(defaultVal("object")).toEqual({});
expect(typeof defaultVal("symbol")).toBe("symbol");
expect(defaultVal("undefined")).toBe(void 0);
expect(defaultVal("")).toEqual({});
expect(defaultVal("number")).toEqual(Number(0));
expect(defaultVal("number")).toBe(0);
let a = {};
a.constructor = { name: null };
expect(getType(a)).toBe("object");
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.