text
stringlengths 3
1.05M
|
---|
(window.webpackJsonp=window.webpackJsonp||[]).push([[42],{211:function(e,t,n){"use strict";n.d(t,"a",(function(){return m})),n.d(t,"b",(function(){return u}));var r=n(0),o=n.n(r);function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?c(Object(n),!0).forEach((function(t){a(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):c(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function l(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},a=Object.keys(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}var p=o.a.createContext({}),s=function(e){var t=o.a.useContext(p),n=t;return e&&(n="function"==typeof e?e(t):i(i({},t),e)),n},m=function(e){var t=s(e.components);return o.a.createElement(p.Provider,{value:t},e.children)},d={inlineCode:"code",wrapper:function(e){var t=e.children;return o.a.createElement(o.a.Fragment,{},t)}},b=o.a.forwardRef((function(e,t){var n=e.components,r=e.mdxType,a=e.originalType,c=e.parentName,p=l(e,["components","mdxType","originalType","parentName"]),m=s(n),b=r,u=m["".concat(c,".").concat(b)]||m[b]||d[b]||a;return n?o.a.createElement(u,i(i({ref:t},p),{},{components:n})):o.a.createElement(u,i({ref:t},p))}));function u(e,t){var n=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var a=n.length,c=new Array(a);c[0]=b;var i={};for(var l in t)hasOwnProperty.call(t,l)&&(i[l]=t[l]);i.originalType=e,i.mdxType="string"==typeof e?e:r,c[1]=i;for(var p=2;p<a;p++)c[p]=n[p];return o.a.createElement.apply(null,c)}return o.a.createElement.apply(null,n)}b.displayName="MDXCreateElement"},96:function(e,t,n){"use strict";n.r(t),n.d(t,"frontMatter",(function(){return a})),n.d(t,"metadata",(function(){return c})),n.d(t,"rightToc",(function(){return i})),n.d(t,"default",(function(){return p}));var r=n(2),o=(n(0),n(211));const a={title:"Element Properties"},c={unversionedId:"frontend-quick-learning/javascript-guide/element-properties",id:"frontend-quick-learning/javascript-guide/element-properties",isDocsHomePage:!1,title:"Element Properties",description:"Goal",source:"@site/docs/frontend-quick-learning/javascript-guide/element-properties.md",permalink:"/docs/frontend-quick-learning/javascript-guide/element-properties",editUrl:"https://github.com/facebook/docusaurus/edit/master/website/docs/frontend-quick-learning/javascript-guide/element-properties.md",sidebar:"frontendQuickLearning",previous:{title:"Element Events",permalink:"/docs/frontend-quick-learning/javascript-guide/element-events"},next:{title:"Various writing ways of JavaScript",permalink:"/docs/frontend-quick-learning/javascript-guide/various-writing-ways"}},i=[{value:"Goal",id:"goal",children:[]},{value:"Element <code>Properties</code>",id:"element-properties",children:[]},{value:"Check properties in console",id:"check-properties-in-console",children:[]},{value:"Change properties",id:"change-properties",children:[]},{value:"Summery",id:"summery",children:[]}],l={rightToc:i};function p({components:e,...t}){return Object(o.b)("wrapper",Object(r.a)({},l,t,{components:e,mdxType:"MDXLayout"}),Object(o.b)("h2",{id:"goal"},"Goal"),Object(o.b)("ul",null,Object(o.b)("li",{parentName:"ul"},"\u26a1 Understand ",Object(o.b)("strong",{parentName:"li"},"(3)")," of the below code")),Object(o.b)("pre",null,Object(o.b)("code",Object(r.a)({parentName:"pre"},{className:"language-html",metastring:'title="js-test1.html"',title:'"js-test1.html"'}),'<script>\n let demoElement = document.getElementById("demo"); --- (1)\n \n demoElement.onclick = function changeContent () { --- (2)\n // highlight-start\n demoElement.innerHTML = "Help me"; --- (3)\n demoElement.style = "color: red"; --- (3)\n // highlight-end\n }\n<\/script>\n')),Object(o.b)("h2",{id:"element-properties"},"Element ",Object(o.b)("inlineCode",{parentName:"h2"},"Properties")),Object(o.b)("p",null,"To understand ",Object(o.b)("strong",{parentName:"p"},"(3)")," we focus on ",Object(o.b)("strong",{parentName:"p"},Object(o.b)("inlineCode",{parentName:"strong"},"Element Properties"))),Object(o.b)("p",null,Object(o.b)("img",Object(r.a)({parentName:"p"},{src:"https://coderhackers-1302290683.cos.ap-singapore.myqcloud.com/2020-05-24-19-40-15.png",alt:null}))),Object(o.b)("p",null,"As described here, HTML element has a lot of properties."),Object(o.b)("p",null,Object(o.b)("img",Object(r.a)({parentName:"p"},{src:"https://storage.googleapis.com/coderhackers-assets/docs/img/2020-05-02-20-28-59.png",alt:"html-element-properties"}))),Object(o.b)("p",null,"Ref: ",Object(o.b)("a",Object(r.a)({parentName:"p"},{href:"https://developer.mozilla.org/en-US/docs/Web/API/Element"}),"https://developer.mozilla.org/en-US/docs/Web/API/Element")),Object(o.b)("p",null,"You see ",Object(o.b)("inlineCode",{parentName:"p"},"innerHTML")," property."),Object(o.b)("p",null,"And ",Object(o.b)("inlineCode",{parentName:"p"},"style")," property is not documented here. It is documented here\n",Object(o.b)("a",Object(r.a)({parentName:"p"},{href:"https://developer.mozilla.org/en-US/docs/Web/API/ElementCSSInlineStyle/style"}),"https://developer.mozilla.org/en-US/docs/Web/API/ElementCSSInlineStyle/style")),Object(o.b)("h2",{id:"check-properties-in-console"},"Check properties in console"),Object(o.b)("p",null,"So, first let's check current ",Object(o.b)("inlineCode",{parentName:"p"},"<div#demo>")," properties."),Object(o.b)("p",null,Object(o.b)("img",Object(r.a)({parentName:"p"},{src:"https://storage.googleapis.com/coderhackers-assets/docs/img/20200509_232636.gif",alt:"check-property"}))),Object(o.b)("h2",{id:"change-properties"},"Change properties"),Object(o.b)("p",null,"You can ",Object(o.b)("strong",{parentName:"p"},Object(o.b)("mark",null,"change these properties by assigning new values")),"."),Object(o.b)("p",null,Object(o.b)("img",Object(r.a)({parentName:"p"},{src:"https://storage.googleapis.com/coderhackers-assets/docs/img/20200509_232934.gif",alt:"change-property"}))),Object(o.b)("p",null,"And we're doing the same thing inside function."),Object(o.b)("pre",null,Object(o.b)("code",Object(r.a)({parentName:"pre"},{className:"language-html"}),'<script>\n let demoElement = document.getElementById("demo"); --- (1)\n \n demoElement.onclick = function changeContent () { --- (2)\n // highlight-start\n demoElement.innerHTML = "Help me"; --- (3)\n demoElement.style = "color: red"; --- (3)\n // highlight-end\n }\n<\/script>\n')),Object(o.b)("h2",{id:"summery"},"Summery"),Object(o.b)("p",null,"I hope you understand this code! \ud83d\ude4b"),Object(o.b)("pre",null,Object(o.b)("code",Object(r.a)({parentName:"pre"},{className:"language-html"}),'<script>\n let demoElement = document.getElementById("demo"); --- (1)\n \n demoElement.onclick = function changeContent () { --- (2)\n demoElement.innerHTML = "Help me"; --- (3)\n demoElement.style = "color: red"; --- (3)\n }\n<\/script>\n')),Object(o.b)("div",{className:"admonition admonition-caution alert alert--warning"},Object(o.b)("div",Object(r.a)({parentName:"div"},{className:"admonition-heading"}),Object(o.b)("h5",{parentName:"div"},Object(o.b)("span",Object(r.a)({parentName:"h5"},{className:"admonition-icon"}),Object(o.b)("svg",Object(r.a)({parentName:"span"},{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 16 16"}),Object(o.b)("path",Object(r.a)({parentName:"svg"},{fillRule:"evenodd",d:"M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 0 0 0 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 0 0 .01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z"})))),"caution")),Object(o.b)("div",Object(r.a)({parentName:"div"},{className:"admonition-content"}),Object(o.b)("p",{parentName:"div"},"If you understand ",Object(o.b)("strong",{parentName:"p"},"the flow of this code"),", it is enough! \ud83d\udcaf"),Object(o.b)("p",{parentName:"div"},Object(o.b)("strong",{parentName:"p"},"70% understanding is enough"),"! Let's go next! \ud83d\udc4d"))))}p.isMDXComponent=!0}}]); |
import Factory from './Factory'
import Sequence from './generators/Sequence'
import Assoc from './generators/Assoc'
import AssocAttrs from './generators/AssocAttrs'
import AssocMany from './generators/AssocMany'
import AssocAttrsMany from './generators/AssocAttrsMany'
import ChanceGenerator from './generators/ChanceGenerator'
import OneOf from './generators/OneOf'
import DefaultAdapter from './adapters/DefaultAdapter'
function wrapGenerator(generator) {
return (...args) => () => generator.generate(...args)
}
export function generatorThunk(factoryGirl, SomeGenerator) {
const generator = new SomeGenerator(factoryGirl)
return wrapGenerator(generator)
}
export default class FactoryGirl {
constructor(options = {}) {
this.factories = {}
this.options = {}
this.adapters = {}
this.created = new Set()
this.assoc = generatorThunk(this, Assoc)
this.assocMany = generatorThunk(this, AssocMany)
this.assocAttrs = generatorThunk(this, AssocAttrs)
this.assocAttrsMany = generatorThunk(this, AssocAttrsMany)
this.seq = this.sequence = (...args) =>
generatorThunk(this, Sequence)(...args)
this.resetSeq = this.resetSequence = id => {
Sequence.reset(id)
}
const chance = new ChanceGenerator(this)
this.chance = wrapGenerator(chance)
this.chance.seed = value => {
chance.seed(value)
}
this.oneOf = generatorThunk(this, OneOf)
this.defaultAdapter = new DefaultAdapter()
this.options = options
}
define(name, Model, initializer, options = {}) {
if (this.getFactory(name, false)) {
throw new Error(`Factory ${name} already defined`)
}
const factory = (this.factories[name] = new Factory(
Model,
initializer,
options,
))
return factory
}
remove(name) {
delete this.factories[name]
}
extend(parent, name, childInitializer, options = {}) {
if (this.getFactory(name, false)) {
throw new Error(`Factory ${name} already defined`)
}
const parentFactory = this.getFactory(parent, true)
const Model = options.model || parentFactory.Model
const jointOptions = { ...parentFactory.options, ...options }
let jointInitializer
function resolveInitializer(initializer, buildOptions) {
return typeof initializer === 'function'
? initializer(buildOptions)
: initializer
}
if (
typeof parentFactory.initializer === 'function' ||
typeof childInitializer === 'function'
) {
jointInitializer = function initializer(buildOptions = {}) {
return Object.assign(
{},
resolveInitializer(parentFactory.initializer, buildOptions),
resolveInitializer(childInitializer, buildOptions),
)
}
} else {
jointInitializer = Object.assign(
{},
parentFactory.initializer,
childInitializer,
)
}
const factory = (this.factories[name] = new Factory(
Model,
jointInitializer,
jointOptions,
))
return factory
}
async attrs(name, attrs, buildOptions = {}) {
return this.getFactory(name).attrs(attrs, buildOptions)
}
async build(name, attrs = {}, buildOptions = {}) {
const adapter = this.getAdapter(name)
return this.getFactory(name)
.build(adapter, attrs, buildOptions)
.then(model =>
(this.options.afterBuild
? this.options.afterBuild(model, attrs, buildOptions)
: model),
)
}
async create(name, attrs, buildOptions = {}) {
const adapter = this.getAdapter(name)
return this.getFactory(name)
.create(adapter, attrs, buildOptions)
.then(createdModel => this.addToCreatedList(adapter, createdModel))
.then(model =>
(this.options.afterCreate
? this.options.afterCreate(model, attrs, buildOptions)
: model),
)
}
attrsMany(name, num, attrs, buildOptions = {}) {
return this.getFactory(name).attrsMany(num, attrs, buildOptions)
}
async buildMany(name, num, attrs, buildOptions = {}) {
const adapter = this.getAdapter(name)
return this.getFactory(name)
.buildMany(adapter, num, attrs, buildOptions)
.then(models =>
(this.options.afterBuild
? Promise.all(
models.map(model =>
this.options.afterBuild(model, attrs, buildOptions),
),
)
: models),
)
}
async createMany(name, num, attrs, buildOptions = {}) {
const adapter = this.getAdapter(name)
return this.getFactory(name)
.createMany(adapter, num, attrs, buildOptions)
.then(models => this.addToCreatedList(adapter, models))
.then(models =>
(this.options.afterCreate
? Promise.all(
models.map(model =>
this.options.afterCreate(model, attrs, buildOptions),
),
)
: models),
)
}
getFactory(name, throwError = true) {
if (!this.factories[name] && throwError) {
throw new Error(`Invalid factory '${name}' requested`)
}
return this.factories[name]
}
withOptions(options, merge = false) {
this.options = merge ? { ...this.options, ...options } : options
}
getAdapter(factory) {
return factory
? this.adapters[factory] || this.defaultAdapter
: this.defaultAdapter
}
addToCreatedList(adapter, models) {
if (!Array.isArray(models)) {
this.created.add([adapter, models])
} else {
// eslint-disable-next-line no-restricted-syntax
for (const model of models) {
this.created.add([adapter, model])
}
}
return models
}
cleanUp() {
const createdArray = []
// eslint-disable-next-line no-restricted-syntax
for (const c of this.created) {
createdArray.unshift(c)
}
const promise = createdArray.reduce(async (prev, [adapter, model]) => {
await prev
if (model === null) {
return
}
await adapter.destroy(model, model.constructor)
}, Promise.resolve())
this.created.clear()
this.resetSeq()
return promise
}
setAdapter(adapter, factoryNames = null) {
if (!factoryNames) {
this.defaultAdapter = adapter
} else {
factoryNames = Array.isArray(factoryNames) ? factoryNames : [factoryNames]
factoryNames.forEach(name => {
this.adapters[name] = adapter
})
}
return adapter
}
}
|
# -*- coding: utf-8 -*-
import argparse
import sys
import waitress
from conf.version import version_
from Doctopus.web.app import get_app
try:
from queue import Queue
except Exception:
from Queue import Queue
from logging import getLogger
from threading import Thread
from Doctopus.lib.logging_init import setup_logging
from Doctopus.lib.Sender import Sender
from Doctopus.lib.transport import Transport
from Doctopus.lib.watchdog import WatchDog
from Doctopus.utils.util import get_conf
if sys.version_info[0] == 3 and sys.version_info[1] >= 5:
from Doctopus.lib.communication import Communication
else:
from Doctopus.lib.communication_2 import Communication
log = getLogger("Doctopus.start")
def start_ziyan():
from plugins.your_plugin import MyCheck, MyHandler
# init queues
queue = {'data_queue': Queue(), 'sender': Queue()}
# load all configs
all_conf = get_conf('conf/conf.toml')
# init log config
setup_logging(all_conf['log_configuration'])
# init instances
checker = MyCheck(all_conf)
handler = MyHandler(all_conf)
sender = Sender(all_conf)
communication = Communication(all_conf)
# name instances
checker.name = 'checker'
handler.name = 'handler'
sender.name = 'sender'
# init work threads set
workers = [checker, handler]
thread_set = dict()
# start workers instance
for worker in workers:
thread = Thread(target=worker.work,
args=(queue, ),
name='%s' % worker.name)
thread.setDaemon(True)
thread.start()
thread_set[worker.name] = thread
# init send set
send_set = [communication, sender]
for send in send_set:
thread = Thread(target=send.work,
args=(queue, ),
name='%s' % send.name)
thread.setDaemon(True)
thread.start()
# start watch instance
watch = WatchDog(all_conf)
watch = Thread(target=watch.work,
name='%s' % watch.name,
args=(thread_set, queue, workers))
watch.setDaemon(True)
watch.start()
def start_chitu():
# load all configs
all_conf = get_conf('conf/conf.toml')
# init log config
setup_logging(all_conf['log_configuration'])
thread_set = dict()
queue = None
workers = list()
for redis_address in all_conf['redis_instance']['address']:
work = Transport(all_conf, redis_address)
work.name = 'redis_' + str(redis_address['db'])
thread = Thread(target=work.work, args=(), name='%s' % work.name)
thread.setDaemon(True)
thread.start()
workers.append(work)
thread_set[work.name] = thread
# start pending data process
pending = Transport(all_conf, redis_address)
pending.name = 'redis_pending_' + str(redis_address['db'])
thread = Thread(target=pending.pending,
args=(),
name='%s' % pending.name)
thread.start()
workers.append(pending)
thread_set[pending.name] = thread
# start communication instance
communication = Communication(all_conf)
thread = Thread(target=communication.work,
args=(),
name='%s' % communication.name)
thread.setDaemon(True)
thread.start()
# start watch instance
watch = WatchDog(all_conf)
watch = Thread(target=watch.work,
name='watchdog',
args=(thread_set, queue, workers))
watch.setDaemon(True)
watch.start()
if __name__ == '__main__':
parse = argparse.ArgumentParser(
prog='Doctopus',
description='A distributed data collector.',
usage=("\npython manage.py [-h] [-a ACTION] [-v] "
"[-t {ziyan,chitu}] [-i IP] [-p PORT]"))
parse.add_argument('-a',
'--action',
action='store',
default='run',
help='Run/test the project, default run')
parse.add_argument('-v',
'--version',
action='version',
default=None,
version='%(prog)s {}'.format(version_))
parse.add_argument('-t',
'--target',
default='ziyan',
choices=['ziyan', 'chitu'],
help='selelct the target, default ziyan')
parse.add_argument('-i',
'--ip',
default='0.0.0.0',
help=("Hostname or IP address on which to listen, "
"default is '0.0.0.0', "
"which means 'all IP addresses on this host'."))
parse.add_argument('-p',
'--port',
default='8000',
help="TCP port on which to listen, default is '8000'.")
command = parse.parse_args().action
target = parse.parse_args().target
host = parse.parse_args().ip
port = parse.parse_args().port
version = parse.parse_args().version
if version:
print(version)
elif command == 'run':
if target == 'ziyan':
start_ziyan()
if target == 'chitu':
start_chitu()
port = port if port != '8000' else str(int(port) + 1)
log.info("Serving on http://{}:{}".format(host, port))
waitress.serve(get_app(), host=host, port=port, _quiet=True)
elif command == 'test':
pass
|
# Copyright 2015 Vinicius Chiele. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .hashers import PasswordHasher
|
from django.urls import path
from . import views
app_name = 'async_media'
urlpatterns = [
path('media_ajax/', views.media_ajax,
name="media_ajax"),
path('media_poll_ajax/', views.media_poll_ajax,
name="media_poll_ajax"),
]
|
import gql from "graphql-tag";
export default gql`
mutation addBook(
$userID: ID
$imageUrl: String
$title: String
$author: String
$createdAt: String
$infoLink: String
) {
addBook(
userID: $userID
imageUrl: $imageUrl
title: $title
author: $author
createdAt: $createdAt
infoLink: $infoLink
) {
id
title
author
infoLink
}
}
`;
|
var formBarang = document.getElementById('formBarang');
formBarang.addEventListener("submit", (e) =>{
e.preventDefault();
let formData = new FormData(formBarang);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (){
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText == 'Input Data Berhasil!') {
swal('Sukses', 'Data barang sukses dibuat', 'success');
goToPage('master/barang');
}else{
swal('Gagal', 'Data barang gagal dibuat', 'error');
}
}
}
xhr.open("POST", "../assets/ajax/createBarang.php", true);
xhr.setRequestHeader('token', getCookie('token'));
xhr.send(formData);
}); |
"use strict";
const http = require('http');
const connect = require('connect');
const reload = require('reload/lib/reload');
const fs = require('fs');
const clc = require('cli-color');
const serveStatic = require('serve-static');
const argv = process.argv.slice(2);
const runFile = argv.shift();
const verbose = (argv.shift() === 'true');
const port = argv.shift();
const root = argv.shift();
const reloadJs = argv.shift();
const headerFile = argv.shift();
const reloadOpts = {
port: port,
verbose: verbose,
noExpress: true
};
let optionalHeaders = [];
if(fs.existsSync(headerFile)) {
const contents = fs.readFileSync(headerFile);
if (headerFile.match(/.json$/)) {
JSON.parse(contents).forEach((header) => {
if (header.length >= 2) {
const key = header[0];
let value = header[1];
if (value.join) {
value = value.join("; ");
}
optionalHeaders.push([key, value]);
}
})
}
}
let app = connect();
const server = http.createServer(app);
const reloadReturned = reload(() => {}, reloadOpts, server);
// Serve static files
app.use(serveStatic(root, {
index: ['index.html'],
setHeaders: (res) => {
optionalHeaders.forEach((h) => {
res.setHeader(h[0], h[1]);
})
},
}));
// Serve reload-client.js file from injected script tag
app.use((req, res, next) => {
if (req.url === reloadJs) {
res.setHeader('Content-Type', 'text/javascript');
res.end(reloadReturned.reloadClientCode());
} else {
next();
}
});
server.listen(port, () => {
if (!fs.existsSync(runFile)) {
fs.writeFileSync(runFile);
console.log('Reload web server:');
console.log(' listening on port ' + clc.blue.bold(port));
console.log(' monitoring root ' + clc.green.bold(root));
console.log(' optional headers:\n ' + optionalHeaders.map((h) => {return h.join(": ")}).join("\n "));
} else {
console.log(clc.green('Server restarted at ' + (new Date()).toTimeString().slice(0, 8)));
}
});
|
{"frequencies":[261.6255653006,268.33391312882,275.39533189537,348.83408706747,373.75080757229,402.50086969323,418.60090448096,436.04260883433,523.2511306012],"description":"Schlesinger's Hypolydian Harmonia in the enharmonic genus"} |
import React from "react";
import Search from "./pages/Search";
import Saved from "./pages/Saved";
import NoMatch from "./pages/NoMatch";
import Nav from "./components/Nav";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
// The app will not render correctly until you setup a Route component.
// Refer to the Basic Example documentation if you need to.
// (https://reacttraining.com/react-router/web/example/basic)
function App() {
return (
<Router>
<div>
<Nav />
<Switch>
<Route exact path={["/", "/books"]}>
<Search />
</Route>
<Route exact path={["/saved", "/saved"]}>
<Saved />
</Route>
<Route>
<NoMatch />
</Route>
</Switch>
</div>
</Router>
);
}
export default App;
|
const Koa = require('koa');
const app = new Koa();
const router = require('koa-router')();
const build = require('./build')
router.get('/', (ctx, next) => {
ctx.body = "ok"
});
router.get('/styles/:id', async (ctx, next) => {
ctx.body = ctx.params.id
ctx.body += build.getStyle()
});
router.get('/scripts/:id', async (ctx, next) => {
ctx.body = ctx.params.id
ctx.body += build.getScript()
});
router.get('/htmls/:id', async (ctx, next) => {
ctx.body = ctx.params.id
ctx.body += build.getHtml()
});
router.get('/modules/:id', async (ctx, next) => {
ctx.body = ctx.params.id
ctx.body += build.getModule()
});
app.use(router.routes());
app.listen(3000) |
import React from "react";
import theme from "theme";
import { Theme, Link, Strong, Box, Section } from "@quarkly/widgets";
import { Helmet } from "react-helmet";
import { GlobalQuarklyPageStyles } from "global-page-styles";
import { Override } from "@quarkly/components";
import * as Components from "components";
export default (() => {
return <Theme theme={theme}>
<GlobalQuarklyPageStyles pageUrl={"index/interface/work-area/props-panel/tips-and-tricks"} />
<Helmet>
<title>
Quarkly export
</title>
<meta name={"description"} content={"Web site created using quarkly.io"} />
<link rel={"shortcut icon"} href={"https://uploads.quarkly.io/readme/cra/favicon-32x32.ico"} type={"image/x-icon"} />
</Helmet>
<Components.MobileMenu>
<Override slot="menu">
<Override slot="item-404" display="none" />
</Override>
</Components.MobileMenu>
<Components.Header />
<Box display="flex" quarkly-title="Content">
<Components.SidebarMenu>
<Override slot="Sub Head Text-styles-basic" />
<Override slot="Sub Head Text-props-panel" />
</Components.SidebarMenu>
<Section background="--color-white" padding="24px 0 64px 0">
<Override slot="SectionContent" max-width="760px" />
<Box margin="48px 0px 0px 0px" id="interface-context-menu">
<Components.HelpHeader2>
Tips&Tricks
</Components.HelpHeader2>
<Components.HelpParagraph>
All units of measurement available in CSS can be used.
</Components.HelpParagraph>
<Components.HelpHeader3>
Math
</Components.HelpHeader3>
<Components.HelpParagraph>
You can use the following mathematical operations in the input field:{" "}
<Components.HelpKey display="inline-block">
+
</Components.HelpKey>
,{" "}
<Components.HelpKey display="inline-block">
-
</Components.HelpKey>
,{" "}
<Components.HelpKey display="inline-block">
*
</Components.HelpKey>
,{" "}
<Components.HelpKey display="inline-block">
/
</Components.HelpKey>
.
</Components.HelpParagraph>
<Components.HelpExample>
For example, enter the{" "}
<Strong>
720px/2
</Strong>
{" "}value, click on Enter and get the{" "}
<Strong>
360px
</Strong>
{" "}value.
</Components.HelpExample>
<Components.HelpHeader3>
Calc()
</Components.HelpHeader3>
<Components.HelpParagraph>
If you enter an expression containing different units, the input field will reformat it into a calc value.{" "}
</Components.HelpParagraph>
<Components.HelpExample>
For example,{" "}
<Strong>
100vh-60px
</Strong>
{" "}will be converted to{" "}
<Strong>
calc(100vh-60px)
</Strong>
.
</Components.HelpExample>
<Components.HelpHeader3>
Input shortcuts
</Components.HelpHeader3>
<Components.HelpTable
cols="3"
rows="8"
width="100%"
showHeader
font="--baseSm"
color="--darkL2"
margin="12px 0px 0px 0px"
>
<Override slot="Text 0-0">
Увеличение числового значения на 1
</Override>
<Override slot="Text 0-1" background="--color-lightD1" display="inline-block" padding="2px 8px 4px 8px">
<Components.HelpKey display="inline-block">
↑
</Components.HelpKey>
</Override>
<Override slot="Text 1-0">
Уменьшение числового значения на 1
</Override>
<Override slot="Text 2-0">
Увеличение числового значения на 10
</Override>
<Override slot="Text 3-0">
Уменьшение числового значения на 10
</Override>
<Override slot="Text 4-0">
Увеличение числового значения на 100
</Override>
<Override slot="Text 5-0">
Уменьшение числового значения на 100
</Override>
<Override slot="Text 6-0">
Увеличение числового значения на 0.1
</Override>
<Override slot="Text 7-0">
Уменьшение числового значения на 0.1
</Override>
<Override slot="Text 8-0">
Уменьшение числового значения на 0.1
</Override>
<Override slot="Cell" padding="0rem 1rem 0rem 1rem" />
<Override slot="Text" margin="12px 0px 12px 0px" border-radius="4px" />
<Override slot="Text THead Col-0" font="700 18px/27px "Source Sans Pro", sans-serif">
Action
</Override>
<Override slot="Text THead Col-2" font="700 18px/27px "Source Sans Pro", sans-serif">
MacOS
</Override>
<Override slot="Text THead Col-1" font="700 18px/27px "Source Sans Pro", sans-serif">
Windows and Linux
</Override>
<Override slot="Text 1-1" background="--color-lightD1" display="inline-block" padding="2px 8px 4px 8px">
<Components.HelpKey display="inline-block">
↓
</Components.HelpKey>
</Override>
<Override slot="Text 1-2" background="--color-lightD1" display="inline-block" padding="2px 8px 4px 8px">
<Components.HelpKey display="inline-block">
↓
</Components.HelpKey>
</Override>
<Override slot="Text 2-1">
<Components.HelpKey display="inline-block">
Shift
</Components.HelpKey>
{" "}+{" "}
<Components.HelpKey display="inline-block">
↑
</Components.HelpKey>
</Override>
<Override slot="Text 2-2">
<Components.HelpKey display="inline-block">
⇧(Shift)
</Components.HelpKey>
{" "}+{" \t\t\t\t\t "}
<Components.HelpKey display="inline-block">
↓
</Components.HelpKey>
</Override>
<Override slot="Text 3-1">
<Components.HelpKey display="inline-block">
Shift
</Components.HelpKey>
{" "}+{" "}
<Components.HelpKey display="inline-block">
↓
</Components.HelpKey>
</Override>
<Override slot="Text 4-1">
<Components.HelpKey display="inline-block">
Ctrl
</Components.HelpKey>
{" "}+{" "}
<Components.HelpKey display="inline-block">
↑
</Components.HelpKey>
</Override>
<Override slot="Text 5-1">
<Components.HelpKey display="inline-block">
Ctrl
</Components.HelpKey>
{" "}+{" "}
<Components.HelpKey display="inline-block">
↓
</Components.HelpKey>
</Override>
<Override slot="Text 6-1">
<Components.HelpKey display="inline-block">
Alt
</Components.HelpKey>
{" "}+{" "}
<Components.HelpKey display="inline-block">
↑
</Components.HelpKey>
</Override>
<Override slot="Text 7-1">
<Components.HelpKey display="inline-block">
Alt
</Components.HelpKey>
{" "}+{" "}
<Components.HelpKey display="inline-block">
↓
</Components.HelpKey>
</Override>
<Override slot="Text 3-2">
<Components.HelpKey display="inline-block">
⇧(Shift)
</Components.HelpKey>
{" "}+{" "}
<Components.HelpKey display="inline-block">
↓
</Components.HelpKey>
</Override>
<Override slot="Text 4-2">
<Components.HelpKey display="inline-block">
⌘(Cmd)
</Components.HelpKey>
{" "}+{" "}
<Components.HelpKey display="inline-block">
↑
</Components.HelpKey>
</Override>
<Override slot="Text 5-2">
<Components.HelpKey display="inline-block">
⌘(Cmd)
</Components.HelpKey>
{" "}+{" "}
<Components.HelpKey display="inline-block">
↓
</Components.HelpKey>
</Override>
<Override slot="Text 6-2">
<Components.HelpKey display="inline-block">
⌥(Option)
</Components.HelpKey>
{" "}+{" \t\t\t\t\t "}
<Components.HelpKey display="inline-block">
↑
</Components.HelpKey>
</Override>
<Override slot="Text 7-2">
<Components.HelpKey display="inline-block">
⌥(Option)
</Components.HelpKey>
{" "}+{" "}
<Components.HelpKey display="inline-block">
↓
</Components.HelpKey>
</Override>
<Override slot="Text 0-2" background="--color-lightD1" display="inline-block" padding="2px 8px 4px 8px">
<Components.HelpKey display="inline-block">
↑
</Components.HelpKey>
</Override>
</Components.HelpTable>
</Box>
<Components.HelpPrevNextButton hierarchy="several" />
</Section>
</Box>
<Components.FooterHigh />
<Link
font={"--capture"}
font-size={"10px"}
position={"fixed"}
bottom={"12px"}
right={"12px"}
z-index={"4"}
border-radius={"4px"}
padding={"5px 12px 4px"}
background-color={"--dark"}
opacity={"0.6"}
hover-opacity={"1"}
color={"--light"}
cursor={"pointer"}
transition={"--opacityOut"}
quarkly-title={"Badge"}
text-decoration-line={"initial"}
href={"https://quarkly.io/"}
target={"_blank"}
>
Made on Quarkly
</Link>
</Theme>;
}); |
import React from 'react';
import PropTypes from 'prop-types';
import {
Text,
TouchableOpacity,
} from 'react-native';
export default function Button({ style, textStyle, text, onPress }) {
return (
<TouchableOpacity style={style}>
<Text style={textStyle} onPress={onPress}>{text}</Text>
</TouchableOpacity>
)
};
Button.propTypes = {
style: PropTypes.object,
textStyle: PropTypes.object,
text: PropTypes.string.isRequired,
onPress: PropTypes.func,
};
Button.defaultProps = {
style: {},
textStyle: {},
onPress: () => {},
}
|
const abbreviateNum = (number, decPlaces = 1) => {
// 2 decimal places => 100, 3 => 1000, etc
decPlaces = Math.pow(10,decPlaces);
// Enumerate number abbreviations
var abbrev = [ "k", "m", "b", "t" ];
// Go through the array backwards, so we do the largest first
for (var i=abbrev.length-1; i>=0; i--) {
// Convert array index to "1000", "1000000", etc
var size = Math.pow(10,(i+1)*3);
// If the number is bigger or equal do the abbreviation
if(size <= number) {
// Here, we multiply by decPlaces, round, and then divide by decPlaces.
// This gives us nice rounding to a particular decimal place.
number = Math.round(number*decPlaces/size)/decPlaces;
// Handle special case where we round up to the next abbreviation
if((number === 1000) && (i < abbrev.length - 1)) {
number = 1;
i++;
}
// Add the letter for the abbreviation
number += abbrev[i];
// We are done... stop
break;
}
}
return number;
};
export default abbreviateNum;
|
const barracks = require('barracks')
const store = barracks()
require('./app')(store)
require('./npc')(store)
require('./nodes')(store)
module.exports = store
|
/*jshint esnext: true */
'use strict';
const google = require('googleapis');
const OAuth2 = google.auth.OAuth2;
const jsonfile = require('jsonfile');
const path = require('path');
const config = jsonfile.readFileSync(path.join(__dirname, '..', 'config', 'credentials.json'));
const token = jsonfile.readFileSync(path.join(__dirname, '..', 'config', 'token.json'));
const oauth2Client = new OAuth2(config.web.client_id, config.web.client_secret, config.web.redirect_uris[0]);
google.options({ auth: oauth2Client });
oauth2Client.setCredentials({
access_token: token.access_token,
token_type: token.token_type,
refresh_token: token.refresh_token,
expiry_date: token.expiry_date
});
module.exports = oauth2Client; |
// @flow
export type MeetingStatusResponse = {
full: boolean
};
export default class MeetingStatus {
type: string;
full: boolean;
constructor({
full,
}: Object = {}) {
this.full = full;
// Useful to compare instead of instanceof with minified code
this.type = 'MeetingStatus';
}
static parse(plain: MeetingStatusResponse): MeetingStatus {
return new MeetingStatus({
full: plain.full,
});
}
}
|
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
require("mocha");
const assert = require("assert");
const vscode_1 = require("vscode");
const testUtils_1 = require("./testUtils");
const abbreviationActions_1 = require("../abbreviationActions");
const htmlContentsForWrapTests = `
<ul class="nav main">
<li class="item1">img</li>
<li class="item2">$hithere</li>
</ul>
`;
const wrapBlockElementExpected = `
<ul class="nav main">
<div>
<li class="item1">img</li>
</div>
<div>
<li class="item2">$hithere</li>
</div>
</ul>
`;
const wrapInlineElementExpected = `
<ul class="nav main">
<span><li class="item1">img</li></span>
<span><li class="item2">$hithere</li></span>
</ul>
`;
const wrapSnippetExpected = `
<ul class="nav main">
<a href=""><li class="item1">img</li></a>
<a href=""><li class="item2">$hithere</li></a>
</ul>
`;
const wrapMultiLineAbbrExpected = `
<ul class="nav main">
<ul>
<li>
<li class="item1">img</li>
</li>
</ul>
<ul>
<li>
<li class="item2">$hithere</li>
</li>
</ul>
</ul>
`;
const wrapInlineElementExpectedFormatFalse = `
<ul class="nav main">
<h1><li class="item1">img</li></h1>
<h1><li class="item2">$hithere</li></h1>
</ul>
`;
suite('Tests for Wrap with Abbreviations', () => {
teardown(testUtils_1.closeAllEditors);
const multiCursors = [new vscode_1.Selection(2, 6, 2, 6), new vscode_1.Selection(3, 6, 3, 6)];
const multiCursorsWithSelection = [new vscode_1.Selection(2, 2, 2, 28), new vscode_1.Selection(3, 2, 3, 33)];
const multiCursorsWithFullLineSelection = [new vscode_1.Selection(2, 0, 2, 28), new vscode_1.Selection(3, 0, 4, 0)];
const oldValueForSyntaxProfiles = vscode_1.workspace.getConfiguration('emmet').inspect('syntaxProfile');
test('Wrap with block element using multi cursor', () => {
return testWrapWithAbbreviation(multiCursors, 'div', wrapBlockElementExpected);
});
test('Wrap with inline element using multi cursor', () => {
return testWrapWithAbbreviation(multiCursors, 'span', wrapInlineElementExpected);
});
test('Wrap with snippet using multi cursor', () => {
return testWrapWithAbbreviation(multiCursors, 'a', wrapSnippetExpected);
});
test('Wrap with multi line abbreviation using multi cursor', () => {
return testWrapWithAbbreviation(multiCursors, 'ul>li', wrapMultiLineAbbrExpected);
});
test('Wrap with block element using multi cursor selection', () => {
return testWrapWithAbbreviation(multiCursorsWithSelection, 'div', wrapBlockElementExpected);
});
test('Wrap with inline element using multi cursor selection', () => {
return testWrapWithAbbreviation(multiCursorsWithSelection, 'span', wrapInlineElementExpected);
});
test('Wrap with snippet using multi cursor selection', () => {
return testWrapWithAbbreviation(multiCursorsWithSelection, 'a', wrapSnippetExpected);
});
test('Wrap with multi line abbreviation using multi cursor selection', () => {
return testWrapWithAbbreviation(multiCursorsWithSelection, 'ul>li', wrapMultiLineAbbrExpected);
});
test('Wrap with block element using multi cursor full line selection', () => {
return testWrapWithAbbreviation(multiCursorsWithFullLineSelection, 'div', wrapBlockElementExpected);
});
test('Wrap with inline element using multi cursor full line selection', () => {
return testWrapWithAbbreviation(multiCursorsWithFullLineSelection, 'span', wrapInlineElementExpected);
});
test('Wrap with snippet using multi cursor full line selection', () => {
return testWrapWithAbbreviation(multiCursorsWithFullLineSelection, 'a', wrapSnippetExpected);
});
test('Wrap with multi line abbreviation using multi cursor full line selection', () => {
return testWrapWithAbbreviation(multiCursorsWithFullLineSelection, 'ul>li', wrapMultiLineAbbrExpected);
});
test('Wrap with abbreviation and comment filter', () => {
const contents = `
<ul class="nav main">
line
</ul>
`;
const expectedContents = `
<ul class="nav main">
<li class="hello">
line
</li>
<!-- /.hello -->
</ul>
`;
return testWrapWithAbbreviation([new vscode_1.Selection(2, 0, 2, 0)], 'li.hello|c', expectedContents, contents);
});
test('Wrap with abbreviation entire node when cursor is on opening tag', () => {
const contents = `
<div class="nav main">
hello
</div>
`;
const expectedContents = `
<div>
<div class="nav main">
hello
</div>
</div>
`;
return testWrapWithAbbreviation([new vscode_1.Selection(1, 1, 1, 1)], 'div', expectedContents, contents);
});
test('Wrap with abbreviation entire node when cursor is on closing tag', () => {
const contents = `
<div class="nav main">
hello
</div>
`;
const expectedContents = `
<div>
<div class="nav main">
hello
</div>
</div>
`;
return testWrapWithAbbreviation([new vscode_1.Selection(3, 1, 3, 1)], 'div', expectedContents, contents);
});
test('Wrap with multiline abbreviation doesnt add extra spaces', () => {
// Issue #29898
const contents = `
hello
`;
const expectedContents = `
<ul>
<li><a href="">hello</a></li>
</ul>
`;
return testWrapWithAbbreviation([new vscode_1.Selection(1, 2, 1, 2)], 'ul>li>a', expectedContents, contents);
});
test('Wrap individual lines with abbreviation', () => {
const contents = `
<ul class="nav main">
<li class="item1">This $10 is not a tabstop</li>
<li class="item2">hi.there</li>
</ul>
`;
const wrapIndividualLinesExpected = `
<ul class="nav main">
<ul>
<li class="hello1"><li class="item1">This $10 is not a tabstop</li></li>
<li class="hello2"><li class="item2">hi.there</li></li>
</ul>
</ul>
`;
return testWrapIndividualLinesWithAbbreviation([new vscode_1.Selection(2, 2, 3, 33)], 'ul>li.hello$*', wrapIndividualLinesExpected, contents);
});
test('Wrap individual lines with abbreviation with extra space selected', () => {
const contents = `
<ul class="nav main">
<li class="item1">img</li>
<li class="item2">hi.there</li>
</ul>
`;
const wrapIndividualLinesExpected = `
<ul class="nav main">
<ul>
<li class="hello1"><li class="item1">img</li></li>
<li class="hello2"><li class="item2">hi.there</li></li>
</ul>
</ul>
`;
return testWrapIndividualLinesWithAbbreviation([new vscode_1.Selection(2, 1, 4, 0)], 'ul>li.hello$*', wrapIndividualLinesExpected, contents);
});
test('Wrap individual lines with abbreviation with comment filter', () => {
const contents = `
<ul class="nav main">
<li class="item1">img</li>
<li class="item2">hi.there</li>
</ul>
`;
const wrapIndividualLinesExpected = `
<ul class="nav main">
<ul>
<li class="hello"><li class="item1">img</li></li>
<!-- /.hello -->
<li class="hello"><li class="item2">hi.there</li></li>
<!-- /.hello -->
</ul>
</ul>
`;
return testWrapIndividualLinesWithAbbreviation([new vscode_1.Selection(2, 2, 3, 33)], 'ul>li.hello*|c', wrapIndividualLinesExpected, contents);
});
test('Wrap individual lines with abbreviation and trim', () => {
const contents = `
<ul class="nav main">
• lorem ipsum
• lorem ipsum
</ul>
`;
const wrapIndividualLinesExpected = `
<ul class="nav main">
<ul>
<li class="hello1">lorem ipsum</li>
<li class="hello2">lorem ipsum</li>
</ul>
</ul>
`;
return testWrapIndividualLinesWithAbbreviation([new vscode_1.Selection(2, 3, 3, 16)], 'ul>li.hello$*|t', wrapIndividualLinesExpected, contents);
});
test('Wrap with abbreviation and format set to false', () => {
return vscode_1.workspace.getConfiguration('emmet').update('syntaxProfiles', { 'html': { 'format': false } }, vscode_1.ConfigurationTarget.Global).then(() => {
return testWrapWithAbbreviation(multiCursors, 'h1', wrapInlineElementExpectedFormatFalse).then(() => {
return vscode_1.workspace.getConfiguration('emmet').update('syntaxProfiles', oldValueForSyntaxProfiles ? oldValueForSyntaxProfiles.globalValue : undefined, vscode_1.ConfigurationTarget.Global);
});
});
});
test('Wrap multi line selections with abbreviation', () => {
const htmlContentsForWrapMultiLineTests = `
<ul class="nav main">
line1
line2
line3
line4
</ul>
`;
const wrapMultiLineExpected = `
<ul class="nav main">
<div>
line1
line2
</div>
<div>
line3
line4
</div>
</ul>
`;
return testWrapWithAbbreviation([new vscode_1.Selection(2, 4, 3, 9), new vscode_1.Selection(5, 4, 6, 9)], 'div', wrapMultiLineExpected, htmlContentsForWrapMultiLineTests);
});
test('Wrap multiline with abbreviation uses className for jsx files', () => {
const wrapMultiLineJsxExpected = `
<ul class="nav main">
<div className="hello">
<li class="item1">img</li>
<li class="item2">$hithere</li>
</div>
</ul>
`;
return testWrapWithAbbreviation([new vscode_1.Selection(2, 2, 3, 33)], '.hello', wrapMultiLineJsxExpected, htmlContentsForWrapTests, 'jsx');
});
test('Wrap individual line with abbreviation uses className for jsx files', () => {
const wrapIndividualLinesJsxExpected = `
<ul class="nav main">
<div className="hello1"><li class="item1">img</li></div>
<div className="hello2"><li class="item2">$hithere</li></div>
</ul>
`;
return testWrapIndividualLinesWithAbbreviation([new vscode_1.Selection(2, 2, 3, 33)], '.hello$*', wrapIndividualLinesJsxExpected, htmlContentsForWrapTests, 'jsx');
});
});
function testWrapWithAbbreviation(selections, abbreviation, expectedContents, input = htmlContentsForWrapTests, fileExtension = 'html') {
return testUtils_1.withRandomFileEditor(input, fileExtension, (editor, _) => {
editor.selections = selections;
const promise = abbreviationActions_1.wrapWithAbbreviation({ abbreviation });
if (!promise) {
assert.equal(1, 2, 'Wrap with Abbreviation returned undefined.');
return Promise.resolve();
}
return promise.then(() => {
assert.equal(editor.document.getText(), expectedContents);
return Promise.resolve();
});
});
}
function testWrapIndividualLinesWithAbbreviation(selections, abbreviation, expectedContents, input = htmlContentsForWrapTests, fileExtension = 'html') {
return testUtils_1.withRandomFileEditor(input, fileExtension, (editor, _) => {
editor.selections = selections;
const promise = abbreviationActions_1.wrapIndividualLinesWithAbbreviation({ abbreviation });
if (!promise) {
assert.equal(1, 2, 'Wrap individual lines with Abbreviation returned undefined.');
return Promise.resolve();
}
return promise.then(() => {
assert.equal(editor.document.getText(), expectedContents);
return Promise.resolve();
});
});
}
//# sourceMappingURL=wrapWithAbbreviation.test.js.map |
const {app, BrowserWindow} = require('electron')
const path = require('path').resolve(__dirname, './../fixtures/test.js')
const url = require('path').resolve(__dirname, './../fixtures/test.html')
app.on('ready', () => {
let win = new BrowserWindow()
win.loadURL('file://' + url)
try {
win.webContents.debugger.attach()
} catch (err) {
console.error('Debugger attach failed : ', err)
}
win.webContents.debugger.on('detach', (event, reason) => {
console.log('Debugger detached due to : ', reason)
})
win.webContents.once('devtools-opened', function () {
console.log('devtools opened')
//setTimeout(win.webContents.reload.bind(win.webContents), 1000)
})
win.webContents.once('did-finish-load', () => {
console.log('win loaded')
setTimeout( () => {
win.webContents.debugger.sendCommand('Debugger.enable', (err) => {
console.log('debugger enabled', err)
setTimeout( () => {
setBreakpointByUrl(win.webContents.debugger, path, () => {
setTimeout(() => {
//win.webContents.debugger.detach()
win.webContents.openDevTools({mode: 'detach'})
}, 1000)
})
}, 1000)
setImmediate( () => {
setBreakpointByUrl(win.webContents.debugger, 'file://' + path)
})
})
}, 1000)
})
})
function setBreakpointByUrl(dbgr, url, cb) {
dbgr.sendCommand(
'Debugger.setBreakpointByUrl',
{
lineNumber: 0,
url: url
},
(err, result) => {
if(err && err.msg){
console.error('Error:', err)
}
console.log('Breakpoint set: ', result)
if (typeof cb == 'function') {
cb(err, result)
}
})
}
|
const { Song, Output } = require('chorus');
require('chorus/names').into(global);
const song = new Song({
bpm: 132,
sections: [{
parts: [{
pitches: [KICK, SNARE, RIM, CLAP, CLOSED_HIHAT, OPEN_HIHAT, CYMBAL],
}]
}]
});
Output.select().then(output => output.play(song));
|
/*
*
* ViewUsers reducer
*
*/
import produce from 'immer';
import { DEFAULT_ACTION } from './constants';
export const initialState = {};
/* eslint-disable default-case, no-param-reassign */
const viewUsersReducer = (state = initialState, action) =>
produce(state, (/* draft */) => {
switch (action.type) {
case DEFAULT_ACTION:
break;
}
});
export default viewUsersReducer;
|
const homePage = require("../../../locators/HomePage");
const reconnectDatasourceModal = require("../../../locators/ReconnectLocators");
describe("Import, Export and Fork application and validate data binding", function() {
let orgid;
let appid;
let newOrganizationName;
let appName;
it("Import application from json and validate data on pageload", function() {
// import application
cy.get(homePage.homeIcon).click();
cy.get(homePage.optionsIcon)
.first()
.click();
cy.get(homePage.orgImportAppOption).click({ force: true });
cy.get(homePage.orgImportAppModal).should("be.visible");
cy.xpath(homePage.uploadLogo).attachFile("forkedApp.json");
cy.get(homePage.importAppProgressWrapper).should("be.visible");
cy.wait("@importNewApplication").then((interception) => {
cy.wait(100);
// should check reconnect modal openning
const { isPartialImport } = interception.response.body.data;
if (isPartialImport) {
// should reconnect button
cy.get(reconnectDatasourceModal.Modal).should("be.visible");
cy.get(reconnectDatasourceModal.SkipToAppBtn).click({ force: true });
cy.wait(2000);
} else {
cy.get(homePage.toastMessage).should(
"contain",
"Application imported successfully",
);
}
const uuid = () => Cypress._.random(0, 1e4);
const name = uuid();
appName = `app${name}`;
cy.get(homePage.applicationName).click({ force: true });
cy.get(`${homePage.applicationEditMenu} li:first-child a`).click({
force: true,
});
cy.wait(2000);
cy.get(homePage.applicationName)
.clear()
.type(appName);
cy.wrap(appName).as("appname");
cy.wait(2000);
// validating data binding for the imported application
cy.xpath("//input[@value='Submit']").should("be.visible");
cy.xpath("//div[text()='schema_name']").should("be.visible");
cy.xpath("//div[text()='id']").should("be.visible");
cy.xpath("//div[text()='title']").should("be.visible");
cy.xpath("//div[text()='due']").should("be.visible");
});
});
it("Fork application and validate data binding for the widgets", function() {
// fork application
cy.get(homePage.homeIcon).click();
cy.get(homePage.searchInput).type(`${appName}`);
cy.wait(2000);
cy.get(homePage.applicationCard)
.first()
.trigger("mouseover");
cy.get(homePage.appMoreIcon)
.first()
.click({ force: true });
cy.get(homePage.forkAppFromMenu).click({ force: true });
cy.get(homePage.forkAppOrgButton).click({ force: true });
cy.wait(4000);
// validating data binding for the forked application
cy.xpath("//input[@value='Submit']").should("be.visible");
cy.xpath("//div[text()='schema_name']").should("be.visible");
cy.xpath("//div[text()='id']").should("be.visible");
cy.xpath("//div[text()='title']").should("be.visible");
cy.xpath("//div[text()='due']").should("be.visible");
});
it("Export and import application and validate data binding for the widgets", function() {
cy.NavigateToHome();
cy.get(homePage.searchInput)
.clear()
.type(`${appName}`);
cy.wait(2000);
cy.get(homePage.applicationCard)
.first()
.trigger("mouseover");
cy.get(homePage.appMoreIcon)
.first()
.click({ force: true });
// export application
cy.get(homePage.exportAppFromMenu).click({ force: true });
cy.get(homePage.searchInput).clear();
cy.get(`a[id=t--export-app-link]`).then((anchor) => {
const url = anchor.prop("href");
cy.request(url).then(({ body, headers }) => {
expect(headers).to.have.property("content-type", "application/json");
expect(headers).to.have.property(
"content-disposition",
`attachment; filename*=UTF-8''${appName}.json`,
);
cy.writeFile("cypress/fixtures/exportedApp.json", body, "utf-8");
cy.generateUUID().then((uid) => {
orgid = uid;
localStorage.setItem("OrgName", orgid);
cy.createOrg();
cy.wait("@createOrg").then((createOrgInterception) => {
newOrganizationName = createOrgInterception.response.body.data.name;
cy.renameOrg(newOrganizationName, orgid);
cy.get(homePage.orgImportAppOption).click({ force: true });
cy.get(homePage.orgImportAppModal).should("be.visible");
// cy.get(".t--import-json-card input").attachFile("exportedApp.json");
cy.xpath(homePage.uploadLogo).attachFile("exportedApp.json");
// import exported application in new organization
// cy.get(homePage.orgImportAppButton).click({ force: true });
cy.wait("@importNewApplication").then((interception) => {
const { isPartialImport } = interception.response.body.data;
if (isPartialImport) {
// should reconnect button
cy.get(reconnectDatasourceModal.Modal).should("be.visible");
cy.get(reconnectDatasourceModal.SkipToAppBtn).click({
force: true,
});
cy.wait(2000);
} else {
cy.get(homePage.toastMessage).should(
"contain",
"Application imported successfully",
);
}
const importedApp = interception.response.body.data.application;
const appSlug = importedApp.slug;
cy.wait("@getPagesForCreateApp").then((interception) => {
const pages = interception.response.body.data.pages;
let defaultPage = pages.find(
(eachPage) => !!eachPage.isDefault,
);
// validating data binding for imported application
cy.xpath("//input[@value='Submit']").should("be.visible");
cy.xpath("//div[text()='schema_name']").should("be.visible");
// cy.xpath("//div[text()='information_schema']").should(
// "be.visible",
// );
cy.xpath("//div[text()='id']").should("be.visible");
cy.xpath("//div[text()='title']").should("be.visible");
cy.xpath("//div[text()='due']").should("be.visible");
cy.url().should(
"include",
`/${appSlug}/${defaultPage.slug}-${defaultPage.id}/edit`,
);
});
});
});
});
});
});
});
});
|
var Util = require('../util');
module.exports = function Player() {
var _this = this;
this.shipState = null;
this.damage = function(shipClass) {
for (var i = 0; i < _this.shipState.length; i++) {
if (_this.shipState[i].type === shipClass) {
_this.shipState[i].hitCount++;
if (_this.shipState[i].hitCount === Util.ships[shipClass].width) {
_this.shipState[i].sunk = 0;
return true;
};
}
}
return false;
}
this.shipsLeft = function() {
var ships = [];
for (var i = 0; i < _this.shipState.length; i++) {
if (_this.shipState[i].sunk === 1) {
ships.push(_this.shipState[i].type);
};
};
return ships;
}
this.shipStateInfo = function(key) {
var reducedObj;
switch (key) {
case 'sunk':
reducedObj = _this.shipState.reduce(function(a, b) {
return {
sunk: a[key] + b[key]
}; // sums the value of a + b (values next to each other)
});
break;
default:
reducedObj = _this.shipState.reduce(function(a, b) {
return {
placed: a[key] + b[key]
}; // sums the value of a + b (values next to each other)
});
break;
}
return reducedObj[key] === 0;
};
}
|
from time import time
import logging
import numpy as np
import tensorflow.contrib.slim as slim
from data_random_short_diagonal import next_batch, visualise_mat, get_relevant_prediction_index
from md_lstm import *
logger = logging.getLogger(__name__)
class FileLogger(object):
def __init__(self, full_filename, headers):
self._headers = headers
self._out_fp = open(full_filename, 'w')
self._write(headers)
def write(self, line):
assert len(line) == len(self._headers)
self._write(line)
def close(self):
self._out_fp.close()
def _write(self, arr):
arr = [str(e) for e in arr]
self._out_fp.write(' '.join(arr) + '\n')
self._out_fp.flush()
def run():
learning_rate = 0.01
batch_size = 16
h = 8
w = 8
channels = 1
hidden_size = 16
x = tf.placeholder(tf.float32, [batch_size, h, w, channels])
y = tf.placeholder(tf.float32, [batch_size, h, w, channels])
rnn_out, _ = MdRnnWhileLoop()(rnn_size=hidden_size, input_data=x)
model_out = slim.fully_connected(inputs=rnn_out, num_outputs=1, activation_fn=tf.nn.sigmoid)
loss = tf.reduce_mean(tf.square(y - model_out))
grad_update = tf.train.AdamOptimizer(learning_rate).minimize(loss)
sess = tf.Session(config=tf.ConfigProto(log_device_placement=False))
sess.run(tf.global_variables_initializer())
fp = FileLogger('out.tsv', ['steps', 'overall_loss', 'time'])
steps = 1000
for i in range(steps):
batch = next_batch(batch_size, h, w)
grad_step_start_time = time()
batch_x = np.expand_dims(batch[0], axis=3)
batch_y = np.expand_dims(batch[1], axis=3)
model_preds, tot_loss_value, _ = sess.run([model_out, loss, grad_update], feed_dict={
x: batch_x,
y: batch_y,
})
"""
____________
| |
| |
| x |
| x <----- extract this prediction. Relevant loss is only computed for this value.
|__________| we don't care about the rest (even though the model is trained on all values
for simplicity). A standard LSTM should have a very high value for relevant loss
whereas a MD LSTM (which can see all the TOP LEFT corner) should perform well.
"""
values = [str(i).zfill(4), tot_loss_value, time() - grad_step_start_time]
format_str = 'steps = {0} | overall loss = {1:.3f} | time {2:.3f}'
logger.info(format_str.format(*values))
fp.write(values)
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)12s - %(levelname)s - %(message)s', level=logging.INFO)
run()
|
for(var i=0;;i++) {
var tx = web3.eth.getTransactionFromBlock(i, 0);
if(tx !== null) {
console.log(tx["to"]);
console.log(i);
if(tx["to"] === null) {
console.log(tx);
break;
}
}
}
|
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
/**
* default size for font size
* @constant
* @type Number
*/
cc.ITEM_SIZE = 32;
cc._globalFontSize = cc.ITEM_SIZE;
cc._globalFontName = "Arial";
cc._globalFontNameRelease = false;
/**
* default tag for current item
* @constant
* @type Number
*/
cc.CURRENT_ITEM = 0xc0c05001;
/**
* default tag for zoom action tag
* @constant
* @type Number
*/
cc.ZOOM_ACTION_TAG = 0xc0c05002;
/**
* default tag for normal
* @constant
* @type Number
*/
cc.NORMAL_TAG = 8801;
/**
* default selected tag
* @constant
* @type Number
*/
cc.SELECTED_TAG = 8802;
/**
* default disabled tag
* @constant
* @type Number
*/
cc.DISABLE_TAG = 8803;
/**
* Subclass cc.MenuItem (or any subclass) to create your custom cc.MenuItem objects.
* @class
* @extends cc.NodeRGBA
*/
cc.MenuItem = cc.NodeRGBA.extend(/** @lends cc.MenuItem# */{
_target:null,
_callback:null,
_isSelected:false,
_isEnabled:false,
ctor:function(){
cc.NodeRGBA.prototype.ctor.call(this);
this._target = null;
this._callback = null;
this._isSelected = false;
this._isEnabled = false;
},
/**
* MenuItem is selected
* @return {Boolean}
*/
isSelected:function () {
return this._isSelected;
},
setOpacityModifyRGB:function (value) {
},
isOpacityModifyRGB:function () {
return false;
},
/**
* set the target/selector of the menu item
* @param {function|String} selector
* @param {cc.Node} rec
* @deprecated
*/
setTarget:function (selector, rec) {
this._target = rec;
this._callback = selector;
},
/**
* MenuItem is Enabled
* @return {Boolean}
*/
isEnabled:function () {
return this._isEnabled;
},
/**
* set enable value of MenuItem
* @param {Boolean} enable
*/
setEnabled:function (enable) {
this._isEnabled = enable;
},
/**
* @param {function|String} callback
* @param {cc.Node} target
* @return {Boolean}
*/
initWithCallback:function (callback, target) {
this.setAnchorPoint(0.5, 0.5);
this._target = target;
this._callback = callback;
this._isEnabled = true;
this._isSelected = false;
return true;
},
/**
* return rect value of cc.MenuItem
* @return {cc.Rect}
*/
rect:function () {
var locPosition = this._position, locContentSize = this._contentSize, locAnchorPoint = this._anchorPoint;
return cc.rect(locPosition.x - locContentSize.width * locAnchorPoint.x,
locPosition.y - locContentSize.height * locAnchorPoint.y,
locContentSize.width, locContentSize.height);
},
/**
* same as setIsSelected(true)
*/
selected:function () {
this._isSelected = true;
},
/**
* same as setIsSelected(false)
*/
unselected:function () {
this._isSelected = false;
},
/**
* set the callback to the menu item
* @param {function|String} callback
* @param {cc.Node} target
*/
setCallback:function (callback, target) {
this._target = target;
this._callback = callback;
},
/**
* call the selector with target
*/
activate:function () {
if (this._isEnabled) {
cc.doCallback(this._callback, this._target,this);
}
}
});
/**
* creates an empty menu item with target and callback<br/>
* Not recommended to use the base class, should use more defined menu item classes
* @param {function|String} callback callback
* @param {cc.Node} target
* @return {cc.MenuItem}
*/
cc.MenuItem.create = function (callback, target) {
var ret = new cc.MenuItem();
ret.initWithCallback(callback,target);
return ret;
};
/**
* Any cc.Node that supports the cc.LabelProtocol protocol can be added.<br/>
* Supported nodes:<br/>
* - cc.BitmapFontAtlas<br/>
* - cc.LabelAtlas<br/>
* - cc.LabelTTF<br/>
* @class
* @extends cc.MenuItem
*/
cc.MenuItemLabel = cc.MenuItem.extend(/** @lends cc.MenuItemLabel# */{
_disabledColor: null,
_label: null,
_orginalScale: 0,
_colorBackup: null,
ctor: function () {
cc.MenuItem.prototype.ctor.call(this);
this._disabledColor = null;
this._label = null;
this._orginalScale = 0;
this._colorBackup = null;
},
/**
* @return {cc.Color3B}
*/
getDisabledColor:function () {
return this._disabledColor;
},
/**
* @param {cc.Color3B} color
*/
setDisabledColor:function (color) {
this._disabledColor = color;
},
/**
* return label of MenuItemLabel
* @return {cc.Node}
*/
getLabel:function () {
return this._label;
},
/**
* @param {cc.Node} label
*/
setLabel:function (label) {
if (label) {
this.addChild(label);
label.setAnchorPoint(0, 0);
this.setContentSize(label.getContentSize());
}
if (this._label) {
this.removeChild(this._label, true);
}
this._label = label;
},
/**
* @param {Boolean} enabled
*/
setEnabled:function (enabled) {
if (this._isEnabled != enabled) {
var locLabel = this._label;
if (!enabled) {
this._colorBackup = locLabel.getColor();
locLabel.setColor(this._disabledColor);
} else {
locLabel.setColor(this._colorBackup);
}
}
cc.MenuItem.prototype.setEnabled.call(this, enabled);
},
/**
* @param {Number} opacity from 0-255
*/
setOpacity:function (opacity) {
this._label.setOpacity(opacity);
},
/**
* @return {Number}
*/
getOpacity:function () {
return this._label.getOpacity();
},
/**
* @param {cc.Color3B} color
*/
setColor:function (color) {
this._label.setColor(color);
},
/**
* @return {cc.Color3B}
*/
getColor:function () {
return this._label.getColor();
},
/**
* @param {cc.Node} label
* @param {function|String} selector
* @param {cc.Node} target
* @return {Boolean}
*/
initWithLabel:function (label, selector, target) {
this.initWithCallback(selector, target);
this._originalScale = 1.0;
this._colorBackup = cc.white();
this._disabledColor = cc.c3b(126, 126, 126);
this.setLabel(label);
this.setCascadeColorEnabled(true);
this.setCascadeOpacityEnabled(true);
return true;
},
/**
* @param {String} label
*/
setString:function (label) {
this._label.setString(label);
this.setContentSize(this._label.getContentSize());
},
/**
* activate the menu item
*/
activate:function () {
if (this._isEnabled) {
this.stopAllActions();
this.setScale(this._originalScale);
cc.MenuItem.prototype.activate.call(this);
}
},
/**
* menu item is selected (runs callback)
*/
selected:function () {
if (this._isEnabled) {
cc.MenuItem.prototype.selected.call(this);
var action = this.getActionByTag(cc.ZOOM_ACTION_TAG);
if (action)
this.stopAction(action);
else
this._originalScale = this.getScale();
var zoomAction = cc.ScaleTo.create(0.1, this._originalScale * 1.2);
zoomAction.setTag(cc.ZOOM_ACTION_TAG);
this.runAction(zoomAction);
}
},
/**
* menu item goes back to unselected state
*/
unselected:function () {
if (this._isEnabled) {
cc.MenuItem.prototype.unselected.call(this);
this.stopActionByTag(cc.ZOOM_ACTION_TAG);
var zoomAction = cc.ScaleTo.create(0.1, this._originalScale);
zoomAction.setTag(cc.ZOOM_ACTION_TAG);
this.runAction(zoomAction);
}
}
});
/**
* @param {cc.Node} label
* @param {function|String|Null} [selector=]
* @param {cc.Node|Null} [target=]
* @return {cc.MenuItemLabel}
*/
cc.MenuItemLabel.create = function (label, selector, target) {
var ret = new cc.MenuItemLabel();
ret.initWithLabel(label, selector, target);
return ret;
};
/**
* Helper class that creates a MenuItemLabel class with a LabelAtlas
* @class
* @extends cc.MenuItemLabel
*/
cc.MenuItemAtlasFont = cc.MenuItemLabel.extend(/** @lends cc.MenuItemAtlasFont# */{
/**
* @param {String} value
* @param {String} charMapFile
* @param {Number} itemWidth
* @param {Number} itemHeight
* @param {String} startCharMap a single character
* @param {function|String|Null} callback
* @param {cc.Node|Null} target
* @return {Boolean}
*/
initWithString:function (value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) {
if(!value || value.length == 0)
throw "cc.MenuItemAtlasFont.initWithString(): value should be non-null and its length should be greater than 0";
var label = new cc.LabelAtlas();
label.initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap);
if (this.initWithLabel(label, callback, target)) {
// do something ?
}
return true;
}
});
/**
* create menu item from string with font
* @param {String} value the text to display
* @param {String} charMapFile the character map file
* @param {Number} itemWidth
* @param {Number} itemHeight
* @param {String} startCharMap a single character
* @param {function|String|Null} [callback=null]
* @param {cc.Node|Null} [target=]
* @return {cc.MenuItemAtlasFont}
* @example
* // Example
* var item = cc.MenuItemAtlasFont.create('text to display', 'font.fnt', 12, 32, ' ')
*
* //OR
* var item = cc.MenuItemAtlasFont.create('text to display', 'font.fnt', 12, 32, ' ', game.run, game)
*/
cc.MenuItemAtlasFont.create = function (value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) {
var ret = new cc.MenuItemAtlasFont();
ret.initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target);
return ret;
};
/**
* Helper class that creates a CCMenuItemLabel class with a Label
* @class
* @extends cc.MenuItemLabel
*/
cc.MenuItemFont = cc.MenuItemLabel.extend(/** @lends cc.MenuItemFont# */{
_fontSize:null,
_fontName:null,
ctor:function(){
cc.MenuItemLabel.prototype.ctor.call(this);
this._fontSize = 0;
this._fontName = "";
},
/**
* @param {String} value text for the menu item
* @param {function|String} callback
* @param {cc.Node} target
* @return {Boolean}
*/
initWithString:function (value, callback, target) {
if(!value || value.length == 0)
throw "Value should be non-null and its length should be greater than 0";
this._fontName = cc._globalFontName;
this._fontSize = cc._globalFontSize;
var label = cc.LabelTTF.create(value, this._fontName, this._fontSize);
if (this.initWithLabel(label, callback, target)) {
// do something ?
}
return true;
},
/**
* @param {Number} s
*/
setFontSize:function (s) {
this._fontSize = s;
this._recreateLabel();
},
/**
*
* @return {Number}
*/
fontSize:function () {
return this._fontSize;
},
/**
* @param {String} name
*/
setFontName:function (name) {
this._fontName = name;
this._recreateLabel();
},
/**
* @return {String}
*/
fontName:function () {
return this._fontName;
},
_recreateLabel:function () {
var label = cc.LabelTTF.create(this._label.getString(),
this._fontName, this._fontSize);
this.setLabel(label);
}
});
/**
* a shared function to set the fontSize for menuitem font
* @param {Number} fontSize
*/
cc.MenuItemFont.setFontSize = function (fontSize) {
cc._globalFontSize = fontSize;
};
/**
* a shared function to get the font size for menuitem font
* @return {Number}
*/
cc.MenuItemFont.fontSize = function () {
return cc._globalFontSize;
};
/**
* a shared function to set the fontsize for menuitem font
* @param name
*/
cc.MenuItemFont.setFontName = function (name) {
if (cc._globalFontNameRelease) {
cc._globalFontName = '';
}
cc._globalFontName = name;
cc._globalFontNameRelease = true;
};
/**
* a shared function to get the font name for menuitem font
* @return {String}
*/
cc.MenuItemFont.fontName = function () {
return cc._globalFontName;
};
/**
* create a menu item from string
* @param {String} value the text to display
* @param {String|function|Null} callback the callback to run, either in function name or pass in the actual function
* @param {cc.Node|Null} target the target to run callback
* @return {cc.MenuItemFont}
* @example
* // Example
* var item = cc.MenuItemFont.create("Game start", 'start', Game)
* //creates a menu item from string "Game start", and when clicked, it will run Game.start()
*
* var item = cc.MenuItemFont.create("Game start", game.start, Game)//same as above
*
* var item = cc.MenuItemFont.create("i do nothing")//create a text menu item that does nothing
*
* //you can set font size and name before or after
* cc.MenuItemFont.setFontName('my Fancy Font');
* cc.MenuItemFont.setFontSize(62);
*/
cc.MenuItemFont.create = function (value, callback, target) {
var ret = new cc.MenuItemFont();
ret.initWithString(value, callback, target);
return ret;
};
/**
* CCMenuItemSprite accepts CCNode<CCRGBAProtocol> objects as items.<br/>
* The images has 3 different states:<br/>
* - unselected image<br/>
* - selected image<br/>
* - disabled image<br/>
* @class
* @extends cc.MenuItem
*/
cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{
_normalImage:null,
_selectedImage:null,
_disabledImage:null,
ctor: function(){
cc.MenuItem.prototype.ctor.call(this);
this._normalImage = null;
this._selectedImage = null;
this._disabledImage = null;
},
/**
* @return {cc.Sprite}
*/
getNormalImage:function () {
return this._normalImage;
},
/**
* @param {cc.Sprite} normalImage
*/
setNormalImage:function (normalImage) {
if (this._normalImage == normalImage) {
return;
}
if (normalImage) {
this.addChild(normalImage, 0, cc.NORMAL_TAG);
normalImage.setAnchorPoint(0, 0);
}
if (this._normalImage) {
this.removeChild(this._normalImage, true);
}
this._normalImage = normalImage;
this.setContentSize(this._normalImage.getContentSize());
this._updateImagesVisibility();
if (normalImage.textureLoaded && !normalImage.textureLoaded()) {
normalImage.addLoadedEventListener(function (sender) {
this.setContentSize(sender.getContentSize());
}, this);
}
},
/**
* @return {cc.Sprite}
*/
getSelectedImage:function () {
return this._selectedImage;
},
/**
* @param {cc.Sprite} selectedImage
*/
setSelectedImage:function (selectedImage) {
if (this._selectedImage == selectedImage)
return;
if (selectedImage) {
this.addChild(selectedImage, 0, cc.SELECTED_TAG);
selectedImage.setAnchorPoint(0, 0);
}
if (this._selectedImage) {
this.removeChild(this._selectedImage, true);
}
this._selectedImage = selectedImage;
this._updateImagesVisibility();
},
/**
* @return {cc.Sprite}
*/
getDisabledImage:function () {
return this._disabledImage;
},
/**
* @param {cc.Sprite} disabledImage
*/
setDisabledImage:function (disabledImage) {
if (this._disabledImage == disabledImage)
return;
if (disabledImage) {
this.addChild(disabledImage, 0, cc.DISABLE_TAG);
disabledImage.setAnchorPoint(0, 0);
}
if (this._disabledImage)
this.removeChild(this._disabledImage, true);
this._disabledImage = disabledImage;
this._updateImagesVisibility();
},
/**
* @param {cc.Node} normalSprite
* @param {cc.Node} selectedSprite
* @param {cc.Node} disabledSprite
* @param {function|String} callback
* @param {cc.Node} target
* @return {Boolean}
*/
initWithNormalSprite:function (normalSprite, selectedSprite, disabledSprite, callback, target) {
this.initWithCallback(callback, target);
this.setNormalImage(normalSprite);
this.setSelectedImage(selectedSprite);
this.setDisabledImage(disabledSprite);
var locNormalImage = this._normalImage;
if (locNormalImage) {
this.setContentSize(locNormalImage.getContentSize());
if (locNormalImage.textureLoaded && !locNormalImage.textureLoaded()) {
locNormalImage.addLoadedEventListener(function (sender) {
this.setContentSize(sender.getContentSize());
this.setCascadeColorEnabled(true);
this.setCascadeOpacityEnabled(true);
}, this);
}
}
this.setCascadeColorEnabled(true);
this.setCascadeOpacityEnabled(true);
return true;
},
/**
* @param {cc.Color3B} color
*/
setColor:function (color) {
this._normalImage.setColor(color);
if (this._selectedImage)
this._selectedImage.setColor(color);
if (this._disabledImage)
this._disabledImage.setColor(color);
},
/**
* @return {cc.Color3B}
*/
getColor:function () {
return this._normalImage.getColor();
},
/**
* @param {Number} opacity 0 - 255
*/
setOpacity:function (opacity) {
this._normalImage.setOpacity(opacity);
if (this._selectedImage)
this._selectedImage.setOpacity(opacity);
if (this._disabledImage)
this._disabledImage.setOpacity(opacity);
},
/**
* @return {Number} opacity from 0 - 255
*/
getOpacity:function () {
return this._normalImage.getOpacity();
},
/**
* menu item is selected (runs callback)
*/
selected:function () {
cc.MenuItem.prototype.selected.call(this);
if (this._normalImage) {
if (this._disabledImage)
this._disabledImage.setVisible(false);
if (this._selectedImage) {
this._normalImage.setVisible(false);
this._selectedImage.setVisible(true);
} else
this._normalImage.setVisible(true);
}
},
/**
* menu item goes back to unselected state
*/
unselected:function () {
cc.MenuItem.prototype.unselected.call(this);
if (this._normalImage) {
this._normalImage.setVisible(true);
if (this._selectedImage)
this._selectedImage.setVisible(false);
if (this._disabledImage)
this._disabledImage.setVisible(false);
}
},
/**
* @param {Boolean} bEnabled
*/
setEnabled:function (bEnabled) {
if (this._isEnabled != bEnabled) {
cc.MenuItem.prototype.setEnabled.call(this, bEnabled);
this._updateImagesVisibility();
}
},
_updateImagesVisibility:function () {
var locNormalImage = this._normalImage, locSelImage = this._selectedImage, locDisImage = this._disabledImage;
if (this._isEnabled) {
if (locNormalImage)
locNormalImage.setVisible(true);
if (locSelImage)
locSelImage.setVisible(false);
if (locDisImage)
locDisImage.setVisible(false);
} else {
if (locDisImage) {
if (locNormalImage)
locNormalImage.setVisible(false);
if (locSelImage)
locSelImage.setVisible(false);
if (locDisImage)
locDisImage.setVisible(true);
} else {
if (locNormalImage)
locNormalImage.setVisible(true);
if (locSelImage)
locSelImage.setVisible(false);
}
}
}
});
/**
* create a menu item from sprite
* @param {Image} normalSprite normal state image
* @param {Image|Null} selectedSprite selected state image
* @param {Image|cc.Node|Null} three disabled state image OR target node
* @param {String|function|cc.Node|Null} four callback function name in string or actual function, OR target Node
* @param {String|function|Null} five callback function name in string or actual function
* @return {cc.MenuItemSprite}
* @example
* // Example
* var item = cc.MenuItemSprite.create(normalImage)//create a menu item from a sprite with no functionality
*
* var item = cc.MenuItemSprite.create(normalImage, selectedImage)//create a menu Item, nothing will happen when clicked
*
* var item = cc.MenuItemSprite.create(normalImage, SelectedImage, disabledImage)//same above, but with disabled state image
*
* var item = cc.MenuItemSprite.create(normalImage, SelectedImage, 'callback', targetNode)//create a menu item, when clicked runs targetNode.callback()
*
* var item = cc.MenuItemSprite.create(normalImage, SelectedImage, disabledImage, targetNode.callback, targetNode)
* //same as above, but with disabled image, and passing in callback function
*/
cc.MenuItemSprite.create = function (normalSprite, selectedSprite, three, four, five) {
var len = arguments.length;
normalSprite = arguments[0];
selectedSprite = arguments[1];
var disabledImage, target, callback;
var ret = new cc.MenuItemSprite();
//when you send 4 arguments, five is undefined
if (len == 5) {
disabledImage = arguments[2];
callback = arguments[3];
target = arguments[4];
} else if (len == 4 && typeof arguments[3] === "function") {
disabledImage = arguments[2];
callback = arguments[3];
} else if (len == 4 && typeof arguments[2] === "function") {
target = arguments[3];
callback = arguments[2];
} else if (len <= 2) {
disabledImage = arguments[2];
}
ret.initWithNormalSprite(normalSprite, selectedSprite, disabledImage, callback, target);
return ret;
};
/**
* cc.MenuItemImage accepts images as items.<br/>
* The images has 3 different states:<br/>
* - unselected image<br/>
* - selected image<br/>
* - disabled image<br/>
* <br/>
* For best results try that all images are of the same size<br/>
* @class
* @extends cc.MenuItemSprite
*/
cc.MenuItemImage = cc.MenuItemSprite.extend(/** @lends cc.MenuItemImage# */{
/**
* sets the sprite frame for the normal image
* @param {cc.SpriteFrame} frame
*/
setNormalSpriteFrame:function (frame) {
this.setNormalImage(cc.Sprite.createWithSpriteFrame(frame));
},
/**
* sets the sprite frame for the selected image
* @param {cc.SpriteFrame} frame
*/
setSelectedSpriteFrame:function (frame) {
this.setSelectedImage(cc.Sprite.createWithSpriteFrame(frame));
},
/**
* sets the sprite frame for the disabled image
* @param {cc.SpriteFrame} frame
*/
setDisabledSpriteFrame:function (frame) {
this.setDisabledImage(cc.Sprite.createWithSpriteFrame(frame));
},
/**
* @param {string|null} normalImage
* @param {string|null} selectedImage
* @param {string|null} disabledImage
* @param {function|string|null} callback
* @param {cc.Node|null} target
* @returns {boolean}
*/
initWithNormalImage:function (normalImage, selectedImage, disabledImage, callback, target) {
var normalSprite = null;
var selectedSprite = null;
var disabledSprite = null;
if (normalImage) {
normalSprite = cc.Sprite.create(normalImage);
}
if (selectedImage) {
selectedSprite = cc.Sprite.create(selectedImage);
}
if (disabledImage) {
disabledSprite = cc.Sprite.create(disabledImage);
}
return this.initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, callback, target);
}
});
/**
* creates a new menu item image
* @param {String} normalImage file name for normal state
* @param {String} selectedImage image for selected state
* @param {String|cc.Node} three Disabled image OR callback function
* @param {String|function|Null} [four] callback function, either name in string or pass the whole function OR the target
* @param {cc.Node|String|function|Null} [five] cc.Node target to run callback when clicked
* @return {cc.MenuItemImage}
* @example
* // Example
* //create a dom menu item with normal and selected state, when clicked it will run the run function from gameScene object
* var item = cc.MenuItemImage.create('normal.png', 'selected.png', 'run', gameScene)
*
* //same as above, but pass in the actual function and disabled image
* var item = cc.MenuItemImage.create('normal.png', 'selected.png', 'disabled.png', gameScene.run, gameScene)
*/
cc.MenuItemImage.create = function (normalImage, selectedImage, three, four, five) {
if (normalImage === undefined) {
return cc.MenuItemImage.create(null, null, null, null, null);
}
else if (four === undefined) {
return cc.MenuItemImage.create(normalImage, selectedImage, null, three, null);
}
else if (five === undefined) {
return cc.MenuItemImage.create(normalImage, selectedImage, null, three, four);
}
var ret = new cc.MenuItemImage();
if (ret.initWithNormalImage(normalImage, selectedImage, three, four, five))
return ret;
return null;
};
/**
* A simple container class that "toggles" it's inner items<br/>
* The inner items can be any MenuItem
* @class
* @extends cc.MenuItem
*/
cc.MenuItemToggle = cc.MenuItem.extend(/** @lends cc.MenuItemToggle# */{
_selectedIndex:0,
_subItems:null,
_opacity:null,
_color:null,
ctor: function(){
cc.MenuItem.prototype.ctor.call(this);
this._selectedIndex = 0;
this._subItems = [];
this._opacity = 0;
this._color = cc.white();
},
/**
* @return {Number}
*/
getOpacity:function () {
return this._opacity;
},
/**
* @param {Number} Opacity
*/
setOpacity:function (Opacity) {
this._opacity = Opacity;
if (this._subItems && this._subItems.length > 0) {
for (var it = 0; it < this._subItems.length; it++) {
this._subItems[it].setOpacity(Opacity);
}
}
},
/**
* @return {cc.Color3B}
*/
getColor:function () {
return this._color;
},
/**
* @param {cc.Color3B} Color
*/
setColor:function (Color) {
this._color = Color;
if (this._subItems && this._subItems.length > 0) {
for (var it = 0; it < this._subItems.length; it++) {
this._subItems[it].setColor(Color);
}
}
},
/**
* @return {Number}
*/
getSelectedIndex:function () {
return this._selectedIndex;
},
/**
* @param {Number} SelectedIndex
*/
setSelectedIndex:function (SelectedIndex) {
if (SelectedIndex != this._selectedIndex) {
this._selectedIndex = SelectedIndex;
var currItem = this.getChildByTag(cc.CURRENT_ITEM);
if (currItem)
currItem.removeFromParent(false);
var item = this._subItems[this._selectedIndex];
this.addChild(item, 0, cc.CURRENT_ITEM);
var s = item.getContentSize();
this.setContentSize(s);
item.setPosition(s.width / 2, s.height / 2);
}
},
/**
* similar to get children
* @return {cc.MenuItem}
*/
getSubItems:function () {
return this._subItems;
},
/**
* @param {cc.MenuItem} SubItems
*/
setSubItems:function (SubItems) {
this._subItems = SubItems;
},
/**
* @param {cc.MenuItem} args[0...last-2] the rest in the array are cc.MenuItems
* @param {function|String} args[last-1] the second item in the args array is the callback
* @param {cc.Node} args[last] the first item in the args array is a target
* @return {Boolean}
*/
initWithItems:function (args) {
var l = args.length;
// passing callback.
if (typeof args[args.length-2] === 'function') {
this.initWithCallback( args[args.length-2], args[args.length-1] );
l = l-2;
} else if(typeof args[args.length-1] === 'function'){
this.initWithCallback( args[args.length-1], null );
l = l-1;
} else {
this.initWithCallback(null, null);
}
var locSubItems = this._subItems;
locSubItems.length = 0;
for (var i = 0; i < l; i++) {
if (args[i])
locSubItems.push(args[i]);
}
this._selectedIndex = cc.UINT_MAX;
this.setSelectedIndex(0);
this.setCascadeColorEnabled(true);
this.setCascadeOpacityEnabled(true);
return true;
},
/**
* @param {cc.MenuItem} item
*/
addSubItem:function (item) {
this._subItems.push(item);
},
/**
* activate the menu item
*/
activate:function () {
// update index
if (this._isEnabled) {
var newIndex = (this._selectedIndex + 1) % this._subItems.length;
this.setSelectedIndex(newIndex);
}
cc.MenuItem.prototype.activate.call(this);
},
/**
* menu item is selected (runs callback)
*/
selected:function () {
cc.MenuItem.prototype.selected.call(this);
this._subItems[this._selectedIndex].selected();
},
/**
* menu item goes back to unselected state
*/
unselected:function () {
cc.MenuItem.prototype.unselected.call(this);
this._subItems[this._selectedIndex].unselected();
},
/**
* @param {Boolean} enabled
*/
setEnabled:function (enabled) {
if (this._isEnabled != enabled) {
cc.MenuItem.prototype.setEnabled.call(this, enabled);
var locItems = this._subItems;
if (locItems && locItems.length > 0) {
for (var it = 0; it < locItems.length; it++)
locItems[it].setEnabled(enabled);
}
}
},
/**
* returns the selected item
* @return {cc.MenuItem}
*/
selectedItem:function () {
return this._subItems[this._selectedIndex];
},
onEnter:function () {
cc.Node.prototype.onEnter.call(this);
this.setSelectedIndex(this._selectedIndex);
}
});
/**
* create a simple container class that "toggles" it's inner items<br/>
* The inner items can be any MenuItem
* @return {cc.MenuItemToggle}
* @example
* // Example
*
* //create a toggle item with 2 menu items (which you can then toggle between them later)
* var toggler = cc.MenuItemToggle.create( cc.MenuItemFont.create("On"), cc.MenuItemFont.create("Off"), this.callback, this)
* //Note: the first param is the target, the second is the callback function, afterwards, you can pass in any number of menuitems
*
* //if you pass only 1 variable, then it must be a cc.MenuItem
* var notYetToggler = cc.MenuItemToggle.create(cc.MenuItemFont.create("On"));//it is useless right now, until you add more stuff to it
* notYetToggler.addSubItem(cc.MenuItemFont.create("Off"));
* //this is useful for constructing a toggler without a callback function (you wish to control the behavior from somewhere else)
*/
cc.MenuItemToggle.create = function (/*Multiple arguments follow*/) {
if((arguments.length > 0) && (arguments[arguments.length-1] == null))
cc.log("parameters should not be ending with null in Javascript");
var ret = new cc.MenuItemToggle();
ret.initWithItems(arguments);
return ret;
};
|
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyGrpcio(PythonPackage):
"""HTTP/2-based RPC framework."""
homepage = "https://grpc.io/"
pypi = "grpcio/grpcio-1.32.0.tar.gz"
version('1.39.0', sha256='57974361a459d6fe04c9ae0af1845974606612249f467bbd2062d963cb90f407')
version('1.38.1', sha256='1f79d8a24261e3c12ec3a6c25945ff799ae09874fd24815bc17c2dc37715ef6c')
version('1.38.0', sha256='abbf9c8c3df4d5233d5888c6cfa85c1bb68a6923749bd4dd1abc6e1e93986f17')
version('1.37.1', sha256='df8305806311d3fe913d4f7eb3ef28e2072159ea12f95baab5d447f1380a71e3')
version('1.37.0', sha256='b3ce16aa91569760fdabd77ca901b2288152eb16941d28edd9a3a75a0c4a8a85')
version('1.36.0', sha256='70b11805bc9385fcd24e15bcdc5bd8bed463026cd2227d9fdd1ebda612ba0cd9')
version('1.35.0', sha256='7bd0ebbb14dde78bf66a1162efd29d3393e4e943952e2f339757aa48a184645c')
version('1.34.1', sha256='1c746a3cd8a830d8d916a9d0476a786aaa98c5cc2a096344af2be955e439f8ac')
version('1.34.0', sha256='f98f746cacbaa681de0bcd90d7aa77b440e3e1327a9988f6a2b580d54e27d4c3')
version('1.33.2', sha256='21265511880056d19ce4f809ce3fbe2a3fa98ec1fc7167dbdf30a80d3276202e')
version('1.33.1', sha256='f19782ec5104599382a0f73f2dfea465d0e65f6818bb3c49ca672b97034c64c3')
version('1.32.0', sha256='01d3046fe980be25796d368f8fc5ff34b7cf5e1444f3789a017a7fe794465639')
version('1.30.0', sha256='e8f2f5d16e0164c415f1b31a8d9a81f2e4645a43d1b261375d6bab7b0adf511f')
version('1.29.0', sha256='a97ea91e31863c9a3879684b5fb3c6ab4b17c5431787548fc9f52b9483ea9c25')
version('1.28.1', sha256='cbc322c5d5615e67c2a15be631f64e6c2bab8c12505bc7c150948abdaa0bdbac')
version('1.27.2', sha256='5ae532b93cf9ce5a2a549b74a2c35e3b690b171ece9358519b3039c7b84c887e')
version('1.25.0', sha256='c948c034d8997526011960db54f512756fb0b4be1b81140a15b4ef094c6594a4')
version('1.16.0', sha256='d99db0b39b490d2469a8ef74197d5f211fa740fc9581dccecbb76c56d080fce1')
depends_on('[email protected]:', when='@1.30:', type=('build', 'run'))
depends_on('[email protected]:2.8,3.5:', type=('build', 'run'))
depends_on('py-setuptools', type='build')
depends_on('[email protected]:', type=('build', 'run'))
depends_on('[email protected]:', when='^python@:3.1', type=('build', 'run'))
depends_on('[email protected]:', when='^python@:3.3', type=('build', 'run'))
depends_on('[email protected]:', type='build')
depends_on('openssl')
# EV version of the constraint, keeping stricter depends_on, but
# reasons are lost in time
depends_on('[email protected]:')
depends_on('zlib')
depends_on('c-ares')
# visionary (hack): when building on newer gccs add missing include
patch('add-include-limits-1.32.0.patch', when='@1.32.0 %[email protected]:', level=0)
def setup_build_environment(self, env):
env.set('GRPC_PYTHON_BUILD_WITH_CYTHON', True)
env.set('GRPC_PYTHON_BUILD_SYSTEM_OPENSSL', True)
env.set('GRPC_PYTHON_BUILD_SYSTEM_ZLIB', True)
env.set('GRPC_PYTHON_BUILD_SYSTEM_CARES', True)
# https://github.com/grpc/grpc/pull/24449
env.set('GRPC_BUILD_WITH_BORING_SSL_ASM', '')
env.set('GRPC_PYTHON_BUILD_EXT_COMPILER_JOBS', str(make_jobs))
for dep in self.spec.dependencies(deptype='link'):
query = self.spec[dep.name]
env.prepend_path('LIBRARY_PATH', query.libs.directories[0])
env.prepend_path('CPATH', query.headers.directories[0])
def patch(self):
if self.spec.satisfies('%fj'):
filter_file("-std=gnu99", "", "setup.py")
|
require("./lib/index"); |
/*!
DataTables Bootstrap 3 integration
©2011-2014 SpryMedia Ltd - datatables.net/license
*/
(function(l, q){var d = function(b, c){b.extend(!0, c.defaults, {dom:"<'row'<'col-sm-6'l><'col-sm-6'f>><'row'<'col-sm-12'tr>><'row'<'col-sm-5'i><'col-sm-7'p>>", renderer:"bootstrap"}); b.extend(c.ext.classes, {sWrapper:"dataTables_wrapper form-inline dt-bootstrap", sFilterInput:"form-control", sLengthSelect:"form-control"}); c.ext.renderer.pageButton.bootstrap = function(g, d, r, s, i, m){var t = new c.Api(g), u = g.oClasses, j = g.oLanguage.oPaginate, e, f, n = 0, p = function(c, d){var k, h, o, a, l = function(a){a.preventDefault();
b(a.currentTarget).hasClass("disabled") || t.page(a.data.action).draw("page")}; k = 0; for (h = d.length; k < h; k++)if (a = d[k], b.isArray(a))p(c, a); else{f = e = ""; switch (a){case "ellipsis":e = "…"; f = "disabled"; break; case "first":e = j.sFirst; f = a + (0 < i?"":" disabled"); break; case "previous":e = j.sPrevious; f = a + (0 < i?"":" disabled"); break; case "next":e = j.sNext; f = a + (i < m - 1?"":" disabled"); break; case "last":e = j.sLast; f = a + (i < m - 1?"":" disabled"); break; default:e = a + 1, f = i === a?"active":""}e && (o = b("<li>", {"class":u.sPageButton +
" " + f, id:0 === r && "string" === typeof a?g.sTableId + "_" + a:null}).append(b("<a>", {href:"#", "aria-controls":g.sTableId, "data-dt-idx":n, tabindex:g.iTabIndex}).html(e)).appendTo(c), g.oApi._fnBindAction(o, {action:a}, l), n++)}}, h; try{h = b(d).find(q.activeElement).data("dt-idx")} catch (l){}p(b(d).empty().html('<ul class="pagination"/>').children("ul"), s); h && b(d).find("[data-dt-idx=" + h + "]").focus()}; c.TableTools && (b.extend(!0, c.TableTools.classes, {container:"DTTT btn-group", buttons:{normal:"btn btn-default", disabled:"disabled"},
collection:{container:"DTTT_dropdown dropdown-menu", buttons:{normal:"", disabled:"disabled"}}, print:{info:"DTTT_print_info"}, select:{row:"active"}}), b.extend(!0, c.TableTools.DEFAULTS.oTags, {collection:{container:"ul", button:"li", liner:"a"}}))}; "function" === typeof define && define.amd?define(["jquery", "datatables"], d):"object" === typeof exports?d(require("jquery"), require("datatables")):jQuery && d(jQuery, jQuery.fn.dataTable)})(window, document); |
import torch, os, time, sys, copy, argparse, csv
import scipy.io as scio
import numpy as np
sys.path.append('../pytorch')
from message_passing import MessagePassingModule
from MP_module import MPModule
from MP_module_manual import test_mp_module_manual
from test_compute_terms import MRFParams, compute_terms_py
sys.path.append('..')
sys.path.append('../utils')
from mean_field import MeanField
from label_context import create_label_context
torch.manual_seed(2019)
torch.cuda.manual_seed_all(2019)
enable_cuda = torch.cuda.is_available()
device = 'cpu' # torch.device('cuda' if enable_cuda else 'cpu')
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
enable_backward = False
def parse_unary_cost(file_path):
assert os.path.exists(file_path)
reader = csv.reader(open(file_path, 'r'), delimiter=",")
data = list(reader)
height, width, n_disp = [int(v) for v in data[0]]
num_nodes = height * width
assert len(data) - 1 == num_nodes
data_cost = []
for i in range(1, len(data)):
data_cost.append(np.array([float(v) for v in data[i]]))
data_cost = np.stack(data_cost, axis=0).reshape(height, width, n_disp).astype(np.float32)
data_cost = torch.from_numpy(data_cost)
return height, width, n_disp, data_cost
def get_seg_all_iter(cost_all):
seg_all = []
for idx in range(cost_all.size(0)):
seg_all.append(torch.from_numpy(np.argmin(cost_all[idx].cpu().numpy(), axis=2).astype(np.float32)))
return torch.stack(seg_all, dim=0)
def test_mp_module(mode, n_iter, unary, n_dir, label_context):
assert mode in ['ISGMR', 'TRWP']
enable_parallel = True if mode == 'ISGMR' else False
batch, n_disp, h, w = 1, unary.size(0), unary.size(1), unary.size(2)
mp_module = MessagePassingModule(max_iter=n_iter, n_labels=n_disp, n_dirs=n_dir, mode=mode,
ISGMR_parallel=enable_parallel, enable_debug=False,
target='Stereo', graph_model='min_sum',
label_context=label_context, n_edge_feats=1, llambda=1.,
enable_Gaussian=False)
mp_module = mp_module.to(device)
unary_score = -unary.unsqueeze(0)
img = torch.randint(0, 1, (batch, 3, h, w), dtype=torch.float32, device=device)
unary_prob, pairwise_prob, message, message_init, label_context, _, _ = mp_module.forward(unary_score, img)
if enable_backward:
loss = unary_prob.sum()
unary.retain_grad() # for CUDA
label_context.retain_grad()
loss.backward()
return unary_prob.squeeze(0), message.permute(1,0,2,3,4).squeeze(1), \
unary.grad.squeeze(0), message_init.grad.permute(1,0,2,3,4).squeeze(1), label_context.grad.squeeze()
else:
return unary_prob.squeeze(0), message.permute(1,0,2,3,4).squeeze(1), None, None, None
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Funny Witch')
parser.add_argument('--data_dir', type=str, default='../datasets')
parser.add_argument('--img_name', type=str, default='tsukuba')
parser.add_argument('--mode', type=str, default='TRWP')
parser.add_argument('--n_dir', type=int, default=4)
parser.add_argument('--n_iter', type=int, default=50)
parser.add_argument('--context', type=str, default='TL')
parser.add_argument('--rho', type=float, default=None)
parser.add_argument('--enable_min_a_dir', action='store_true', default=False)
parser.add_argument('--enable_saving_label', action='store_true', default=False)
parser.add_argument('--truncated', type=int, default=1)
parser.add_argument('--n_disp', type=int, default=10)
parser.add_argument('--p_weight', type=int, default=10)
parser.add_argument('--left_img_path', type=str, default=None)
parser.add_argument('--right_img_path', type=str, default=None)
parser.add_argument('--save_dir', type=str, default='../experiments')
args = parser.parse_args()
img_name = args.img_name
n_dir = args.n_dir
n_iter = args.n_iter
enable_min_a_dir = args.enable_min_a_dir != 0
enable_saving_label = args.enable_saving_label != 0
rho = args.rho
mode = args.mode
context = args.context
truncated = args.truncated
n_disp = args.n_disp
p_weight = args.p_weight
grad_thresh, grad_penalty = 0, 0
if rho is None:
rho = 0.5 if (mode == 'TRWP') else 1
assert n_disp <= 256
# Compute terms
if args.img_name in {'house', 'penguin'}:
unary_file = '{}/Denoise/{}_unary.csv'.format(args.data_dir, img_name)
h, w, n_disp, data_cost = parse_unary_cost(unary_file)
args.n_classes = n_disp
args.mpnet_n_dirs = n_dir
args.mpnet_max_iter = n_iter
args.mpnet_smoothness_mode = context
args.mpnet_smoothness_trunct_loc = -1
args.mpnet_smoothness_trunct_value = truncated
args.mpnet_term_weight = p_weight
args.enable_cuda = enable_cuda
args.mpnet_smoothness_train = None
smoothness_context, _, _ = create_label_context(args, enable_seg=True, enable_symmetric=True)
else:
if args.left_img_path is None or args.right_img_path is None:
data_dir = args.data_dir
if args.img_name[0:3] == '000':
left_img_path = os.path.join(data_dir, 'KITTI2015/image_2/{}.png'.format(args.img_name))
right_img_path = os.path.join(data_dir, 'KITTI2015/image_3/{}.png'.format(args.img_name))
elif args.img_name.split('_')[-1][-2:] in ['1l', '2l', '3l', '1s', '2s', '3s']:
left_img_path = os.path.join(data_dir, 'ETH3D/training/{}/im0.png'.format(args.img_name))
right_img_path = os.path.join(data_dir, 'ETH3D/training/{}/im1.png'.format(args.img_name))
else:
postfix = 'pgm' if args.img_name == 'map' else 'ppm'
left_img_path = os.path.join(data_dir, 'Middlebury/{}/imL.{}'.format(args.img_name, postfix))
right_img_path = os.path.join(data_dir, 'Middlebury/{}/imR.{}'.format(args.img_name, postfix))
else:
left_img_path = args.left_img_path
right_img_path = args.right_img_path
assert left_img_path is not None and os.path.exists(left_img_path), \
'Left image {} not exist'.format(left_img_path)
assert right_img_path is not None and os.path.exists(right_img_path), \
'Right image {} not exist'.format(right_img_path)
# ==== Get terms
param = MRFParams(left_img_path, right_img_path, context, n_disp, grad_thresh,
grad_penalty, truncated)
data_cost, RGB, smoothness_context, param = compute_terms_py(param)
smoothness_context *= p_weight
h, w = param.height, param.width
# ==== Save file path
if enable_saving_label:
save_dir = '{}/energy/{}'.format(args.save_dir, args.img_name)
if not os.path.exists(save_dir):
os.makedirs(save_dir)
file_path = os.path.join(save_dir, '{}_{}_iter_{}_{}_trunc_{}_dir_{}_rho_{}' \
.format(img_name, mode, n_iter, context, truncated,
n_dir, rho))
file_path = file_path + '_minAdir' if enable_min_a_dir else file_path
file_path = file_path + '.mat'
if os.path.exists(file_path):
print('{} exist, exit.'.format(file_path))
exit()
else:
file_path = None
# ==== Inference
repeats, n_cv, manual_thre = 1, 1, 1
# ==== Auto
smoothness_context = smoothness_context.view(1, n_disp, n_disp).repeat(n_dir, 1, 1)
label_context = smoothness_context.contiguous()
unary = data_cost.permute(2, 0, 1).contiguous()
unary_auto = copy.deepcopy(unary)
unary_auto.requires_grad = True if enable_backward else False
unary_auto = unary_auto.to(device)
label_context_auto = copy.deepcopy(label_context).to(device)
torch.cuda.synchronize()
time_start = time.time()
unary_final_ref = None
if (repeats == 1) and (not enable_saving_label) and (mode in ['ISGMR', 'TRWP']):
assert n_cv == 1
unary_final_ref, message_final_ref, dunary_final_ref, dmessage_final_ref, \
dlabel_context_ref = test_mp_module(mode, n_iter, unary_auto, n_dir,
label_context_auto)
unary_final4 = unary_final_ref
message_final4 = message_final_ref
dunary_final4 = dunary_final_ref
dmessage_final4 = dmessage_final_ref
dlabel_context4 = dlabel_context_ref
torch.cuda.synchronize()
print('pytorch auto time: {:.4f} s'.format(time.time() - time_start))
# ==== Manual
unary_manual = copy.deepcopy(unary)
unary_manual.requires_grad = True if enable_backward else False
unary_manual = unary_manual.view(1,1,n_disp,h,w).to(device)
label_context_manual = copy.deepcopy(label_context).to(device)
torch.cuda.synchronize()
time_start = time.time()
if (repeats == 1) and (h * w <= manual_thre) and (mode == 'ISGMR'):
assert n_cv == 1
unary_final_ref, message_final_ref, msg_indx_ref, msg_norm_indx_ref, \
dunary_final_ref, dmessage_final_ref, dlabel_context_ref = \
test_mp_module_manual(n_dir, n_iter, unary_manual, label_context_manual,
rho, enable_backward)
unary_final5 = unary_final_ref
message_final5 = message_final_ref
dunary_final5 = dunary_final_ref
dmessage_final5 = dmessage_final_ref
dlabel_context5 = dlabel_context_ref
torch.cuda.synchronize()
print('pytorch manual time: {:.4f} s'.format(time.time() - time_start))
# ==== CUDA
time_all, time_all_forward, time_all_backward = 0, 0, 0
for idx in range(repeats):
torch.cuda.empty_cache()
unary_cuda = copy.deepcopy(unary)
unary_cuda.requires_grad = True if enable_backward else False
unary_cuda = unary_cuda.view(1, 1, n_disp,h,w).to('cuda')
label_context_cuda = copy.deepcopy(label_context).to('cuda')
if mode == 'SGM':
unary_cuda = unary_cuda.cpu()
label_context_cuda = label_context_cuda.cpu()
torch.cuda.synchronize()
time_start = time.time()
args.n_classes = n_disp
args.mpnet_n_dirs = n_dir
args.mpnet_max_iter = n_iter
args.mpnet_term_weight = p_weight
args.mpnet_smoothness_train = None
if mode == 'MeanField':
args.mpnet_smoothness_mode = context
args.mpnet_smoothness_trunct_loc = -1
args.mpnet_smoothness_trunct_value = truncated
args.enable_cuda = enable_cuda
mp_module = MeanField(args, enable_create_label_context=False)
mp_module.set_label_context(label_context_cuda[0])
else:
args.mpnet_mrf_mode = mode
args.rho = rho
mp_module = MPModule(args,
enable_create_label_context=False,
enable_saving_label=enable_saving_label,
enable_min_a_dir=enable_min_a_dir)
mp_module.set_label_context(label_context_cuda, None, None)
torch.cuda.synchronize()
create_time = time.time() - time_start
if enable_backward:
mp_module.train()
else:
mp_module.eval()
torch.cuda.synchronize()
time_start = time.time()
if mode == 'MeanField':
results = mp_module(unary_cuda)
cost_final6 = results[0]
cost_all = results[2]
if cost_all is None:
seg_all = cost_final6.squeeze()
else:
seg_all = []
for idx in range(len(cost_all)):
seg_all.append(get_seg_all_iter(cost_all[idx].unsqueeze(0)))
seg_all = torch.cat(seg_all, dim=0).squeeze(1).squeeze(1)
else:
# cost_final6:(1,1,n_disp,h,w); cost_all:(n_iter,1,1,h,w)
results = mp_module(unary_cuda)
cost_final6 = results[0]
cost_all = results[2]
if (cost_all is not None) and (len(cost_all) > 0):
seg_all = cost_all.squeeze(1).squeeze(1)
else:
seg_all = cost_final6.squeeze()
cost_final6 = -cost_final6 # convert to fake prob
torch.cuda.synchronize()
forward_time = time.time() - time_start
time_all_forward += forward_time
torch.cuda.synchronize()
time_start = time.time()
if enable_backward:
loss = cost_final6.sum()
mp_module.label_context.retain_grad()
unary_cuda.retain_grad()
loss.backward()
torch.cuda.synchronize()
backward_time = time.time() - time_start
time_all_backward += backward_time
print(idx, 'cuda time, create: {:.4f} s, forward: {:.4f} s, backward: {:.4f} s, all: {:.4f} s' \
.format(create_time, forward_time, backward_time, create_time + forward_time + backward_time))
print('final cost sum, cuda: {}'.format(cost_final6.abs().cpu().sum())) if repeats != 1 else None
time_all += create_time + forward_time + backward_time
torch.cuda.empty_cache()
# ==== Save for energy
if enable_saving_label:
scio.savemat(file_path, {'n_iter': n_iter,
'n_dir': n_dir,
'rho': rho,
'p_func': context,
'n_disp': n_disp,
'p_weight': p_weight,
'trunct': truncated,
'min_a_dir': int(enable_min_a_dir),
'unary': unary_cuda.squeeze().permute(1, 2, 0).detach().cpu().numpy(),
'label_context': smoothness_context.permute(1, 2, 0).detach().cpu().numpy(),
'seg_all': seg_all.permute(1, 2, 0).detach().cpu().numpy().astype(np.uint8)})
if (repeats > 1) and enable_backward:
print(unary_cuda.grad.abs().mean().cpu().numpy(),
mp_module.label_context.grad.abs().mean().cpu().numpy())
print(unary_cuda.grad.abs().long().sum().cpu().numpy(),
mp_module.label_context.grad.long().abs().sum().cpu().numpy())
if idx != repeats - 1:
del unary_cuda, label_context_cuda
print('cuda average time {:.4f}s, forward {:.4f}s, backward {:.4f}s' \
.format(time_all / repeats, time_all_forward / repeats, time_all_backward / repeats))
if (repeats == 1) and (not enable_saving_label) and (unary_final_ref is not None):
# CPU and GPU precisions are different, so use CPU or GPU for both
print('final cost check, ref: {}, cuda: {}'
.format(unary_final_ref.cpu().sum(), cost_final6.cpu().sum()))
# if (h * w <= manual_thre):
# print('msg_indx check, ref: {}, cuda: {}' \
# .format(msg_indx_ref.abs().cpu().sum(), msg_indx6.abs().cpu().sum()))
# print('msg_norm_indx check, ref: {}, cuda: {}' \
# .format(msg_norm_indx_ref.abs().cpu().sum(), msg_norm_indx6.abs().cpu().sum()))
if enable_backward:
print('ref, dunary:', dunary_final_ref.long().sum().cpu().numpy(),
', dcontext:', dlabel_context_ref.long().sum().cpu().numpy())
print('cuda, dunary:', unary_cuda.grad.long().sum().cpu().numpy(),
', dcontext:', mp_module.label_context.grad.long().sum().cpu().numpy())
# ==============
if (repeats == 1) and (h * w <= manual_thre) and enable_backward:
unary_abs_diff = (unary_final4.squeeze()-unary_final5.squeeze()).abs()
message_abs_diff = (message_final4.squeeze()-message_final5.squeeze()).abs()
dunary_abs_diff = (dunary_final4.squeeze()-dunary_final5.squeeze()).abs()
dmessage_abs_diff = (dmessage_final4.squeeze()-dmessage_final5.squeeze()).abs()
dlabel_context_abs_diff = (dlabel_context4.squeeze() - dlabel_context5.squeeze()).abs()
print('===> pytorch auto and manual check, unary: {}, message: {}, dunary: {},'
' dmessage: {}, dlabel_context: {}' \
.format(unary_abs_diff.sum(), message_abs_diff.sum(), dunary_abs_diff.sum(),
dmessage_abs_diff.sum(), dlabel_context_abs_diff.sum()))
|
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-5-b-64.js
* @description Object.defineProperties - 'configurable' property of 'descObj' is own data property that overrides an inherited accessor property (8.10.5 step 4.a)
*/
function testcase() {
var obj = {};
var proto = {};
Object.defineProperty(proto, "configurable", {
get: function () {
return true;
}
});
var Con = function () { };
Con.prototype = proto;
var descObj = new Con();
Object.defineProperty(descObj, "configurable", {
value: false
});
Object.defineProperties(obj, {
prop: descObj
});
var result1 = obj.hasOwnProperty("prop");
delete obj.prop;
var result2 = obj.hasOwnProperty("prop");
return result1 === true && result2 === true;
}
runTestCase(testcase);
|
function main() {
const v4 = [13.37,13.37,13.37,13.37,13.37];
const v6 = [1337,1337,1337,1337];
const v7 = [13.37];
const v8 = {find:v6,fill:RegExp,length:"number",acos:"number"};
const v9 = {MIN_VALUE:"number",multiline:v8};
let v10 = v6;
const v15 = [13.37,13.37,13.37,13.37,13.37];
const v17 = [1337,1337,1337,1337];
const v18 = [13.37];
const v19 = {find:v17,fill:RegExp,length:"number",acos:"number"};
const v20 = {MIN_VALUE:"number",multiline:v19};
let v21 = v17;
const v26 = [13.37,13.37,13.37,13.37,13.37];
const v27 = RegExp[65537];
v26.cbrt = 13.37;
delete (13.37)[13.37];
const v29 = "number"["number"];
const v30 = [1337,1337,1337,1337];
const v35 = [13.37,13.37,13.37,13.37,13.37];
const v37 = [1337,1337,1337,1337];
const v38 = [13.37];
const v39 = {find:v37,fill:RegExp,length:"number",acos:"number"};
const v40 = {MIN_VALUE:"number",multiline:v39};
let v41 = v37;
const v46 = [13.37,13.37,13.37,13.37,13.37];
const v47 = RegExp[65537];
v46.cbrt = 13.37;
delete (13.37)[13.37];
const v49 = "number"["number"];
const v50 = [1337,1337,1337,1337];
const v51 = [13.37];
const v52 = {find:v50,fill:RegExp,length:"number",acos:"number"};
const v53 = {MIN_VALUE:"number",multiline:v52};
let v54 = v50;
const v58 = [13.37,13.37,13.37,13.37,13.37];
const v60 = [1337,1337,1337,1337];
const v61 = [13.37];
const v62 = {find:v60,fill:RegExp,length:"number",acos:"number"};
const v63 = {MIN_VALUE:"number",multiline:v62};
let v64 = v60;
const v69 = [-956001.3254401154,-956001.3254401154,-956001.3254401154,-956001.3254401154,-956001.3254401154];
const v71 = [1337,1337,1337,1337];
const v72 = [-956001.3254401154];
const v73 = {find:v71,fill:arguments,length:"number",acos:"number"};
const v74 = {MIN_VALUE:"number",multiline:v73};
let v75 = v71;
const v77 = Object();
const v79 = -521713708 * v63;
const v80 = Object("number","number",v74);
const v81 = Object();
const v82 = v63.isFrozen;
let v85 = 0;
do {
v74.length = v85;
const v86 = v85 + 1;
v85 = v86;
} while (v85 < 10);
const v87 = [13.37];
const v88 = {find:v30,fill:RegExp,length:"number",acos:"number"};
const v89 = {MIN_VALUE:"number",multiline:v88};
let v90 = v30;
const v95 = [13.37,13.37,13.37,13.37,13.37];
const v97 = [1337,1337,1337,1337];
const v98 = [13.37];
const v99 = {find:v97,fill:Map,length:"number",acos:"number"};
const v100 = {MIN_VALUE:"number",multiline:v99};
let v101 = v97;
const v106 = [-956001.3254401154,-956001.3254401154,-956001.3254401154,-956001.3254401154,-956001.3254401154];
const v108 = [1337,1337,1337,1337];
const v109 = [-956001.3254401154];
const v110 = {find:v108,fill:arguments,length:"number",acos:"number"};
const v111 = {MIN_VALUE:"number",multiline:v110};
let v112 = v108;
const v114 = gc();
const v116 = -521713708 * v100;
const v117 = new Object("number","number",v111);
const v118 = Object();
}
%NeverOptimizeFunction(main);
main();
|
let searchTerms; // array of search terms
let lastSearchIdx; // index of last term searched
let weatherReports; // array of weather reports;
// For each search term there will be a related entry in weatherReports
// at the same index.
// Compute dates for 5 day forcast
let now = Date.now();
let oneDay = 24*60*60*1000; // milliseconds in one day
let dateStr;
let day = [];
for (let cnt = 0; cnt <= 5; cnt++) {
dateStr = new Date(now + (oneDay * cnt)).toLocaleDateString();
day.push(dateStr);
}
// initialize list of search terms from localStorage
let tmp = localStorage.getItem('wAppSearchTerms');
if (tmp == null) {
searchTerms = [];
} else {
searchTerms = JSON.parse(tmp);
// populate search list
for (let idx=0; idx < searchTerms.length; idx++) {
addItemToSearchList( searchTerms[idx] );
}
}
tmp = localStorage.getItem('wAppWeatherReports');
if (tmp == null) {
weatherReports = [];
} else {
weatherReports = JSON.parse(tmp);
}
tmp = localStorage.getItem('wAppLastSearchIdx');
if (tmp == null) {
lastSearchIdx = -1;
// No previous searches; hide display
document.querySelector('main').style.display = "none";
} else {
lastSearchIdx = Number(tmp);
// Initialize display with last searched city
retrieveCityWeather();
}
function addItemToSearchList( searchTerm ) {
let btn = document.createElement('button');
btn.setAttribute('type', 'button');
btn.classList.add('list-group-item', 'list-group-item-action');
btn.innerHTML = searchTerm;
document.querySelector('.list-group').appendChild(btn);
}
function displayCityWeather() {
for (let idx=0; idx <= 5; idx++) {
document.getElementById(`day${idx}`).innerHTML = day[idx];
document.getElementById(`temp-day${idx}`).innerHTML = weatherReports[lastSearchIdx].forecast[idx].temp;
document.getElementById(`hum-day${idx}`).innerHTML = weatherReports[lastSearchIdx].forecast[idx].humidity;
document.getElementById(`icon-day${idx}`)
.setAttribute('src', `assets/images/${weatherReports[lastSearchIdx].forecast[idx].icon}_2x.png`);
}
document.getElementById('wind').innerHTML = weatherReports[lastSearchIdx].wind;
document.getElementById('city').innerHTML = weatherReports[lastSearchIdx].displayName;
let uvBadge = document.getElementById('uv');
let uvVal = Number(weatherReports[lastSearchIdx].uv);
uvBadge.innerHTML = uvVal;
if (uvVal <= 2) {
uvBadge.classList.add('uv-low');
} else if (uvVal <= 5) {
uvBadge.classList.add('uv-moderate');
} else if (uvVal <= 7) {
uvBadge.classList.add('uv-high');
} else if (uvVal <= 10) {
uvBadge.classList.add('uv-very-high');
} else {
uvBadge.classList.add('uv-extreme');
}
}
async function fetchCityWeather(searchTerm, sidx) {
// Do API call for fresh data
// For now, pull data from local storage for debugging
/* Save subset of info in new report object literal with the following format:
forecast: [ {temp: xx, humidity: xx, icon: xx}, ... ]
wind: xx,
uv: xx,
time: xx,
searchTerm: xx,
displayName: xx
*/
let lat, lon;
let newReport = { forecast: [] };
let tempHumIcon = { };
let url = `https://api.openweathermap.org/data/2.5/weather?q=${searchTerm}&units=metric&APPID=${APPID}`;
let response = await fetch(url);
if (!response.ok) {
document.getElementById('warning').innerHTML = `An error occured: ${response.status}`;
return;
}
let weather = await response.json();
// console.log(`[fetchCityWeather] weather:`, weather);
// dbg: let weather = JSON.parse(localStorage.getItem('weather'));
// dbg: newReport.displayName = searchTerm;
newReport.searchTerm = searchTerm;
newReport.displayName = weather.name;
newReport.wind = weather.wind.speed;
newReport.time = Date.now();
lat = weather.coord.lat;
lon = weather.coord.lon;
tempHumIcon.temp = weather.main.temp;
tempHumIcon.humidity = weather.main.humidity;
tempHumIcon.icon = weather.weather[0].icon;
newReport.forecast.push(tempHumIcon);
// Get the 5 day forcast
url = `https://api.openweathermap.org/data/2.5/forecast?q=${searchTerm}&units=metric&APPID=${APPID}`;
response = await fetch(url);
if (!response.ok) {
document.getElementById('warning').innerHTML += `An error occured: ${response.status}`;
return;
}
let forecast = await response.json();
// console.log(`[fetchCityWeather] forecast:`, forecast);
// dbg: let forecast = JSON.parse(localStorage.getItem('forecast'));
// Search for first mid-day temperature
let idx, jdx;
for (idx=0; idx < forecast.list.length; idx++) {
if ((forecast.list[idx].dt_txt).indexOf("15:00:00") > 0) {
break;
}
}
// forecast are every 3hrs, so mid-day entries are 8 indicies apart
for (jdx=idx; jdx < 40; jdx+=8) {
tempHumIcon = {};
tempHumIcon.temp = forecast.list[jdx].main.temp;
tempHumIcon.humidity = forecast.list[jdx].main.humidity;
tempHumIcon.icon = forecast.list[jdx].weather[0].icon;
newReport.forecast.push(tempHumIcon);
}
// get uv
url = `https://api.openweathermap.org/data/2.5/uvi?lat=${lat}&lon=${lon}&APPID=${APPID}`
response = await fetch(url);
if (!response.ok) {
document.getElementById('warning').innerHTML += `An error occured: ${response.status}`;
return;
}
let uv = await response.json();
// console.log(`[fetchCityWeather] uv:`, uv);
// dbg: let uv = JSON.parse(localStorage.getItem('uv'));
newReport.uv = uv.value;
if (sidx >= 0) {
weatherReports[lastSearchIdx] = newReport;
} else {
// If this is the very first search (lastSearchIdx=-1), then enable the display
if (lastSearchIdx==-1) {
document.querySelector('main').style.display = "block";
}
weatherReports.push(newReport);
searchTerms.push(searchTerm);
lastSearchIdx = searchTerms.length - 1;
// Add searchTerm to search list
addItemToSearchList( searchTerm );
// Update search list in local storage
localStorage.setItem('wAppSearchTerms', JSON.stringify(searchTerms));
}
// Update items in local storage
localStorage.setItem('wAppLastSearchIdx', `${lastSearchIdx}`);
localStorage.setItem('wAppWeatherReports', JSON.stringify(weatherReports));
console.log(`[fetchCityWeather] Fetch data from API for ${searchTerms[lastSearchIdx]}.`);
displayCityWeather();
}
function retrieveCityWeather() {
// Check if 10min has passed since data saved
let now = Date.now();
let then = weatherReports[lastSearchIdx].time;
// console.log(`[retrieveCityWeather] now:${now}, then:${then}, diff(min):${Math.floor((now-then)/(60*1000))}`);
// Find diff btw 'now' and 'then' in minutes
if (Math.floor((now-then)/(60*1000)) > 10) {
console.log(`[retrieveCityWeather] Stored data is old. Get fresh data for ${searchTerms[lastSearchIdx]}.`);
fetchCityWeather(searchTerms[lastSearchIdx], lastSearchIdx);
} else {
console.log(`[retrieveCityWeather] Retrieve data from storage for ${searchTerms[lastSearchIdx]}.`);
// Update last search index in storage
localStorage.setItem('wAppLastSearchIdx', `${lastSearchIdx}`);
displayCityWeather();
}
}
function findCityWeather() {
// clear any previous warning messages
document.getElementById('warning').innerHTML = "";
let newSearchTerm = document.getElementById('search-term').value;
// check if user has repeated a previous search
let idx = searchTerms.indexOf(newSearchTerm);
if (idx >= 0 ) {
// item exists
lastSearchIdx = idx;
retrieveCityWeather();
} else {
// fresh search
fetchCityWeather(newSearchTerm, -1);
}
}
function repeatCitySearch( event ) {
// clear any previous warning messages
document.getElementById('warning').innerHTML = "";
let oldSearchTerm = event.target.innerHTML;
lastSearchIdx = searchTerms.indexOf(oldSearchTerm);
retrieveCityWeather();
}
// add event listeners
document.getElementById('search').addEventListener('click', findCityWeather);
document.querySelector('.list-group').addEventListener('click', repeatCitySearch) |
(function () {
'use strict';
angular.module('ngTestData')
.service('testdataAlertService', function ($window) {
return {
addMessage: function (message) {
$window.alert(message);
}
};
})
.controller('testdataController', function ($scope, $http, apiBase, testdataAlertService) {
$scope.models = {};
$http.get(apiBase + '/testdata')
.success(function (data) {
$scope.datasets = {};
data.forEach(function (n) {
$scope.datasets[n.fullName] = n;
});
})
.error(testdataAlertService.addMessage);
function submit(dataSet) {
var model = {};
model[dataSet.fullName] = $scope.models[dataSet.fullName];
dataSet.dependencies.forEach(function (d) {
model[d] = $scope.models[d];
});
$http.post(apiBase + '/testdata', JSON.stringify({
dataSet: dataSet.fullName,
properties: model
}))
.success(function (data) {
var messages = data.join(', ');
testdataAlertService.addMessage('DataSet Complete - ' + messages, 'success');
})
.error(testdataAlertService.addMessage);
}
function selectDataSet(ds) {
$scope.selectedDataSet = ds;
$scope.selectedDataSetList = [$scope.datasets[ds.fullName]];
ds.dependencies.forEach(function (d) {
$scope.selectedDataSetList.push($scope.datasets[d]);
});
}
function dataSetsWithProperties(value) {
return value.properties.length > 0;
}
$scope.submit = submit;
$scope.selectDataSet = selectDataSet;
$scope.dataSetsWithProperties = dataSetsWithProperties;
});
})(); |
import Icon from '../components/Icon.vue'
Icon.register({"subway":{"width":1536,"height":1792,"paths":[{"d":"M1088 0q185 0 316.5 93.5t131.5 226.5v896q0 130-125.5 222t-305.5 97l213 202q16 15 8 35t-30 20h-1056q-22 0-30-20t8-35l213-202q-180-5-305.5-97t-125.5-222v-896q0-133 131.5-226.5t316.5-93.5h640zM288 1312q66 0 113-47t47-113-47-113-113-47-113 47-47 113 47 113 113 47zM704 768v-512h-544v512h544zM1248 1312q66 0 113-47t47-113-47-113-113-47-113 47-47 113 47 113 113 47zM1408 768v-512h-576v512h576z"}]}}) |
"""A module for testing pep8 compliance."""
import os
import textwrap
from typing import List
import pycodestyle # formerly known as pep8
__all__: List[str] = []
def test_pep8_conformance():
"""Test that we conform to PEP-8."""
check_paths = [
'sbu',
'test',
]
exclude_paths = []
print("PEP8 check of directories: {}\n".format(', '.join(check_paths)))
# Get paths wrt package root
package_root = os.path.dirname(os.path.dirname(__file__))
for paths in (check_paths, exclude_paths):
for i, path in enumerate(paths):
paths[i] = os.path.join(package_root, path)
style = pycodestyle.StyleGuide(max_line_length=100)
style.options.exclude.extend(exclude_paths)
success = style.check_files(check_paths).total_errors == 0
if not success:
print(textwrap.dedent("""
Your Python code does not conform to the official Python style
guide (PEP8), see https://www.python.org/dev/peps/pep-0008
A list of warning and error messages can be found above,
prefixed with filename:line number:column number.
Run `yapf -i yourfile.py` to automatically fix most errors.
Run `yapf -d yourfile.py` to preview what would be changed.
Run `pip install --upgrade yapf` to install the latest version
of yapf.
"""))
assert success, "Your code does not conform to PEP8"
|
"""[Semantics!]
"""
def my_func(a, b):
# code |
(this["webpackJsonpesbuild-reactjs"]=this["webpackJsonpesbuild-reactjs"]||[]).push([[0],{14:function(e,t,a){e.exports=a(24)},24:function(e,t,a){"use strict";a.r(t);var n=a(0),l=a.n(n),c=a(9),s=a.n(c),r=a(10),o=a(11),m=a(13),u=a(12),i=a(2),E=function(e){var t=Object(n.useState)(""),a=Object(i.a)(t,2),c=a[0],s=a[1],r=Object(n.useState)([]),o=Object(i.a)(r,2),m=o[0],u=o[1];return Object(n.useEffect)((function(){fetch("https://spreadsheets.google.com/feeds/list/1EYJ9WPjqKqe26InIhdzyFKZzBKgAKRkM04w7aaFQhxk/od6/public/values?alt=json").then((function(e){return e.json()})).then((function(e){return e.feed.entry})).then((function(t){var a=[];t.forEach((function(e){var t=e.gsx$head.$t;t.length>0&&a.push(t)})),0==e.jpn?s(a[0]):s(a[1]),u(a),document.title=c}))})),l.a.createElement(l.a.Fragment,null,l.a.createElement("div",{className:"header f"},l.a.createElement("h1",null,c),l.a.createElement("br",null),l.a.createElement("div",null,l.a.createElement("b",null,l.a.createElement("a",{href:"#about",onClick:function(){e.handlePage("about")}},e.jpn?m[3]:m[2]),l.a.createElement("a",{href:"#cv",onClick:function(){e.handlePage("cv")}},e.jpn?m[5]:m[4]),l.a.createElement("a",{href:"#projects",onClick:function(){e.handlePage("projects")}},e.jpn?m[7]:m[6]),l.a.createElement("a",{href:"#skills",onClick:function(){e.handlePage("skills")}},e.jpn?m[9]:m[8]))),l.a.createElement("br",null),l.a.createElement("div",{id:"lang"},l.a.createElement("a",{onClick:function(){e.handleJPN(!1)}},"English"),l.a.createElement("a",{onClick:function(){e.handleJPN(!0)}},"\u65e5\u672c\u8a9e")),l.a.createElement("br",null)))},h=function(e){var t=Object(n.useState)(""),a=Object(i.a)(t,2),c=a[0],s=a[1],r=Object(n.useState)(""),o=Object(i.a)(r,2),m=o[0],u=o[1],E=Object(n.useState)([]),h=Object(i.a)(E,2),f=h[0],p=h[1],d=Object(n.useState)([]),g=Object(i.a)(d,2),b=g[0],j=g[1],v=Object(n.useState)(!0),k=Object(i.a)(v,2),O=k[0],P=k[1];Object(n.useEffect)((function(){fetch("https://spreadsheets.google.com/feeds/list/1EYJ9WPjqKqe26InIhdzyFKZzBKgAKRkM04w7aaFQhxk/od6/public/values?alt=json").then((function(e){return e.json()})).then((function(e){return e.feed.entry})).then((function(t){var a=[],n=[],l=0;t.forEach((function(t){var c=t["gsx$"+e.class].$t;c.length>0&&(3==l&&n.push(c),l%2==0?a.push(c):n.push(c),l++)}));var c=e.handleJPN?n:a;console.log(c),u(c[0]),console.log("title"+m),s(c[1]),console.log("english"+a),console.log("jpn"+n),e.handleJPN||(c.shift(),c.shift()),console.log(c),p(c),j(c),console.log(f),console.log(b)}))}),[]);var x={};return x="about"==e.class?{minHeight:"300px",border:"0.5em black solid",borderRadius:"100em",margin:"1em"}:{height:"100px",padding:"1em"},l.a.createElement("div",{class:"box f",id:e.class},""!=c&&l.a.createElement("img",{src:c,style:x}),l.a.createElement("h3",{onClick:function(){P(!O)}},m),("about"==e.class||O)&&l.a.createElement("p",{class:"text"},e.handleJPN?b.map((function(e){return l.a.createElement(l.a.Fragment,null,e,l.a.createElement("br",null))})):f.map((function(e){return l.a.createElement(l.a.Fragment,null,e,l.a.createElement("br",null))}))))},f=function(e){return l.a.createElement(l.a.Fragment,null,l.a.createElement("div",{class:"body f"},l.a.createElement(h,{class:"about"})),l.a.createElement("br",null))},p=function(e){return l.a.createElement(l.a.Fragment,null,l.a.createElement("div",{id:"cv",class:"body f"},l.a.createElement(h,{class:"asu"}),l.a.createElement(h,{class:"sbu"}),l.a.createElement(h,{class:"codepath"}),l.a.createElement(h,{class:"appen"}),l.a.createElement(h,{class:"ask"}),l.a.createElement(h,{class:"triplebyte"}),l.a.createElement(h,{class:"geek"}),l.a.createElement(h,{class:"ibm"}),l.a.createElement(h,{class:"google"}),l.a.createElement(h,{class:"fcc"}),l.a.createElement(h,{class:"hrank"}),l.a.createElement(h,{class:"tekovery"}),l.a.createElement(h,{class:"facebook"}),l.a.createElement(h,{class:"softheon"}),l.a.createElement(h,{class:"peking"})),l.a.createElement("br",null))},d=function(e){return l.a.createElement(l.a.Fragment,null,l.a.createElement("div",{id:"projects",class:"body f"},l.a.createElement(h,{class:"music"}),l.a.createElement(h,{class:"connect4"}),l.a.createElement(h,{class:"regiovinco"}),l.a.createElement(h,{class:"blackjack"}),l.a.createElement(h,{class:"pkmn"}),l.a.createElement(h,{class:"gsachs"}),l.a.createElement(h,{class:"calc"}),l.a.createElement(h,{class:"txt"}),l.a.createElement(h,{class:"snake"}),l.a.createElement(h,{class:"space"}),l.a.createElement(h,{class:"cloudflare"})),l.a.createElement("br",null))},g=function(e){return l.a.createElement(l.a.Fragment,null,l.a.createElement("div",{id:"skills",class:"body f"},l.a.createElement(h,{class:"html"}),l.a.createElement(h,{class:"css"}),l.a.createElement(h,{class:"js"}),l.a.createElement(h,{class:"node"}),l.a.createElement(h,{class:"react"}),l.a.createElement(h,{class:"python"}),l.a.createElement(h,{class:"java"}),l.a.createElement(h,{class:"docker"}),l.a.createElement(h,{class:"kube"}),l.a.createElement(h,{class:"vbox"}),l.a.createElement(h,{class:"wireshark"}),l.a.createElement(h,{class:"burp"}),l.a.createElement(h,{class:"postman"}),l.a.createElement(h,{class:"terra"}),l.a.createElement(h,{class:"gcloud"}),l.a.createElement(h,{class:"ibmcloud"}),l.a.createElement(h,{class:"aws"}),l.a.createElement(h,{class:"bash"}),l.a.createElement(h,{class:"pshell"}),l.a.createElement(h,{class:"vi"}),l.a.createElement(h,{class:"git"}),l.a.createElement(h,{class:"jira"})),l.a.createElement("br",null))},b=function(e){return l.a.createElement(l.a.Fragment,null,"about"==e.page&&l.a.createElement(f,null),"cv"==e.page&&l.a.createElement(p,null),"projects"==e.page&&l.a.createElement(d,null),"skills"==e.page&&l.a.createElement(g,null))},j=a(3),v=a(5),k=a(4),O=function(e){return n.createElement(n.Fragment,null,n.createElement("div",{class:"buttons"},n.createElement("p",null,n.createElement("a",{href:"mailto:[email protected]"},n.createElement(j.a,{icon:k.b,size:"2x"})),n.createElement("a",{href:"https://drive.google.com/file/d/1B7G2BOXRs0rq03I48kNq2Pch1aJbk-oG/preview"},n.createElement(j.a,{icon:k.c,size:"2x"})),n.createElement("a",{href:"https://linkedin.com/in/jonxreyes"},n.createElement(j.a,{icon:v.c,size:"2x"})),n.createElement("a",{href:"https://github.com/jonreyes"},n.createElement(j.a,{icon:v.a,size:"2x"})),n.createElement("a",{href:"https://instagram.com/jrex.co/"},n.createElement(j.a,{icon:v.b,size:"2x"})),n.createElement("a",{href:"https://act.webull.com/nt/DEr7ucoaAetT/av8/inviteUs/"},n.createElement(j.a,{icon:k.a,size:"2x"})),n.createElement("a",{href:"https://drd.sh/SSClz3/"},n.createElement(j.a,{icon:k.d,size:"2x"})))))},P=function(e){return l.a.createElement("div",{class:"footer f"},l.a.createElement(O,{style:{backgroundColor:"white",color:"black",padding:"0.25em"}}),l.a.createElement("p",null,"Jon Reyes \xa9 ",(new Date).getFullYear()))},x=function(e){Object(m.a)(a,e);var t=Object(u.a)(a);function a(e){var n;return Object(r.a)(this,a),(n=t.call(this,e)).setPage=function(e){n.setState({page:e}),console.log(n.state.page)},n.getJPN=function(){return n.state.jpn},n.setJPN=function(e){n.setState({jpn:e}),console.log(n.state.jpn)},n.state={splash:!0,count:0,page:"about",jpn:!1},n}return Object(o.a)(a,[{key:"renderSplash",value:function(){var e=this;return setInterval((function(){e.setState({count:e.state.count+1})}),100),setTimeout((function(){e.setState({splash:!1})}),1e3),l.a.createElement(b,{time:this.state.count})}},{key:"render",value:function(){return l.a.createElement(l.a.Fragment,null,l.a.createElement(E,{handlePage:this.setPage,jpn:this.state.jpn,handleJPN:this.setJPN}),l.a.createElement(b,{page:this.state.page,handleJPN:this.getJPN}),l.a.createElement(P,{name:this.props.name}))}}]),a}(l.a.Component);s.a.render(l.a.createElement(x,null),document.getElementById("root"))}},[[14,1,2]]]);
//# sourceMappingURL=main.6da94200.chunk.js.map |
var path = require('path');
var util = require('util');
var fs = require('fs');
var childProcess = require('child_process');
var ansi = require("./ansi.js");
var existsSync = fs.existsSync || path.existsSync;
var isArray = Array.isArray;
function Builder () {
this.flagGroups = {};
this.target = "native_bindings";
this.sourceFiles = [];
this.verbose = false;
this.showWarnings = false;
this.cppCompiler = "g++";
this.linker = "g++";
this.objectFiles = [];
if (process.platform == 'win32') {
if (!process.env["VCINSTALLDIR"] && !process.env["VS100COMNTOOLS"]) {
this.fail("You appear to not be running in a Visual Studio prompt.");
}
}
if (process.platform == 'win32') {
this.cppCompiler = "cl.exe";
this.linker = "link.exe";
this.nodeDir = process.env["NODE_HOME"];
} else {
this.nodeDir = process.env["NODE_HOME"] || path.join(process.execPath, '..', '..');
}
if (this.nodeDir) {
this.nodeDir = this.trimQuotes(this.nodeDir);
this.failIfNotExists(this.nodeDir, 'Node path "%s" not found, try setting NODE_HOME');
} else {
this.fail("You must specify NODE_HOME.");
}
// process.execPath should equal node.
if (process.platform == 'win32') {
this.nodeIncludeDir = path.join(this.nodeDir, 'src');
this.v8IncludeDir = path.join(this.nodeDir, 'deps/v8/include');
this.uvIncludeDir = path.join(this.nodeDir, 'deps/uv/include');
this.nodeLibDir = path.join(this.nodeDir, 'Release');
} else {
this.nodeIncludeDir = path.join(this.nodeDir, 'include', 'node');
this.nodeLibDir = path.join(this.nodeDir, 'lib');
}
this.projectDir = path.resolve('.');
this.buildDir = path.resolve(this.projectDir, 'build');
this.ouputDir = path.resolve(this.buildDir, 'Release');
this.appendUnique('CXXFLAGS', '-c');
if (process.platform == 'win32') {
this.appendUnique('CXXFLAGS', [
'-nologo',
'-DWIN32',
'-D_WINDOWS',
'-D_WINDLL',
'-EHsc',
'-c',
'-Oi-',
'-Od',
'-Gd',
'-analyze-'
]);
this.appendUnique('LINKFLAGS', [
'-nologo',
'-dll',
'-MANIFEST:NO',
'-SUBSYSTEM:WINDOWS',
'-TLBID:1',
'-DYNAMICBASE',
'-NXCOMPAT'
]);
this.appendLinkerLibrary('node');
this.appendLinkerLibrary('uv');
} else {
this.appendUnique('CXXFLAGS', [
'-D_LARGEFILE_SOURCE',
'-D_FILE_OFFSET_BITS=64',
'-D_GNU_SOURCE',
'-DPIC',
'-g',
'-fPIC',
'-MD'
]);
if (process.platform == 'darwin') {
this.appendUnique('LINKFLAGS', [
'-bundle',
'-undefined',
'dynamic_lookup'
]);
} else {
this.appendUnique('LINKFLAGS', [
'-shared'
]);
}
}
}
Builder.prototype.appendLinkerLibrary = function (lib) {
if (isArray(lib)) {
return lib.forEach(this.appendLinkerLibrary.bind(this));
}
var flag;
if (process.platform == 'win32') {
flag = lib.replace(/(?:\.lib)?$/, '.lib');
} else {
flag = '-l' + lib;
}
this.appendUnique('LINKFLAGS', flag);
};
Builder.prototype.appendLinkerSearchDir = function (dir) {
if (isArray(dir)) {
return dir.forEach(this.appendLinkerSearchDir.bind(this));
}
var flag;
if (process.platform == 'win32') {
flag = '-LIBPATH:' + dir;
} else {
flag = '-L' + dir;
}
this.appendUnique('LINKFLAGS', flag);
};
Builder.prototype.appendIncludeDir = function (dir) {
if (isArray(dir)) {
return dir.forEach(this.appendIncludeDir.bind(this));
}
this.appendUnique('CXXFLAGS', '-I' + dir);
};
Builder.prototype.getFlags = function (flagGroupName) {
var flags = this.flagGroups[flagGroupName];
if (!flags) {
flags = this.flagGroups[flagGroupName] = [];
}
return flags;
};
Builder.prototype.appendUnique = function (flagGroupName, newFlags) {
newFlags = isArray(newFlags) ? newFlags : [newFlags];
var flags = this.getFlags(flagGroupName);
for (var i = 0; i < newFlags.length; i++) {
if (flags.indexOf(newFlags[i]) == -1) {
flags.push(newFlags[i]);
}
}
};
Builder.prototype.appendSource = function (fileName) {
if (isArray(fileName)) {
return fileName.forEach(this.appendSource.bind(this));
}
this.sourceFiles.push(fileName);
};
Builder.prototype.appendSourceDir = function (dirName) {
if (isArray(dirName)) {
return dirName.forEach(this.appendSourceDir.bind(this));
}
var files = fs.readdirSync(dirName);
for (var i = 0; i < files.length; i++) {
var fileName = files[i];
if (fileName.match(/\.cpp$/) || fileName.match(/\.c$/) || fileName.match(/\.cxx$/)) {
this.appendSource(path.join(dirName, fileName));
}
}
};
Builder.prototype.getCompilerArgs = function (fileName, outFileName) {
fileName = path.resolve(fileName);
this.createDir(path.dirname(outFileName));
var args = [];
var flags = this.getFlags('CXXFLAGS');
args = args.concat(flags);
args.push(fileName);
if (process.platform == 'win32') {
args.push("-Fo" + outFileName);
} else {
args.push("-o");
args.push(outFileName);
}
return args;
};
Builder.prototype.getLinkerArgs = function (outFileName) {
this.createDir(path.dirname(outFileName));
var args = [];
var flags = this.getFlags('LINKFLAGS');
args = args.concat(this.objectFiles);
if (process.platform == 'win32') {
args.push("-out:" + outFileName);
} else {
args.push("-o");
args.push(outFileName);
}
args = args.concat(flags);
return args;
};
Builder.prototype.createDir = function (dirName) {
var parent = path.dirname(dirName);
if (!existsSync(parent)) {
this.createDir(parent);
}
if (!existsSync(dirName)) {
fs.mkdirSync(dirName);
}
};
Builder.prototype._runCommandLine = function (cmd, args, callback) {
var child = childProcess.spawn(cmd, args);
child.stdout.on('data', function (data) {
process.stdout.write(data);
});
child.stderr.on('data', function (data) {
process.stderr.write(data);
});
child.on('exit', function (code) {
callback(code);
});
};
Builder.prototype._flattenArray = function (arr) {
var results = [];
for (var i = 0; i < arr.length; i++) {
results = results.concat(arr[i]);
}
return results;
};
Builder.prototype._parseDepFile = function (depData) {
var deps = depData.split('\n').slice(1).map(function (item) {
return item
.replace(/ \\$/, '')
.replace(/^ /, '')
.split(' ');
});
deps = this._flattenArray(deps);
deps = deps.filter(function (item) {
return item.length > 0;
});
return deps;
};
Builder.prototype._getMaxTime = function (files) {
var maxTime = new Date(1900);
for (var i = 0; i < files.length; i++) {
var stat = fs.statSync(files[i]);
if (stat.mtime > maxTime) {
maxTime = stat.mtime;
}
}
return maxTime;
};
Builder.prototype._shouldCompile = function (outFileName, depFileName) {
try {
var depFiles = this._parseDepFile(fs.readFileSync(depFileName, 'ascii'));
var outTime = this._getMaxTime([outFileName]);
var maxDepTime = this._getMaxTime(depFiles);
return outTime < maxDepTime;
} catch (e) {
//console.log(e);
return true;
}
};
Builder.prototype._shouldLink = function (outFileName, objectFiles) {
try {
var outTime = this._getMaxTime([outFileName]);
var maxObjectFileTime = this._getMaxTime(objectFiles);
return outTime < maxObjectFileTime;
} catch (e) {
//console.log(e);
return true;
}
};
Builder.prototype._compile = function (curFileIdx, callback) {
var self = this;
var fileName = path.resolve(this.sourceFiles[curFileIdx]);
var outFileName = path.join(this.ouputDir, path.relative(this.projectDir, fileName));
var outExt = process.platform == 'win32' ? '.obj' : '.o';
outFileName = outFileName.replace(/\.cpp$/, outExt);
var depFileName = outFileName.replace(new RegExp('\\' + outExt + '$'), '.d');
this.objectFiles.push(outFileName);
if (this._shouldCompile(outFileName, depFileName)) {
console.log(ansi.green(util.format(
"[%d/%d] cxx: %s -> %s",
this.currentTask + 1,
this.totalTasks,
path.relative(this.projectDir, fileName),
path.relative(this.projectDir, outFileName))));
var args = this.getCompilerArgs(fileName, outFileName);
if (this.verbose) {
console.log(this.cppCompiler, args.join(' '));
}
this._runCommandLine(this.cppCompiler, args, function (code) {
self.currentTask++;
callback(code);
});
} else {
console.log(ansi.green(util.format(
"[%d/%d] SKIPPING cxx: %s -> %s",
this.currentTask + 1,
this.totalTasks,
path.relative(this.projectDir, fileName),
path.relative(this.projectDir, outFileName))));
self.currentTask++;
callback(0);
}
};
Builder.prototype.compile = function (callback) {
this.currentTask = this.currentTask || 0;
this.totalTasks = this.totalTasks || this.sourceFiles.length;
callback = callback || function () {};
var self = this;
this.createDir(this.ouputDir);
// append this late because it could be set later in the process
if (this.showWarnings) {
this.appendUnique('CXXFLAGS', ['-Wall']);
}
// need to append these last to reduce conflicts
this.appendIncludeDir(this.nodeIncludeDir);
if (process.platform == 'win32') {
this.appendIncludeDir(this.v8IncludeDir);
this.appendIncludeDir(this.uvIncludeDir);
}
// no source then fail
if (this.sourceFiles.length == 0) {
callback(new Error("Nothing to compile!"));
return;
}
var curFileIdx = 0;
var doCompile;
var err = false;
doCompile = function () {
if (curFileIdx < self.sourceFiles.length) {
self._compile(curFileIdx, function (code) {
if (code != 0) {
err = true;
}
curFileIdx++;
doCompile();
});
} else {
if (self.verbose) {
console.log("Done compiling.");
}
if (err) {
callback(new Error("At least one file failed to compile."));
} else {
callback();
}
}
};
doCompile();
};
Builder.prototype.link = function (callback) {
this.currentTask = this.currentTask || 0;
this.totalTasks = this.totalTasks || 1;
callback = callback || function () {};
var self = this;
this.createDir(this.ouputDir);
var outFileName = path.resolve(path.join(this.ouputDir, this.target + ".node"));
var objectFilesStr = this.objectFiles.map(
function (f) { return path.relative(self.projectDir, f); }).join(' ');
// append last to reduce conflict
if (process.platform == 'win32') {
this.appendLinkerSearchDir(path.join(this.nodeLibDir, 'lib'));
}
this.appendLinkerSearchDir(this.nodeLibDir);
// do the linking
if (this._shouldLink(outFileName, this.objectFiles)) {
console.log(ansi.yellow(util.format(
"[%d/%d] cxx_link: %s -> %s",
this.currentTask + 1,
this.totalTasks,
objectFilesStr,
path.relative(this.projectDir, outFileName))));
var args = this.getLinkerArgs(outFileName);
if (this.verbose) {
console.log(this.linker, args.join(' '));
}
this._runCommandLine(this.linker, args, function (code) {
self.currentTask++;
if (self.verbose) {
console.log("Done linking.");
}
if (code != 0) {
callback(new Error("Failed to link."));
} else {
callback();
}
});
} else {
console.log(ansi.yellow(util.format(
"[%d/%d] SKIPPING cxx_link: %s -> %s",
this.currentTask + 1,
this.totalTasks,
objectFilesStr,
path.relative(this.projectDir, outFileName))));
}
};
Builder.prototype.compileAndLink = function (callback) {
this.currentTask = 0;
this.totalTasks = this.sourceFiles.length + 1; // +1 is for linking
callback = callback || function () {};
var self = this;
this.compile(function (err) {
if (err) {
self.fail(err);
return;
}
self.link(function (err) {
if (err) {
self.fail(err);
return;
}
if (self.verbose) {
console.log("Done.");
}
callback();
});
});
};
Builder.prototype.run = function (options, callback) {
callback = callback || function () {};
options = options || {};
this.action = null;
for (var i = 0; i < process.argv.length; i++) {
var arg = process.argv[i];
if (arg == '-v' || arg == '--verbose') {
options.verbose = true;
} else if (arg == '-Wall' || arg == '--showWarnings') {
options.showWarnings = true;
} else if (arg == 'build' || arg == 'compile' || arg == 'link' || arg == 'help') {
options.action = arg;
}
}
this.verbose = options.verbose;
this.showWarnings = options.showWarnings;
this.action = options.action;
if (this.action == 'build') {
this.compileAndLink(callback);
} else if (this.action == 'compile') {
this.compile(callback);
} else if (this.action == 'link') {
this.link(callback);
} else if (this.action == 'help') {
this.printHelp();
} else {
console.error(ansi.red("No action specified"));
this.printHelp();
callback(null);
}
};
Builder.prototype.printHelp = function () {
console.log("mnm [options] action");
console.log("");
console.log(" Actions");
console.log(" build Compile and link the native module");
console.log(" compile Only run the compiler step.");
console.log(" link Only run the linker step.");
console.log("");
console.log(" Options");
console.log(" -v, --verbose Print verbose messages.");
console.log(" -Wall, --showWarnings Show all compiler warnings.");
console.log("");
};
Builder.prototype.failIfNotExists = function (dirName, message) {
dirName = path.resolve(dirName);
if (!existsSync(dirName)) {
message = message || "Could not find '%s'.";
this.fail(message, dirName);
}
};
Builder.prototype.fail = function (message) {
var msg = util.format.apply(this, arguments);
console.error(ansi.red("ERROR: " + msg));
process.exit(1);
};
Builder.prototype.trimQuotes = function (str) {
if (str) {
str = str.replace(/^"/, '').replace(/"$/, '');
}
return str;
};
module.exports = Builder;
|
# pylint: good-names=auth, settings, db
import logging
from operator import itemgetter
from collections import OrderedDict
import urllib.parse
import six
import pandas as pd
import numpy as np
from db_dashboard import DashboardDataAnalyzer
from rs_practice import _get_practice_data
logger = logging.getLogger(settings.logger)
logger.setLevel(settings.log_level)
admin_logger(logger)
# this is for admin links
# use auth.requires_membership('manager')
#
# create a simple index to provide a page of links
# - re build the book
# - list assignments
# - find assignments for a student
# - show totals for all students
# select acid, sid from code as T where timestamp = (select max(timestamp) from code where sid=T.sid and acid=T.acid);
def _get_dburl():
# DAL uses "postgres:", while SQLAlchemy (and the PostgreSQL spec) uses "postgresql:". Fix.
dburl = settings.database_uri
remove_prefix = "postgres://"
if dburl.startswith(remove_prefix):
dburl = "postgresql://" + dburl[len(remove_prefix) :]
return dburl
class ChapterGet:
# chapnum_map={}
# sub_chapters={}
# subchap_map={}
# subchapnum_map={}
# subchapNum_map={}
def __init__(self, chapters):
self.Cmap = {}
self.Smap = {} # dictionary organized by chapter and section labels
self.SAmap = {} # organized just by section label
for chapter in chapters:
label = chapter.chapter_label
self.Cmap[label] = chapter
sub_chapters = db(db.sub_chapters.chapter_id == chapter.id).select(
db.sub_chapters.ALL
) # FIX: get right course_id, too
# NOTE: sub_chapters table doesn't have a course name column in it, kind of a problem
self.Smap[label] = {}
for sub_chapter in sub_chapters:
self.Smap[label][sub_chapter.sub_chapter_label] = sub_chapter
self.SAmap[sub_chapter.sub_chapter_label] = sub_chapter
def ChapterNumber(self, label):
"""Given the label of a chapter, return its number"""
try:
return self.Cmap[label].chapter_num
except KeyError:
return ""
def ChapterName(self, label):
try:
return self.Cmap[label].chapter_name
except KeyError:
return label
def SectionName(self, chapter, section):
try:
return self.Smap[chapter][section].sub_chapter_name
except KeyError:
return section
def SectionNumber(self, chapter, section=None):
try:
if section is None:
lookup = self.SAmap
section = chapter
else:
lookup = self.Smap[chapter]
return lookup[section].sub_chapter_num
except KeyError:
return 999
@auth.requires(
lambda: verifyInstructorStatus(auth.user.course_name, auth.user),
requires_login=True,
)
def index():
selected_chapter = None
questions = []
sections = []
if settings.academy_mode and not settings.docker_institution_mode:
if auth.user.course_name in [
"thinkcspy",
"pythonds",
"JavaReview",
"JavaReview-RU",
"StudentCSP",
"csawesome",
"fopp",
]:
session.flash = "Student Progress page not available for {}".format(
auth.user.course_name
)
return redirect(URL("admin", "admin"))
course = db(db.courses.id == auth.user.course_id).select().first()
assignments = db(db.assignments.course == course.id).select(
db.assignments.ALL, orderby=db.assignments.name
)
chapters = db(db.chapters.course_id == course.base_course).select(
orderby=db.chapters.chapter_num
)
logger.debug("getting chapters for {}".format(auth.user.course_name))
chapget = ChapterGet(chapters)
for chapter in chapters.find(
lambda chapter: chapter.chapter_label == request.vars["chapter"]
):
selected_chapter = chapter
if selected_chapter is None:
selected_chapter = chapters.first()
logger.debug("making an analyzer")
data_analyzer = DashboardDataAnalyzer(auth.user.course_id, selected_chapter)
logger.debug("loading chapter metrics for course {}".format(auth.user.course_name))
data_analyzer.load_chapter_metrics(selected_chapter)
logger.debug("loading problem metrics")
problem_metrics = data_analyzer.problem_metrics
logger.debug("loading progress_metrics metrics")
progress_metrics = data_analyzer.progress_metrics
logger.debug("starting problem_id, metric loop")
for problem_id, metric in six.iteritems(problem_metrics.problems):
stats = metric.user_response_stats()
if data_analyzer.questions[problem_id]:
chtmp = data_analyzer.questions[problem_id].chapter
schtmp = data_analyzer.questions[problem_id].subchapter
entry = {
"id": problem_id,
"text": metric.problem_text,
"chapter": chtmp,
"chapter_title": chapget.ChapterName(chtmp),
"chapter_number": chapget.ChapterNumber(chtmp),
"sub_chapter": schtmp,
"sub_chapter_number": chapget.SectionNumber(chtmp, schtmp),
"sub_chapter_title": chapget.SectionName(chtmp, schtmp),
"correct": stats[2],
"correct_mult_attempt": stats[3],
"incomplete": stats[1],
"not_attempted": stats[0],
"attemptedBy": stats[1] + stats[2] + stats[3],
}
else:
entry = {
"id": problem_id,
"text": metric.problem_text,
"chapter": "unknown",
"sub_chapter": "unknown",
"sub_chapter_number": 0,
"sub_chapter_title": "unknown",
"chapter_title": "unknown",
"correct": stats[2],
"correct_mult_attempt": stats[3],
"incomplete": stats[1],
"not_attempted": stats[0],
"attemptedBy": stats[1] + stats[2] + stats[3],
}
questions.append(entry)
logger.debug("ADDING QUESTION %s ", entry["chapter"])
logger.debug("getting questions")
try:
questions = sorted(questions, key=itemgetter("chapter", "sub_chapter_number"))
except Exception as e:
logger.error("FAILED TO SORT {} Error detail: {}".format(questions, e))
logger.debug("starting sub_chapter loop")
for sub_chapter, metric in six.iteritems(progress_metrics.sub_chapters):
sections.append(
{
"id": metric.sub_chapter_label,
"text": metric.sub_chapter_text,
"name": metric.sub_chapter_name,
"number": chapget.SectionNumber(
selected_chapter.chapter_label, metric.sub_chapter_label
),
# FIX: Using selected_chapter here might be a kludge
# Better if metric contained chapter numbers associated with sub_chapters
"readPercent": metric.get_completed_percent(),
"startedPercent": metric.get_started_percent(),
"unreadPercent": metric.get_not_started_percent(),
}
)
read_data = []
correct_data = []
missed_data = []
recent_data = []
recent_correct = []
recent_missed = []
daily_data = []
daily_correct = []
daily_missed = []
logger.debug("getting user activity")
user_activity = data_analyzer.user_activity
# All of this can be replaced by a nice crosstab call
# See UserActivityCrosstab.ipynb
for user, activity in six.iteritems(user_activity.user_activities):
read_data.append(
{
"student": activity.name, # causes username instead of full name to show in the report, but it works ?? how to display the name but use the username on click??
"sid": activity.username,
"count": activity.get_page_views(),
}
)
correct_data.append(
{
"student": activity.name, # causes username instead of full name to show in the report, but it works ?? how to display the name but use the username on click??
"sid": activity.username,
"count": activity.get_correct_count(),
}
)
missed_data.append(
{
"student": activity.name, # causes username instead of full name to show in the report, but it works ?? how to display the name but use the username on click??
"sid": activity.username,
"count": activity.get_missed_count(),
}
)
recent_data.append(
{
"student": activity.name,
"sid": activity.username,
"count": activity.get_recent_page_views(),
}
)
recent_correct.append(
{
"student": activity.name,
"sid": activity.username,
"count": activity.get_recent_correct(),
}
)
recent_missed.append(
{
"student": activity.name,
"sid": activity.username,
"count": activity.get_recent_missed(),
}
)
daily_data.append(
{
"student": activity.name,
"sid": activity.username,
"count": activity.get_daily_page_views(),
}
)
daily_correct.append(
{
"student": activity.name,
"sid": activity.username,
"count": activity.get_daily_correct(),
}
)
daily_missed.append(
{
"student": activity.name,
"sid": activity.username,
"count": activity.get_daily_missed(),
}
)
logger.debug("finishing")
# TODO -- this is not right and explains why all are the same!!
studentactivity = [
{"data": read_data, "name": "Sections Read"},
{"data": correct_data, "name": "Exercises Correct"},
{"data": missed_data, "name": "Exercises Missed"},
]
recentactivity = [
{"data": recent_data, "name": "Sections Read"},
{"data": recent_correct, "name": "Exercises Correct"},
{"data": recent_missed, "name": "Exercises Missed"},
]
dailyactivity = [
{"data": daily_data, "name": "Sections Read"},
{"data": daily_correct, "name": "Exercises Correct"},
{"data": daily_missed, "name": "Exercises Missed"},
]
return dict(
assignments=assignments,
course=course,
questions=questions,
sections=sections,
chapters=chapters,
selected_chapter=selected_chapter,
studentactivity=studentactivity,
recentactivity=recentactivity,
dailyactivity=dailyactivity,
)
@auth.requires_login()
def studentreport():
data_analyzer = DashboardDataAnalyzer(auth.user.course_id)
for_dashboard = verifyInstructorStatus(auth.user.course_id, auth.user.id)
if "id" in request.vars and for_dashboard:
sid = request.vars.id
else:
sid = auth.user.username
response.view = "assignments/index.html"
logger.debug(f"id = {request.vars.id} is instructor = {for_dashboard} sid = {sid}")
data_analyzer.load_user_metrics(sid)
data_analyzer.load_assignment_metrics(sid, not for_dashboard)
chapters = []
for chapter_label, chapter in six.iteritems(
data_analyzer.chapter_progress.chapters
):
chapters.append(
{
"label": chapter.chapter_label,
"status": chapter.status_text(),
"subchapters": chapter.get_sub_chapter_progress(),
}
)
activity = data_analyzer.formatted_activity
logger.debug("GRADES = %s", data_analyzer.grades)
pd_dict = dict()
if response.view == "assignments/index.html":
(
pd_dict["now"],
pd_dict["now_local"],
pd_dict["practice_message1"],
pd_dict["practice_message2"],
pd_dict["practice_graded"],
pd_dict["spacing"],
pd_dict["interleaving"],
pd_dict["practice_completion_count"],
pd_dict["remaining_days"],
pd_dict["max_days"],
pd_dict["max_questions"],
pd_dict["day_points"],
pd_dict["question_points"],
pd_dict["presentable_flashcards"],
pd_dict["flashcard_count"],
pd_dict["practiced_today_count"],
pd_dict["questions_to_complete_day"],
pd_dict["practice_today_left"],
pd_dict["points_received"],
pd_dict["total_possible_points"],
pd_dict["flashcard_creation_method"],
) = _get_practice_data(
auth.user,
float(session.timezoneoffset) if "timezoneoffset" in session else 0,
db,
)
pd_dict["total_today_count"] = min(
pd_dict["practice_today_left"] + pd_dict["practiced_today_count"],
pd_dict["questions_to_complete_day"],
)
dburl = _get_dburl()
if request.vars.action == "dlcsv":
mtbl = pd.read_sql_query(
"""
select * from useinfo where sid = %(sid)s and course_id = %(course)s
""",
dburl,
params={"sid": sid, "course": auth.user.course_name},
)
response.headers["Content-Type"] = "application/vnd.ms-excel"
response.headers[
"Content-Disposition"
] = "attachment; filename=data_for_{}.csv".format(sid)
session.flash = f"Downloading to data_for_{sid}.csv"
return mtbl.to_csv(na_rep=" ")
if request.vars.action == "dlcode":
mtbl = pd.read_sql_query(
"""
select * from code where sid = %(sid)s and course_id = %(course)s
""",
dburl,
params={"sid": sid, "course": auth.user.course_id},
)
response.headers["Content-Type"] = "application/vnd.ms-excel"
response.headers[
"Content-Disposition"
] = "attachment; filename=code_for_{}.csv".format(sid)
session.flash = f"Downloading to code_for_{sid}.csv"
return mtbl.to_csv(na_rep=" ")
return dict(
course=get_course_row(db.courses.ALL),
user=data_analyzer.user,
chapters=chapters,
activity=activity,
assignments=data_analyzer.grades,
**pd_dict,
)
@auth.requires_login()
def studentprogress():
return dict(course_name=auth.user.course_name)
@auth.requires(
lambda: verifyInstructorStatus(auth.user.course_name, auth.user),
requires_login=True,
)
def grades():
response.title = "Gradebook"
course = db(db.courses.id == auth.user.course_id).select().first()
if not course:
session.flash = "Your course does not exist"
redirect(URL("dashboard", "index"))
assignments = db(db.assignments.course == course.id).select(
db.assignments.ALL, orderby=(db.assignments.duedate, db.assignments.id)
)
# recalculate total points for each assignment in case the stored
# total is out of sync.
duedates = []
for assign in assignments:
assign.points = update_total_points(assign.id)
duedates.append(date2String(assign.duedate))
students = db(
(db.user_courses.course_id == auth.user.course_id)
& (db.auth_user.id == db.user_courses.user_id)
).select(
db.auth_user.username,
db.auth_user.first_name,
db.auth_user.last_name,
db.auth_user.id,
db.auth_user.email,
db.auth_user.course_name,
orderby=(db.auth_user.last_name, db.auth_user.first_name),
)
query = """select score, points, assignments.id, auth_user.id, is_submit
from auth_user join grades on (auth_user.id = grades.auth_user)
join assignments on (grades.assignment = assignments.id)
where points is not null and assignments.course = %s and auth_user.id in
(select user_id from user_courses where course_id = %s)
order by last_name, first_name, assignments.duedate, assignments.id;"""
rows = db.executesql(query, [course["id"], course["id"]])
studentinfo = {}
practice_setting = (
db(db.course_practice.course_name == auth.user.course_name).select().first()
)
practice_average = 0
total_possible_points = 0
for s in students:
if practice_setting:
if practice_setting.spacing == 1:
practice_completion_count = db(
(db.user_topic_practice_completion.course_name == s.course_name)
& (db.user_topic_practice_completion.user_id == s.id)
).count()
total_possible_points = (
practice_setting.day_points * practice_setting.max_practice_days
)
points_received = (
practice_setting.day_points * practice_completion_count
)
else:
practice_completion_count = db(
(db.user_topic_practice_log.course_name == s.course_name)
& (db.user_topic_practice_log.user_id == s.id)
& (db.user_topic_practice_log.q != 0)
& (db.user_topic_practice_log.q != -1)
).count()
total_possible_points = (
practice_setting.question_points
* practice_setting.max_practice_questions
)
points_received = (
practice_setting.question_points * practice_completion_count
)
if total_possible_points > 0:
practice_average += 100 * points_received / total_possible_points
studentinfo[s.id] = {
"last_name": s.last_name,
"first_name": s.first_name,
"username": s.username,
"email": s.email,
"practice": "{0:.2f}".format(
(100 * points_received / total_possible_points)
)
if total_possible_points > 0
else "n/a",
}
practice_average /= len(students)
practice_average = "{0:.2f}".format(practice_average)
# create a matrix indexed by user.id and assignment.id
gradebook = OrderedDict((sid.id, OrderedDict()) for sid in students)
avgs = OrderedDict((assign.id, {"total": 0, "count": 0}) for assign in assignments)
for k in gradebook:
gradebook[k] = OrderedDict((assign.id, "n/a") for assign in assignments)
for score, points, assignments_id, auth_user_id, is_submit in rows:
if (score is not None) and (points > 0):
percent_grade = 100 * score / points
gradebook_entry = "{0:.2f}".format(percent_grade)
avgs[assignments_id]["total"] += percent_grade
avgs[assignments_id]["count"] += 1
elif is_submit:
gradebook_entry = is_submit
else:
gradebook_entry = "n/a"
gradebook[auth_user_id][assignments_id] = gradebook_entry
logger.debug("GRADEBOOK = {}".format(gradebook))
# now transform the matrix into the gradetable needed by the template
gradetable = []
averagerow = []
for k in gradebook:
studentrow = []
studentrow.append(studentinfo[k]["first_name"])
studentrow.append(studentinfo[k]["last_name"])
studentrow.append(urllib.parse.quote(studentinfo[k]["username"]))
studentrow.append(studentinfo[k]["email"])
studentrow.append(studentinfo[k]["practice"])
for assignment in gradebook[k]:
studentrow.append(gradebook[k][assignment])
gradetable.append(studentrow)
# Then build the average row for the table
for g in avgs:
if avgs[g]["count"] > 0:
averagerow.append("{0:.2f}".format(avgs[g]["total"] / avgs[g]["count"]))
else:
averagerow.append("n/a")
return dict(
course=course,
assignments=assignments,
gradetable=gradetable,
averagerow=averagerow,
practice_average=practice_average,
duedates=duedates,
)
def date2String(date_time):
day = str(date_time.strftime("%b")) + " " + str(date_time.day)
time = date_time.strftime("%I:%M %p")
displayDate = day + ", " + time
return displayDate
# This is meant to be called from a form submission, not as a bare controller endpoint
@auth.requires(
lambda: verifyInstructorStatus(auth.user.course_name, auth.user),
requires_login=True,
)
def questiongrades():
if "sid" not in request.vars or "assignment_id" not in request.vars:
logger.error("It Appears questiongrades was called without any request vars")
session.flash = "Cannot call questiongrades directly"
redirect(URL("dashboard", "index"))
course = db(db.courses.id == auth.user.course_id).select().first()
# make sure points total is up to date
assignment_id = request.vars.assignment_id
if assignment_id.isnumeric():
assignmatch = db.assignments.id == request.vars.assignment_id
else:
assignmatch = db.assignments.name == request.vars.assignment_id
assignment = db(assignmatch & (db.assignments.course == course.id)).select().first()
assignment_id = assignment.id
update_total_points(assignment_id)
sid = request.vars.sid
student = db(db.auth_user.username == sid).select(
db.auth_user.first_name, db.auth_user.last_name, db.auth_user.username
)
student[0].username = urllib.parse.quote(student[0].username)
query = """select questions.name, score, points
from questions join assignment_questions on (questions.id = assignment_questions.question_id)
left outer join question_grades on (questions.name = question_grades.div_id
and sid = %s and question_grades.course_name = %s)
where assignment_id = %s ;"""
rows = db.executesql(query, [sid, course.course_name, assignment["id"]])
if not student or not rows:
session.flash = "Student {} not found for course {}".format(
sid, course.course_name
)
return redirect(URL("dashboard", "grades"))
return dict(
assignment=assignment, student=student, rows=rows, total=0, course=course
)
def update_total_points(assignment_id):
sum_op = db.assignment_questions.points.sum()
total = (
db(db.assignment_questions.assignment_id == assignment_id)
.select(sum_op)
.first()[sum_op]
)
if total is None:
total = 0
db(db.assignments.id == assignment_id).update(points=total)
return total
# Note this is meant to be called from a form submission not as a bare endpoint
@auth.requires(
lambda: verifyInstructorStatus(auth.user.course_name, auth.user),
requires_login=True,
)
def exercisemetrics():
if "chapter" not in request.vars:
logger.error("It Appears exercisemetrics was called without any request vars")
session.flash = "Cannot call exercisemetrics directly"
redirect(URL("dashboard", "index"))
chapter = request.vars["chapter"]
base_course = (
db(db.courses.course_name == auth.user.course_name).select().first().base_course
)
chapter = (
db(
(
(db.chapters.course_id == auth.user.course_name)
| (db.chapters.course_id == base_course)
)
& (db.chapters.chapter_label == chapter)
)
.select()
.first()
)
if not chapter:
logger.error(
"Error -- No Chapter information for {} and {}".format(
auth.user.course_name, request.vars["chapter"]
)
)
session.flash = "No Chapter information for {} and {}".format(
auth.user.course_name, request.vars["chapter"]
)
redirect(URL("dashboard", "index"))
# TODO: When all old style courses were gone this can be just a base course
data_analyzer = DashboardDataAnalyzer(auth.user.course_id, chapter)
data_analyzer.load_exercise_metrics(request.vars["id"])
problem_metrics = data_analyzer.problem_metrics
prob_id = request.vars["id"]
answers = []
attempt_histogram = []
logger.debug(problem_metrics.problems)
try:
problem_metric = problem_metrics.problems[prob_id]
except KeyError:
session.flash = f"Not enough data for {prob_id}"
redirect(request.env.http_referer)
response_frequency = problem_metric.aggregate_responses
for username, user_responses in six.iteritems(problem_metric.user_responses):
responses = user_responses.responses[:4]
responses += [""] * (4 - len(responses))
answers.append(
{
"user": user_responses.user,
"username": urllib.parse.quote(user_responses.username),
"answers": responses,
}
)
for attempts, count in six.iteritems(problem_metric.user_number_responses()):
attempt_histogram.append({"attempts": attempts, "frequency": count})
return dict(
course=get_course_row(db.courses.ALL),
answers=answers,
response_frequency=response_frequency,
attempt_histogram=attempt_histogram,
exercise_label=problem_metric.problem_text,
)
def format_cell(sid, chap, subchap, val):
sid = urllib.parse.quote(sid)
if np.isnan(val):
return ""
else:
return f"""<a href="/runestone/dashboard/subchapdetail?chap={chap}&sub={subchap}&sid={sid}">{val}</a>"""
@auth.requires(
lambda: verifyInstructorStatus(auth.user.course_name, auth.user),
requires_login=True,
)
def subchapoverview():
thecourse = db(db.courses.id == auth.user.course_id).select().first()
course = auth.user.course_name
is_instructor = verifyInstructorStatus(course, auth.user.id)
if not is_instructor:
session.flash = "Not Authorized for this page"
return redirect(URL("default", "user"))
dburl = _get_dburl()
data = pd.read_sql_query(
"""
select sid, useinfo.timestamp, div_id, chapter, subchapter from useinfo
join questions on div_id = name and base_course = '{}' join auth_user on username = useinfo.sid
where useinfo.course_id = '{}' and active='T' and useinfo.timestamp >= '{}'""".format(
thecourse.base_course, course, thecourse.term_start_date
),
dburl,
parse_dates=["timestamp"],
)
data = data[~data.sid.str.contains(r"^\d{38,38}@")]
tdoff = pd.Timedelta(
hours=float(session.timezoneoffset) if "timezoneoffset" in session else 0
)
data["timestamp"] = data.timestamp.map(lambda x: x - tdoff)
if "tablekind" not in request.vars:
request.vars.tablekind = "sccount"
values = "timestamp"
idxlist = ["chapter", "subchapter", "div_id"]
if request.vars.tablekind == "sccount":
values = "div_id"
afunc = "nunique"
idxlist = ["chapter", "subchapter"]
elif request.vars.tablekind == "dividmin":
afunc = "min"
elif request.vars.tablekind == "dividmax":
afunc = "max"
else:
afunc = "count"
pt = data.pivot_table(index=idxlist, values=values, columns="sid", aggfunc=afunc)
# TODO: debug tests so these can be live
if pt.empty:
logger.error(
"Empty Dataframe after pivot for {} ".format(auth.user.course_name)
)
session.flash = "Error: Not enough data"
return redirect(URL("dashboard", "index"))
if request.vars.tablekind == "sccount":
x = pt.to_dict()
for k in x:
for j in x[k]:
if request.vars.action != "tocsv":
x[k][j] = format_cell(k, j[0], j[1], x[k][j])
pt = pd.DataFrame(x)
cmap = pd.read_sql_query(
"""select chapter_num, sub_chapter_num, chapter_label, sub_chapter_label
from sub_chapters join chapters on chapters.id = sub_chapters.chapter_id
where chapters.course_id = '{}'
order by chapter_num, sub_chapter_num;
""".format(
thecourse.base_course
),
dburl,
)
act_count = pd.read_sql_query(
"""
select chapter, subchapter, count(*) act_count
from questions
where base_course = '{}'
group by chapter, subchapter order by chapter, subchapter;
""".format(
thecourse.base_course
),
dburl,
)
if request.vars.tablekind != "sccount":
pt = pt.reset_index(2)
mtbl = pt.merge(
cmap,
left_index=True,
right_on=["chapter_label", "sub_chapter_label"],
how="outer",
)
mtbl = mtbl.set_index(["chapter_num", "sub_chapter_num"]).sort_index()
mtbl = mtbl.reset_index()
mtbl = mtbl.merge(
act_count,
left_on=["chapter_label", "sub_chapter_label"],
right_on=["chapter", "subchapter"],
)
def to_int(x):
try:
res = int(x)
return res
except ValueError:
return ""
if request.vars.tablekind == "sccount":
mtbl["chapter_label"] = mtbl.apply(
lambda row: "{}.{} {}/{} ({})".format(
to_int(row.chapter_num),
to_int(row.sub_chapter_num),
row.chapter_label,
row.sub_chapter_label,
row.act_count - 1,
),
axis=1,
)
else:
mtbl["chapter_label"] = mtbl.apply(
lambda row: "{}.{} {}/{}".format(
to_int(row.chapter_num),
to_int(row.sub_chapter_num),
row.chapter_label,
row.sub_chapter_label,
),
axis=1,
)
neworder = mtbl.columns.to_list()
neworder = neworder[-5:-4] + neworder[2:-5]
mtbl = mtbl[neworder]
if request.vars.action == "tocsv":
response.headers["Content-Type"] = "application/vnd.ms-excel"
response.headers[
"Content-Disposition"
] = "attachment; filename=data_for_{}.csv".format(auth.user.course_name)
return mtbl.to_csv(na_rep=" ")
else:
return dict(
course_name=auth.user.course_name,
course_id=auth.user.course_name,
course=thecourse,
summary=mtbl.to_json(orient="records", date_format="iso"),
)
@auth.requires(
lambda: verifyInstructorStatus(auth.user.course_name, auth.user),
requires_login=True,
)
def active():
course = db(db.courses.id == auth.user.course_id).select().first()
res = db.executesql(
"""select useinfo.timestamp, useinfo.sid, div_id
from useinfo join
(select sid, count(*), max(id)
from useinfo where course_id = %(cname)s
and event = 'page'
and timestamp > now() - interval '15 minutes' group by sid) as T
on useinfo.id = T.max""",
dict(cname=course.course_name),
)
newres = []
for row in res:
div_id = row[2]
components = div_id.rsplit("/", 2)
div_id = "/".join(components[1:])
time_local = row[0] - datetime.timedelta(
hours=float(session.timezoneoffset) if "timezoneoffset" in session else 0
)
newres.append(dict(timestamp=time_local, sid=row[1], div_id=div_id))
print(newres)
logger.error(newres)
return dict(activestudents=newres, course=course)
GRADEABLE_TYPES = {
"mchoice": "mchoice_answers",
"clickablearea": "clickablearea_answers",
"fillintheblank": "fitb_answers",
"parsonsprob": "parsons_answers",
"dragndrop": "dragndrop_answers",
}
@auth.requires(
lambda: verifyInstructorStatus(auth.user.course_name, auth.user),
requires_login=True,
)
def subchapdetail():
# 1. select the name, question_type, from questions for this chapter/subchapter/base_course
# 2. for each question get tries to correct, min time, max time, total
thecourse = db(db.courses.id == auth.user.course_id).select().first()
questions = db(
(db.questions.chapter == request.vars.chap)
& (db.questions.subchapter == request.vars.sub)
& (db.questions.base_course == thecourse.base_course)
& (db.questions.question_type != "page")
).select(db.questions.name, db.questions.question_type)
res = db.executesql(
"""
select name, question_type, min(useinfo.timestamp) as first, max(useinfo.timestamp) as last, count(*) as clicks
from questions join useinfo on name = div_id and course_id = %s
where chapter = %s and subchapter = %s
and base_course = %s and sid = %s
group by name, question_type""",
(
auth.user.course_name,
request.vars.chap,
request.vars.sub,
thecourse.base_course,
request.vars.sid,
),
as_dict=True,
)
tdoff = datetime.timedelta(
hours=float(session.timezoneoffset) if "timezoneoffset" in session else 0
)
for row in res:
row["first"] = row["first"] - tdoff
row["last"] = row["last"] - tdoff
if row["question_type"] in GRADEABLE_TYPES.keys():
tname = GRADEABLE_TYPES[row["question_type"]]
isc = (
db(
(db[tname].sid == request.vars.sid)
& (db[tname].correct == "T")
& (db[tname].div_id == row["name"])
)
.select()
.first()
)
if isc:
row["correct"] = "Yes"
else:
row["correct"] = "No"
elif row["question_type"] == "activecode":
isU = (
db(
(db.questions.name == row["name"])
& (db.questions.autograde == "unittest")
& (db.questions.base_course == thecourse.base_course)
)
.select()
.first()
)
if isU:
isC = (
db(
(db.useinfo.sid == request.vars.sid)
& (db.useinfo.div_id == row["name"])
& (db.useinfo.course_id == thecourse.course_name)
& (db.useinfo.event == "unittest")
& (db.useinfo.act.like("percent:100%"))
)
.select()
.first()
)
if isC:
row["correct"] = "Yes"
else:
row["correct"] = "No"
else:
row["correct"] = "NA"
else:
row["correct"] = "NA"
active = set([r["name"] for r in res])
allq = set([r.name for r in questions])
qtype = {r.name: r.question_type for r in questions}
missing = allq - active
for q in missing:
res.append(
{
"name": q,
"question_type": qtype[q],
"first": "",
"last": "",
"clicks": "",
"correct": "",
}
)
print(res)
return dict(
rows=res,
sid=request.vars.sid,
chapter=request.vars.chap,
subchapter=request.vars.sub,
course_name=auth.user.course_name,
course_id=auth.user.course_name,
course=thecourse,
)
|
// @flow
import 'react-native'
import React from 'react'
import renderer from 'react-test-renderer'
import Loader from '../loader'
describe('<Loader />', () => {
it('should render properly and match the snapshot', () => {
const component = renderer.create(<Loader delay={0} message="test" />)
const tree = component.toJSON()
expect(tree).toMatchSnapshot()
})
it('should check that delay works', () => {
const component = renderer.create(<Loader delay={1000} message="test" />)
const tree = component.toJSON()
expect(tree).toBe(null)
})
xit('should check that interval works', () => {
// const component = renderer.create(<Loader />)
// const tree = component.toJSON()
// expect(tree).toMatchSnapshot()
})
xit('should check that timeout works', () => {
// const component = renderer.create(<Loader />)
// const tree = component.toJSON()
// expect(tree).toMatchSnapshot()
})
it('should check that custom message works', () => {
const component = renderer.create(<Loader message="sovrin is cool" />)
const tree = component.toJSON()
expect(tree).toMatchSnapshot()
})
it('should check that showMessage works as expected when true', () => {
const component = renderer.create(<Loader showMessage message="show me" />)
const tree = component.toJSON()
expect(tree).toMatchSnapshot()
})
it('should check that showMessage works as expected when false', () => {
const component = renderer.create(
<Loader showMessage={false} message="don't show me" />
)
const tree = component.toJSON()
expect(tree).toMatchSnapshot()
})
it('should check that light type works', () => {
const component = renderer.create(
<Loader type="light" showMessage={false} />
)
const tree = component.toJSON()
expect(tree).toMatchSnapshot()
})
it('should check that dark type works', () => {
const component = renderer.create(
<Loader type="dark" showMessage={false} />
)
const tree = component.toJSON()
expect(tree).toMatchSnapshot()
})
it('should check that size works', () => {
const component = renderer.create(<Loader size={48} showMessage={false} />)
const tree = component.toJSON()
expect(tree).toMatchSnapshot()
})
})
|
import React, {Component} from 'react';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {term: '' };
}
render() {
return (
<div>
<input
value = {this.state.term}
onChange = {event => this.setState({term: event.target.value})} />
</div>
);
}
}
export default SearchBar; |
angular.module('emerilFoods', ['foodController', 'foodService']);
|
import Flv from 'flv.js'
import Hls from 'hls.js'
import dashjs from 'dashjs'
import globals from './global'
var customKernelFun = function(video,src) {
// hls decode
let hlsDecodeAction = () => {
console.log('custom hls create...');
let hlsConfig = {
autoStartLoad:true,
debug:false,
}
let hls = new Hls(hlsConfig);
hls.attachMedia(video);
hls.on(Hls.Events.MEDIA_ATTACHED,function() {
hls.loadSource(src);
})
hls.on(Hls.Events.ERROR,function(errMes) {
console.error(errMes);
// 发送错误报告
globals.mp.sendError(errMes);
});
}
// flv decode
let flvDecodeAction = () => {
console.log('custom flv create...');
let flvConfig = {
type:'flv',
url:src,
}
let flv = Flv.createPlayer(flvConfig);
flv.attachMediaElement(video);
flv.load();
flv.on(Flv.Events.ERROR,function(errMes) {
console.error(errMes);
// 发送错误报告
globals.mp.sendError(errMes);
});
}
// dash decode
let dashDecodeAction = () => {
let dashMedia = dashjs.MediaPlayer().create();
dashMedia.initialize(video, src,false);
dashMedia.on(dashjs.MediaPlayer.events.ERROR,function(errMes) {
console.error(errMes);
// 发送错误报告
globals.mp.sendError(errMes);
dashMedia.reset();
})
}
// mp4 decode play
let mp4DecodeAction = () => {
console.log('>> mp4 parse medie resource paly');
video.src = src;
}
// execute the appropriate decoder
src.indexOf('.m3u8') != -1 ? hlsDecodeAction() : '';
src.indexOf('.flv') != -1 ? flvDecodeAction() : '';
src.indexOf('.mpd') != -1 ? dashDecodeAction() : '';
src.indexOf('.mp4') != -1 ? mp4DecodeAction() : '';
}
export default {
// type:'hls',
// loader:Hls,
// config:{
// debug:false,
// },
// type:'flv',
// loader:Flv,
// config:{
// cors:true
// },
customKernel:customKernelFun, // 自定义核心解码加载程序
} |
/**
* tiling - The TinyJS plugin
*
* Copy to https://github.com/pixijs/pixi.js/tree/v4.8.9/src/extras
* Some code (c) 2013-2017 Mathew Groves, Chad Engler and other contributors.
* See https://github.com/pixijs/pixi.js/graphs/contributors for the full list of contributors.
*
* @name tinyjs-plugin-tiling
* @overview A fast way of rendering a tiling image
* @author yiiqii
* @license MIT
*/
/**
* Tiny.js
* @external Tiny
* @see {@link http://tinyjs.net/}
*/
/**
* @namespace Tiny.tiling
*/
export { default as TilingSprite } from './TilingSprite';
export { default as TilingSpriteRenderer } from './webgl/TilingSpriteRenderer';
|
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const PostRoutes = require('./routes/posts');
const commentRoutes = require('./routes/comments');
// Configuration statements
const port = 4000;
app.use(bodyParser.json());
app.use((req,res,next) => {
res.setHeader('Access-Control-Allow-Origin',"*");
res.setHeader('Access-Contro;-Allow-Headers','Origin,x-Requested-With,Content-type,Accept,Authorization,Role')
res.setHeader('Access-Control-Allow-Methods','GET,POST,PATCH,PUT,DELETE');
next();
})
app.use('/ap11',PostRoutes);
app.use('/api1',commentRoutes);
app.use((error, req, res, next) => {
res.status(error.code);
res.json({ message: error.message || 'Unknown error occured', code: error.code });
});
mongoose.connect('mongodb+srv://nikhilrai:[email protected]/myFirstDatabase?retryWrites=true&w=majority', {
useUnifiedTopology: true,
useNewUrlParser: true
}).then(() => {
app.listen(port, () => {
console.log('App running')
});
}).catch(err => {
console.log(err);
}); |
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Joshua Stone
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from .request import get_filters, get_filter_data
from .helpers import api_key, join_params, set_limit, validate_filter
__all__ = [
"Filters",
"Filter"
]
system_filters = {"default": 100073,
"everything": 56027,
"r34": 37432,
"legacy default": 37431,
"maximum spoilers": 37430,
"dark": 37429}
class Filters(object):
def __init__(self, key="", filters_id="", limit=50, per_page=25, page=1,
url_domain="https://derpibooru.org", proxies={}):
self.proxies = proxies
self.url_domain = url_domain
self._params = {
"key": api_key(key),
"per_page": set_limit(per_page),
"page": set_limit(page)
}
if filters_id not in {"system", "user"}:
if key:
filters_id = "user"
else:
filters_id = "system"
self._limit = set_limit(limit)
self._search = get_filters(filters_id, self._params,
self._limit, url_domain=self.url_domain, proxies=self.proxies)
def __iter__(self):
"""
Make Filters() iterable so that new search results can be lazily generated
for performance reasons.
"""
return self
@property
def parameters(self):
"""
Returns a list of available parameters; useful for passing state to new
instances of Filters().
"""
return self._params
@property
def url(self):
"""
Returns a standart URL of avaliable filters list
"""
return f"{self.url_domain}/filters"
def key(self, key=""):
"""
Takes a user's API key string which applies content settings. API keys can
be found at <https://derpibooru.org/registration/edit>.
"""
params = join_params(self.parameters, {"key": key,
"limit": self._limit,
"url_domain": self.url_domain,
"proxies": self.proxies}
)
return self.__class__(**params)
def limit(self, limit):
"""
Set absolute limit on number of filters to return, or set to None to return
as many results as needed; default 50 posts. This limit on app-level.
"""
params = join_params(self.parameters, {"limit": limit,
"url_domain": self.url_domain,
"proxies": self.proxies})
return self.__class__(**params)
def get_page(self,page):
"""
Set page for gets result of search.
"""
params = join_params(self.parameters, {"page": set_limit(page),
"limit": self._limit,
"url_domain": self.url_domain,
"proxies": self.proxies}
)
return self.__class__(**params)
def per_page(self,limit):
"""
Set absolute limit on number of filters to get, or set to None to return
defaulting 25 posts; max 50 filters. This limit on API-level.
"""
params = join_params(self.parameters, {"per_page": set_limit(limit),
"limit": self._limit,
"url_domain": self.url_domain,
"proxies": self.proxies}
)
return self.__class__(**params)
def __next__(self):
"""
Returns a result wrapped in a new instance of Filter().
"""
return Filter(None, data=next(self._search), url_domain=self.url_domain, proxies=self.proxies)
class Filter(object):
"""
This class provides a thin wrapper around JSON data, mapping each value to
its own property. Once instantiated the data is immutable so as to reflect
the stateless nature of a REST API.
"""
def __init__(self, filter_id, data=None, url_domain="https://derpibooru.org", proxies={}):
self.proxies = proxies
self.url_domain = url_domain
if filter_id is None and data:
self._data = data
else:
norm_str_filter_id = f"{filter_id}".lower()
if norm_str_filter_id in system_filters:
filter_id = system_filters[norm_str_filter_id]
self._data = data = get_filter_data(validate_filter(filter_id),
url_domain=url_domain, proxies=proxies)
for field, body in data.items():
if not hasattr(self, field):
setattr(self, field, body)
def __str__(self):
return f"Filter({self.name})"
@property
def data(self):
return self._data
def update(self):
data = get_image_data(self.id, proxies=self.proxies)
if data:
self._data = data |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Initial States (:mod:`qiskit.chemistry.components.initial_states`)
==================================================================
These are chemistry specific Aqua Initial States where they inherit from
Aqua :class:`~qiskit.aqua.components.initial_states.InitialState`.
As they rely on chemistry specific knowledge and/or functions they live here rather than in Aqua.
.. currentmodule:: qiskit.chemistry.components.initial_states
Initial States
==============
.. autosummary::
:toctree: ../stubs/
:nosignatures:
HartreeFock
VSCF
"""
from .hartree_fock import HartreeFock
from .vscf import VSCF
__all__ = ['HartreeFock', 'VSCF']
|
"""
To trace sqlalchemy queries, add instrumentation to the engine class or
instance you are using::
from ddtrace import tracer
from ddtrace.contrib.sqlalchemy import trace_engine
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:')
trace_engine(engine, tracer, 'my-database')
engine.connect().execute('select count(*) from users')
"""
# 3p
import sqlalchemy
from sqlalchemy.event import listen
# project
import ddtrace
from ddtrace import config
from ...constants import ANALYTICS_SAMPLE_RATE_KEY
from ...constants import SPAN_MEASURED_KEY
from ...ext import SpanTypes
from ...ext import net as netx
from ...ext import sql as sqlx
from ...pin import Pin
def trace_engine(engine, tracer=None, service=None):
"""
Add tracing instrumentation to the given sqlalchemy engine or instance.
:param sqlalchemy.Engine engine: a SQLAlchemy engine class or instance
:param ddtrace.Tracer tracer: a tracer instance. will default to the global
:param str service: the name of the service to trace.
"""
tracer = tracer or ddtrace.tracer # by default use global
EngineTracer(tracer, service, engine)
def _wrap_create_engine(func, module, args, kwargs):
"""Trace the SQLAlchemy engine, creating an `EngineTracer`
object that will listen to SQLAlchemy events. A PIN object
is attached to the engine instance so that it can be
used later.
"""
# the service name is set to `None` so that the engine
# name is used by default; users can update this setting
# using the PIN object
engine = func(*args, **kwargs)
EngineTracer(ddtrace.tracer, None, engine)
return engine
class EngineTracer(object):
def __init__(self, tracer, service, engine):
self.tracer = tracer
self.engine = engine
self.vendor = sqlx.normalize_vendor(engine.name)
self.service = service or self.vendor
self.name = "%s.query" % self.vendor
# attach the PIN
Pin(app=self.vendor, tracer=tracer, service=self.service).onto(engine)
listen(engine, "before_cursor_execute", self._before_cur_exec)
listen(engine, "after_cursor_execute", self._after_cur_exec)
# Determine name of error event to listen for
# Ref: https://github.com/DataDog/dd-trace-py/issues/841
if sqlalchemy.__version__[0] != "0":
error_event = "handle_error"
else:
error_event = "dbapi_error"
listen(engine, error_event, self._handle_db_error)
def _before_cur_exec(self, conn, cursor, statement, *args):
pin = Pin.get_from(self.engine)
if not pin or not pin.enabled():
# don't trace the execution
return
span = pin.tracer.trace(
self.name,
service=pin.service,
span_type=SpanTypes.SQL,
resource=statement,
)
span.set_tag(SPAN_MEASURED_KEY)
if not _set_tags_from_url(span, conn.engine.url):
_set_tags_from_cursor(span, self.vendor, cursor)
# set analytics sample rate
sample_rate = config.sqlalchemy.get_analytics_sample_rate()
if sample_rate is not None:
span.set_tag(ANALYTICS_SAMPLE_RATE_KEY, sample_rate)
def _after_cur_exec(self, conn, cursor, statement, *args):
pin = Pin.get_from(self.engine)
if not pin or not pin.enabled():
# don't trace the execution
return
span = pin.tracer.current_span()
if not span:
return
try:
if cursor and cursor.rowcount >= 0:
span.set_tag(sqlx.ROWS, cursor.rowcount)
finally:
span.finish()
def _handle_db_error(self, *args):
pin = Pin.get_from(self.engine)
if not pin or not pin.enabled():
# don't trace the execution
return
span = pin.tracer.current_span()
if not span:
return
try:
span.set_traceback()
finally:
span.finish()
def _set_tags_from_url(span, url):
"""set connection tags from the url. return true if successful."""
if url.host:
span.set_tag(netx.TARGET_HOST, url.host)
if url.port:
span.set_tag(netx.TARGET_PORT, url.port)
if url.database:
span.set_tag(sqlx.DB, url.database)
return bool(span.get_tag(netx.TARGET_HOST))
def _set_tags_from_cursor(span, vendor, cursor):
"""attempt to set db connection tags by introspecting the cursor."""
if "postgres" == vendor:
if hasattr(cursor, "connection") and hasattr(cursor.connection, "dsn"):
dsn = getattr(cursor.connection, "dsn", None)
if dsn:
d = sqlx.parse_pg_dsn(dsn)
span.set_tag(sqlx.DB, d.get("dbname"))
span.set_tag(netx.TARGET_HOST, d.get("host"))
span.set_tag(netx.TARGET_PORT, d.get("port"))
|
var searchData=
[
['taggedcommandline_20330',['TaggedCommandLine',['../class_t_r_i_m_1_1_s_d_k_1_1_external_link.html#a65a441671d5b8d5415536d69cffac7d8',1,'TRIM::SDK::ExternalLink']]],
['task_20331',['Task',['../class_t_r_i_m_1_1_s_d_k_1_1_minute_item_action_arising.html#a352a0709b8cc4cdd69ad901b3798c9b1',1,'TRIM::SDK::MinuteItemActionArising']]],
['taskid_20332',['TaskId',['../class_t_r_i_m_1_1_s_d_k_1_1_external_workflow_task.html#a485e6f5fddd6585731d8ab34fc7ac555',1,'TRIM::SDK::ExternalWorkflowTask']]],
['taskname_20333',['TaskName',['../class_t_r_i_m_1_1_s_d_k_1_1_external_workflow_task.html#ac3fe3dee6de686528d83c0b021e290b2',1,'TRIM::SDK::ExternalWorkflowTask']]],
['tcpaddress_20334',['TCPAddress',['../class_t_r_i_m_1_1_s_d_k_1_1_trim_enterprise_workgroup_server.html#a26116a80c0ad0e8bf4cf61431ae12232',1,'TRIM::SDK::TrimEnterpriseWorkgroupServer']]],
['template_20335',['Template',['../class_t_r_i_m_1_1_s_d_k_1_1_activity.html#a167202c42c11bf128180f8355c9f1c53',1,'TRIM.SDK.Activity.Template()'],['../class_t_r_i_m_1_1_s_d_k_1_1_alert.html#a2ce9655408c5214f35c339cb573ea16e',1,'TRIM.SDK.Alert.Template()'],['../class_t_r_i_m_1_1_s_d_k_1_1_alert_subscriber.html#a8cc33e8f191c4261a0f5d1f6bf144bc8',1,'TRIM.SDK.AlertSubscriber.Template()'],['../class_t_r_i_m_1_1_s_d_k_1_1_consignment.html#a0f56e1fa216568fd4e8144bdf0032738',1,'TRIM.SDK.Consignment.Template()'],['../class_t_r_i_m_1_1_s_d_k_1_1_html_layout.html#ac60047595532987013b67c7fb72e2af6',1,'TRIM.SDK.HtmlLayout.Template()'],['../class_t_r_i_m_1_1_s_d_k_1_1_workflow.html#a8ff4d8e51510a301b059c67c1653fe33',1,'TRIM.SDK.Workflow.Template()']]],
['temporarypath_20336',['TemporaryPath',['../class_t_r_i_m_1_1_s_d_k_1_1_trim_application.html#a07f81dd9a4b2e2d75b64cd6715684fdc',1,'TRIM::SDK::TrimApplication']]],
['temptablesecurityfiltering_20337',['TempTableSecurityFiltering',['../class_t_r_i_m_1_1_s_d_k_1_1_search_user_options.html#ac0e36d3a54933eded36231a10628a186',1,'TRIM.SDK.SearchUserOptions.TempTableSecurityFiltering()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_main_object_search.html#adc4974dc001058fc816eaba891c59f55',1,'TRIM.SDK.TrimMainObjectSearch.TempTableSecurityFiltering()']]],
['tenantid_20338',['TenantID',['../class_t_r_i_m_1_1_s_d_k_1_1_policy_centre_user_options.html#ad8797f594c4b5e0fb3d716596c64db3d',1,'TRIM::SDK::PolicyCentreUserOptions']]],
['textsummary_20339',['TextSummary',['../class_t_r_i_m_1_1_s_d_k_1_1_history.html#a2ba98a7a5b84a4ff9cc4fcfc76e64945',1,'TRIM::SDK::History']]],
['this_5bint_20idx_5d_20340',['this[int idx]',['../class_t_r_i_m_1_1_s_d_k_1_1_record_1_1_sp_lir_id_property.html#a1ca7ad731ace0b8105ddfa180de65275',1,'TRIM.SDK.Record.SpLirIdProperty.this[int idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_1_1_sp_lir_list_record_property.html#a91319697487850586f3b14381d7a2548',1,'TRIM.SDK.Record.SpLirListRecordProperty.this[int idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_1_1_sp_lir_list_u_r_l_property.html#ab2e7488daf63aff9ae1b91234d4305a8',1,'TRIM.SDK.Record.SpLirListURLProperty.this[int idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_1_1_sp_lir_list_g_u_i_d_property.html#aaaa6a481ff6c5388b5e137aa1abf5b7b',1,'TRIM.SDK.Record.SpLirListGUIDProperty.this[int idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_1_1_sp_lir_list_type_property.html#aa430b06797b8d72684c7cfc5fef83f8f',1,'TRIM.SDK.Record.SpLirListTypeProperty.this[int idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_1_1_sp_lir_u_r_l_property.html#aefe94f2f2a25d3a5b33364a756a70361',1,'TRIM.SDK.Record.SpLirURLProperty.this[int idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_1_1_sp_lir_status_property.html#ab356b5e1564b0676cf76ba02ba8ba1ce',1,'TRIM.SDK.Record.SpLirStatusProperty.this[int idx]()']]],
['this_5bint_20index_5d_20341',['this[int index]',['../class_t_r_i_m_1_1_s_d_k_1_1_api_explorer_row_list.html#aa46ac3afff2e8a69ddbd71fafad0f134',1,'TRIM.SDK.ApiExplorerRowList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_base_object_types_list.html#aeee4e393e07e23d2ab21f5da73132cb5',1,'TRIM.SDK.BaseObjectTypesList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_checkin_place_list.html#ae649ef872109032d524070b2f598b3d9',1,'TRIM.SDK.CheckinPlaceList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_command_def_list.html#a0d19c88a6c5f03a4fba9596aa2fd38e3',1,'TRIM.SDK.CommandDefList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_database_list.html#a1c7f9076672964b7c7d9d419280f13e7',1,'TRIM.SDK.DatabaseList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_email_attachment_list.html#a33aef814670fb5996d1cbe973f2107d5',1,'TRIM.SDK.EmailAttachmentList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_email_participant_list.html#a3c579fac1f30417460b6d56202b56738',1,'TRIM.SDK.EmailParticipantList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_enum_item_list.html#aaa743533f35b1a171d91ee1e3c09c407',1,'TRIM.SDK.EnumItemList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_enum_list.html#a007e61cd90cfbb5e5ba450fc4edc9979',1,'TRIM.SDK.EnumList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_event_processor_counters_list.html#a8368da66f016884bbced5b2f20e9047e',1,'TRIM.SDK.EventProcessorCountersList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_event_process_type_list.html#a2cd67ef0355df499d94aa686475e330a',1,'TRIM.SDK.EventProcessTypeList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_explorer_category_list.html#a78d73600bfee0ff023f0771f492090fe',1,'TRIM.SDK.ExplorerCategoryList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_field_definition_list.html#a18bf00e4ec1b6799ac15acf881ce9afb',1,'TRIM.SDK.FieldDefinitionList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_int_list.html#a58ac783cc6d95c5872da579fb83bc9fa',1,'TRIM.SDK.IntList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_location_list.html#aafc375d66030eb1d354120c1f39c41d8',1,'TRIM.SDK.LocationList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_menu_item_list.html#af3bcfdb3e3f277c147d2b2c340a91b90',1,'TRIM.SDK.MenuItemList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_mobile_client_menu_item_list.html#ab76be3b59bb94b942de10ce176cfdbcf',1,'TRIM.SDK.MobileClientMenuItemList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_object_def_list.html#a15ca76109b4a28828b33587352b077f9',1,'TRIM.SDK.ObjectDefList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_origin_email_capture_spam_rule_list.html#a3321ebe03d0991d2ab8f972884c02c58',1,'TRIM.SDK.OriginEmailCaptureSpamRuleList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_property_def_list.html#a2eb0747e358f33230f1030c6d61288fb',1,'TRIM.SDK.PropertyDefList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_property_or_field_def_list.html#a3f6559397f54746d0af6577bb1d80920',1,'TRIM.SDK.PropertyOrFieldDefList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_property_or_field_value_list.html#a5548d20e1dc62daacf56e92149ec0e0a',1,'TRIM.SDK.PropertyOrFieldValueList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_property_value_list.html#a22288833a0ae275781cbfc555c5eeb54',1,'TRIM.SDK.PropertyValueList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_search_clause_ids_list.html#a9f39c453a244cd3c174e3e1f6db22d5b',1,'TRIM.SDK.SearchClauseIdsList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_search_clause_or_field_def_list.html#a340c9b254a41a9b7e7b81c4643fdaef2',1,'TRIM.SDK.SearchClauseOrFieldDefList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_security_guide_list.html#a750f54dddbbb0432ec9be672bca69972',1,'TRIM.SDK.SecurityGuideList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_string_array.html#a851de1d255522c9f85693c02f5e0b46f',1,'TRIM.SDK.StringArray.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_tray_type_list.html#a59c9235489b6907bc80f1d450177e921',1,'TRIM.SDK.TrayTypeList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_menu_link_list.html#a3e6d0d4b11c4312abed2eadd53708e54',1,'TRIM.SDK.TrimMenuLinkList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_object_change_list.html#a12a7e0c16b1eb3c53616720480e205ab',1,'TRIM.SDK.TrimObjectChangeList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_object_list.html#aaeb88e7e096e2b61b3f83cc62d587aee',1,'TRIM.SDK.TrimObjectList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_search_clause_list.html#a529bcb48da9c506e77d3456555ec1fb9',1,'TRIM.SDK.TrimSearchClauseList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_search_sort_item_list.html#a88a52eff60064a607473c38144932fa7',1,'TRIM.SDK.TrimSearchSortItemList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_search_stack_item_list.html#a31f8bbee223e4df87287c344f60dae9b',1,'TRIM.SDK.TrimSearchStackItemList.this[int index]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_u_r_i_list.html#a1d4bcfb38578515ae55e93b28aaedb5a',1,'TRIM.SDK.TrimURIList.this[int index]()']]],
['this_5buint_20idx_5d_20342',['this[uint idx]',['../class_t_r_i_m_1_1_s_d_k_1_1_action_def_steps.html#a330709c686fd9d5d5cf31e585e35649c',1,'TRIM.SDK.ActionDefSteps.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_activity_authorizations.html#a25da8ced8baab0c117f796ec380d0f32',1,'TRIM.SDK.ActivityAuthorizations.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_activity_documents.html#afb874e09c3afdf71c3ddef6dd0ab7791',1,'TRIM.SDK.ActivityDocuments.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_activity_email_recipients.html#a85d8fe6d88bc14a794b71d8916337b62',1,'TRIM.SDK.ActivityEmailRecipients.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_activity_escalations.html#a146402fb3131c2877e17c22a35fb632e',1,'TRIM.SDK.ActivityEscalations.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_activity_results.html#aebf00fbd1bba15299e42590b25710210',1,'TRIM.SDK.ActivityResults.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_activity_start_conditions.html#ad8c64f444f4c17604dbe68fc09d337d8',1,'TRIM.SDK.ActivityStartConditions.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_agenda_item_attachments.html#ae6991c38b3b222fb55618d44b281348d',1,'TRIM.SDK.AgendaItemAttachments.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_agenda_item_type_attachments.html#a61caa950b9bec76589d86753aa82a5a2',1,'TRIM.SDK.AgendaItemTypeAttachments.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_alert_subscribers.html#a6c2a3e7913fda1f2bd3094a82898f4c3',1,'TRIM.SDK.AlertSubscribers.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_archive_event_occurrences.html#aa133ce213b89d74d17d1476043f2ba82',1,'TRIM.SDK.ArchiveEventOccurrences.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_classification_only_record_types.html#a6b7163e010319a6aed735cb7564d0791',1,'TRIM.SDK.ClassificationOnlyRecordTypes.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_classification_sap_business_objects.html#a9a9b68ff052cd94e4a041504f55839a2',1,'TRIM.SDK.ClassificationSapBusinessObjects.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_communication_details.html#a5c0ed92550fcc195d946468e5e53ef5e',1,'TRIM.SDK.CommunicationDetails.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_jurisdiction_members.html#a2c2aa81c030687942b11891a5916d066',1,'TRIM.SDK.JurisdictionMembers.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_location_addresses.html#aa0c9bdec5150031bb08e6e608d14ae37',1,'TRIM.SDK.LocationAddresses.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_location_e_addresses.html#a2cfd627c6d86641cb1b4a6d5044205db',1,'TRIM.SDK.LocationEAddresses.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_meeting_documents.html#aa5aaced9e6233643be88d7efc767419b',1,'TRIM.SDK.MeetingDocuments.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_meeting_invitations.html#a04f5f8c734bcf095a5b7f379db2be3fb',1,'TRIM.SDK.MeetingInvitations.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_meeting_type_usual_participants.html#ad0e875b3425b2e8a9a4561012fdf20e0',1,'TRIM.SDK.MeetingTypeUsualParticipants.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_minute_item_action_arisings.html#a7d6e2ee19024edef0a6cd7cabe9e452f',1,'TRIM.SDK.MinuteItemActionArisings.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_client_matter_parties.html#a5c265f23766cf41f704df81f07afdbe3',1,'TRIM.SDK.RecordClientMatterParties.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_client_matter_roles.html#ae0ff1303ee6270c5672452732257158f',1,'TRIM.SDK.RecordClientMatterRoles.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_holds.html#ab5dedc5fb964171d401b0bee41505069',1,'TRIM.SDK.RecordHolds.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_jurisdictions.html#a0f77afb51df39f1d49c5cd970024d4b4',1,'TRIM.SDK.RecordJurisdictions.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_keywords.html#ac2f5712d851f4bc843f1812664947b86',1,'TRIM.SDK.RecordKeywords.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_linked_documents.html#ab00df8bd96ccc64a2d0f71c7b5c42a5c',1,'TRIM.SDK.RecordLinkedDocuments.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_locations.html#acba10a321990b391373588a2f6380ca5',1,'TRIM.SDK.RecordLocations.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_relationships.html#aa6ac5526fda4d04ba32a17e7b8a327d8',1,'TRIM.SDK.RecordRelationships.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_renditions.html#a3c782e5679c0877b4a16e95143295a2e',1,'TRIM.SDK.RecordRenditions.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_sap_components.html#afb401a9051d790844afb36bbdb0b65d5',1,'TRIM.SDK.RecordSapComponents.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_type_auto_sub_folders.html#a69236ca2df065fe6a8784b6f4d946baf',1,'TRIM.SDK.RecordTypeAutoSubFolders.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_scheduled_task_historys.html#a6e2d3aa477454fb043257694b49e049b',1,'TRIM.SDK.ScheduledTaskHistorys.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_schedule_triggers.html#ab14c51f31a3c3ea095089fb0c24c3bdc',1,'TRIM.SDK.ScheduleTriggers.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_todo_item_item_references.html#a3120d13dbda291cef1d394314c08190d',1,'TRIM.SDK.TodoItemItemReferences.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_child_object_list.html#a27790f41a7b5ead0f900d5041d4faf47',1,'TRIM.SDK.TrimChildObjectList.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_workflow_documents.html#aac3b33af294af16d0601b7bf6a5d8be4',1,'TRIM.SDK.WorkflowDocuments.this[uint idx]()'],['../class_t_r_i_m_1_1_s_d_k_1_1_workflow_template_documents.html#a879546a5a21669e3d3dd9570035ad4ef',1,'TRIM.SDK.WorkflowTemplateDocuments.this[uint idx]()']]],
['threadtimeout_20343',['ThreadTimeout',['../class_t_r_i_m_1_1_s_d_k_1_1_document_store_incremental_check_task.html#a577c12139f9a270a2afe2fb923d31f68',1,'TRIM.SDK.DocumentStoreIncrementalCheckTask.ThreadTimeout()'],['../class_t_r_i_m_1_1_s_d_k_1_1_document_store_integrity_check_task.html#a0503f8e35fb0702abd180f9b9b629bf3',1,'TRIM.SDK.DocumentStoreIntegrityCheckTask.ThreadTimeout()']]],
['timefrom_20344',['TimeFrom',['../class_t_r_i_m_1_1_s_d_k_1_1_origin.html#a1cf521b3a04cf3359d8d6f1d355c14b2',1,'TRIM::SDK::Origin']]],
['timeofday_20345',['TimeOfDay',['../class_t_r_i_m_1_1_s_d_k_1_1_trim_date_time.html#af1c13264fd1555b398c3dee6301e88a8',1,'TRIM::SDK::TrimDateTime']]],
['timeperiod_20346',['TimePeriod',['../class_t_r_i_m_1_1_s_d_k_1_1_document_store_incremental_check_task.html#a089df6ab4c388592fc617b54a0f101ee',1,'TRIM::SDK::DocumentStoreIncrementalCheckTask']]],
['timerevents_20347',['TimerEvents',['../class_t_r_i_m_1_1_s_d_k_1_1_event_processor_counters.html#ade0b1d24da22d5d13fb05fb67a5151db',1,'TRIM::SDK::EventProcessorCounters']]],
['timerfailedevents_20348',['TimerFailedEvents',['../class_t_r_i_m_1_1_s_d_k_1_1_event_processor_counters.html#adaa1080e8a448473c8b388acb0e9d492',1,'TRIM::SDK::EventProcessorCounters']]],
['timesareuniversal_20349',['TimesAreUniversal',['../class_t_r_i_m_1_1_s_d_k_1_1_input_document.html#a633c9f3fec680c4ad69656bd2872a0a9',1,'TRIM::SDK::InputDocument']]],
['timeto_20350',['TimeTo',['../class_t_r_i_m_1_1_s_d_k_1_1_origin.html#a218d2cbabde8624dc7e16419b228f0d6',1,'TRIM::SDK::Origin']]],
['title_20351',['Title',['../class_t_r_i_m_1_1_s_d_k_1_1_activity_document.html#afb6a22e4cfffd7a41593e38a07d8cea4',1,'TRIM.SDK.ActivityDocument.Title()'],['../class_t_r_i_m_1_1_s_d_k_1_1_alert.html#afc0fe4bb94792d2f5b0be77c055248d2',1,'TRIM.SDK.Alert.Title()'],['../class_t_r_i_m_1_1_s_d_k_1_1_archive_event.html#a336b3fdf734d2d09f4488d06cfc290bb',1,'TRIM.SDK.ArchiveEvent.Title()'],['../class_t_r_i_m_1_1_s_d_k_1_1_classification.html#a337d05371adb7ccb35e9377f55dd0851',1,'TRIM.SDK.Classification.Title()'],['../class_t_r_i_m_1_1_s_d_k_1_1_minute_item_action_arising.html#a389eba5e031da4e633b64cc766803b6a',1,'TRIM.SDK.MinuteItemActionArising.Title()'],['../class_t_r_i_m_1_1_s_d_k_1_1_offline_record.html#a2b5bd0500363ade29105fa49e1053310',1,'TRIM.SDK.OfflineRecord.Title()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record.html#a335440b0ca5a8ce04f83b660d8719d5b',1,'TRIM.SDK.Record.Title()'],['../class_t_r_i_m_1_1_s_d_k_1_1_record_type_auto_sub_folder.html#adaa18d699f7e42e59b4d7aa1252bd713',1,'TRIM.SDK.RecordTypeAutoSubFolder.Title()'],['../class_t_r_i_m_1_1_s_d_k_1_1_schedule.html#af4b5128a721d512ca9bb497d2e50c23b',1,'TRIM.SDK.Schedule.Title()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_main_object_search.html#aa06ae77cd2765d2c291911057bea0f6b',1,'TRIM.SDK.TrimMainObjectSearch.Title()'],['../class_t_r_i_m_1_1_s_d_k_1_1_workflow_document.html#a61927d0563e856e0c2d159b167e53f21',1,'TRIM.SDK.WorkflowDocument.Title()'],['../class_t_r_i_m_1_1_s_d_k_1_1_workflow_template_document.html#acf560eb82cff6f82997a66dcf6c9fcaf',1,'TRIM.SDK.WorkflowTemplateDocument.Title()'],['../class_t_r_i_m_1_1_s_d_k_1_1_working_copy.html#a014b357da1621e84062020ca323d6789',1,'TRIM.SDK.WorkingCopy.Title()']]],
['titlingmethod_20352',['TitlingMethod',['../class_t_r_i_m_1_1_s_d_k_1_1_record_type.html#a5733ec688281e70a904f9c0c4d304f6f',1,'TRIM::SDK::RecordType']]],
['tnacompliant_20353',['TNAcompliant',['../class_t_r_i_m_1_1_s_d_k_1_1_database.html#a4fcd77ebf9b7f0122873ecc1f89be78b',1,'TRIM::SDK::Database']]],
['today_20354',['Today',['../class_t_r_i_m_1_1_s_d_k_1_1_trim_date_time.html#aa6003e0692fb063699caadefc528dc21',1,'TRIM::SDK::TrimDateTime']]],
['todo_20355',['Todo',['../class_t_r_i_m_1_1_s_d_k_1_1_todo_item.html#a3f3620cf447b83990503c611efe4c4df',1,'TRIM::SDK::TodoItem']]],
['todoitems_20356',['TodoItems',['../class_t_r_i_m_1_1_s_d_k_1_1_startup_user_options.html#a0e280ed6e61721bbc8e94975fc46969a',1,'TRIM::SDK::StartupUserOptions']]],
['token_20357',['Token',['../class_t_r_i_m_1_1_s_d_k_1_1_event_monitor.html#a77225d8418ace260c00ccff5f8d6f80a',1,'TRIM::SDK::EventMonitor']]],
['tooltippropertyid_20358',['ToolTipPropertyId',['../class_t_r_i_m_1_1_s_d_k_1_1_object_def.html#ac172700e2f8af91e6e8833d815ef8a88',1,'TRIM::SDK::ObjectDef']]],
['topcontainersfilter_20359',['TopContainersFilter',['../class_t_r_i_m_1_1_s_d_k_1_1_trim_main_object_search.html#a6468a3917840b4950692a0aeae58859d',1,'TRIM::SDK::TrimMainObjectSearch']]],
['toplevelactions_20360',['TopLevelActions',['../class_t_r_i_m_1_1_s_d_k_1_1_record.html#a5a23550337009f42a9e40aaf501e59cc',1,'TRIM::SDK::Record']]],
['totalactualcost_20361',['TotalActualCost',['../class_t_r_i_m_1_1_s_d_k_1_1_workflow.html#adccb08a6152d5e4c0b4f34eb878b65ee',1,'TRIM::SDK::Workflow']]],
['totalactualduration_20362',['TotalActualDuration',['../class_t_r_i_m_1_1_s_d_k_1_1_workflow.html#aefd22905051c939354f61239c7101ce8',1,'TRIM::SDK::Workflow']]],
['totaldownloadsize_20363',['TotalDownloadSize',['../class_t_r_i_m_1_1_s_d_k_1_1_download_notifier_base.html#a21d28ace014e87399b90f9917be76cc9',1,'TRIM::SDK::DownloadNotifierBase']]],
['totalestimatedcost_20364',['TotalEstimatedCost',['../class_t_r_i_m_1_1_s_d_k_1_1_workflow.html#aef2f104360e64864db7f7dd87ba36c2e',1,'TRIM.SDK.Workflow.TotalEstimatedCost()'],['../class_t_r_i_m_1_1_s_d_k_1_1_workflow_template.html#afbc3212c157cd9a27d0b55e8982ef06a',1,'TRIM.SDK.WorkflowTemplate.TotalEstimatedCost()']]],
['totalestimatedduration_20365',['TotalEstimatedDuration',['../class_t_r_i_m_1_1_s_d_k_1_1_workflow.html#a5b74cf2421186cab856c17f3ce7a5d87',1,'TRIM.SDK.Workflow.TotalEstimatedDuration()'],['../class_t_r_i_m_1_1_s_d_k_1_1_workflow_template.html#a04d0421d63af38c7678ee2bb8fdb8004',1,'TRIM.SDK.WorkflowTemplate.TotalEstimatedDuration()']]],
['totalhits_20366',['TotalHits',['../class_t_r_i_m_1_1_s_d_k_1_1_trim_aggregate_result_iterator.html#abf77e5420795f5c256301e521ff872a0',1,'TRIM::SDK::TrimAggregateResultIterator']]],
['totalremainingduration_20367',['TotalRemainingDuration',['../class_t_r_i_m_1_1_s_d_k_1_1_workflow.html#a23499b9a277755db01802b6368b45274',1,'TRIM::SDK::Workflow']]],
['totalsuspensionduration_20368',['TotalSuspensionDuration',['../class_t_r_i_m_1_1_s_d_k_1_1_activity.html#a480cdb820029de5e84e1c640632df6c2',1,'TRIM::SDK::Activity']]],
['transferhashcheck_20369',['TransferHashCheck',['../class_t_r_i_m_1_1_s_d_k_1_1_database.html#a1a931aec1926e041ad4cd38a4bc1eb07',1,'TRIM::SDK::Database']]],
['transferlocation_20370',['TransferLocation',['../class_t_r_i_m_1_1_s_d_k_1_1_consignment.html#a68ca248881b45d4f8536741247ee512a',1,'TRIM.SDK.Consignment.TransferLocation()'],['../class_t_r_i_m_1_1_s_d_k_1_1_consignment_template.html#a29d8a795c626372b57806c565ace2d77',1,'TRIM.SDK.ConsignmentTemplate.TransferLocation()']]],
['transferto_20371',['TransferTo',['../class_t_r_i_m_1_1_s_d_k_1_1_schedule_trigger.html#aba0a249e9a073d8001404258afcb00e8',1,'TRIM::SDK::ScheduleTrigger']]],
['transitaddress_20372',['TransitAddress',['../class_t_r_i_m_1_1_s_d_k_1_1_request.html#a5374a458b491dcb7055862afada1e655',1,'TRIM::SDK::Request']]],
['transitlocation_20373',['TransitLocation',['../class_t_r_i_m_1_1_s_d_k_1_1_request.html#a3b646f9a2982743a52ab650faed8056a',1,'TRIM::SDK::Request']]],
['traytype_20374',['TrayType',['../class_t_r_i_m_1_1_s_d_k_1_1_explorer_row.html#a300cab5c287579dfe92835907f90e22d',1,'TRIM::SDK::ExplorerRow']]],
['treatpendingasmissing_20375',['TreatPendingAsMissing',['../class_t_r_i_m_1_1_s_d_k_1_1_document_store_incremental_check_task.html#a7084907541f8eb91eab8fa01611edae4',1,'TRIM.SDK.DocumentStoreIncrementalCheckTask.TreatPendingAsMissing()'],['../class_t_r_i_m_1_1_s_d_k_1_1_document_store_integrity_check_task.html#a9fba0d21a679c8bd74ce12b44edc11bc',1,'TRIM.SDK.DocumentStoreIntegrityCheckTask.TreatPendingAsMissing()']]],
['triggeredby_20376',['TriggeredBy',['../class_t_r_i_m_1_1_s_d_k_1_1_archive_event_occurrence.html#a13ba2779ca94805044c771f31bb79002',1,'TRIM::SDK::ArchiveEventOccurrence']]],
['triggertype_20377',['TriggerType',['../class_t_r_i_m_1_1_s_d_k_1_1_schedule_trigger.html#ab1a8cdcfa68466407dd87233fca6fd17',1,'TRIM::SDK::ScheduleTrigger']]],
['triggertypedescription_20378',['TriggerTypeDescription',['../class_t_r_i_m_1_1_s_d_k_1_1_schedule_trigger.html#a263aaf66c5d6be177dd79c8f4d834e8b',1,'TRIM::SDK::ScheduleTrigger']]],
['trimbinariesloadpath_20379',['TrimBinariesLoadPath',['../class_t_r_i_m_1_1_s_d_k_1_1_trim_application_base.html#a30828d7645e47eeae5047cdd4f338757',1,'TRIM::SDK::TrimApplicationBase']]],
['trimiconid_20380',['TrimIconId',['../class_t_r_i_m_1_1_s_d_k_1_1_record_type.html#abc5681ca0b24d8f0ed504456fe3b1547',1,'TRIM::SDK::RecordType']]],
['trimsearchstackiterator_20381',['TrimSearchStackIterator',['../class_t_r_i_m_1_1_s_d_k_1_1_trim_search_stack.html#a76498576848938b75dec5249afd419cc',1,'TRIM::SDK::TrimSearchStack']]],
['trimtype_20382',['TrimType',['../class_t_r_i_m_1_1_s_d_k_1_1_trim_child_object_list.html#af856f2fd436dc3a75d98bdd905b046dd',1,'TRIM.SDK.TrimChildObjectList.TrimType()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_main_object_search.html#a1fda30c722ce4e6add3b015768b87b5c',1,'TRIM.SDK.TrimMainObjectSearch.TrimType()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_object.html#ab3133bff7b3771ef69e19bdd88057e59',1,'TRIM.SDK.TrimObject.TrimType()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_search_clause.html#af5b44a3ad12018440aedfd090f9e4413',1,'TRIM.SDK.TrimSearchClause.TrimType()'],['../class_t_r_i_m_1_1_s_d_k_1_1_trim_search_stack.html#a9b774c5bfe7a412d0a797fdc177582f2',1,'TRIM.SDK.TrimSearchStack.TrimType()']]],
['truestring_20383',['TrueString',['../class_t_r_i_m_1_1_s_d_k_1_1_property_def.html#aca9082b422772e6df0e131375633144a',1,'TRIM::SDK::PropertyDef']]],
['trusteduser_20384',['TrustedUser',['../class_t_r_i_m_1_1_s_d_k_1_1_database.html#a2d4415a2069dfbcc2cfbc1fb232a73c9',1,'TRIM::SDK::Database']]],
['typedtitle_20385',['TypedTitle',['../class_t_r_i_m_1_1_s_d_k_1_1_record.html#a1071e7620af36626207eac8c64e983d7',1,'TRIM::SDK::Record']]],
['typeofattendee_20386',['TypeOfAttendee',['../class_t_r_i_m_1_1_s_d_k_1_1_meeting_invitation.html#ae55a94e23e2b2ce1ed66223aab9e065c',1,'TRIM::SDK::MeetingInvitation']]],
['typeofcontact_20387',['TypeOfContact',['../class_t_r_i_m_1_1_s_d_k_1_1_record_location.html#a474374ca659e2f3652288fe50b4acbad',1,'TRIM::SDK::RecordLocation']]],
['typeofdeclassification_20388',['TypeOfDeclassification',['../class_t_r_i_m_1_1_s_d_k_1_1_security_guide.html#af87a425212dd45e00b24fb35456360e2',1,'TRIM::SDK::SecurityGuide']]],
['typeofinvite_20389',['TypeOfInvite',['../class_t_r_i_m_1_1_s_d_k_1_1_meeting_invitation.html#a8bf9760ac0e121152759a636e1f5ab47',1,'TRIM.SDK.MeetingInvitation.TypeOfInvite()'],['../class_t_r_i_m_1_1_s_d_k_1_1_meeting_type_usual_participant.html#a4e55c2ce18d53b53a151100ccaabba61',1,'TRIM.SDK.MeetingTypeUsualParticipant.TypeOfInvite()']]],
['typeoflocation_20390',['TypeOfLocation',['../class_t_r_i_m_1_1_s_d_k_1_1_location.html#a16c5eeff5020c6e5a80b80711f6e19f2',1,'TRIM::SDK::Location']]],
['typeoforigin_20391',['TypeOfOrigin',['../class_t_r_i_m_1_1_s_d_k_1_1_origin.html#aab3c3fc7acee992454c2f055f05ae95b',1,'TRIM::SDK::Origin']]],
['typeofrecordlocation_20392',['TypeOfRecordLocation',['../class_t_r_i_m_1_1_s_d_k_1_1_record_location.html#a0c126fe4e6fa8a7c348ae671a5d2949b',1,'TRIM::SDK::RecordLocation']]],
['typeofrendition_20393',['TypeOfRendition',['../class_t_r_i_m_1_1_s_d_k_1_1_record_rendition.html#af75b6455b2b5acbc6b84dd4e109f0c85',1,'TRIM::SDK::RecordRendition']]]
];
|
# !/usr/bin/python
# -*- coding: latin-1 -*-
"""
A module for utility funtions
"""
import glob
import itertools
import os
import re
import requests
import shutil
import urllib
from astropy.io import fits
import bokeh.palettes as bpal
from scipy.interpolate import RegularGridInterpolator
import numpy as np
from svo_filters import svo
from .throughputs import JWST_THROUGHPUTS
# Supported profiles
PROFILES = ['uniform', 'linear', 'quadratic',
'square-root', 'logarithmic', 'exponential',
'3-parameter', '4-parameter']
# Supported filters
FILTERS = svo.filters()
NON_JWST = [filt for filt in FILTERS if not filt.startswith('NIRISS') and not filt.startswith('NIRCam') and not filt.startswith('NIRSpec') and not filt.startswith('MIRI')]
FILTERS_LIST = sorted(NON_JWST + JWST_THROUGHPUTS)
DATA_URLS = {
'exoctk_contam': ['https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/exoctk_contam.tar.gz'],
'groups_integrations': ['https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/groups_integrations.tar.gz'],
'fortney': ['https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/fortney.tar.gz'],
'generic': ['https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/generic.tar.gz'],
'exoctk_log': ['https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/exoctk_log.tar.gz'],
'modelgrid': ['https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/modelgrid_ATLAS9.tar.gz',
'https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/modelgrid_ACES_1.tar.gz',
'https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/modelgrid_ACES_2.tar.gz'],
'all': ['https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/modelgrid_ATLAS9.tar.gz',
'https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/modelgrid_ACES_1.tar.gz',
'https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/modelgrid_ACES_2.tar.gz',
'https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/generic.tar.gz',
'https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/fortney.tar.gz',
'https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/groups_integrations.tar.gz',
'https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/groups_integrations.tar.gz',
'https://data.science.stsci.edu/redirect/JWST/ExoCTK/compressed/exoctk_contam.tar.gz']}
# If the variable is blank or doesn't exist
HOME_DIR = os.path.expanduser('~')
EXOCTK_DATA = os.environ.get('EXOCTK_DATA', os.path.join(HOME_DIR, 'exoctk_data'))
ON_GITHUB_ACTIONS_OR_RTD = HOME_DIR == '/home/runner' or HOME_DIR == '/Users/runner' or HOME_DIR == '/home/docs'
if not ON_GITHUB_ACTIONS_OR_RTD:
if not EXOCTK_DATA:
print(
'WARNING: The $EXOCTK_DATA environment variable is not set. Please set the '
'value of this variable to point to the location of the exoctk_data '
'download folder. Users may retrieve this folder by clicking the '
'"ExoCTK Data Download" button on the ExoCTK website, or by using '
'the exoctk.utils.download_exoctk_data() function.')
else:
# If the variable exists but doesn't point to a real location
if not os.path.exists(EXOCTK_DATA):
print(
'WARNING: The $EXOCTK_DATA environment variable is set to a location that '
'cannot be accessed.')
# If the variable exists, points to a real location, but is missing contents
for item in DATA_URLS.keys():
if item not in [os.path.basename(item) for item in glob.glob(os.path.join(EXOCTK_DATA, '*'))]:
os.makedirs(os.path.join(EXOCTK_DATA, item))
EXOCTK_CONTAM_DIR = os.path.join(EXOCTK_DATA, 'exoctk_contam/')
EXOCTKLOG_DIR = os.path.join(EXOCTK_DATA, 'exoctk_log/')
FORTGRID_DIR = os.path.join(EXOCTK_DATA, 'fortney/')
GENERICGRID_DIR = os.path.join(EXOCTK_DATA, 'generic/')
GROUPS_INTEGRATIONS_DIR = os.path.join(EXOCTK_DATA, 'groups_integrations/')
MODELGRID_DIR = os.path.join(EXOCTK_DATA, 'modelgrid/')
def build_target_url(target_name):
"""Build restful api url based on target name.
Parameters
----------
target_name : string
The name of the target transit.
Returns
-------
target_url : string
"""
# Encode the target name string.
encode_target_name = urllib.parse.quote(target_name, encoding='utf-8')
target_url = "https://exo.mast.stsci.edu/api/v0.1/exoplanets/{}/properties/".format(encode_target_name)
return target_url
def calc_zoom(R_f, arr):
"""
Calculate the zoom factor required to make the given
array into the given resolution
Parameters
----------
R_f: int
The desired final resolution of the wavelength array
arr: array-like
The array to zoom
"""
# Get initial resolution
lam = arr[-1] - arr[0]
d_lam_i = np.nanmean(np.diff(arr))
# R_i = lam/d_lam_i
# Calculate zoom
d_lam_f = lam / R_f
z = d_lam_i / d_lam_f
return z
def check_for_data(tool):
"""Checks to see if the necessary data has been downloaded for the
given tool
Parameters
----------
tool: str
The tool to check for
"""
# Validate tool
if tool not in DATA_URLS:
raise ValueError("'{}' not a supported tool. Try {}".format(tool, list(DATA_URLS.keys())))
# Make a path and glob the files
path = os.path.join(EXOCTK_DATA, tool)
files = glob.glob(os.path.join(path, '*'))
print(path, files)
if len(files) == 0:
raise IOError("This tool requires the '{0}' data. Try downloading with exoctk.utils.download_exoctk_data('{0}')".format(tool))
def color_gen(colormap='viridis', key=None, n=10):
"""Color generator for Bokeh plots
Parameters
----------
colormap: str, sequence
The name of the color map
Returns
-------
generator
A generator for the color palette
"""
if colormap in dir(bpal):
palette = getattr(bpal, colormap)
if isinstance(palette, dict):
if key is None:
key = list(palette.keys())[0]
palette = palette[key]
elif callable(palette):
palette = palette(n)
else:
raise TypeError("pallette must be a bokeh palette name or a sequence of color hex values.")
elif isinstance(colormap, (list, tuple)):
palette = colormap
else:
raise TypeError("pallette must be a bokeh palette name or a sequence of color hex values.")
yield from itertools.cycle(palette)
COLORS = color_gen('Category10')
def download_exoctk_data(tool='all', exoctk_data_dir=EXOCTK_DATA):
"""Retrieves the ``exoctk_data`` materials from Box, downloads them
to the user's local machine, uncompresses the files, and arranges
them into an ``exoctk_data`` directory.
Parameters
----------
tool: str
The ExoCTK tool data to download
exoctk_data_dir : string
The path to where the ExoCTK data package will be downloaded.
The default setting is the user's $HOME directory.
"""
# Validate tool
if tool not in DATA_URLS:
raise ValueError("'{}' not a supported tool. Try {}".format(tool, list(DATA_URLS.keys())))
print('\nDownloading ExoCTK data package. This may take a few minutes.')
print('Materials will be downloaded to {}/\n'.format(exoctk_data_dir))
# Ensure the exoctk_data/ directory exists in user's home directory
try:
if not os.path.exists(exoctk_data_dir):
os.makedirs(exoctk_data_dir)
except PermissionError:
print('Data download failed. Unable to create {}. Please check permissions.'.format(exoctk_data_dir))
# Select the URLs and always include the log files
urls = DATA_URLS[tool]
urls += DATA_URLS['exoctk_log']
# Build landing paths for downloads
download_paths = [os.path.join(exoctk_data_dir, os.path.basename(url)) for url in urls]
# Perform the downloads
for i, url in enumerate(urls):
landing_path = os.path.join(exoctk_data_dir, os.path.basename(url))
print('({}/{}) Downloading data to {} from {}'.format(i + 1, len(urls), landing_path, url))
with requests.get(url, stream=True) as response:
with open(landing_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=2048):
if chunk:
f.write(chunk)
print('\nDownload complete\n')
# Uncompress data
print('Uncompressing data:\n')
for path in download_paths:
# Uncompress data
print('\t{}'.format(path))
shutil.unpack_archive(path, exoctk_data_dir)
# Remove original .tar.gz files
os.remove(path)
# Combine modelgrid directories
print('\nOrganizing files into exoctk_data/ directory')
try:
os.makedirs(os.path.join(exoctk_data_dir, 'modelgrid', 'ATLAS9'))
os.makedirs(os.path.join(exoctk_data_dir, 'modelgrid', 'ACES'))
except FileExistsError:
pass
modelgrid_files = glob.glob(os.path.join(exoctk_data_dir, 'modelgrid.*', '*'))
for src in modelgrid_files:
if 'ATLAS9' in src:
dst = os.path.join(exoctk_data_dir, 'modelgrid', 'ATLAS9')
elif 'ACES_' in src:
dst = os.path.join(exoctk_data_dir, 'modelgrid', 'ACES')
try:
shutil.move(src, dst)
except shutil.Error:
print('Unable to organize modelgrid/ directory')
for dir in ['modelgrid.ATLAS9', 'modelgrid.ACES_1', 'modelgrid.ACES_2']:
path = os.path.join(exoctk_data_dir, dir)
if os.path.exists(path):
shutil.rmtree(path)
print('Completed!')
def filter_table(table, **kwargs):
"""Retrieve the filtered rows
Parameters
----------
table: astropy.table.Table, pandas.DataFrame
The table to filter
param: str
The parameter to filter by, e.g. 'Teff'
value: str, float, int, sequence
The criteria to filter by,
which can be single valued like 1400
or a range with operators [<,<=,>,>=],
e.g. ('>1200','<=1400')
Returns
-------
astropy.table.Table, pandas.DataFrame
The filtered table
"""
for param, value in kwargs.items():
# Check it is a valid column
if param not in table.colnames:
raise KeyError("No column named {}".format(param))
# Wildcard case
if isinstance(value, (str, bytes)) and '*' in value:
# Get column data
data = list(map(str, table[param]))
if not value.startswith('*'):
value = '^' + value
if not value.endswith('*'):
value = value + '$'
# Strip double quotes and decod
value = value.replace("'", '').replace('"', '').replace('*', '(.*)')
# Regex
reg = re.compile(value, re.IGNORECASE)
keep = list(filter(reg.findall, data))
# Get indexes
idx = np.where([i in keep for i in data])
# Filter table
table = table[idx]
else:
# Make single value string into conditions
if isinstance(value, str):
# Check for operator
if any([value.startswith(o) for o in ['<', '>', '=']]):
value = [value]
# Assume eqality if no operator
else:
value = ['==' + value]
# Turn numbers into strings
if isinstance(value, (int, float, np.float16)):
value = ["=={}".format(value)]
# Iterate through multiple conditions
for cond in value:
# Equality
if cond.startswith('='):
v = cond.replace('=', '')
if v.replace('.', '', 1).isdigit():
table = table[table[param] == eval(v)]
else:
table = table[table[param] == v]
# Less than or equal
elif cond.startswith('<='):
v = cond.replace('<=', '')
table = table[table[param] <= eval(v)]
# Less than
elif cond.startswith('<'):
v = cond.replace('<', '')
table = table[table[param] < eval(v)]
# Greater than or equal
elif cond.startswith('>='):
v = cond.replace('>=', '')
table = table[table[param] >= eval(v)]
# Greater than
elif cond.startswith('>'):
v = cond.replace('>', '')
table = table[table[param] > eval(v)]
else:
raise ValueError("'{}' operator not valid.".format(cond))
return table
def find_closest(axes, points, n=1, values=False):
"""Find the n-neighboring elements of a given value in an array
Parameters
----------
axes: list, np.array
The array(s) to search
points: array-like, float
The point(s) to search for
n: int
The number of values to the left and right of the points
Returns
-------
np.ndarray
The n-values to the left and right of 'points' in 'axes'
"""
results = []
if not isinstance(axes, list):
axes = [axes]
points = [points]
for i, (axis, point) in enumerate(zip(axes, points)):
if point >= min(axis) and point <= max(axis):
axis = np.asarray(axis)
idx = np.clip(axis.searchsorted(point), 1, len(axis) - 1)
slc = slice(max(0, idx - n), min(idx + n, len(axis)))
if values:
result = axis[slc]
else:
result = np.arange(0, len(axis))[slc].astype(int)
results.append(result)
else:
print('Point {} outside grid.'.format(point))
return
return results
def get_canonical_name(target_name):
"""Get ExoMAST prefered name for exoplanet.
Parameters
----------
target_name : string
The name of the target transit.
Returns
-------
canonical_name : string
"""
target_url = "https://exo.mast.stsci.edu/api/v0.1/exoplanets/identifiers/"
# Create params dict for url parsing. Easier than trying to format yourself.
params = {"name": target_name}
r = requests.get(target_url, params=params)
planetnames = r.json()
canonical_name = planetnames['canonicalName']
return canonical_name
def get_env_variables():
"""Returns a dictionary containing various environment variable
information.
Returns
-------
env_variables : dict
A dictionary containing various environment variable data
"""
env_variables = {}
# Get the location of EXOCTK_DATA environvment variable and check that it is valid
env_variables['exoctk_data'] = os.environ.get('EXOCTK_DATA')
# If the variable is blank or doesn't exist
ON_GITHUB_ACTIONS = os.path.expanduser('~') == '/home/runner' or os.path.expanduser('~') == '/Users/runner'
if not ON_GITHUB_ACTIONS:
if not env_variables['exoctk_data']:
raise ValueError(
'The $EXOCTK_DATA environment variable is not set. Please set the '
'value of this variable to point to the location of the ExoCTK data '
'download folder. Users may retreive this folder by clicking the '
'"ExoCTK Data Download" button on the ExoCTK website.'
)
# If the variable exists but doesn't point to a real location
if not os.path.exists(env_variables['exoctk_data']):
raise FileNotFoundError(
'The $EXOCTK_DATA environment variable is set to a location that '
'cannot be accessed.')
# If the variable exists, points to a real location, but is missing contents
for item in ['modelgrid', 'fortney', 'exoctk_log', 'generic']:
if item not in [os.path.basename(item) for item in glob.glob(os.path.join(env_variables['exoctk_data'], '*'))]:
raise KeyError('Missing {}/ directory from {}'.format(item, env_variables['exoctk_data']))
env_variables['modelgrid_dir'] = os.path.join(env_variables['exoctk_data'], 'modelgrid/')
env_variables['fortgrid_dir'] = os.path.join(env_variables['exoctk_data'], 'fortney/')
env_variables['exoctklog_dir'] = os.path.join(env_variables['exoctk_data'], 'exoctk_log/')
env_variables['genericgrid_dir'] = os.path.join(env_variables['exoctk_data'], 'generic/')
return env_variables
def get_target_data(target_name):
"""Send request to exomast restful api for target information.
Parameters
----------
target_name : string
The name of the target transit
Returns
-------
target_data: json:
json object with target data.
"""
canonical_name = get_canonical_name(target_name)
target_url = build_target_url(canonical_name)
r = requests.get(target_url)
if r.status_code == 200:
target_data = r.json()
else:
print('Whoops, no data for this target!')
# Some targets have multiple catalogs
# nexsci is the first choice.
if len(target_data) > 1:
# Get catalog names from exomast and make then the keys of a dictionary
# and the values are its position in the json object.
catalog_dict = {data['catalog_name']: index for index, data in enumerate(target_data)}
# Parse based on catalog accuracy.
if 'nexsci' in list(catalog_dict.keys()):
target_data = target_data[catalog_dict['nexsci']]
elif 'exoplanets.org' in list(catalog_dict.keys()):
target_data = target_data[catalog_dict['exoplanets.org']]
else:
target_data = target_data[0]
else:
target_data = target_data[0]
# Strip spaces and non numeric or alphabetic characters and combine.
url = 'https://exo.mast.stsci.edu/exomast_planet.html?planet={}'.format(re.sub(r'\W+', '', canonical_name))
return target_data, url
def interp_flux(mu, flux, params, values):
"""
Interpolate a cube of synthetic spectra for a
given index of mu
Parameters
----------
mu: int
The index of the (Teff, logg, FeH, *mu*, wavelength)
data cube to interpolate
flux: np.ndarray
The 5D data array
params: list
A list of each free parameter range
values: list
A list of each free parameter values
Returns
-------
tu
The array of new flux values
"""
# Iterate over each wavelength (-1 index of flux array)
shp = flux.shape[-1]
flx = np.zeros(shp)
generators = []
for lam in range(shp):
interp_f = RegularGridInterpolator(params, flux[:, :, :, mu, lam])
f, = interp_f(values)
flx[lam] = f
generators.append(interp_f)
return flx, generators
def medfilt(x, window_len):
"""Apply a length-k median filter to a 1D array x.
Boundaries are extended by repeating endpoints.
Parameters
----------
x: np.array
The 1D array to smooth
window_len: int
The size of the smoothing window
Returns
-------
np.ndarray
The smoothed 1D array
"""
# assert x.ndim == 1, "Input must be one-dimensional."
if window_len % 2 == 0:
s1 = "Median filter length ("
s2 = ") must be odd. Adding 1."
print(s1 + str(window_len) + s2)
window_len += 1
window_len = int(window_len)
k2 = int((window_len - 1) // 2)
s = np.r_[2 * np.median(x[0: int(window_len / 5)]) - x[window_len: 1: -1], x, 2 * np.median(x[int(-window_len / 5):]) - x[-1: -window_len: -1]]
y = np.zeros((len(s), window_len), dtype=s.dtype)
y[:, k2] = s
for i in range(k2):
j = k2 - i
y[j:, i] = s[:-j]
y[: j, i] = s[0]
y[: -j, -(i + 1)] = s[j:]
y[-j:, -(i + 1)] = s[-1]
return np.median(y[window_len - 1: -window_len + 1], axis=1)
def rebin_spec(spec, wavnew, oversamp=100, plot=False):
"""
Rebin a spectrum to a new wavelength array while preserving
the total flux
Parameters
----------
spec: array-like
The wavelength and flux to be binned
wavenew: array-like
The new wavelength array
Returns
-------
np.ndarray
The rebinned flux
"""
wave, flux = spec
nlam = len(wave)
x0 = np.arange(nlam, dtype=float)
x0int = np.arange((nlam - 1.) * oversamp + 1., dtype=float) / oversamp
w0int = np.interp(x0int, x0, wave)
spec0int = np.interp(w0int, wave, flux) / oversamp
# Set up the bin edges for down-binning
maxdiffw1 = np.diff(wavnew).max()
w1bins = np.concatenate(([wavnew[0] - maxdiffw1], .5 * (wavnew[1::] + wavnew[0: -1]), [wavnew[-1] + maxdiffw1]))
# Bin down the interpolated spectrum:
w1bins = np.sort(w1bins)
nbins = len(w1bins) - 1
specnew = np.zeros(nbins)
inds2 = [[w0int.searchsorted(w1bins[ii], side='left'), w0int.searchsorted(w1bins[ii + 1], side='left')] for ii in range(nbins)]
for ii in range(nbins):
specnew[ii] = np.sum(spec0int[inds2[ii][0]: inds2[ii][1]])
return specnew
def smooth(x, window_len=10, window='hanning'):
"""smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the
signal. The signal is prepared by introducing reflected copies of
the signal (with the window size) in both ends so that transient
parts are minimized in the begining and end part of the output
signal.
Parameters
----------
x: sequence
The input signal
window_len: int
The dimension of the smoothing window
window: str
The type of window from 'flat', 'hanning', 'hamming',
'bartlett', 'blackman'. 'flat' window will produce a moving
average smoothing.
Retruns
-------
np.ndarray
The smoothed signal
Example
-------
t = linspace(-2, 2, 0.1)
x = sin(t)+randn(len(t))*0.1
y = smooth(x)
"""
if x.ndim != 1:
raise ValueError("smooth only accepts 1 dimension arrays.")
if x.size < window_len:
raise ValueError("Input vector needs to be bigger than window size.")
if window_len < 3:
return x
if window not in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
raise ValueError("Window is one of 'flat', 'hanning', 'hamming',\
'bartlett', 'blackman'")
s = np.r_[2 * np.median(x[0: window_len / 5]) - x[window_len: 1: -1], x, 2 * np.median(x[-window_len / 5:]) - x[-1: -window_len: -1]]
if window == 'flat':
w = np.ones(window_len, 'd')
else:
w = eval('np.' + window + '(window_len)')
y = np.convolve(w / w.sum(), s, mode='same')
return y[window_len - 1: -window_len + 1]
def writeFITS(filename, extensions, headers=()):
"""
Write some data to a new FITS file
Parameters
----------
filename: str
The filename of the output FITS file
extensions: dict
The extension name and associated data to include
in the file
headers: array-like
The (keyword, value, comment) groups for the PRIMARY
header extension
"""
# Write the arrays to a FITS file
prihdu = fits.PrimaryHDU()
prihdu.name = 'PRIMARY'
hdulist = fits.HDUList([prihdu])
# Write the header to the PRIMARY HDU
hdulist['PRIMARY'].header.extend(headers, end=True)
# Write the data to the HDU
for k, v in extensions.items():
hdulist.append(fits.ImageHDU(data=v, name=k))
# Write the file
hdulist.writeto(filename, clobber=True)
hdulist.close()
# Insert END card to prevent header error
# hdulist[0].header.tofile(filename, endcard=True, clobber=True)
|
import React, {
useState,
useContext,
useEffect,
useLayoutEffect,
useRef,
} from "react";
import { Container, Row, Col, Form, Button } from "react-bootstrap";
import { Link } from "react-router-dom";
import { DomainContext } from "../../../context";
import { useTranslation } from "react-i18next";
import { useToasts } from "react-toast-notifications";
import ErrorHandler from "../../../Methods/ErrorHandler";
import Gender from "../../../Enums/Gender";
import axios from "axios";
import "./assets/Register.scss";
const RegisterPlayer = () => {
const [cities, setCities] = useState();
const { t } = useTranslation();
const [domain, setDomain] = useContext(DomainContext);
const { addToast } = useToasts();
const playerName = useRef();
const playerSurname = useRef();
const playerNickName = useRef();
const playerPhoneNumber = useRef();
const playerMailAddress = useRef();
const playerPassword = useRef();
const playerPasswordAgain = useRef();
const playerCity = useRef();
const playerBirthDate = useRef();
const playerGender = useRef();
const checkBox = useRef();
useLayoutEffect(() => {
GetCities();
}, []);
const GetCities = () => {
const requestUrl = domain + "get-cities";
axios
.get(requestUrl)
.then((response) => {
const citiyOptions = response.data.map((city) => {
return <option value={city.Id}>{city.Name}</option>;
});
setCities(citiyOptions);
})
.catch((error) => {
addToast(t("SomethingWentWrong"), {
appearance: "error",
autoDismiss: true,
});
});
};
const SendRegisterRequest = () => {
const emailRegex = new RegExp(
"^([\\w\\.\\-]+)@([\\w\\-]+)((\\.(\\w){2,3})+)$"
);
const phoneRegex = new RegExp("\\(?\\d{3}\\)?-? *\\d{3}-? *-?\\d{4}");
if (playerNickName.current.value.length === 0) {
addToast(t("PlayerNicknameMustBeFilled"), {
appearance: "error",
autoDismiss: true,
});
} else if (playerName.current.value.length === 0) {
addToast(t("PlayerNameMustBeFilled"), {
appearance: "error",
autoDismiss: true,
});
} else if (playerSurname.current.value.length === 0) {
addToast(t("PlayerSurnameMustBeFilled"), {
appearance: "error",
autoDismiss: true,
});
} else if (
playerMailAddress.current.value.length === 0 ||
!emailRegex.test(playerMailAddress.current.value)
) {
addToast(t("MailMustBeFilled"), {
appearance: "error",
autoDismiss: true,
});
} else if (
playerPhoneNumber.current.value.length === 0 ||
!phoneRegex.test(playerPhoneNumber.current.value)
) {
addToast(t("PhoneNumberMustBeFilled"), {
appearance: "error",
autoDismiss: true,
});
} else if (playerPassword.current.value.length < 7) {
addToast(t("PasswordMustBeFilled"), {
appearance: "error",
autoDismiss: true,
});
} else if (playerPasswordAgain.current.value.length < 7) {
addToast(t("PasswordMustBeFilled"), {
appearance: "error",
autoDismiss: true,
});
} else if (
playerPassword.current.value !== playerPasswordAgain.current.value
) {
addToast(t("MustBeSamePassword"), {
appearance: "error",
autoDismiss: true,
});
} else if (playerGender.current.value.length === 0) {
addToast(t("GenderMustBeSelected"), {
appearance: "error",
autoDismiss: true,
});
} else if (playerBirthDate.current.value === "") {
addToast(t("BirthDateMustBeSelected"), {
appearance: "error",
autoDismiss: true,
});
} else if (playerCity.current.value.length === 0) {
addToast(t("CityMustBeSelected"), {
appearance: "error",
autoDismiss: true,
});
} else if (!checkBox.current.checked) {
addToast(t("MustBeChecked"), {
appearance: "error",
autoDismiss: true,
});
} else {
const requestUrl = domain + "player-register";
let formData = new FormData();
formData.append("Name", playerName.current.value);
formData.append("Surname", playerSurname.current.value);
formData.append("Nickname", playerNickName.current.value);
formData.append("PhoneNumber", playerPhoneNumber.current.value);
formData.append("MailAddress", playerMailAddress.current.value);
formData.append("Password", playerPassword.current.value);
formData.append("CityId", playerCity.current.value);
formData.append("BirthDate", playerBirthDate.current.value);
formData.append("Gender", playerGender.current.value);
axios
.post(requestUrl, formData, {
headers: {
"content-type": "multipart/form-data",
},
})
.then((response) => {
if (response.status === 200) {
if (response.data == true) {
addToast(t("RegisterSuccess"), {
appearance: "success",
autoDismiss: true,
});
} else {
addToast(t(ErrorHandler(response.data)), {
appearance: "error",
autoDismiss: true,
});
}
} else {
addToast(t("SomethingWentWrong"), {
appearance: "error",
autoDismiss: true,
});
}
})
.catch((error) => {
addToast(t("SomethingWentWrong"), {
appearance: "error",
autoDismiss: true,
});
});
}
};
return (
<section className={"registerContainer"}>
<Container>
<Row>
<Col xs={12} md={12} xl={12} className={"container"}>
<div className={"registerBox"}>
<h4>{t("RegisterWelcome")}</h4>
<span>{t("RegisterWelcomeAlt")}</span>
<Form>
<Form.Group controlId="formGridNickname">
<Form.Label>{t("Nickname")}</Form.Label>
<Form.Control
ref={playerNickName}
placeholder={t("NicknamePlaceHolder")}
/>
</Form.Group>
<Form.Row>
<Form.Group as={Col} controlId="formGridPlayerName">
<Form.Label>{t("Name")}</Form.Label>
<Form.Control
ref={playerName}
placeholder={t("NamePlaceHolder")}
/>
</Form.Group>
<Form.Group as={Col} controlId="formGridPlayerSurname">
<Form.Label>{t("Surname")}</Form.Label>
<Form.Control
ref={playerSurname}
placeholder={t("SurnamePlaceHolder")}
/>
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group as={Col} controlId="formGridEmail">
<Form.Label>{t("Email")}</Form.Label>
<Form.Control
type="email"
ref={playerMailAddress}
placeholder={t("EmailPlaceHolder")}
/>
</Form.Group>
<Form.Group as={Col} controlId="formGridPhoneNumber">
<Form.Label>{t("PhoneNumber")}</Form.Label>
<Form.Control
ref={playerPhoneNumber}
placeholder={t("PhoneNumberPlaceHolder")}
/>
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group as={Col} controlId="formGridPassword">
<Form.Label>{t("Password")}</Form.Label>
<Form.Control
type="password"
ref={playerPassword}
placeholder={t("PasswordPlaceHolder")}
/>
</Form.Group>
<Form.Group as={Col} controlId="formGridPasswordAgain">
<Form.Label>{t("PasswordAgain")}</Form.Label>
<Form.Control
type="password"
ref={playerPasswordAgain}
placeholder={t("PasswordPlaceHolder")}
/>
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group as={Col} controlId="formGridGender">
<Form.Label>{t("Gender")}</Form.Label>
<Form.Control as="select" ref={playerGender}>
<option value={""}>{t("GenderPlaceHolder")}</option>
<option value={Gender.Man}>{t("Man")}</option>
<option value={Gender.Woman}>{t("Woman")}</option>
</Form.Control>
</Form.Group>
<Form.Group as={Col} controlId="formGridBirthDate">
<Form.Label>{t("BirthDate")}</Form.Label>
<Form.Control
type="date"
ref={playerBirthDate}
></Form.Control>
</Form.Group>
</Form.Row>
<Form.Group controlId="formGridCity">
<Form.Label>{t("City")}</Form.Label>
<Form.Control as="select" ref={playerCity}>
<option value={""}>{t("CityPlaceHolder")}</option>
{cities}
</Form.Control>
</Form.Group>
<Form.Group controlId="formGridCheckbox" id="formGridCheckbox">
<Form.Check
type="checkbox"
label={t("AcceptContracts")}
ref={checkBox}
/>
<br />
<Button
variant="outline-dark"
type="button"
onClick={SendRegisterRequest}
>
{t("Register")}
</Button>
</Form.Group>
</Form>
<hr />
<div style={{ textAlign: "left", marginLeft: 25 }}>
<span>
{t("DoYouHaveAccount")} <Link to="/">{t("Login")}</Link>
</span>
</div>
</div>
</Col>
</Row>
</Container>
</section>
);
};
export default RegisterPlayer;
|
import {
getNodeId,
getNodeIcon
} from './utils.js'
export default class TreeNode {
constructor (data, options, tree) {
this.data = data
this.tree = tree
this._vNode = null
this.id = getNodeId(data, tree)
this.icon = getNodeIcon(data, tree)
this.level = options.level
this.index = options.index
this.parent = options.parent
this.isLeaf = true
this.children = []
this.state = {
checked: false,
expanded: false,
disabled: false,
visible: true
}
this.checked = tree.defaultCheckedNodes.includes(this.id)
this.expanded = tree.defaultExpandedNodes.includes(this.id)
this.disabled = tree.defaultDisabledNodes.includes(this.id)
this.timer = null
}
get name () {
return this.data[this.tree.nodeOptions.nameKey]
}
set vNode (vNode) {
this._vNode = vNode
if (this.expanded) {
this.recaculateLinkLine()
}
}
get vNode () {
return this._vNode
}
get parents () {
if (!this.parent) {
return []
}
return [...this.parent.parents, this.parent]
}
get descendants () {
const descendants = []
this.children.forEach(node => {
descendants.push(node)
descendants.push(...node.descendants)
})
return descendants
}
get isFirst () {
return this.index === 0 || this.childIndex === 0
}
get isLast () {
if (this.parent) {
return this.childIndex === (this.parent.children.length - 1)
}
return false
}
get hasCheckbox () {
const showCheckbox = this.tree.showCheckbox
if (typeof showCheckbox === 'function') {
return showCheckbox(this.data)
}
return showCheckbox
}
get collapseIcon () {
return this.icon.collapse
}
get selected () {
return this.tree.selectable && this.tree.selected === this.id
}
get expandIcon () {
return this.icon.expand
}
get nodeIcon () {
return this.icon.node
}
set checked (checked) {
if (this.state.checked === checked) {
return false
}
this.state.checked = checked
}
get checked () {
return this.state.checked
}
set expanded (expanded) {
if (this.state.expanded === expanded) {
return false
}
this.state.expanded = expanded
if (expanded && this.parent) {
this.parent.expanded = true
}
this.children.forEach(node => {
node.visible = expanded
})
this.recaculateLinkLine()
}
get expanded () {
return this.state.expanded
}
set disabled (disabled) {
if (this.state.disabled === disabled) {
return false
}
this.state.disabled = disabled
}
get disabled () {
return this.state.disabled
}
set visible (visible) {
if (this.state.visible === visible) {
return false
}
this.state.visible = visible
this.children.forEach(node => {
node.visible = visible
})
}
get visible () {
return this.state.visible
}
recaculateLinkLine () {
if (this.tree.showLinkLine) {
const needsCalculateNodes = this.tree.needsCalculateNodes
if (needsCalculateNodes.includes(this)) {
return false
}
needsCalculateNodes.push(this)
this.parent && this.parent.recaculateLinkLine()
}
}
appendChild (node, offset) {
const nodes = Array.isArray(node) ? node : [node]
this.children.splice(offset, 0, ...nodes)
this.children.slice(offset).forEach((node, index) => {
node.childIndex = offset + index
})
this.isLeaf = false
this.expanded = true
this.recaculateLinkLine()
return nodes
}
removeChild (node) {
const nodes = Array.isArray(node) ? node : [node]
const removedChildIndex = []
const removedIndex = []
nodes.forEach(node => {
const childIndex = node.childIndex
removedChildIndex.push(childIndex)
removedIndex.push(node.index)
this.children.splice(childIndex, 1)
})
const minIndex = Math.min(...removedChildIndex)
this.children.slice(minIndex).forEach((node, index) => {
node.childIndex = minIndex + index
})
this.isLeaf = !this.children.length
this.recaculateLinkLine()
return nodes
}
}
|
var config = require("config");
var supertest = require("supertest");
var assert = require("assert");
module.exports = function (server, product) {
return {
server: server,
product: product,
exec: function () {
test("Should insert a new blog product and return a response with status: 201 and the product data as body", (done) => {
this.server
.post('/product/')
.send({
data: this.product
})
.expect("Content-type", /json/)
.expect(201)
.end((err, res) => {
if (err) throw err;
assert(res.body.hasOwnProperty("data"), "The response body has NOT 'data' property");
var product = res.body.data;
assert(product.hasOwnProperty("uid") && product.uid === this.product.uid, "The response body data has NOT the insert uid value");
assert(product.hasOwnProperty("name") && product.name === this.product.name, "The response body data has NOT the insert name value");
done();
});
});
}
}
}
|
// flow-typed signature: 2e23d8e8445126dc866b027087619d15
// flow-typed version: <<STUB>>/@commitlint/config-lerna-scopes_v^3.1.1/flow_v0.49.1
/**
* This is an autogenerated libdef stub for:
*
* '@commitlint/config-lerna-scopes'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module '@commitlint/config-lerna-scopes' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
// Filename aliases
declare module '@commitlint/config-lerna-scopes/index' {
declare module.exports: $Exports<'@commitlint/config-lerna-scopes'>;
}
declare module '@commitlint/config-lerna-scopes/index.js' {
declare module.exports: $Exports<'@commitlint/config-lerna-scopes'>;
}
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
//common libraries
var angular = require('angular');
require('angular-ui-router');
var jQuery = require('jquery');
window.$ = window.jQuery = jQuery;
//constants
var app_constants_1 = require('./constants/app.constants');
//setup
var routes_setup_1 = require('./setup/routes.setup');
var transitions_setup_1 = require('./setup/transitions.setup');
//controllers
var main_controller_1 = require('./controllers/main.controller');
//services
var animation_service_1 = require('./services/animation.service');
//import MainService from './services/main.service';
//import DemoDirective from './directives/demo.directive';
//services
var template_service_1 = require('./services/template.service');
angular.module('MainApp', ['ui.router', 'Templates']).constant('AppConstants', app_constants_1.default.init).config(routes_setup_1.default).run(transitions_setup_1.default).controller('MainCtrl', main_controller_1.default).service('Animation', animation_service_1.default).service('TemplateService', template_service_1.default);
//.service('MainService', MainService)
//.directive('demoDirective', DemoDirective.instance());
console.log('finish!');
},{"./constants/app.constants":2,"./controllers/main.controller":3,"./services/animation.service":4,"./services/template.service":5,"./setup/routes.setup":6,"./setup/transitions.setup":7,"angular":"angular","angular-ui-router":"angular-ui-router","jquery":"jquery"}],2:[function(require,module,exports){
"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"); } }
var AppConstants = function () {
function AppConstants() {
_classCallCheck(this, AppConstants);
}
_createClass(AppConstants, null, [{
key: 'init',
value: function init() {
return {
appName: 'Demo',
appVersion: '1.0',
serverUrl: 'http://127.0.0.1:3000'
};
}
}]);
return AppConstants;
}();
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = AppConstants;
},{}],3:[function(require,module,exports){
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var MainCtrl = function MainCtrl($http) {
_classCallCheck(this, MainCtrl);
this.$http = $http;
this.myTitle = "Hello from MainCtrl";
};
MainCtrl.$inject = ["$http"];
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = MainCtrl;
},{}],4:[function(require,module,exports){
"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"); } }
var Animation = function () {
function Animation() {
_classCallCheck(this, Animation);
this.loadingContainer = document.getElementById('loading');
this.spinner = new Spinner().spin();
}
//private containerElement: JQuery = $('.container');
_createClass(Animation, [{
key: 'loading',
value: function loading(value) {
if (value) {
//this.buttonElements.prop('disabled', true);
//this.loadingContainer.fadeIn(250);
console.log('animation start!');
console.log(this.loadingContainer);
this.spinner.spin(this.loadingContainer);
} else {
//this.buttonElements.prop('disabled', false);
//this.loadingContainer.fadeOut(250);
this.spinner.stop();
}
}
}]);
return Animation;
}();
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Animation;
},{}],5:[function(require,module,exports){
"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"); } }
var TemplateService = function () {
function TemplateService($templateCache) {
_classCallCheck(this, TemplateService);
this.$templateCache = $templateCache;
//console.log($templateCache.info());
}
_createClass(TemplateService, [{
key: "load",
value: function load(file) {
var _this = this;
return new Promise(function (resolve, reject) {
var template = _this.$templateCache.get(file);
if (template) {
resolve(template);
} else {
reject(false);
}
});
}
}]);
return TemplateService;
}();
TemplateService.$inject = ['$templateCache'];
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = TemplateService;
},{}],6:[function(require,module,exports){
"use strict";
function Routes($stateProvider, $urlRouterProvider, $httpProvider) {
console.log("routesConfig");
var viewPath = 'views/';
var authState = {
name: 'authState',
url: '/',
fileName: 'auth/index.html',
resolve: {
template: ['TemplateService', function (loadTemplate) {
return loadTemplate.load(authState.fileName).then(function (data) {
return data;
}, function (error) {
console.log(error);
});
}]
},
templateProvider: function templateProvider(template) {
return template;
}
};
$urlRouterProvider.otherwise('/');
$stateProvider.state(authState);
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Routes;
},{}],7:[function(require,module,exports){
"use strict";
function Transitions($location, $transitions, Animation) {
console.log("runConfig");
$transitions.onBefore({}, function () {
console.log("onBefore");
Animation.loading(true);
});
$transitions.onStart({}, function () {
console.log("onStart");
});
$transitions.onFinish({}, function () {
console.log('onFinish');
});
$transitions.onError({}, function (error) {});
$transitions.onSuccess({}, function () {
console.log("onSuccess");
Animation.loading(false);
});
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Transitions;
},{}]},{},[1]);
|
"use strict";
var gulp = require('gulp'),
sass = require('gulp-sass'),
del = require('del'),
uglify = require('gulp-uglify'),
cleanCSS = require('gulp-clean-css'),
concat = require("gulp-concat"),
rename = require("gulp-rename"),
merge = require('merge-stream'),
htmlreplace = require('gulp-html-replace'),
autoprefixer = require('gulp-autoprefixer'),
browserSync = require('browser-sync').create();
// Clean task
gulp.task('clean', function() {
return del(['dist', 'assets/css/app.css']);
});
// Copy third party libraries from node_modules into /vendor
gulp.task('vendor:js', function() {
return gulp.src([
'./node_modules/bootstrap/dist/js/*',
'./node_modules/jquery/dist/*',
'!./node_modules/jquery/dist/core.js',
'./node_modules/popper.js/dist/umd/popper.*'
])
.pipe(gulp.dest('./assets/js/vendor'));
});
// Copy font-awesome from node_modules into /fonts
gulp.task('vendor:fonts', function() {
return gulp.src([
'./node_modules/font-awesome/**/*',
'!./node_modules/font-awesome/{less,less/*}',
'!./node_modules/font-awesome/{scss,scss/*}',
'!./node_modules/font-awesome/.*',
'!./node_modules/font-awesome/*.{txt,json,md}'
])
.pipe(gulp.dest('./assets/fonts/font-awesome'))
});
// vendor task
gulp.task('vendor', gulp.parallel('vendor:fonts', 'vendor:js'));
// Copy vendor's js to /dist
gulp.task('vendor:build', function() {
var jsStream = gulp.src([
'./assets/js/vendor/bootstrap.bundle.min.js',
'./assets/js/vendor/jquery.slim.min.js',
'./assets/js/vendor/popper.min.js',
'./assets/js/vendor/bootstrap-dropdownhover.min.js'
])
.pipe(gulp.dest('./dist/assets/js/vendor'));
var fontStream = gulp.src(['./assets/fonts/font-awesome/**/*.*']).pipe(gulp.dest('./dist/assets/fonts/font-awesome'));
return merge (jsStream, fontStream);
})
// Copy Bootstrap SCSS(SASS) from node_modules to /assets/scss/bootstrap
gulp.task('bootstrap:scss', function() {
return gulp.src(['./node_modules/bootstrap/scss/**/*'])
.pipe(gulp.dest('./assets/scss/bootstrap'));
});
// Compile SCSS(SASS) files
gulp.task('scss', gulp.series('bootstrap:scss', function compileScss() {
return gulp.src(['./assets/scss/*.scss'])
.pipe(sass.sync({
outputStyle: 'expanded'
}).on('error', sass.logError))
.pipe(autoprefixer())
.pipe(gulp.dest('./assets/css'))
}));
// Minify CSS
gulp.task('css:minify', gulp.series('scss', function cssMinify() {
return gulp.src("./assets/css/app.css")
.pipe(cleanCSS())
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('./dist/assets/css'))
.pipe(browserSync.stream());
}));
// Minify Js
gulp.task('js:minify', function () {
return gulp.src([
'./assets/js/app.js'
])
.pipe(uglify())
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('./dist/assets/js'))
.pipe(browserSync.stream());
});
// Replace HTML block for Js and Css file upon build and copy to /dist
gulp.task('replaceHtmlBlock', function () {
return gulp.src(['*.html'])
.pipe(htmlreplace({
'js': 'assets/js/app.min.js',
'css': 'assets/css/app.min.css'
}))
.pipe(gulp.dest('dist/'));
});
// Configure the browserSync task and watch file path for change
gulp.task('dev', function browserDev(done) {
browserSync.init({
server: {
baseDir: "./"
}
});
gulp.watch(['assets/scss/*.scss','assets/scss/**/*.scss','!assets/scss/bootstrap/**'], gulp.series('css:minify', function cssBrowserReload (done) {
browserSync.reload();
done(); //Async callback for completion.
}));
gulp.watch('assets/js/app.js', gulp.series('js:minify', function jsBrowserReload (done) {
browserSync.reload();
done();
}));
gulp.watch(['*.html']).on('change', browserSync.reload);
done();
});
// Build task
gulp.task("build", gulp.series(gulp.parallel('css:minify', 'js:minify', 'vendor'), 'vendor:build', function copyAssets() {
return gulp.src([
'*.html',
'favicon.ico',
"assets/img/**"
], { base: './'})
.pipe(gulp.dest('dist'));
}));
// Default task
gulp.task("default", gulp.series("dev", "clean", 'build', 'replaceHtmlBlock')); |
exports.up = function (knex) {
return knex.schema.createTable('categories', tbl => {
// primary id for categories
tbl.increments();
// title
tbl.string('title')
.notNullable()
.unique()
}).createTable('recipes', tbl => {
// primary recipe id
tbl.increments();
// recipe title (required)
tbl.string('title')
.notNullable()
// recipe source
tbl.string('source')
// category id
tbl.integer('category_id')
.unsigned()
.notNullable()
.references('id')
.inTable('categories')
.onUpdate('CASCADE')
.onDelete('CASCADE');
// user id
tbl.integer('user_id')
.unsigned()
.notNullable()
.references('id')
.inTable('users')
.onUpdate('CASCADE')
.onDelete('CASCADE');
}).createTable('instructions', tbl => {
// primary instruction id
tbl.increments();
// step number
tbl.integer('step')
.notNullable();
// description
tbl.string('description')
.notNullable();
// foreign key for recipe id
tbl.integer('recipe_id')
.unsigned()
.notNullable()
.references('id')
.inTable('recipes')
.onUpdate('CASCADE')
.onDelete('CASCADE');
}).createTable('ingredients', tbl => {
// primary ingredient id
tbl.increments();
// ingredient name
tbl.string('name')
.notNullable()
.unique()
// description
tbl.string('description')
}).createTable('recipe_ingredients', tbl => {
// quantity
tbl.integer('quantity')
.notNullable()
// units
tbl.string('units')
.notNullable()
// foreign key to recipe id
tbl.integer('recipe_id')
.unsigned()
.notNullable()
.references('id')
.inTable('recipes')
.onUpdate('CASCADE')
.onDelete('CASCADE');
// foreign key to ingredient id
tbl.integer('ingredient_id')
.unsigned()
.notNullable()
.references('id')
.inTable('ingredients')
.onUpdate('CASCADE')
.onDelete('CASCADE');
})
};
exports.down = function (knex) {
return knex.schema.dropTableIfExists('recipe_ingredients')
.dropTableIfExists('ingredients')
.dropTableIfExists('instructions')
.dropTableIfExists('recipes')
.dropTableIfExists('categories');
};
|
import { createGlobalStyle } from 'styled-components';
import { theme } from './Theme';
const GlobalStyle = createGlobalStyle`
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
/* background: #1b1b1b; */
background: radial-gradient(#525252,#000000);
font-family: 'Inter', sans-serif;
overflow-x: hidden;
}
button {
font-weight: bold;
font-size: 1.2rem;
cursor: pointer;
padding: 1rem 2rem;
border: 3px solid ${(props) => props.theme.primaryColor};
background: transparent;
color: white;
transition: all 0.5s ease;
font-family: 'Inter', sans-serif;
&:hover {
background-color: ${(props) => props.theme.primaryColor};
color: white;
}
}
h2 {
font-weight: lighter;
font-size: 4rem;
}
h3 {
color: white;
}
h4 {
font-weight: bold;
font-size: 2rem;
}
a {
font-size: 1.1rem;
}
span {
font-weight: bold;
color: ${(props) => props.theme.primaryColor};
}
p {
padding: 3rem 0rem;
color: #ccc;
font-size: 1.4rem;
line-height: 150%;
}
.section-title {
padding-bottom: 5rem;
@media (max-width: 1300px) {
text-align: center;
}
}
// Conditional classes
.blur {
filter: blur(8px) !important;
}
.rotate90 {
transform: rotate(-90deg) !important;
}
.height100 {
height: 100vh !important;
}
// Buttons
.cta-btn {
background: ${(props) => props.theme.primaryButtonColor};
border-radius: 30px;
padding: 15px 30px;
text-decoration: none;
color: black;
transition: all 0.25s ease;
cursor: pointer;
margin: 1rem 0;
display:block;
width: fit-content;
z-index: 999;
&:hover {
background: ${(props) => props.theme.primaryButtonHoverColor};
}
}
// Media Queries
html {
@media (max-width: 1700px) {
font-size: 75%;
}
}
`;
export default GlobalStyle;
|
// @flow
/* global FormData, window */
import {fileApiRouteMap} from '../../../../../server/src/api/api-route-map';
import {fileApiConst} from '../../../../../server/src/api/part/file-api-const';
import {promiseCatch} from '../../../lib/promise';
import type {MainServerApiResponseType} from '../../../type/response';
import {isError} from '../../../lib/is';
export type SharpFitResizeNameType = 'contain' | 'cover' | 'fill' | 'inside' | 'outside';
export const sharpFitResizeNameMap = {
contain: 'contain',
cover: 'cover',
fill: 'fill',
inside: 'inside',
outside: 'outside',
};
export type SharpKernelResizeNameType = 'nearest' | 'cubic' | 'mitchell' | 'lanczos2' | 'lanczos3';
export const sharpKernelResizeNameMap = {
nearest: 'nearest',
cubic: 'cubic',
mitchell: 'mitchell',
lanczos2: 'lanczos2',
lanczos3: 'lanczos3',
};
export function uploadFileList(fileList: Array<File>): Promise<Error | Array<string>> {
const formData = new FormData();
fileList.forEach((file: File): mixed => formData.append(fileApiConst.fileListFormPropertyName, file));
return window
.fetch(fileApiRouteMap.uploadFileList, {method: 'POST', body: formData})
.then((response: Response): Promise<Array<string>> => response.json())
.then((savedFileList: Array<string>): Array<string> | Error => {
if (savedFileList.length !== fileList.length) {
return new Error('Not All files saved!');
}
return savedFileList;
})
.catch(promiseCatch);
}
export function uploadFile(file: File): Promise<Error | string> {
return uploadFileList([file])
.then((uploadResult: Error | Array<string>): Error | string => {
if (isError(uploadResult)) {
return uploadResult;
}
if (uploadResult.length === 0) {
return new Error('Can not save file!');
}
return uploadResult[0];
})
.catch(promiseCatch);
}
export function getResizedImage(
src: string,
width: number,
height: number,
fit: SharpFitResizeNameType = sharpFitResizeNameMap.inside
): string {
return `${fileApiRouteMap.getResizedImage}/${src}?width=${width}&height=${height}&fit=${fit}`;
}
export function getMarkdownResizedImage(src: string): string {
return `})`;
}
export function getMarkdownAudio(src: string): string {
const audioSrc = fileApiConst.pathToUploadFiles + '/' + src;
return `\n\n<audio controls src="${audioSrc}"/> \\\\\n`;
}
export function getFileList(): Promise<Array<string> | Error | MainServerApiResponseType> {
return window
.fetch(fileApiRouteMap.getFileList)
.then((response: Response): Promise<Array<string> | MainServerApiResponseType> => response.json())
.catch(promiseCatch);
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const world_1 = require("../../world");
const action_1 = require("./action");
const game_1 = require("../../game");
/**
* Handles the action of placing a new tile in the world.
*/
class PlaceTileAction extends action_1.Action {
constructor() {
super(...arguments);
/**
* Lists the possible positions and orientations at which the drawn tile can be placed.
*/
this.possibleTilePlacements = this.getPossibleTilePlacements();
}
/**
* Places the tile in the world.
*
* @param position The position at which the tile will be placed
* @param orientation The orientation at which the tile will be placed
* @param game The current game state
*/
placeTile(position, orientation) {
let turnPart = this.game.currentTurn.currentTurnPart;
let world = this.game.world.placeTile(turnPart.tile, position, orientation);
return this.game
.set({
world,
turns: game_1.Game.setCurrentTurnPart(this.game, {
tilePlacement: new world_1.PlacedTile(turnPart.tile, position, orientation),
figurePlacement: undefined,
gameBeforeTilePlacement: this.game
})
});
}
getPossibleTilePlacements() {
let turnPart = this.game.currentTurn.currentTurnPart;
return this.game.world.getPossibleTilePlacements(turnPart.tile);
}
}
exports.PlaceTileAction = PlaceTileAction;
//# sourceMappingURL=place-tile-action.js.map |
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
delete require.cache[require.resolve('./paths')];
if (!process.env.NODE_ENV) {
throw new Error(
'The process.env.NODE_ENV environment variable is required but was not specified.'
);
}
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
const dotenvFiles = [
`${paths.dotenv}.${process.env.NODE_ENV}.local`,
`${paths.dotenv}.${process.env.NODE_ENV}`,
process.env.NODE_ENV !== 'test' && `${paths.dotenv}.local`,
paths.dotenv,
].filter(Boolean);
dotenvFiles.forEach((dotenvFile) => {
if (fs.existsSync(dotenvFile)) {
require('dotenv').config({
path: dotenvFile,
});
}
});
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || '')
.split(path.delimiter)
.filter((folder) => folder && !path.isAbsolute(folder))
.map((folder) => path.resolve(appDirectory, folder))
.join(path.delimiter);
module.exports = () => {
// define env vars you want to use in your client app here.
// CAREFUL: don't use any secrets like api keys or database passwords as they are exposed publicly!
const raw = {
PORT: process.env.PORT || 8500,
NODE_ENV: process.env.NODE_ENV || 'development',
HOST: process.env.HOST || `http://localhost:${process.env.PORT || 8500}`,
};
// Stringify all values so we can feed into Webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
return { raw, stringified };
};
|
/* @flow */
import type {Reporter} from '../../reporters/index.js';
import type {InstallCwdRequest, InstallPrepared} from './install.js';
import type {DependencyRequestPatterns} from '../../types.js';
import type Config from '../../config.js';
import Lockfile from '../../lockfile/wrapper.js';
import * as PackageReference from '../../package-reference.js';
import PackageRequest from '../../package-request.js';
import {buildTree} from './ls.js';
import {Install, _setFlags} from './install.js';
import {MessageError} from '../../errors.js';
const invariant = require('invariant');
export class Add extends Install {
constructor(
args: Array<string>,
flags: Object,
config: Config,
reporter: Reporter,
lockfile: Lockfile,
) {
super(flags, config, reporter, lockfile);
this.args = args;
}
args: Array<string>;
/**
* TODO
*/
prepare(patterns: Array<string>, requests: DependencyRequestPatterns): Promise<InstallPrepared> {
const requestsWithArgs = requests.slice();
for (const pattern of this.args) {
requestsWithArgs.push({
pattern,
registry: 'npm',
visibility: PackageReference.USED,
optional: false,
});
}
return Promise.resolve({
patterns: patterns.concat(this.args),
requests: requestsWithArgs,
skip: false,
});
}
/**
* Description
*/
async init(): Promise<Array<string>> {
const patterns = await Install.prototype.init.call(this);
await this.maybeOutputSaveTree(patterns);
await this.savePackages();
return patterns;
}
/**
* Description
*/
fetchRequestFromCwd(): Promise<InstallCwdRequest> {
return Install.prototype.fetchRequestFromCwd.call(this, this.args);
}
/**
* Output a tree of any newly added dependencies.
*/
async maybeOutputSaveTree(patterns: Array<string>): Promise<void> {
const {trees, count} = await buildTree(this.resolver, this.linker, patterns, true, true);
this.reporter.success(
count === 1 ?
this.reporter.lang('savedNewDependency')
:
this.reporter.lang('savedNewDependencies', count),
);
this.reporter.tree('newDependencies', trees);
}
/**
* Save added packages to manifest if any of the --save flags were used.
*/
async savePackages(): Promise<void> {
const {dev, exact, tilde, optional, peer} = this.flags;
// get all the different registry manifests in this folder
const jsons = await this.getRootManifests();
// add new patterns to their appropriate registry manifest
for (const pattern of this.resolver.dedupePatterns(this.args)) {
const pkg = this.resolver.getResolvedPattern(pattern);
invariant(pkg, `missing package ${pattern}`);
const ref = pkg._reference;
invariant(ref, 'expected package reference');
const parts = PackageRequest.normalizePattern(pattern);
let version;
if (parts.hasVersion && parts.range) {
// if the user specified a range then use it verbatim
version = parts.range;
} else if (PackageRequest.getExoticResolver(pattern)) {
// wasn't a name/range tuple so this is just a raw exotic pattern
version = pattern;
} else if (tilde) { // --save-tilde
version = `~${pkg.version}`;
} else if (exact) { // --save-exact
version = pkg.version;
} else { // default to save prefix
version = `${String(this.config.getOption('save-prefix'))}${pkg.version}`;
}
// build up list of objects to put ourselves into from the cli args
const targetKeys: Array<string> = [];
if (dev) {
targetKeys.push('devDependencies');
}
if (peer) {
targetKeys.push('peerDependencies');
}
if (optional) {
targetKeys.push('optionalDependencies');
}
if (!targetKeys.length) {
targetKeys.push('dependencies');
}
// add it to manifest
const object = jsons[ref.registry].object;
for (const key of targetKeys) {
const target = object[key] = object[key] || {};
target[pkg.name] = version;
}
// add pattern so it's aliased in the lockfile
const newPattern = `${pkg.name}@${version}`;
if (newPattern === pattern) {
continue;
}
this.resolver.addPattern(newPattern, pkg);
this.resolver.removePattern(pattern);
}
await this.saveRootManifests(jsons);
}
}
export function setFlags(commander: Object) {
commander.usage('add [packages ...] [flags]');
_setFlags(commander);
commander.option('--dev', 'save package to your `devDependencies`');
commander.option('--peer', 'save package to your `peerDependencies`');
commander.option('--optional', 'save package to your `optionalDependencies`');
commander.option('--exact', '');
commander.option('--tilde', '');
}
export async function run(
config: Config,
reporter: Reporter,
flags: Object,
args: Array<string>,
): Promise<void> {
if (!args.length) {
throw new MessageError(reporter.lang('missingAddDependencies'));
}
const lockfile = await Lockfile.fromDirectory(config.cwd, reporter);
const install = new Add(args, flags, config, reporter, lockfile);
await install.init();
}
|
import Cookies from 'js-cookie'
// cookie保存的天数
import config from '@/config'
import { forEach, hasOneOf, objEqual } from '@/libs/tools'
export const TOKEN_KEY = 'token'
export const setToken = (token) => {
Cookies.set(TOKEN_KEY, token, {expires: config.cookieExpires || 1})
}
export const getToken = () => {
const token = Cookies.get(TOKEN_KEY)
if (token) return token
else return false
}
export const hasChild = (item) => {
return item.children && item.children.length !== 0
}
const showThisMenuEle = (item, access) => {
if (item.meta && item.meta.access && item.meta.access.length) {
if (hasOneOf(item.meta.access, access)) return true
else return false
} else return true
}
/**
* @param {Array} list 通过路由列表得到菜单列表
* @returns {Array}
*/
export const getMenuByRouter = (list, access) => {
let res = []
forEach(list, item => {
if (!item.meta || (item.meta && !item.meta.hideInMenu)) {
let obj = {
icon: (item.meta && item.meta.icon) || '',
name: item.name,
meta: item.meta
}
if ((hasChild(item) || (item.meta && item.meta.showAlways)) && showThisMenuEle(item, access)) {
obj.children = getMenuByRouter(item.children, access)
}
if (item.meta && item.meta.href) obj.href = item.meta.href
if (showThisMenuEle(item, access)) res.push(obj)
}
})
return res
}
/**
* @param {Array} routeMetched 当前路由metched
* @returns {Array}
*/
export const getBreadCrumbList = (route, homeRoute) => {
let homeItem = { ...homeRoute, icon: homeRoute.meta.icon }
let routeMetched = route.matched
if (routeMetched.some(item => item.name === homeRoute.name)) return [homeItem]
let res = routeMetched.filter(item => {
return item.meta === undefined || !item.meta.hide
}).map(item => {
let meta = {...item.meta}
if (meta.title && typeof meta.title === 'function') meta.title = meta.title(route)
let obj = {
icon: (item.meta && item.meta.icon) || '',
name: item.name,
meta: meta
}
return obj
})
res = res.filter(item => {
return !item.meta.hideInMenu
})
return [{...homeItem, to: homeRoute.path}, ...res]
}
export const getRouteTitleHandled = (route) => {
let router = {...route}
let meta = {...route.meta}
let title = ''
if (meta.title) {
if (typeof meta.title === 'function') title = meta.title(router)
else title = meta.title
}
meta.title = title
router.meta = meta
return router
}
export const showTitle = (item, vm) => {
let title = item.meta.title
if (vm.$config.useI18n) {
if (title.includes('{{') && title.includes('}}') && vm.$config.useI18n) title = title.replace(/({{[\s\S]+?}})/, (m, str) => str.replace(/{{([\s\S]*)}}/, (m, _) => vm.$t(_.trim())))
else title = vm.$t(item.name)
} else title = (item.meta && item.meta.title) || item.name
return title
}
/**
* @description 本地存储和获取标签导航列表
*/
export const setTagNavListInLocalstorage = list => {
// localStorage.tagNaveList = JSON.stringify(list)
localSave('tagNaveList', JSON.stringify(list))
}
/**
* @returns {Array} 其中的每个元素只包含路由原信息中的name, path, meta三项
*/
export const getTagNavListFromLocalstorage = () => {
// const list = localStorage.tagNaveList
const list = localRead('tagNaveList')
return list ? JSON.parse(list) : []
}
/**
* @param {Array} routers 路由列表数组
* @description 用于找到路由列表中name为home的对象
*/
export const getHomeRoute = (routers, homeName = 'home') => {
let i = -1
let len = routers.length
let homeRoute = {}
while (++i < len) {
let item = routers[i]
if (item.children && item.children.length) {
let res = getHomeRoute(item.children, homeName)
if (res.name) return res
} else {
if (item.name === homeName) homeRoute = item
}
}
return homeRoute
}
/**
* @param {*} list 现有标签导航列表
* @param {*} newRoute 新添加的路由原信息对象
* @description 如果该newRoute已经存在则不再添加
*/
export const getNewTagList = (list, newRoute) => {
const { name, path, meta } = newRoute
let newList = [...list]
if (newList.findIndex(item => item.name === name) >= 0) return newList
else newList.push({ name, path, meta })
return newList
}
/**
* @param {*} access 用户权限数组,如 ['super_admin', 'admin']
* @param {*} route 路由列表
*/
const hasAccess = (access, route) => {
if (route.meta && route.meta.access) return hasOneOf(access, route.meta.access)
else return true
}
/**
* 权鉴
* @param {*} name 即将跳转的路由name
* @param {*} access 用户权限数组
* @param {*} routes 路由列表
* @description 用户是否可跳转到该页
*/
export const canTurnTo = (name, access, routes) => {
const routePermissionJudge = (list) => {
return list.some(item => {
if (item.children && item.children.length) {
return routePermissionJudge(item.children)
} else if (item.name === name) {
return hasAccess(access, item)
}
})
}
return routePermissionJudge(routes)
}
/**
* @param {String} url
* @description 从URL中解析参数
*/
export const getParams = url => {
const keyValueArr = url.split('?')[1].split('&')
let paramObj = {}
keyValueArr.forEach(item => {
const keyValue = item.split('=')
paramObj[keyValue[0]] = keyValue[1]
})
return paramObj
}
/**
* @param {Array} list 标签列表
* @param {String} name 当前关闭的标签的name
*/
export const getNextRoute = (list, route) => {
let res = {}
if (list.length === 2) {
res = getHomeRoute(list)
} else {
const index = list.findIndex(item => routeEqual(item, route))
if (index === list.length - 1) res = list[list.length - 2]
else res = list[index + 1]
}
return res
}
/**
* @param {Number} times 回调函数需要执行的次数
* @param {Function} callback 回调函数
*/
export const doCustomTimes = (times, callback) => {
let i = -1
while (++i < times) {
callback(i)
}
}
/**
* @param {Object} file 从上传组件得到的文件对象
* @returns {Promise} resolve参数是解析后的二维数组
* @description 从Csv文件中解析出表格,解析成二维数组
*/
export const getArrayFromFile = (file) => {
let nameSplit = file.name.split('.')
let format = nameSplit[nameSplit.length - 1]
return new Promise((resolve, reject) => {
let reader = new FileReader()
reader.readAsText(file) // 以文本格式读取
let arr = []
reader.onload = function (evt) {
let data = evt.target.result // 读到的数据
let pasteData = data.trim()
arr = pasteData.split((/[\n\u0085\u2028\u2029]|\r\n?/g)).map(row => {
return row.split('\t')
}).map(item => {
return item[0].split(',')
})
if (format === 'csv') resolve(arr)
else reject(new Error('[Format Error]:你上传的不是Csv文件'))
}
})
}
/**
* @param {Array} array 表格数据二维数组
* @returns {Object} { columns, tableData }
* @description 从二维数组中获取表头和表格数据,将第一行作为表头,用于在iView的表格中展示数据
*/
export const getTableDataFromArray = (array) => {
let columns = []
let tableData = []
if (array.length > 1) {
let titles = array.shift()
columns = titles.map(item => {
return {
title: item,
key: item
}
})
tableData = array.map(item => {
let res = {}
item.forEach((col, i) => {
res[titles[i]] = col
})
return res
})
}
return {
columns,
tableData
}
}
export const findNodeUpper = (ele, tag) => {
if (ele.parentNode) {
if (ele.parentNode.tagName === tag.toUpperCase()) {
return ele.parentNode
} else {
return findNodeUpper(ele.parentNode, tag)
}
}
}
export const findNodeUpperByClasses = (ele, classes) => {
let parentNode = ele.parentNode
if (parentNode) {
let classList = parentNode.classList
if (classList && classes.every(className => classList.contains(className))) {
return parentNode
} else {
return findNodeUpperByClasses(parentNode, classes)
}
}
}
export const findNodeDownward = (ele, tag) => {
const tagName = tag.toUpperCase()
if (ele.childNodes.length) {
let i = -1
let len = ele.childNodes.length
while (++i < len) {
let child = ele.childNodes[i]
if (child.tagName === tagName) return child
else return findNodeDownward(child, tag)
}
}
}
export const showByAccess = (access, canViewAccess) => {
return hasOneOf(canViewAccess, access)
}
/**
* @description 根据name/params/query判断两个路由对象是否相等
* @param {*} route1 路由对象
* @param {*} route2 路由对象
*/
export const routeEqual = (route1, route2) => {
const params1 = route1.params || {}
const params2 = route2.params || {}
const query1 = route1.query || {}
const query2 = route2.query || {}
return (route1.name === route2.name) && objEqual(params1, params2) && objEqual(query1, query2)
}
/**
* 判断打开的标签列表里是否已存在这个新添加的路由对象
*/
export const routeHasExist = (tagNavList, routeItem) => {
let len = tagNavList.length
let res = false
doCustomTimes(len, (index) => {
if (routeEqual(tagNavList[index], routeItem)) res = true
})
return res
}
export const localSave = (key, value) => {
sessionStorage.setItem(key, value)
}
export const localRead = (key) => {
return sessionStorage.getItem(key) || ''
}
|
( function ( $ ) {
"use strict";
jQuery( '#vmap' ).vectorMap( {
map: 'world_en',
backgroundColor: null,
color: '#ffffff',
hoverOpacity: 0.7,
selectedColor: '#1de9b6',
enableZoom: true,
showTooltip: true,
values: sample_data,
scaleColors: [ '#1de9b6', '#03a9f5' ],
normalizeFunction: 'polynomial'
} );
jQuery( '#vmap2' ).vectorMap( {
map: 'dz_fr',
color: '#581D22',
borderColor: '#fff',
backgroundColor: '#fff',
borderOpacity: 1,
enableZoom: true,
showTooltip: true
} );
jQuery( '#vmap3' ).vectorMap( {
map: 'argentina_en',
color: '#581D22',
borderColor: '#fff',
backgroundColor: '#fff',
onRegionClick: function ( element, code, region ) {
var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
alert( message );
}
} );
jQuery( '#vmap4' ).vectorMap( {
map: 'brazil_br',
color: '#581D22',
borderColor: '#fff',
backgroundColor: '#fff',
onRegionClick: function ( element, code, region ) {
var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
alert( message );
}
} );
jQuery( '#vmap5' ).vectorMap( {
map: 'france_fr',
color: '#581D22',
borderColor: '#fff',
backgroundColor: '#fff',
enableZoom: true,
showTooltip: true
} );
jQuery( '#vmap6' ).vectorMap( {
map: 'germany_en',
color: '#581D22',
borderColor: '#fff',
backgroundColor: '#fff',
onRegionClick: function ( element, code, region ) {
var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
alert( message );
}
} );
jQuery( '#vmap7' ).vectorMap( {
map: 'greece',
color: '#581D22',
borderColor: '#fff',
backgroundColor: '#fff',
onRegionClick: function ( element, code, region ) {
var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
alert( message );
}
} );
jQuery( '#vmap8' ).vectorMap( {
map: 'iran_ir',
onRegionClick: function ( element, code, region ) {
var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
alert( message );
}
} );
jQuery( '#vmap9' ).vectorMap( {
map: 'iraq',
color: '#581D22',
borderColor: '#fff',
backgroundColor: '#fff',
onRegionClick: function ( element, code, region ) {
var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
alert( message );
}
} );
jQuery( '#vmap10' ).vectorMap( {
map: 'russia_en',
color: '#581D22',
borderColor: '#fff',
backgroundColor: '#fff',
hoverOpacity: 0.7,
selectedColor: '#999999',
enableZoom: true,
showTooltip: true,
scaleColors: [ '#C8EEFF', '#006491' ],
normalizeFunction: 'polynomial'
} );
jQuery( '#vmap11' ).vectorMap( {
map: 'tunisia',
color: '#581D22',
borderColor: '#fff',
backgroundColor: '#fff',
onRegionClick: function ( element, code, region ) {
var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
alert( message );
}
} );
jQuery( '#vmap12' ).vectorMap( {
map: 'europe_en',
color: '#581D22',
borderColor: '#fff',
backgroundColor: '#fff',
enableZoom: true,
showTooltip: true
} );
jQuery( '#vmap13' ).vectorMap( {
map: 'usa_en',
color: '#581D22',
borderColor: '#fff',
backgroundColor: '#fff',
enableZoom: true,
showTooltip: true,
selectedColor: null,
hoverColor: null,
colors: {
mo: '#001BFF',
fl: '#001BFF',
or: '#001BFF'
},
onRegionClick: function ( event, code, region ) {
event.preventDefault();
}
} );
jQuery( '#vmap14' ).vectorMap( {
map: 'turkey',
color: '#581D22',
borderColor: '#fff',
backgroundColor: '#fff',
onRegionClick: function ( element, code, region ) {
var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
alert( message );
}
} );
} )( jQuery );
var map;
jQuery( document ).ready( function () {
// Store currentRegion
var currentRegion = 'fl';
// List of Regions we'll let clicks through for
var enabledRegions = [ 'mo', 'fl', 'or' ];
map = jQuery( '#vmap15' ).vectorMap( {
map: 'usa_en',
color: '#581D22',
borderColor: '#fff',
backgroundColor: '#fff',
enableZoom: true,
showTooltip: true,
selectedColor: '#001BFF',
selectedRegions: [ 'fl' ],
hoverColor: null,
colors: {
mo: '#001BFF',
fl: '#001BFF',
or: '#001BFF'
},
onRegionClick: function ( event, code, region ) {
// Check if this is an Enabled Region, and not the current selected on
if ( enabledRegions.indexOf( code ) === -1 || currentRegion === code ) {
// Not an Enabled Region
event.preventDefault();
} else {
// Enabled Region. Update Newly Selected Region.
currentRegion = code;
}
},
onRegionSelect: function ( event, code, region ) {
console.log( map.selectedRegions );
},
onLabelShow: function ( event, label, code ) {
if ( enabledRegions.indexOf( code ) === -1 ) {
event.preventDefault();
}
}
} );
} );
|
import jwt from 'jsonwebtoken';
import config from './config';
const getToken = (user) => {
return jwt.sign(
{
_id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin
}
, config.JWT_SECRET, {
expiresIn: '48h'
});
};
const isAuth = (req, res, next) => {
const token = req.headers.authorization;
if (token){
const onlyToken = token.slice(6, token.length);
jwt.verify(onlyToken, config.JWT_SECRET, (err, decode) => {
if(err){
return res.status(401).send({msg: 'Invalid Token'});
}
req.user = decode;
next();
return;
});
}
else{
return res.status(401).send({msg: 'No token provided!'});
}
}
const isAdmin = (req, res, next) => {
if(req.user && req.user.isAdmin){
return next();
}
return res.status(401).send({msg: 'Admin token invalid!'});
}
export {
getToken, isAuth, isAdmin
}; |
'use strict';
if (typeof window !== 'undefined' && typeof exports === 'undefined') {
if (typeof window.utils !== 'object') {
window.utils = {};
}
}
if (typeof exports !== 'undefined') {
var _ = require('underscore');
}
(function(exports) {
//
// Message Text Formatting
//
var markdownFormatter = window.markdownit('zero', {
html: false,
breaks: true,
linkify: true
}).enable([
'backticks',
'emphasis',
'link',
'linkify',
'newline',
'blockquote',
'code',
'fence',
'list'
]);
function markdownFormat(text) {
return markdownFormatter
.render(text)
.replace(/<a /g, '<a target="_blank" ');
}
function encodeEntities(value) {
return value.
replace(/&/g, '&').
replace(surrogatePairRegexp, function(value) {
var hi = value.charCodeAt(0),
low = value.charCodeAt(1);
return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
}).
replace(nonAlphanumericRegexp, function(value) {
return '&#' + value.charCodeAt(0) + ';';
}).
replace(/</g, '<').
replace(/>/g, '>');
}
function getBaseUrl() {
var parts = window.location.pathname.split('/');
parts = _.filter(parts, function(part) {
return part.length;
});
var path = window.location.origin;
if (parts.length) {
path = path + '/' + parts.join('/');
}
return path + '/';
}
function trim(text) {
return text.trim();
}
function mentions(text) {
var mentionPattern = /\B@([\w\.]+)(?!@)\b/g;
return text.replace(mentionPattern, '<span class="lcb-message-mention">@$1</span>');
}
function roomLinks(text, data) {
if (!data.rooms) {
return text;
}
var slugPattern = /\B(\#[a-z0-9_]+)\b/g;
return text.replace(slugPattern, function(slug) {
var s = slug.substring(1);
var room = data.rooms.find(function(room) {
return room.attributes.slug === s;
});
if (!room) {
return slug;
}
return '<a href="#!/room/' + room.id + '">#' + s + '</a>';
});
}
function uploads(text) {
var pattern = /^\s*(upload:\/\/[-A-Z0-9+&*@#\/%?=~_|!:,.;'"!()]*)\s*$/i;
return text.replace(pattern, function(url) {
return getBaseUrl() + url.substring(9);
});
}
function links(text) {
if (imagePattern.test(text)) {
return text.replace(imagePattern, function(url) {
var uri = encodeEntities(_.unescape(url));
return '<a class="thumbnail" href="' + uri +
'" target="_blank" rel="noreferrer nofollow"><img src="' + uri +
'" alt="Pasted Image" /></a>';
});
} else {
return text.replace(linkPattern, function(url) {
var uri = encodeEntities(_.unescape(url));
return '<a href="' + uri + '" target="_blank" rel="noreferrer nofollow">' + url + '</a>';
});
}
return text.replace(imagePattern, function(url) {
var uri = encodeURI(_.unescape(url));
return '<a class="thumbnail" href="' + uri +
'" target="_blank"><img src="' + uri +
'" alt="Pasted Image" /></a>';
});
}
function embeds(text) {
text = uploads(text);
var imagePattern = /^\s*((https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;'"!()]*[-A-Z0-9+&@#\/%=~_|][.](jpe?g|png|gif))\s*$/i;
if (!text.match(imagePattern)) {
return false;
}
return text.replace(imagePattern, function(url) {
var uri = encodeURI(_.unescape(url));
return '<a class="thumbnail" href="' + uri +
'" target="_blank"><img src="' + uri +
'" alt="Pasted Image" /></a>';
});
}
function emotes(text, data) {
var regex = new RegExp('\\B(:[a-z0-9_\\+\\-]+:)[\\b]?', 'ig');
return text.replace(regex, function(group) {
var key = group.split(':')[1];
var emote = _.find(data.emotes, function(emote) {
return emote.emote === key;
});
if (!emote) {
return group;
}
var image = _.escape(emote.image),
emo = _.escape(':' + emote.emote + ':'),
size = _.escape(emote.size || 20);
return '<img class="emote" src="' + image + '" title="' + emo + '" alt="' + emo + '" width="' + size + '" height="' + size + '" />';
});
}
function replacements(text, data) {
_.each(data.replacements, function(replacement) {
text = text.replace(new RegExp(replacement.regex, 'ig'), replacement.template);
});
return text;
}
var surrogatePairRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
// Match everything outside of normal chars and " (quote character)
nonAlphanumericRegexp = /([^\#-~| |!])/g,
imagePattern = /^\s*((https?|ftp):\/\/[-A-Z0-9\u00a1-\uffff+&@#\/%?=~_|!:,.;'"!()]*[-A-Z0-9\u00a1-\uffff+&@#\/%=~_|][.](jpe?g|png|gif))\s*(\?[\w-]+(=[\w-]*)?(&[\w-]+(=[\w-]*)?)*)?$/i,
linkPattern = /((https?|ftp):\/\/[-A-Z0-9\u00a1-\uffff+&*@#\/%?=~_|!:,.;'"!()]*[-A-Z0-9\u00a1-\uffff+&@#\/%=~_|])/ig;
exports.format = function(text, data) {
var embed = embeds(text);
if (embed) {
return embed;
}
var pipeline = [
markdownFormat,
mentions,
roomLinks,
emotes,
replacements
];
_.each(pipeline, function(func) {
text = func(text, data);
});
return text;
};
})(typeof exports === 'undefined' ? window.utils.message = {} : exports);
|
import React, { Component } from 'react'
import API from './utils/api'
class PortfolioSquare extends Component {
constructor(props){
super(props)
this.state = {
isEditing: this.props.editing,
isDirty: false
}
}
componentWillMount(){
const store = API.getDataFromLocalStore('toptal-portfolio-list') || API.portfolioList;
this.setState( () => ({ portfolioList:store }))
API.EEmiter.addListener( 'save-portfolio', () => {
API.saveDataToLocalStore('toptal-portfolio-list', this.state.portfolioList);
})
}
handleSubmit(e){
e.preventDefault();
}
handleChange(e){
const elements = document.querySelectorAll('.portfolio__square .form__row');
const nextState = [];
e.target.value != "" ? this.setState( ( ) => ({ isDirty: true }) ) : this.setState( ( ) => ({ isDirty: false }) )
elements.forEach( (row) => {
const project = row.children[0].value;
const techs = row.children[1].value;
if( project !== "" && techs !== "" )
nextState.push({ title: project, skills: techs });
} )
this.setState( ( ) => ({ portfolioList: nextState }) )
}
renderFormRow(){
const content = []
for( let i = 0; i < 7; i++ ){
content.push(
<div key={i} className="form__row">
<input type="text" placeholder="Project name" defaultValue={this.state.portfolioList[i] ? this.state.portfolioList[i].title : '' } />
<input type="text" placeholder="Skills used" defaultValue={this.state.portfolioList[i] ? this.state.portfolioList[i].skills : '' } />
</div>
)
}
return content;
}
renderForm(){
return (
<div className="columns medium-3 small-12" >
<div className="profile__square profile__square--black portfolio__square">
<h3 className="profile__square--title profile__square--title--white">{this.props.title}</h3>
<form
onInput={this.handleChange.bind(this)}
onChange={this.handleChange.bind(this)} >
{ this.renderFormRow() }
</form>
{
this.state.portfolioList.length !== 0 ? <span className="add__skill__form--checked">✓</span> : null
}
</div>
</div>
)
}
renderContent(){
const uniqueSkills = []
this.state.portfolioList.map(function(elem, pos) {
uniqueSkills.indexOf(elem.skills) == -1 ? uniqueSkills.push(elem.skills) : false;
});
return(
<div className="columns medium-3 small-12" >
<div className="portfolio__square">
<h3 className="profile__square--title profile__square--title--hasSub">{this.props.title}</h3>
<span className="portfolio__subtitle">
{ uniqueSkills.join(', ')}
</span>
{
this.state.portfolioList == '' ? <p className="no__content">Add Content </p> : false
}
<ul className="portfolio__list">
{
this.state.portfolioList.map( (project, index) => {
return <li key={index}><b>{project.title}</b>, {project.skills}</li>
})
}
</ul>
</div>
</div>
)
}
render () {
return this.props.editing ? this.renderForm() : this.renderContent();
}
}
export default PortfolioSquare |
(function (window) {
var names = ["Yaakov", "John", "Jen", "Jason", "Paul", "Frank", "Larry", "Paula", "Laura", "Jim"];
for (var i = 0; i < names.length; i++) {
var firstLetter = names[i].charAt(0).toLowerCase();
if (firstLetter == 'j') {
byeSpeaker.speak(names[i]);
}
else {
helloSpeaker.speak(names[i]);
}
}
}) (window);
|
import React from "react";
export default function UnitPiece({image}) {
return (
<>
<div
style={{
opacity: 1,
display: "flex",
alignItems: "center",
justifyContent: "center",
width: "100%",
height: "100%",
position: "absolute"
}}
>
<img
src={image}
alt="test"
style={{
maxWidth: "100%",
maxHeight: "100%"
}}
/>
</div>
</>
);
}
|
import os
import commands
import argparse
def split_loops_into_anchors(file_name):
"""
Split loops into anchors.
"""
left = []
right = []
run = file_name.split('.')[0]
i = -1
with open(file_name, 'r') as f:
for line in f:
if '#' in line:
# Skip header
continue
i += 1
loop_id = str(i)
entry = line.strip().split()
# Left anchor
chrom_a = entry[0]
start_a = entry[1]
end_a = entry[2]
left.append(
[chrom_a, start_a, end_a, loop_id, '0', '+'])
# Right anchor
chrom_b = entry[3]
start_b = entry[4]
end_b = entry[5]
right.append(
[chrom_b, start_b, end_b, loop_id, '0', '+'])
## Write left anchors to BED file
left_file = 'temp_left_anchors.bed'
with open(left_file, 'w') as out:
for row in left:
out.write('\t'.join(row) + '\n')
## Write right anchors to BED file
right_file = 'temp_right_anchors.bed'
with open(right_file, 'w') as out:
for row in right:
out.write('\t'.join(row) + '\n')
return left_file, right_file
def bedtools_intersect(anchor_bed, peaks_file, inter_bed):
"""
bedtools intersect.
"""
# Remove previous overlap BED file for extra caution
if os.path.exists(inter_bed):
os.remove(inter_bed)
command = ('module load bedtools/2.26.0;'
' bedtools intersect -u -a {anchor_bed} -b {peaks_file}'
' > {inter_bed}').format(
anchor_bed=anchor_bed,
peaks_file=peaks_file,
inter_bed=inter_bed)
#p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
#out, err = p.communicate()
commands.getoutput(command)
def annotate_loops_with_peak_support(
loop_file, peaks_file):
"""
Annotate loops with peak support (0, 1, 2).
"""
left_anchor_file, right_anchor_file = \
split_loops_into_anchors(loop_file)
# Set BED file names
left_inter_file = 'temp_left_anchors_intersect_peaks.bed'
right_inter_file = 'temp_right_anchors_intersect_peaks.bed'
# Intersect two anchors with peaks
bedtools_intersect(left_anchor_file, peaks_file, left_inter_file)
bedtools_intersect(right_anchor_file, peaks_file, right_inter_file)
pk_supp = {}
for inter_file in [left_inter_file, right_inter_file]:
with open(inter_file, 'r') as f:
for line in f:
entry = line.strip().split()
idx = int(entry[3])
if idx not in pk_supp:
pk_supp[idx] = 1
else:
pk_supp[idx] += 1
# Read Loop file
res = []
with open(loop_file, 'r') as f:
for line in f:
entry = line.strip().split()
res.append(entry)
## Write results
out_file = loop_file + '.peak_annot'
with open(out_file, 'w') as f:
idx = -1
for entry in res:
idx += 1
if idx not in pk_supp.keys():
count = 0
else:
count = pk_supp[idx]
entry.append(str(count))
f.write('\t'.join(entry) + '\n')
def parse_command_line_args():
"""
Parse command-line arguments.
Returns:
args (class 'argparse.Namespace'):
An object containing the parsed command-line arguments.
For every command-line option, the values are stored as follows:
args.{option}
"""
# Initiate the argument parser
parser = argparse.ArgumentParser()
required = parser.add_argument_group('required arguments')
# Indicate the required arguments
required.add_argument(
'-l', '--loop_file', required=True,
help=('The file of intrachrom loops with PET count >= 2.'))
required.add_argument(
'-p', '--peak_file', required=True,
help=('The file of peaks.'))
# Parse the arguments from the command-line input
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_command_line_args()
annotate_loops_with_peak_support(
args.loop_file, args.peak_file)
|
const manifestOptions = require("./public/assets/manifest.json");
module.exports = {
chainWebpack: (config) => {
config.module
.rule("yaml")
.test(/\.ya?ml$/)
.use("raw-loader")
.loader("raw-loader")
.end();
},
publicPath: "",
pwa: {
manifestPath: "assets/manifest.json",
manifestCrossorigin: "use-credentials",
appleMobileWebAppStatusBarStyle: "black",
appleMobileWebAppCapable: "yes",
name: manifestOptions.name,
themeColor: manifestOptions.theme_color,
manifestOptions,
iconPaths: {
favicon32: "assets/favicons/favicon-32x32.png",
favicon16: "assets/favicons/favicon-16x16.png",
appleTouchIcon: "assets/favicons/icon-maskable.png",
maskIcon: "assets/favicons/safari-pinned-tab.svg",
msTileImage: "assets/favicons/icon-any.png",
},
},
};
|
"""
Contact package
Returns contact information for a given search.
Integrates with molly.providers.contact.*
"""
|
"""
Corrently.io
*Corrently - from italian corrente, which is energy* # Introduction The Corrently ecosystem gets maintained by [STROMDAO GmbH](https://www.stromdao.de/) to support green energy services for prosumers, grid operators, regulators, integrators or any other party with an emerging need of consensus driven management. As the [energy product Corrently](https://www.corrently.de/) got first launched in Germany parts of this documentation provide simple translations for better understanding. # noqa: E501
The version of the OpenAPI document: 2.0.0
Contact: [email protected]
Generated by: https://openapi-generator.tech
"""
import unittest
import openapi_client
from openapi_client.api.dispatch__green_energy_distribution_api_api import DispatchGreenEnergyDistributionAPIApi # noqa: E501
class TestDispatchGreenEnergyDistributionAPIApi(unittest.TestCase):
"""DispatchGreenEnergyDistributionAPIApi unit test stubs"""
def setUp(self):
self.api = DispatchGreenEnergyDistributionAPIApi() # noqa: E501
def tearDown(self):
pass
def test_gsi_dispatch(self):
"""Test case for gsi_dispatch
Dispatch (Green Energy Distribution Schedule) # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main()
|
# The plot server must be running
# Go to http://localhost:5006/bokeh to view this plot
import numpy as np
from bokeh.plotting import figure, gridplot, output_server, show
N = 50
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
output_server("grid")
TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
l = figure(title="line", tools=TOOLS, plot_width=300, plot_height=300)
l.line(x,y, line_width=3, color="gold")
aw = figure(title="annular wedge", tools=TOOLS, plot_width=300, plot_height=300)
aw.annular_wedge(x, y, 10, 20, 0.6, 4.1, color="navy", alpha=0.5,
inner_radius_units="screen", outer_radius_units="screen")
bez = figure(title="bezier", tools=TOOLS, plot_width=300, plot_height=300)
bez.bezier(x, y, x+0.4, y, x+0.1, y+0.2, x-0.1, y-0.2,
line_width=2, color="olive")
q = figure(title="quad", tools=TOOLS, plot_width=300, plot_height=300)
q.quad(x, x-0.2, y, y-0.2, color="tomato", alpha=0.4)
# specify "empty" grid cells with None
p = gridplot([[l, None, aw], [bez, q, None]])
show(p)
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "df03b9c077a923b6e36f0e1b411179b6",
"url": "/spinners/index.html"
},
{
"revision": "b4384fb505793f0e8c75",
"url": "/spinners/static/css/main.65a49a9b.chunk.css"
},
{
"revision": "53451aa83d87d5577005",
"url": "/spinners/static/js/2.34c0f6d7.chunk.js"
},
{
"revision": "5e9b6f5c16b720e8a86875f97734673e",
"url": "/spinners/static/js/2.34c0f6d7.chunk.js.LICENSE.txt"
},
{
"revision": "b4384fb505793f0e8c75",
"url": "/spinners/static/js/main.b3eda917.chunk.js"
},
{
"revision": "026269861549899ec005",
"url": "/spinners/static/js/runtime-main.82c28fce.js"
},
{
"revision": "c4f6c573b0dba9711c3741acd13878cb",
"url": "/spinners/static/media/angular.c4f6c573.svg"
},
{
"revision": "24eaa5c46ba525a9489039b01ef898b5",
"url": "/spinners/static/media/fb.24eaa5c4.svg"
},
{
"revision": "6251a2e12b5ccc659a85168a94376f58",
"url": "/spinners/static/media/github-logo.6251a2e1.svg"
},
{
"revision": "8cb68050d2a9f59ab9b42ff4c6a4a99c",
"url": "/spinners/static/media/github.8cb68050.svg"
},
{
"revision": "6571519029c6a3ab822a70b3407ee70a",
"url": "/spinners/static/media/in.65715190.svg"
},
{
"revision": "2b622f80b7c3ddfee60cdefe81c24ef4",
"url": "/spinners/static/media/logo.2b622f80.svg"
},
{
"revision": "0a7ac7d9ae74cf6a3431c6b4bc8caf04",
"url": "/spinners/static/media/react.0a7ac7d9.svg"
},
{
"revision": "1ebf08dd3a1e8087d6cd9c3c4a8748a7",
"url": "/spinners/static/media/tw.1ebf08dd.svg"
}
]); |
import { FastField } from 'formik';
import { i18n } from 'i18n';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import FormErrors from 'view/shared/form/formErrors';
import AsyncSelect from 'react-select/async';
import {
components as materialUiComponents,
styles as materialUiStyles,
} from 'view/shared/form/items/shared/reactSelectMaterialUi';
import { withStyles } from '@material-ui/core/styles';
import { IconButton } from '@material-ui/core';
import AddIcon from '@material-ui/icons/Add';
const AUTOCOMPLETE_SERVER_FETCH_SIZE = 100;
class AutocompleteFormItemNotFast extends Component {
value = () => {
const { mode } = this.props;
if (mode === 'multiple') {
return this.valueMultiple();
} else {
return this.valueOne();
}
};
valueMultiple = () => {
const { form, name, mapper } = this.props;
if (form.values[name]) {
return form.values[name].map((value) =>
mapper.toAutocomplete(value),
);
}
return [];
};
valueOne = () => {
const { form, name, mapper } = this.props;
if (form.values[name]) {
return mapper.toAutocomplete(form.values[name]);
}
return null;
};
handleSelect = (value) => {
const { form, name } = this.props;
form.setFieldTouched(name);
const { mode } = this.props;
if (mode === 'multiple') {
return this.handleSelectMultiple(value);
} else {
return this.handleSelectOne(value);
}
};
handleSelectMultiple = (values) => {
const { form, name, mapper } = this.props;
if (!values) {
form.setFieldValue(name, []);
return;
}
form.setFieldValue(
name,
values.map((value) => mapper.toValue(value)),
);
};
handleSelectOne = (value) => {
const { form, name, mapper } = this.props;
if (!value) {
form.setFieldValue(name, '');
return;
}
form.setFieldValue(name, mapper.toValue(value));
};
handleSearch = async (value) => {
const { fetchFn, mapper } = this.props;
try {
const results = await fetchFn(
value,
AUTOCOMPLETE_SERVER_FETCH_SIZE,
);
return results.map((result) =>
mapper.toAutocomplete(result),
);
} catch (error) {
console.error(error);
return [];
}
};
render() {
const {
form,
label,
name,
hint,
placeholder,
autoFocus,
inputProps,
errorMessage,
mode,
required,
isClearable,
classes,
} = this.props;
const isInvalid = !!FormErrors.displayableError(
form,
name,
errorMessage,
);
const controlStyles = {
container: (provided) => ({
...provided,
width: '100%',
marginTop: '16px',
marginBottom: '8px',
}),
control: (provided) => ({
...provided,
borderColor: isInvalid ? 'red' : undefined,
}),
};
return (
<div
style={{ display: 'flex', alignItems: 'center' }}
>
<AsyncSelect
styles={controlStyles}
classes={classes}
inputId={name}
TextFieldProps={{
label,
required,
variant: 'outlined',
fullWidth: true,
error: !!FormErrors.displayableError(
form,
name,
errorMessage,
),
helperText:
FormErrors.displayableError(
form,
name,
errorMessage,
) || hint,
InputLabelProps: {
shrink: true,
},
}}
components={materialUiComponents}
defaultOptions={true}
isMulti={mode === 'multiple' ? true : false}
loadOptions={this.handleSearch}
placeholder={placeholder || ''}
autoFocus={autoFocus || undefined}
onChange={this.handleSelect}
value={this.value()}
isClearable={isClearable}
loadingMessage={() =>
i18n('autocomplete.loading')
}
noOptionsMessage={() =>
i18n('autocomplete.noOptions')
}
{...inputProps}
/>
{this.props.showCreate &&
this.props.hasPermissionToCreate ? (
<IconButton
style={{
marginLeft: '16px',
marginTop: '16px',
marginBottom: '8px',
}}
color="secondary"
onClick={this.props.onOpenModal}
>
<AddIcon />
</IconButton>
) : null}
</div>
);
}
}
AutocompleteFormItemNotFast.defaultProps = {
isClearable: true,
mode: 'default',
required: false,
};
AutocompleteFormItemNotFast.propTypes = {
form: PropTypes.object.isRequired,
fetchFn: PropTypes.func.isRequired,
mapper: PropTypes.object.isRequired,
required: PropTypes.bool,
mode: PropTypes.string,
name: PropTypes.string.isRequired,
label: PropTypes.string,
hint: PropTypes.string,
autoFocus: PropTypes.bool,
placeholder: PropTypes.string,
errorMessage: PropTypes.string,
isClearable: PropTypes.bool,
inputProps: PropTypes.object,
showCreate: PropTypes.bool,
hasPermissionToCreate: PropTypes.bool,
};
class AutocompleteFormItem extends Component {
render() {
return (
<FastField
name={this.props.name}
render={({ form }) => (
<AutocompleteFormItemNotFast
{...this.props}
form={form}
/>
)}
/>
);
}
}
export default withStyles(materialUiStyles)(
AutocompleteFormItem,
);
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import '../index.css'
class ErrorHandle extends Component {
render() {
if (this.props.jobs === 0) {
return (
<div>
<div className="Search-Directions">
<p>No results for {this.props.query}. Please try searching a different area.</p>
</div>
</div>
);
} else {
return(null);
}
}
}
const mapStateToProps = state => ({
addedCategories: state.jobs.addedCategories,
jobs: state.jobs.jobs,
query: state.jobs.query
});
export default connect(mapStateToProps)(ErrorHandle);
|
const jwt = require("jsonwebtoken");
const config = require("../config/auth.config.js");
const db = require("../models");
const User = db.user;
verifyToken = (req, res, next) => {
//let token = req.headers["x-access-token"];
let token = req.cookies.user_token;
if (!token) {
return res.status(403).send({
message: "No token provided!",
});
}
console.log("im in auth ");
jwt.verify(token, config.JWT_SECRET, (err, decoded) => {
if (err) {
console.error(err);
return res.status(401).send({
message: "Unauthorized!",
});
}
req.userId = decoded.id;
next();
});
};
const authJwt = {
verifyToken: verifyToken,
};
module.exports = authJwt;
|
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('requirements.txt') as f:
install_requires = f.read().strip().split('\n')
# get version from __version__ variable in argemsan/__init__.py
from argemsan import __version__ as version
setup(
name='argemsan',
version=version,
description='Argemsan için yazılan Custom Kodlar',
author='Frappe',
author_email='[email protected]',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
install_requires=install_requires
)
|
module.exports={A:{A:{"2":"J D E F A B oB"},B:{"2":"C K L G M N O P a b c d e f S H g","450":"Q R U V W X Y Z"},C:{"2":"0 1 2 3 4 5 6 7 8 9 pB fB I h J D E F A B C K L G M N O i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB gB MB hB NB OB T PB QB RB SB TB UB VB WB XB YB ZB aB bB cB P Q R iB U V W X Y Z a b c d e f S H g qB rB"},D:{"2":"0 1 2 3 4 5 6 7 8 9 I h J D E F A B C K L G M N O i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB gB MB hB NB OB T PB QB RB SB TB UB VB WB XB YB ZB aB bB cB P a b c d e f S H g sB tB uB","450":"Q R U V W X Y Z"},E:{"2":"I h J D E F A B C K L G vB jB wB xB yB zB kB dB eB 0B 1B 2B lB 3B"},F:{"2":"0 1 2 3 4 5 6 7 8 9 F B C G M N O i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB T PB QB 4B 5B 6B 7B dB mB 8B eB","450":"RB SB TB UB VB WB XB YB ZB aB bB cB P Q R iB"},G:{"2":"E jB 9B nB AC BC CC DC EC FC GC HC IC JC KC LC MC NC OC PC QC RC SC lB"},H:{"2":"TC"},I:{"2":"fB I H UC VC WC XC nB YC ZC"},J:{"2":"D A"},K:{"2":"A B C T dB mB eB"},L:{"257":"H"},M:{"2":"S"},N:{"2":"A B"},O:{"2":"aC"},P:{"2":"I bC cC dC eC fC kB gC hC iC jC kC"},Q:{"2":"lC"},R:{"2":"mC"},S:{"2":"nC"}},B:7,C:"Web NFC"};
|
import React from "react";
import renderer from "react-test-renderer";
import AuthorImage from "../../js/templates/AuthorImage";
describe("Author image component snapshot", () => {
it("matches as author image snapshot", () => {
const tree = renderer
.create(<AuthorImage url="https://example.com/12345" />)
.toJSON();
expect(tree).toMatchSnapshot();
});
});
|
const Resource = require("../database/model/resource.model");
async function createResource(data, res) {
const newResource = await new Resource(data);
await newResource.save().then((newData) => {
res.status(201).json({ success: 1, message: "Created new resource" });
});
}
async function getResource(res) {
return await Resource.find({});
}
async function upVote(resid, usrid, res) {
if(!resid || !userid) res.status(404).json({ success: 0, message: "Can not find resourceid or userid" });
else {
const found = await Resource.find({
$and: [{ _id: resid }, { upvotedBy: usrid }],
});
if (found.length == 0) {
await Resource.findOneAndUpdate(
{
_id: resid,
},
{
$push: { upvotedBy: usrid },
$inc: {
upvotecount: 1,
},
}
)
.then((dat) => {
res.status(201).json({ success: 1, message: "Upvoted", data: dat });
})
.catch((err) => {
console.log(err);
res.status(404).json({ success: 0, message: "Can not find resource" });
});
} else {
res.status(409).json({ success: 0, message: "You can upvote only once" });
}
}
}
async function downVote(resid, usrid, res) {
if(!resid || !usrid) res.status(404).json({ success: 0, message: "Can not find resourceid or userid" });
else {
const found = await Resource.find({
$and: [{ _id: resid }, { downvotedBy: usrid }],
});
console.log("found dataa",found.length);
if (found.length === 0) {
await Resource.findOneAndUpdate(
{
_id: resid,
},
{
$push: { downvotedBy: usrid },
$inc: {
downvotecount: 1,
},
}
)
.then((dat) => {
res.status(201).json({ success: 1, message: "Downvoted", data: dat });
})
.catch((err) => {
console.log(err);
res.status(404).json({ success: 0, message: "Can not find resource" });
});
} else {
res.status(409).json({ success: 0, message: "You can downvote only once" });
}
}
}
module.exports = {
createResource,
getResource,
upVote,
downVote,
};
|
import { playerConstants } from '../_constants';
import { playerService } from '../_services';
import { alertActions } from '.';
import { history } from '../_helpers';
export const playerActions = {
login,
logout,
getAllPlayers,
createPlayer,
updatePlayer,
deletePlayer,
};
function login(email, password) {
return (dispatch) => {
dispatch(request({ email }));
playerService.login(email, password).then(
(user) => {
dispatch(success(user));
history.push('/');
},
(error) => {
if (error && error.message) {
error = error.message;
}
dispatch(failure(error));
dispatch(alertActions.error(error));
},
);
};
function request(user) {
return { type: playerConstants.LOGIN_REQUEST, user };
}
function success(user) {
return { type: playerConstants.LOGIN_SUCCESS, user };
}
function failure(error) {
return { type: playerConstants.LOGIN_FAILURE, error };
}
}
function logout() {
playerService.logout();
return { type: playerConstants.LOGOUT };
}
function getAllPlayers(managerId) {
return (dispatch) => {
dispatch(request());
playerService
.getAllPlayers(managerId)
.then(
(players) => dispatch(success(players)),
(error) => dispatch(failure(error)),
);
};
function request() {
return { type: playerConstants.GETALL_REQUEST };
}
function success(players) {
return { type: playerConstants.GETALL_SUCCESS, players };
}
function failure(error) {
return { type: playerConstants.GETALL_FAILURE, error };
}
}
function createPlayer(player) {
return (dispatch) => {
dispatch(request(player));
playerService.createPlayer(player).then(
() => {
dispatch(success());
dispatch(getAllPlayers(player.managerId));
},
(error) => {
if (error && error.message) {
error = error.message;
}
dispatch(failure(error));
dispatch(alertActions.error(error));
dispatch(getAllPlayers(player.managerId));
},
);
};
function request(player) {
return { type: playerConstants.CREATEONE_REQUEST, player };
}
function success() {
return { type: playerConstants.CREATEONE_SUCCESS };
}
function failure(error) {
return { type: playerConstants.CREATEONE_FAILURE, error };
}
}
function updatePlayer(managerId, updatedPlayer) {
return (dispatch) => {
dispatch(request(updatedPlayer));
playerService.updatePlayer(managerId, updatedPlayer).then(
(player) => {
dispatch(success(player));
dispatch(getAllPlayers(managerId));
},
(error) => {
if (error && error.message) {
error = error.message;
}
dispatch(failure(error));
dispatch(alertActions.error(error));
dispatch(getAllPlayers(managerId));
},
);
};
function request(player) {
return { type: playerConstants.UPDATE_REQUEST, player };
}
function success(player) {
return { type: playerConstants.UPDATE_SUCCESS, player };
}
function failure(error) {
return { type: playerConstants.UPDATE_FAILURE, error };
}
}
function deletePlayer(managerId, id) {
return (dispatch) => {
dispatch(request(id));
playerService.deletePlayer(managerId, id).then(
() => {
dispatch(success());
dispatch(getAllPlayers(managerId));
},
(error) => {
if (error && error.message) {
error = error.message;
}
dispatch(failure(error));
dispatch(alertActions.error(error));
dispatch(getAllPlayers(managerId));
},
);
};
function request(id) {
return { type: playerConstants.DELETE_REQUEST, id };
}
function success() {
return { type: playerConstants.DELETE_SUCCESS };
}
function failure(error) {
return { type: playerConstants.DELETE_FAILURE, error };
}
}
|
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from hashlib import sha1
from pants.base.payload_field import PayloadField
from pants.engine.fs import PathGlobs, Snapshot
from pants.source.filespec import matches_filespec
from pants.source.source_root import SourceRootConfig
from pants.source.wrapped_globs import EagerFilesetWithSpec, FilesetWithSpec
from pants.util.memo import memoized_property
class SourcesField(PayloadField):
"""A PayloadField encapsulating specified sources."""
@staticmethod
def _validate_sources(sources):
if not isinstance(sources, FilesetWithSpec):
raise ValueError('Expected a FilesetWithSpec. `sources` should be '
'instantiated via `create_sources_field`.')
return sources
def __init__(self, sources, ref_address=None):
"""
:param sources: FilesetWithSpec representing the underlying sources.
:param ref_address: optional address spec of target that provides these sources
"""
self._sources = self._validate_sources(sources)
self._ref_address = ref_address
@property
def source_root(self):
""":returns: the source root for these sources, or None if they're not under a source root."""
# TODO: It's a shame that we have to access the singleton directly here, instead of getting
# the SourceRoots instance from context, as tasks do. In the new engine we could inject
# this into the target, rather than have it reach out for global singletons.
return SourceRootConfig.global_instance().get_source_roots().find_by_path(self.rel_path)
def matches(self, path):
return self.sources.matches(path) or matches_filespec(path, self.filespec)
@property
def filespec(self):
return self.sources.filespec
@property
def rel_path(self):
return self.sources.rel_root
@property
def sources(self):
return self._sources
@memoized_property
def source_paths(self):
return list(self.sources)
@property
def address(self):
"""Returns the address this sources field refers to (used by some derived classes)"""
return self._ref_address
def snapshot(self, scheduler=None):
"""
Returns a Snapshot containing the sources, relative to the build root.
This API is experimental, and subject to change.
"""
if isinstance(self._sources, EagerFilesetWithSpec):
snapshot = self._sources.snapshot
if snapshot is not None:
return snapshot
input_pathglobs = PathGlobs(tuple(self.relative_to_buildroot()))
return scheduler.product_request(Snapshot, [input_pathglobs])[0]
def relative_to_buildroot(self):
"""All sources joined with their relative paths."""
return list(self.sources.paths_from_buildroot_iter())
def _compute_fingerprint(self):
hasher = sha1()
hasher.update(self.rel_path.encode())
hasher.update(self.sources.files_hash)
return hasher.hexdigest()
|
import styled from 'styled-components'
export const StyledFooter = styled.footer`
height: 80px;
width: 100%;
display: flex;
flex-direction: row;
justify-content: center;
align-content: center;
` |
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// set template engine: ejs
app.set('view engine', 'ejs');
// use public path
app.use('/public',express.static('public'));
app.use('/', cookieParser());
// use urlencode
app.use(express.urlencoded({
extended: true
}));
// use json
app.use(express.json());
// register middlewares
app.use(require('./middlewares/AuthMiddleware').auth);
// register routers
app.use('/', require('./routes/HomeRouter'));
app.use('/user', require('./routes/AuthRouter'));
app.use('/survey', require('./routes/SurveyRouter'));
app.use('/question', require('./routes/QuestionRouter'));
app.use('/report', require('./routes/ReportRouter'));
app.listen(3000, function(){
console.log('server started at port 3000');
}); |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { __extends } from 'tslib';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { ContentChild, Directive, ElementRef, Input, TemplateRef, ChangeDetectionStrategy, Component, IterableDiffers, ViewContainerRef, ViewEncapsulation, Attribute, ChangeDetectorRef, ContentChildren, EmbeddedViewRef, Inject, isDevMode, Optional, ViewChild, InjectionToken, NgModule } from '@angular/core';
import { Directionality } from '@angular/cdk/bidi';
import { isDataSource } from '@angular/cdk/collections';
export { DataSource } from '@angular/cdk/collections';
import { Platform } from '@angular/cdk/platform';
import { DOCUMENT, CommonModule } from '@angular/common';
import { BehaviorSubject, Observable, of, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Mixin to provide a directive with a function that checks if the sticky input has been
* changed since the last time the function was called. Essentially adds a dirty-check to the
* sticky value.
* \@docs-private
* @template T
* @param {?} base
* @return {?}
*/
function mixinHasStickyInput(base) {
return /** @class */ (function (_super) {
__extends(class_1, _super);
function class_1() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var _this = _super.apply(this, args) || this;
_this._sticky = false;
/**
* Whether the sticky input has changed since it was last checked.
*/
_this._hasStickyChanged = false;
return _this;
}
Object.defineProperty(class_1.prototype, "sticky", {
/** Whether sticky positioning should be applied. */
get: /**
* Whether sticky positioning should be applied.
* @return {?}
*/
function () { return this._sticky; },
set: /**
* @param {?} v
* @return {?}
*/
function (v) {
/** @type {?} */
var prevValue = this._sticky;
this._sticky = coerceBooleanProperty(v);
this._hasStickyChanged = prevValue !== this._sticky;
},
enumerable: true,
configurable: true
});
/** Whether the sticky value has changed since this was last called. */
/**
* Whether the sticky value has changed since this was last called.
* @return {?}
*/
class_1.prototype.hasStickyChanged = /**
* Whether the sticky value has changed since this was last called.
* @return {?}
*/
function () {
/** @type {?} */
var hasStickyChanged = this._hasStickyChanged;
this._hasStickyChanged = false;
return hasStickyChanged;
};
/** Resets the dirty check for cases where the sticky state has been used without checking. */
/**
* Resets the dirty check for cases where the sticky state has been used without checking.
* @return {?}
*/
class_1.prototype.resetStickyChanged = /**
* Resets the dirty check for cases where the sticky state has been used without checking.
* @return {?}
*/
function () {
this._hasStickyChanged = false;
};
return class_1;
}(base));
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Cell definition for a CDK table.
* Captures the template of a column's data row cell as well as cell-specific properties.
*/
var CdkCellDef = /** @class */ (function () {
function CdkCellDef(/** @docs-private */ template) {
this.template = template;
}
CdkCellDef.decorators = [
{ type: Directive, args: [{ selector: '[cdkCellDef]' },] },
];
/** @nocollapse */
CdkCellDef.ctorParameters = function () { return [
{ type: TemplateRef }
]; };
return CdkCellDef;
}());
/**
* Header cell definition for a CDK table.
* Captures the template of a column's header cell and as well as cell-specific properties.
*/
var CdkHeaderCellDef = /** @class */ (function () {
function CdkHeaderCellDef(/** @docs-private */ template) {
this.template = template;
}
CdkHeaderCellDef.decorators = [
{ type: Directive, args: [{ selector: '[cdkHeaderCellDef]' },] },
];
/** @nocollapse */
CdkHeaderCellDef.ctorParameters = function () { return [
{ type: TemplateRef }
]; };
return CdkHeaderCellDef;
}());
/**
* Footer cell definition for a CDK table.
* Captures the template of a column's footer cell and as well as cell-specific properties.
*/
var CdkFooterCellDef = /** @class */ (function () {
function CdkFooterCellDef(/** @docs-private */ template) {
this.template = template;
}
CdkFooterCellDef.decorators = [
{ type: Directive, args: [{ selector: '[cdkFooterCellDef]' },] },
];
/** @nocollapse */
CdkFooterCellDef.ctorParameters = function () { return [
{ type: TemplateRef }
]; };
return CdkFooterCellDef;
}());
// Boilerplate for applying mixins to CdkColumnDef.
/**
* \@docs-private
*/
var
// Boilerplate for applying mixins to CdkColumnDef.
/**
* \@docs-private
*/
CdkColumnDefBase = /** @class */ (function () {
function CdkColumnDefBase() {
}
return CdkColumnDefBase;
}());
/** @type {?} */
var _CdkColumnDefBase = mixinHasStickyInput(CdkColumnDefBase);
/**
* Column definition for the CDK table.
* Defines a set of cells available for a table column.
*/
var CdkColumnDef = /** @class */ (function (_super) {
__extends(CdkColumnDef, _super);
function CdkColumnDef() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._stickyEnd = false;
return _this;
}
Object.defineProperty(CdkColumnDef.prototype, "name", {
/** Unique name for this column. */
get: /**
* Unique name for this column.
* @return {?}
*/
function () {
return this._name;
},
set: /**
* @param {?} name
* @return {?}
*/
function (name) {
// If the directive is set without a name (updated programatically), then this setter will
// trigger with an empty string and should not overwrite the programatically set value.
if (!name) {
return;
}
this._name = name;
this.cssClassFriendlyName = name.replace(/[^a-z0-9_-]/ig, '-');
},
enumerable: true,
configurable: true
});
Object.defineProperty(CdkColumnDef.prototype, "stickyEnd", {
/**
* Whether this column should be sticky positioned on the end of the row. Should make sure
* that it mimics the `CanStick` mixin such that `_hasStickyChanged` is set to true if the value
* has been changed.
*/
get: /**
* Whether this column should be sticky positioned on the end of the row. Should make sure
* that it mimics the `CanStick` mixin such that `_hasStickyChanged` is set to true if the value
* has been changed.
* @return {?}
*/
function () {
return this._stickyEnd;
},
set: /**
* @param {?} v
* @return {?}
*/
function (v) {
/** @type {?} */
var prevValue = this._stickyEnd;
this._stickyEnd = coerceBooleanProperty(v);
this._hasStickyChanged = prevValue !== this._stickyEnd;
},
enumerable: true,
configurable: true
});
CdkColumnDef.decorators = [
{ type: Directive, args: [{
selector: '[cdkColumnDef]',
inputs: ['sticky'],
providers: [{ provide: 'MAT_SORT_HEADER_COLUMN_DEF', useExisting: CdkColumnDef }],
},] },
];
CdkColumnDef.propDecorators = {
name: [{ type: Input, args: ['cdkColumnDef',] }],
stickyEnd: [{ type: Input, args: ['stickyEnd',] }],
cell: [{ type: ContentChild, args: [CdkCellDef, { static: false },] }],
headerCell: [{ type: ContentChild, args: [CdkHeaderCellDef, { static: false },] }],
footerCell: [{ type: ContentChild, args: [CdkFooterCellDef, { static: false },] }]
};
return CdkColumnDef;
}(_CdkColumnDefBase));
/**
* Base class for the cells. Adds a CSS classname that identifies the column it renders in.
*/
var /**
* Base class for the cells. Adds a CSS classname that identifies the column it renders in.
*/
BaseCdkCell = /** @class */ (function () {
function BaseCdkCell(columnDef, elementRef) {
/** @type {?} */
var columnClassName = "cdk-column-" + columnDef.cssClassFriendlyName;
elementRef.nativeElement.classList.add(columnClassName);
}
return BaseCdkCell;
}());
/**
* Header cell template container that adds the right classes and role.
*/
var CdkHeaderCell = /** @class */ (function (_super) {
__extends(CdkHeaderCell, _super);
function CdkHeaderCell(columnDef, elementRef) {
return _super.call(this, columnDef, elementRef) || this;
}
CdkHeaderCell.decorators = [
{ type: Directive, args: [{
selector: 'cdk-header-cell, th[cdk-header-cell]',
host: {
'class': 'cdk-header-cell',
'role': 'columnheader',
},
},] },
];
/** @nocollapse */
CdkHeaderCell.ctorParameters = function () { return [
{ type: CdkColumnDef },
{ type: ElementRef }
]; };
return CdkHeaderCell;
}(BaseCdkCell));
/**
* Footer cell template container that adds the right classes and role.
*/
var CdkFooterCell = /** @class */ (function (_super) {
__extends(CdkFooterCell, _super);
function CdkFooterCell(columnDef, elementRef) {
return _super.call(this, columnDef, elementRef) || this;
}
CdkFooterCell.decorators = [
{ type: Directive, args: [{
selector: 'cdk-footer-cell, td[cdk-footer-cell]',
host: {
'class': 'cdk-footer-cell',
'role': 'gridcell',
},
},] },
];
/** @nocollapse */
CdkFooterCell.ctorParameters = function () { return [
{ type: CdkColumnDef },
{ type: ElementRef }
]; };
return CdkFooterCell;
}(BaseCdkCell));
/**
* Cell template container that adds the right classes and role.
*/
var CdkCell = /** @class */ (function (_super) {
__extends(CdkCell, _super);
function CdkCell(columnDef, elementRef) {
return _super.call(this, columnDef, elementRef) || this;
}
CdkCell.decorators = [
{ type: Directive, args: [{
selector: 'cdk-cell, td[cdk-cell]',
host: {
'class': 'cdk-cell',
'role': 'gridcell',
},
},] },
];
/** @nocollapse */
CdkCell.ctorParameters = function () { return [
{ type: CdkColumnDef },
{ type: ElementRef }
]; };
return CdkCell;
}(BaseCdkCell));
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* The row template that can be used by the mat-table. Should not be used outside of the
* material library.
* @type {?}
*/
var CDK_ROW_TEMPLATE = "<ng-container cdkCellOutlet></ng-container>";
/**
* Base class for the CdkHeaderRowDef and CdkRowDef that handles checking their columns inputs
* for changes and notifying the table.
* @abstract
*/
var /**
* Base class for the CdkHeaderRowDef and CdkRowDef that handles checking their columns inputs
* for changes and notifying the table.
* @abstract
*/
BaseRowDef = /** @class */ (function () {
function BaseRowDef(template, _differs) {
this.template = template;
this._differs = _differs;
}
/**
* @param {?} changes
* @return {?}
*/
BaseRowDef.prototype.ngOnChanges = /**
* @param {?} changes
* @return {?}
*/
function (changes) {
// Create a new columns differ if one does not yet exist. Initialize it based on initial value
// of the columns property or an empty array if none is provided.
if (!this._columnsDiffer) {
/** @type {?} */
var columns = (changes['columns'] && changes['columns'].currentValue) || [];
this._columnsDiffer = this._differs.find(columns).create();
this._columnsDiffer.diff(columns);
}
};
/**
* Returns the difference between the current columns and the columns from the last diff, or null
* if there is no difference.
*/
/**
* Returns the difference between the current columns and the columns from the last diff, or null
* if there is no difference.
* @return {?}
*/
BaseRowDef.prototype.getColumnsDiff = /**
* Returns the difference between the current columns and the columns from the last diff, or null
* if there is no difference.
* @return {?}
*/
function () {
return this._columnsDiffer.diff(this.columns);
};
/** Gets this row def's relevant cell template from the provided column def. */
/**
* Gets this row def's relevant cell template from the provided column def.
* @param {?} column
* @return {?}
*/
BaseRowDef.prototype.extractCellTemplate = /**
* Gets this row def's relevant cell template from the provided column def.
* @param {?} column
* @return {?}
*/
function (column) {
if (this instanceof CdkHeaderRowDef) {
return column.headerCell.template;
}
if (this instanceof CdkFooterRowDef) {
return column.footerCell.template;
}
else {
return column.cell.template;
}
};
return BaseRowDef;
}());
// Boilerplate for applying mixins to CdkHeaderRowDef.
/**
* \@docs-private
*/
var
// Boilerplate for applying mixins to CdkHeaderRowDef.
/**
* \@docs-private
*/
CdkHeaderRowDefBase = /** @class */ (function (_super) {
__extends(CdkHeaderRowDefBase, _super);
function CdkHeaderRowDefBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
return CdkHeaderRowDefBase;
}(BaseRowDef));
/** @type {?} */
var _CdkHeaderRowDefBase = mixinHasStickyInput(CdkHeaderRowDefBase);
/**
* Header row definition for the CDK table.
* Captures the header row's template and other header properties such as the columns to display.
*/
var CdkHeaderRowDef = /** @class */ (function (_super) {
__extends(CdkHeaderRowDef, _super);
function CdkHeaderRowDef(template, _differs) {
return _super.call(this, template, _differs) || this;
}
// Prerender fails to recognize that ngOnChanges in a part of this class through inheritance.
// Explicitly define it so that the method is called as part of the Angular lifecycle.
// Prerender fails to recognize that ngOnChanges in a part of this class through inheritance.
// Explicitly define it so that the method is called as part of the Angular lifecycle.
/**
* @param {?} changes
* @return {?}
*/
CdkHeaderRowDef.prototype.ngOnChanges =
// Prerender fails to recognize that ngOnChanges in a part of this class through inheritance.
// Explicitly define it so that the method is called as part of the Angular lifecycle.
/**
* @param {?} changes
* @return {?}
*/
function (changes) {
_super.prototype.ngOnChanges.call(this, changes);
};
CdkHeaderRowDef.decorators = [
{ type: Directive, args: [{
selector: '[cdkHeaderRowDef]',
inputs: ['columns: cdkHeaderRowDef', 'sticky: cdkHeaderRowDefSticky'],
},] },
];
/** @nocollapse */
CdkHeaderRowDef.ctorParameters = function () { return [
{ type: TemplateRef },
{ type: IterableDiffers }
]; };
return CdkHeaderRowDef;
}(_CdkHeaderRowDefBase));
// Boilerplate for applying mixins to CdkFooterRowDef.
/**
* \@docs-private
*/
var
// Boilerplate for applying mixins to CdkFooterRowDef.
/**
* \@docs-private
*/
CdkFooterRowDefBase = /** @class */ (function (_super) {
__extends(CdkFooterRowDefBase, _super);
function CdkFooterRowDefBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
return CdkFooterRowDefBase;
}(BaseRowDef));
/** @type {?} */
var _CdkFooterRowDefBase = mixinHasStickyInput(CdkFooterRowDefBase);
/**
* Footer row definition for the CDK table.
* Captures the footer row's template and other footer properties such as the columns to display.
*/
var CdkFooterRowDef = /** @class */ (function (_super) {
__extends(CdkFooterRowDef, _super);
function CdkFooterRowDef(template, _differs) {
return _super.call(this, template, _differs) || this;
}
// Prerender fails to recognize that ngOnChanges in a part of this class through inheritance.
// Explicitly define it so that the method is called as part of the Angular lifecycle.
// Prerender fails to recognize that ngOnChanges in a part of this class through inheritance.
// Explicitly define it so that the method is called as part of the Angular lifecycle.
/**
* @param {?} changes
* @return {?}
*/
CdkFooterRowDef.prototype.ngOnChanges =
// Prerender fails to recognize that ngOnChanges in a part of this class through inheritance.
// Explicitly define it so that the method is called as part of the Angular lifecycle.
/**
* @param {?} changes
* @return {?}
*/
function (changes) {
_super.prototype.ngOnChanges.call(this, changes);
};
CdkFooterRowDef.decorators = [
{ type: Directive, args: [{
selector: '[cdkFooterRowDef]',
inputs: ['columns: cdkFooterRowDef', 'sticky: cdkFooterRowDefSticky'],
},] },
];
/** @nocollapse */
CdkFooterRowDef.ctorParameters = function () { return [
{ type: TemplateRef },
{ type: IterableDiffers }
]; };
return CdkFooterRowDef;
}(_CdkFooterRowDefBase));
/**
* Data row definition for the CDK table.
* Captures the header row's template and other row properties such as the columns to display and
* a when predicate that describes when this row should be used.
* @template T
*/
var CdkRowDef = /** @class */ (function (_super) {
__extends(CdkRowDef, _super);
// TODO(andrewseguin): Add an input for providing a switch function to determine
// if this template should be used.
function CdkRowDef(template, _differs) {
return _super.call(this, template, _differs) || this;
}
CdkRowDef.decorators = [
{ type: Directive, args: [{
selector: '[cdkRowDef]',
inputs: ['columns: cdkRowDefColumns', 'when: cdkRowDefWhen'],
},] },
];
/** @nocollapse */
CdkRowDef.ctorParameters = function () { return [
{ type: TemplateRef },
{ type: IterableDiffers }
]; };
return CdkRowDef;
}(BaseRowDef));
/**
* Outlet for rendering cells inside of a row or header row.
* \@docs-private
*/
var CdkCellOutlet = /** @class */ (function () {
function CdkCellOutlet(_viewContainer) {
this._viewContainer = _viewContainer;
CdkCellOutlet.mostRecentCellOutlet = this;
}
/**
* @return {?}
*/
CdkCellOutlet.prototype.ngOnDestroy = /**
* @return {?}
*/
function () {
// If this was the last outlet being rendered in the view, remove the reference
// from the static property after it has been destroyed to avoid leaking memory.
if (CdkCellOutlet.mostRecentCellOutlet === this) {
CdkCellOutlet.mostRecentCellOutlet = null;
}
};
/**
* Static property containing the latest constructed instance of this class.
* Used by the CDK table when each CdkHeaderRow and CdkRow component is created using
* createEmbeddedView. After one of these components are created, this property will provide
* a handle to provide that component's cells and context. After init, the CdkCellOutlet will
* construct the cells with the provided context.
*/
CdkCellOutlet.mostRecentCellOutlet = null;
CdkCellOutlet.decorators = [
{ type: Directive, args: [{ selector: '[cdkCellOutlet]' },] },
];
/** @nocollapse */
CdkCellOutlet.ctorParameters = function () { return [
{ type: ViewContainerRef }
]; };
return CdkCellOutlet;
}());
/**
* Header template container that contains the cell outlet. Adds the right class and role.
*/
var CdkHeaderRow = /** @class */ (function () {
function CdkHeaderRow() {
}
CdkHeaderRow.decorators = [
{ type: Component, args: [{selector: 'cdk-header-row, tr[cdk-header-row]',
template: CDK_ROW_TEMPLATE,
host: {
'class': 'cdk-header-row',
'role': 'row',
},
// See note on CdkTable for explanation on why this uses the default change detection strategy.
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.None,
},] },
];
return CdkHeaderRow;
}());
/**
* Footer template container that contains the cell outlet. Adds the right class and role.
*/
var CdkFooterRow = /** @class */ (function () {
function CdkFooterRow() {
}
CdkFooterRow.decorators = [
{ type: Component, args: [{selector: 'cdk-footer-row, tr[cdk-footer-row]',
template: CDK_ROW_TEMPLATE,
host: {
'class': 'cdk-footer-row',
'role': 'row',
},
// See note on CdkTable for explanation on why this uses the default change detection strategy.
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.None,
},] },
];
return CdkFooterRow;
}());
/**
* Data row template container that contains the cell outlet. Adds the right class and role.
*/
var CdkRow = /** @class */ (function () {
function CdkRow() {
}
CdkRow.decorators = [
{ type: Component, args: [{selector: 'cdk-row, tr[cdk-row]',
template: CDK_ROW_TEMPLATE,
host: {
'class': 'cdk-row',
'role': 'row',
},
// See note on CdkTable for explanation on why this uses the default change detection strategy.
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.None,
},] },
];
return CdkRow;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* List of all possible directions that can be used for sticky positioning.
* \@docs-private
* @type {?}
*/
var STICKY_DIRECTIONS = ['top', 'bottom', 'left', 'right'];
/**
* Applies and removes sticky positioning styles to the `CdkTable` rows and columns cells.
* \@docs-private
*/
var /**
* Applies and removes sticky positioning styles to the `CdkTable` rows and columns cells.
* \@docs-private
*/
StickyStyler = /** @class */ (function () {
/**
* @param _isNativeHtmlTable Whether the sticky logic should be based on a table
* that uses the native `<table>` element.
* @param _stickCellCss The CSS class that will be applied to every row/cell that has
* sticky positioning applied.
* @param direction The directionality context of the table (ltr/rtl); affects column positioning
* by reversing left/right positions.
* @param _isBrowser Whether the table is currently being rendered on the server or the client.
*/
function StickyStyler(_isNativeHtmlTable, _stickCellCss, direction, _isBrowser) {
if (_isBrowser === void 0) { _isBrowser = true; }
this._isNativeHtmlTable = _isNativeHtmlTable;
this._stickCellCss = _stickCellCss;
this.direction = direction;
this._isBrowser = _isBrowser;
}
/**
* Clears the sticky positioning styles from the row and its cells by resetting the `position`
* style, setting the zIndex to 0, and unsetting each provided sticky direction.
* @param rows The list of rows that should be cleared from sticking in the provided directions
* @param stickyDirections The directions that should no longer be set as sticky on the rows.
*/
/**
* Clears the sticky positioning styles from the row and its cells by resetting the `position`
* style, setting the zIndex to 0, and unsetting each provided sticky direction.
* @param {?} rows The list of rows that should be cleared from sticking in the provided directions
* @param {?} stickyDirections The directions that should no longer be set as sticky on the rows.
* @return {?}
*/
StickyStyler.prototype.clearStickyPositioning = /**
* Clears the sticky positioning styles from the row and its cells by resetting the `position`
* style, setting the zIndex to 0, and unsetting each provided sticky direction.
* @param {?} rows The list of rows that should be cleared from sticking in the provided directions
* @param {?} stickyDirections The directions that should no longer be set as sticky on the rows.
* @return {?}
*/
function (rows, stickyDirections) {
for (var _i = 0, rows_1 = rows; _i < rows_1.length; _i++) {
var row = rows_1[_i];
// If the row isn't an element (e.g. if it's an `ng-container`),
// it won't have inline styles or `children` so we skip it.
if (row.nodeType !== row.ELEMENT_NODE) {
continue;
}
this._removeStickyStyle(row, stickyDirections);
for (var i = 0; i < row.children.length; i++) {
/** @type {?} */
var cell = (/** @type {?} */ (row.children[i]));
this._removeStickyStyle(cell, stickyDirections);
}
}
};
/**
* Applies sticky left and right positions to the cells of each row according to the sticky
* states of the rendered column definitions.
* @param rows The rows that should have its set of cells stuck according to the sticky states.
* @param stickyStartStates A list of boolean states where each state represents whether the cell
* in this index position should be stuck to the start of the row.
* @param stickyEndStates A list of boolean states where each state represents whether the cell
* in this index position should be stuck to the end of the row.
*/
/**
* Applies sticky left and right positions to the cells of each row according to the sticky
* states of the rendered column definitions.
* @param {?} rows The rows that should have its set of cells stuck according to the sticky states.
* @param {?} stickyStartStates A list of boolean states where each state represents whether the cell
* in this index position should be stuck to the start of the row.
* @param {?} stickyEndStates A list of boolean states where each state represents whether the cell
* in this index position should be stuck to the end of the row.
* @return {?}
*/
StickyStyler.prototype.updateStickyColumns = /**
* Applies sticky left and right positions to the cells of each row according to the sticky
* states of the rendered column definitions.
* @param {?} rows The rows that should have its set of cells stuck according to the sticky states.
* @param {?} stickyStartStates A list of boolean states where each state represents whether the cell
* in this index position should be stuck to the start of the row.
* @param {?} stickyEndStates A list of boolean states where each state represents whether the cell
* in this index position should be stuck to the end of the row.
* @return {?}
*/
function (rows, stickyStartStates, stickyEndStates) {
/** @type {?} */
var hasStickyColumns = stickyStartStates.some((/**
* @param {?} state
* @return {?}
*/
function (state) { return state; })) || stickyEndStates.some((/**
* @param {?} state
* @return {?}
*/
function (state) { return state; }));
if (!rows.length || !hasStickyColumns || !this._isBrowser) {
return;
}
/** @type {?} */
var firstRow = rows[0];
/** @type {?} */
var numCells = firstRow.children.length;
/** @type {?} */
var cellWidths = this._getCellWidths(firstRow);
/** @type {?} */
var startPositions = this._getStickyStartColumnPositions(cellWidths, stickyStartStates);
/** @type {?} */
var endPositions = this._getStickyEndColumnPositions(cellWidths, stickyEndStates);
/** @type {?} */
var isRtl = this.direction === 'rtl';
for (var _i = 0, rows_2 = rows; _i < rows_2.length; _i++) {
var row = rows_2[_i];
for (var i = 0; i < numCells; i++) {
/** @type {?} */
var cell = (/** @type {?} */ (row.children[i]));
if (stickyStartStates[i]) {
this._addStickyStyle(cell, isRtl ? 'right' : 'left', startPositions[i]);
}
if (stickyEndStates[i]) {
this._addStickyStyle(cell, isRtl ? 'left' : 'right', endPositions[i]);
}
}
}
};
/**
* Applies sticky positioning to the row's cells if using the native table layout, and to the
* row itself otherwise.
* @param rowsToStick The list of rows that should be stuck according to their corresponding
* sticky state and to the provided top or bottom position.
* @param stickyStates A list of boolean states where each state represents whether the row
* should be stuck in the particular top or bottom position.
* @param position The position direction in which the row should be stuck if that row should be
* sticky.
*
*/
/**
* Applies sticky positioning to the row's cells if using the native table layout, and to the
* row itself otherwise.
* @param {?} rowsToStick The list of rows that should be stuck according to their corresponding
* sticky state and to the provided top or bottom position.
* @param {?} stickyStates A list of boolean states where each state represents whether the row
* should be stuck in the particular top or bottom position.
* @param {?} position The position direction in which the row should be stuck if that row should be
* sticky.
*
* @return {?}
*/
StickyStyler.prototype.stickRows = /**
* Applies sticky positioning to the row's cells if using the native table layout, and to the
* row itself otherwise.
* @param {?} rowsToStick The list of rows that should be stuck according to their corresponding
* sticky state and to the provided top or bottom position.
* @param {?} stickyStates A list of boolean states where each state represents whether the row
* should be stuck in the particular top or bottom position.
* @param {?} position The position direction in which the row should be stuck if that row should be
* sticky.
*
* @return {?}
*/
function (rowsToStick, stickyStates, position) {
// Since we can't measure the rows on the server, we can't stick the rows properly.
if (!this._isBrowser) {
return;
}
// If positioning the rows to the bottom, reverse their order when evaluating the sticky
// position such that the last row stuck will be "bottom: 0px" and so on.
/** @type {?} */
var rows = position === 'bottom' ? rowsToStick.reverse() : rowsToStick;
/** @type {?} */
var stickyHeight = 0;
for (var rowIndex = 0; rowIndex < rows.length; rowIndex++) {
if (!stickyStates[rowIndex]) {
continue;
}
/** @type {?} */
var row = rows[rowIndex];
if (this._isNativeHtmlTable) {
for (var j = 0; j < row.children.length; j++) {
/** @type {?} */
var cell = (/** @type {?} */ (row.children[j]));
this._addStickyStyle(cell, position, stickyHeight);
}
}
else {
// Flex does not respect the stick positioning on the cells, needs to be applied to the row.
// If this is applied on a native table, Safari causes the header to fly in wrong direction.
this._addStickyStyle(row, position, stickyHeight);
}
if (rowIndex === rows.length - 1) {
// prevent unnecessary reflow from getBoundingClientRect()
return;
}
stickyHeight += row.getBoundingClientRect().height;
}
};
/**
* When using the native table in Safari, sticky footer cells do not stick. The only way to stick
* footer rows is to apply sticky styling to the tfoot container. This should only be done if
* all footer rows are sticky. If not all footer rows are sticky, remove sticky positioning from
* the tfoot element.
*/
/**
* When using the native table in Safari, sticky footer cells do not stick. The only way to stick
* footer rows is to apply sticky styling to the tfoot container. This should only be done if
* all footer rows are sticky. If not all footer rows are sticky, remove sticky positioning from
* the tfoot element.
* @param {?} tableElement
* @param {?} stickyStates
* @return {?}
*/
StickyStyler.prototype.updateStickyFooterContainer = /**
* When using the native table in Safari, sticky footer cells do not stick. The only way to stick
* footer rows is to apply sticky styling to the tfoot container. This should only be done if
* all footer rows are sticky. If not all footer rows are sticky, remove sticky positioning from
* the tfoot element.
* @param {?} tableElement
* @param {?} stickyStates
* @return {?}
*/
function (tableElement, stickyStates) {
if (!this._isNativeHtmlTable) {
return;
}
/** @type {?} */
var tfoot = (/** @type {?} */ (tableElement.querySelector('tfoot')));
if (stickyStates.some((/**
* @param {?} state
* @return {?}
*/
function (state) { return !state; }))) {
this._removeStickyStyle(tfoot, ['bottom']);
}
else {
this._addStickyStyle(tfoot, 'bottom', 0);
}
};
/**
* Removes the sticky style on the element by removing the sticky cell CSS class, re-evaluating
* the zIndex, removing each of the provided sticky directions, and removing the
* sticky position if there are no more directions.
*/
/**
* Removes the sticky style on the element by removing the sticky cell CSS class, re-evaluating
* the zIndex, removing each of the provided sticky directions, and removing the
* sticky position if there are no more directions.
* @param {?} element
* @param {?} stickyDirections
* @return {?}
*/
StickyStyler.prototype._removeStickyStyle = /**
* Removes the sticky style on the element by removing the sticky cell CSS class, re-evaluating
* the zIndex, removing each of the provided sticky directions, and removing the
* sticky position if there are no more directions.
* @param {?} element
* @param {?} stickyDirections
* @return {?}
*/
function (element, stickyDirections) {
for (var _i = 0, stickyDirections_1 = stickyDirections; _i < stickyDirections_1.length; _i++) {
var dir = stickyDirections_1[_i];
element.style[dir] = '';
}
element.style.zIndex = this._getCalculatedZIndex(element);
// If the element no longer has any more sticky directions, remove sticky positioning and
// the sticky CSS class.
/** @type {?} */
var hasDirection = STICKY_DIRECTIONS.some((/**
* @param {?} dir
* @return {?}
*/
function (dir) { return !!element.style[dir]; }));
if (!hasDirection) {
element.style.position = '';
element.classList.remove(this._stickCellCss);
}
};
/**
* Adds the sticky styling to the element by adding the sticky style class, changing position
* to be sticky (and -webkit-sticky), setting the appropriate zIndex, and adding a sticky
* direction and value.
*/
/**
* Adds the sticky styling to the element by adding the sticky style class, changing position
* to be sticky (and -webkit-sticky), setting the appropriate zIndex, and adding a sticky
* direction and value.
* @param {?} element
* @param {?} dir
* @param {?} dirValue
* @return {?}
*/
StickyStyler.prototype._addStickyStyle = /**
* Adds the sticky styling to the element by adding the sticky style class, changing position
* to be sticky (and -webkit-sticky), setting the appropriate zIndex, and adding a sticky
* direction and value.
* @param {?} element
* @param {?} dir
* @param {?} dirValue
* @return {?}
*/
function (element, dir, dirValue) {
element.classList.add(this._stickCellCss);
element.style[dir] = dirValue + "px";
element.style.cssText += 'position: -webkit-sticky; position: sticky; ';
element.style.zIndex = this._getCalculatedZIndex(element);
};
/**
* Calculate what the z-index should be for the element, depending on what directions (top,
* bottom, left, right) have been set. It should be true that elements with a top direction
* should have the highest index since these are elements like a table header. If any of those
* elements are also sticky in another direction, then they should appear above other elements
* that are only sticky top (e.g. a sticky column on a sticky header). Bottom-sticky elements
* (e.g. footer rows) should then be next in the ordering such that they are below the header
* but above any non-sticky elements. Finally, left/right sticky elements (e.g. sticky columns)
* should minimally increment so that they are above non-sticky elements but below top and bottom
* elements.
*/
/**
* Calculate what the z-index should be for the element, depending on what directions (top,
* bottom, left, right) have been set. It should be true that elements with a top direction
* should have the highest index since these are elements like a table header. If any of those
* elements are also sticky in another direction, then they should appear above other elements
* that are only sticky top (e.g. a sticky column on a sticky header). Bottom-sticky elements
* (e.g. footer rows) should then be next in the ordering such that they are below the header
* but above any non-sticky elements. Finally, left/right sticky elements (e.g. sticky columns)
* should minimally increment so that they are above non-sticky elements but below top and bottom
* elements.
* @param {?} element
* @return {?}
*/
StickyStyler.prototype._getCalculatedZIndex = /**
* Calculate what the z-index should be for the element, depending on what directions (top,
* bottom, left, right) have been set. It should be true that elements with a top direction
* should have the highest index since these are elements like a table header. If any of those
* elements are also sticky in another direction, then they should appear above other elements
* that are only sticky top (e.g. a sticky column on a sticky header). Bottom-sticky elements
* (e.g. footer rows) should then be next in the ordering such that they are below the header
* but above any non-sticky elements. Finally, left/right sticky elements (e.g. sticky columns)
* should minimally increment so that they are above non-sticky elements but below top and bottom
* elements.
* @param {?} element
* @return {?}
*/
function (element) {
/** @type {?} */
var zIndexIncrements = {
top: 100,
bottom: 10,
left: 1,
right: 1,
};
/** @type {?} */
var zIndex = 0;
for (var _i = 0, STICKY_DIRECTIONS_1 = STICKY_DIRECTIONS; _i < STICKY_DIRECTIONS_1.length; _i++) {
var dir = STICKY_DIRECTIONS_1[_i];
if (element.style[dir]) {
zIndex += zIndexIncrements[dir];
}
}
return zIndex ? "" + zIndex : '';
};
/** Gets the widths for each cell in the provided row. */
/**
* Gets the widths for each cell in the provided row.
* @param {?} row
* @return {?}
*/
StickyStyler.prototype._getCellWidths = /**
* Gets the widths for each cell in the provided row.
* @param {?} row
* @return {?}
*/
function (row) {
/** @type {?} */
var cellWidths = [];
/** @type {?} */
var firstRowCells = row.children;
for (var i = 0; i < firstRowCells.length; i++) {
/** @type {?} */
var cell = (/** @type {?} */ (firstRowCells[i]));
cellWidths.push(cell.getBoundingClientRect().width);
}
return cellWidths;
};
/**
* Determines the left and right positions of each sticky column cell, which will be the
* accumulation of all sticky column cell widths to the left and right, respectively.
* Non-sticky cells do not need to have a value set since their positions will not be applied.
*/
/**
* Determines the left and right positions of each sticky column cell, which will be the
* accumulation of all sticky column cell widths to the left and right, respectively.
* Non-sticky cells do not need to have a value set since their positions will not be applied.
* @param {?} widths
* @param {?} stickyStates
* @return {?}
*/
StickyStyler.prototype._getStickyStartColumnPositions = /**
* Determines the left and right positions of each sticky column cell, which will be the
* accumulation of all sticky column cell widths to the left and right, respectively.
* Non-sticky cells do not need to have a value set since their positions will not be applied.
* @param {?} widths
* @param {?} stickyStates
* @return {?}
*/
function (widths, stickyStates) {
/** @type {?} */
var positions = [];
/** @type {?} */
var nextPosition = 0;
for (var i = 0; i < widths.length; i++) {
if (stickyStates[i]) {
positions[i] = nextPosition;
nextPosition += widths[i];
}
}
return positions;
};
/**
* Determines the left and right positions of each sticky column cell, which will be the
* accumulation of all sticky column cell widths to the left and right, respectively.
* Non-sticky cells do not need to have a value set since their positions will not be applied.
*/
/**
* Determines the left and right positions of each sticky column cell, which will be the
* accumulation of all sticky column cell widths to the left and right, respectively.
* Non-sticky cells do not need to have a value set since their positions will not be applied.
* @param {?} widths
* @param {?} stickyStates
* @return {?}
*/
StickyStyler.prototype._getStickyEndColumnPositions = /**
* Determines the left and right positions of each sticky column cell, which will be the
* accumulation of all sticky column cell widths to the left and right, respectively.
* Non-sticky cells do not need to have a value set since their positions will not be applied.
* @param {?} widths
* @param {?} stickyStates
* @return {?}
*/
function (widths, stickyStates) {
/** @type {?} */
var positions = [];
/** @type {?} */
var nextPosition = 0;
for (var i = widths.length; i > 0; i--) {
if (stickyStates[i]) {
positions[i] = nextPosition;
nextPosition += widths[i];
}
}
return positions;
};
return StickyStyler;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Returns an error to be thrown when attempting to find an unexisting column.
* \@docs-private
* @param {?} id Id whose lookup failed.
* @return {?}
*/
function getTableUnknownColumnError(id) {
return Error("Could not find column with id \"" + id + "\".");
}
/**
* Returns an error to be thrown when two column definitions have the same name.
* \@docs-private
* @param {?} name
* @return {?}
*/
function getTableDuplicateColumnNameError(name) {
return Error("Duplicate column definition name provided: \"" + name + "\".");
}
/**
* Returns an error to be thrown when there are multiple rows that are missing a when function.
* \@docs-private
* @return {?}
*/
function getTableMultipleDefaultRowDefsError() {
return Error("There can only be one default row without a when predicate function.");
}
/**
* Returns an error to be thrown when there are no matching row defs for a particular set of data.
* \@docs-private
* @param {?} data
* @return {?}
*/
function getTableMissingMatchingRowDefError(data) {
return Error("Could not find a matching row definition for the" +
("provided row data: " + JSON.stringify(data)));
}
/**
* Returns an error to be thrown when there is no row definitions present in the content.
* \@docs-private
* @return {?}
*/
function getTableMissingRowDefsError() {
return Error('Missing definitions for header, footer, and row; ' +
'cannot determine which columns should be rendered.');
}
/**
* Returns an error to be thrown when the data source does not match the compatible types.
* \@docs-private
* @return {?}
*/
function getTableUnknownDataSourceError() {
return Error("Provided data source did not match an array, Observable, or DataSource");
}
/**
* Returns an error to be thrown when the text column cannot find a parent table to inject.
* \@docs-private
* @return {?}
*/
function getTableTextColumnMissingParentTableError() {
return Error("Text column could not find a parent table for registration.");
}
/**
* Returns an error to be thrown when a table text column doesn't have a name.
* \@docs-private
* @return {?}
*/
function getTableTextColumnMissingNameError() {
return Error("Table text column must have a name.");
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Provides a handle for the table to grab the view container's ng-container to insert data rows.
* \@docs-private
*/
var DataRowOutlet = /** @class */ (function () {
function DataRowOutlet(viewContainer, elementRef) {
this.viewContainer = viewContainer;
this.elementRef = elementRef;
}
DataRowOutlet.decorators = [
{ type: Directive, args: [{ selector: '[rowOutlet]' },] },
];
/** @nocollapse */
DataRowOutlet.ctorParameters = function () { return [
{ type: ViewContainerRef },
{ type: ElementRef }
]; };
return DataRowOutlet;
}());
/**
* Provides a handle for the table to grab the view container's ng-container to insert the header.
* \@docs-private
*/
var HeaderRowOutlet = /** @class */ (function () {
function HeaderRowOutlet(viewContainer, elementRef) {
this.viewContainer = viewContainer;
this.elementRef = elementRef;
}
HeaderRowOutlet.decorators = [
{ type: Directive, args: [{ selector: '[headerRowOutlet]' },] },
];
/** @nocollapse */
HeaderRowOutlet.ctorParameters = function () { return [
{ type: ViewContainerRef },
{ type: ElementRef }
]; };
return HeaderRowOutlet;
}());
/**
* Provides a handle for the table to grab the view container's ng-container to insert the footer.
* \@docs-private
*/
var FooterRowOutlet = /** @class */ (function () {
function FooterRowOutlet(viewContainer, elementRef) {
this.viewContainer = viewContainer;
this.elementRef = elementRef;
}
FooterRowOutlet.decorators = [
{ type: Directive, args: [{ selector: '[footerRowOutlet]' },] },
];
/** @nocollapse */
FooterRowOutlet.ctorParameters = function () { return [
{ type: ViewContainerRef },
{ type: ElementRef }
]; };
return FooterRowOutlet;
}());
/**
* The table template that can be used by the mat-table. Should not be used outside of the
* material library.
* \@docs-private
* @type {?}
*/
var CDK_TABLE_TEMPLATE =
// Note that according to MDN, the `caption` element has to be projected as the **first**
// element in the table. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption
"\n <ng-content select=\"caption\"></ng-content>\n <ng-container headerRowOutlet></ng-container>\n <ng-container rowOutlet></ng-container>\n <ng-container footerRowOutlet></ng-container>\n";
/**
* Class used to conveniently type the embedded view ref for rows with a context.
* \@docs-private
* @abstract
* @template T
*/
var /**
* Class used to conveniently type the embedded view ref for rows with a context.
* \@docs-private
* @abstract
* @template T
*/
RowViewRef = /** @class */ (function (_super) {
__extends(RowViewRef, _super);
function RowViewRef() {
return _super !== null && _super.apply(this, arguments) || this;
}
return RowViewRef;
}(EmbeddedViewRef));
/**
* A data table that can render a header row, data rows, and a footer row.
* Uses the dataSource input to determine the data to be rendered. The data can be provided either
* as a data array, an Observable stream that emits the data array to render, or a DataSource with a
* connect function that will return an Observable stream that emits the data array to render.
* @template T
*/
var CdkTable = /** @class */ (function () {
function CdkTable(_differs, _changeDetectorRef, _elementRef, role, _dir, _document, _platform) {
this._differs = _differs;
this._changeDetectorRef = _changeDetectorRef;
this._elementRef = _elementRef;
this._dir = _dir;
this._platform = _platform;
/**
* Subject that emits when the component has been destroyed.
*/
this._onDestroy = new Subject();
/**
* Map of all the user's defined columns (header, data, and footer cell template) identified by
* name. Collection populated by the column definitions gathered by `ContentChildren` as well as
* any custom column definitions added to `_customColumnDefs`.
*/
this._columnDefsByName = new Map();
/**
* Column definitions that were defined outside of the direct content children of the table.
* These will be defined when, e.g., creating a wrapper around the cdkTable that has
* column definitions as *its* content child.
*/
this._customColumnDefs = new Set();
/**
* Data row definitions that were defined outside of the direct content children of the table.
* These will be defined when, e.g., creating a wrapper around the cdkTable that has
* built-in data rows as *its* content child.
*/
this._customRowDefs = new Set();
/**
* Header row definitions that were defined outside of the direct content children of the table.
* These will be defined when, e.g., creating a wrapper around the cdkTable that has
* built-in header rows as *its* content child.
*/
this._customHeaderRowDefs = new Set();
/**
* Footer row definitions that were defined outside of the direct content children of the table.
* These will be defined when, e.g., creating a wrapper around the cdkTable that has a
* built-in footer row as *its* content child.
*/
this._customFooterRowDefs = new Set();
/**
* Whether the header row definition has been changed. Triggers an update to the header row after
* content is checked. Initialized as true so that the table renders the initial set of rows.
*/
this._headerRowDefChanged = true;
/**
* Whether the footer row definition has been changed. Triggers an update to the footer row after
* content is checked. Initialized as true so that the table renders the initial set of rows.
*/
this._footerRowDefChanged = true;
/**
* Cache of the latest rendered `RenderRow` objects as a map for easy retrieval when constructing
* a new list of `RenderRow` objects for rendering rows. Since the new list is constructed with
* the cached `RenderRow` objects when possible, the row identity is preserved when the data
* and row template matches, which allows the `IterableDiffer` to check rows by reference
* and understand which rows are added/moved/removed.
*
* Implemented as a map of maps where the first key is the `data: T` object and the second is the
* `CdkRowDef<T>` object. With the two keys, the cache points to a `RenderRow<T>` object that
* contains an array of created pairs. The array is necessary to handle cases where the data
* array contains multiple duplicate data objects and each instantiated `RenderRow` must be
* stored.
*/
this._cachedRenderRowsMap = new Map();
/**
* CSS class added to any row or cell that has sticky positioning applied. May be overriden by
* table subclasses.
*/
this.stickyCssClass = 'cdk-table-sticky';
this._multiTemplateDataRows = false;
// TODO(andrewseguin): Remove max value as the end index
// and instead calculate the view on init and scroll.
/**
* Stream containing the latest information on what rows are being displayed on screen.
* Can be used by the data source to as a heuristic of what data should be provided.
*
* \@docs-private
*/
this.viewChange = new BehaviorSubject({ start: 0, end: Number.MAX_VALUE });
if (!role) {
this._elementRef.nativeElement.setAttribute('role', 'grid');
}
this._document = _document;
this._isNativeHtmlTable = this._elementRef.nativeElement.nodeName === 'TABLE';
}
Object.defineProperty(CdkTable.prototype, "trackBy", {
/**
* Tracking function that will be used to check the differences in data changes. Used similarly
* to `ngFor` `trackBy` function. Optimize row operations by identifying a row based on its data
* relative to the function to know if a row should be added/removed/moved.
* Accepts a function that takes two parameters, `index` and `item`.
*/
get: /**
* Tracking function that will be used to check the differences in data changes. Used similarly
* to `ngFor` `trackBy` function. Optimize row operations by identifying a row based on its data
* relative to the function to know if a row should be added/removed/moved.
* Accepts a function that takes two parameters, `index` and `item`.
* @return {?}
*/
function () {
return this._trackByFn;
},
set: /**
* @param {?} fn
* @return {?}
*/
function (fn) {
if (isDevMode() && fn != null && typeof fn !== 'function' && (/** @type {?} */ (console)) &&
(/** @type {?} */ (console.warn))) {
console.warn("trackBy must be a function, but received " + JSON.stringify(fn) + ".");
}
this._trackByFn = fn;
},
enumerable: true,
configurable: true
});
Object.defineProperty(CdkTable.prototype, "dataSource", {
/**
* The table's source of data, which can be provided in three ways (in order of complexity):
* - Simple data array (each object represents one table row)
* - Stream that emits a data array each time the array changes
* - `DataSource` object that implements the connect/disconnect interface.
*
* If a data array is provided, the table must be notified when the array's objects are
* added, removed, or moved. This can be done by calling the `renderRows()` function which will
* render the diff since the last table render. If the data array reference is changed, the table
* will automatically trigger an update to the rows.
*
* When providing an Observable stream, the table will trigger an update automatically when the
* stream emits a new array of data.
*
* Finally, when providing a `DataSource` object, the table will use the Observable stream
* provided by the connect function and trigger updates when that stream emits new data array
* values. During the table's ngOnDestroy or when the data source is removed from the table, the
* table will call the DataSource's `disconnect` function (may be useful for cleaning up any
* subscriptions registered during the connect process).
*/
get: /**
* The table's source of data, which can be provided in three ways (in order of complexity):
* - Simple data array (each object represents one table row)
* - Stream that emits a data array each time the array changes
* - `DataSource` object that implements the connect/disconnect interface.
*
* If a data array is provided, the table must be notified when the array's objects are
* added, removed, or moved. This can be done by calling the `renderRows()` function which will
* render the diff since the last table render. If the data array reference is changed, the table
* will automatically trigger an update to the rows.
*
* When providing an Observable stream, the table will trigger an update automatically when the
* stream emits a new array of data.
*
* Finally, when providing a `DataSource` object, the table will use the Observable stream
* provided by the connect function and trigger updates when that stream emits new data array
* values. During the table's ngOnDestroy or when the data source is removed from the table, the
* table will call the DataSource's `disconnect` function (may be useful for cleaning up any
* subscriptions registered during the connect process).
* @return {?}
*/
function () {
return this._dataSource;
},
set: /**
* @param {?} dataSource
* @return {?}
*/
function (dataSource) {
if (this._dataSource !== dataSource) {
this._switchDataSource(dataSource);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(CdkTable.prototype, "multiTemplateDataRows", {
/**
* Whether to allow multiple rows per data object by evaluating which rows evaluate their 'when'
* predicate to true. If `multiTemplateDataRows` is false, which is the default value, then each
* dataobject will render the first row that evaluates its when predicate to true, in the order
* defined in the table, or otherwise the default row which does not have a when predicate.
*/
get: /**
* Whether to allow multiple rows per data object by evaluating which rows evaluate their 'when'
* predicate to true. If `multiTemplateDataRows` is false, which is the default value, then each
* dataobject will render the first row that evaluates its when predicate to true, in the order
* defined in the table, or otherwise the default row which does not have a when predicate.
* @return {?}
*/
function () {
return this._multiTemplateDataRows;
},
set: /**
* @param {?} v
* @return {?}
*/
function (v) {
this._multiTemplateDataRows = coerceBooleanProperty(v);
// In Ivy if this value is set via a static attribute (e.g. <table multiTemplateDataRows>),
// this setter will be invoked before the row outlet has been defined hence the null check.
if (this._rowOutlet && this._rowOutlet.viewContainer.length) {
this._forceRenderDataRows();
}
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
CdkTable.prototype.ngOnInit = /**
* @return {?}
*/
function () {
var _this = this;
this._setupStickyStyler();
if (this._isNativeHtmlTable) {
this._applyNativeTableSections();
}
// Set up the trackBy function so that it uses the `RenderRow` as its identity by default. If
// the user has provided a custom trackBy, return the result of that function as evaluated
// with the values of the `RenderRow`'s data and index.
this._dataDiffer = this._differs.find([]).create((/**
* @param {?} _i
* @param {?} dataRow
* @return {?}
*/
function (_i, dataRow) {
return _this.trackBy ? _this.trackBy(dataRow.dataIndex, dataRow.data) : dataRow;
}));
};
/**
* @return {?}
*/
CdkTable.prototype.ngAfterContentChecked = /**
* @return {?}
*/
function () {
// Cache the row and column definitions gathered by ContentChildren and programmatic injection.
this._cacheRowDefs();
this._cacheColumnDefs();
// Make sure that the user has at least added header, footer, or data row def.
if (!this._headerRowDefs.length && !this._footerRowDefs.length && !this._rowDefs.length) {
throw getTableMissingRowDefsError();
}
// Render updates if the list of columns have been changed for the header, row, or footer defs.
this._renderUpdatedColumns();
// If the header row definition has been changed, trigger a render to the header row.
if (this._headerRowDefChanged) {
this._forceRenderHeaderRows();
this._headerRowDefChanged = false;
}
// If the footer row definition has been changed, trigger a render to the footer row.
if (this._footerRowDefChanged) {
this._forceRenderFooterRows();
this._footerRowDefChanged = false;
}
// If there is a data source and row definitions, connect to the data source unless a
// connection has already been made.
if (this.dataSource && this._rowDefs.length > 0 && !this._renderChangeSubscription) {
this._observeRenderChanges();
}
this._checkStickyStates();
};
/**
* @return {?}
*/
CdkTable.prototype.ngOnDestroy = /**
* @return {?}
*/
function () {
this._rowOutlet.viewContainer.clear();
this._headerRowOutlet.viewContainer.clear();
this._footerRowOutlet.viewContainer.clear();
this._cachedRenderRowsMap.clear();
this._onDestroy.next();
this._onDestroy.complete();
if (isDataSource(this.dataSource)) {
this.dataSource.disconnect(this);
}
};
/**
* Renders rows based on the table's latest set of data, which was either provided directly as an
* input or retrieved through an Observable stream (directly or from a DataSource).
* Checks for differences in the data since the last diff to perform only the necessary
* changes (add/remove/move rows).
*
* If the table's data source is a DataSource or Observable, this will be invoked automatically
* each time the provided Observable stream emits a new data array. Otherwise if your data is
* an array, this function will need to be called to render any changes.
*/
/**
* Renders rows based on the table's latest set of data, which was either provided directly as an
* input or retrieved through an Observable stream (directly or from a DataSource).
* Checks for differences in the data since the last diff to perform only the necessary
* changes (add/remove/move rows).
*
* If the table's data source is a DataSource or Observable, this will be invoked automatically
* each time the provided Observable stream emits a new data array. Otherwise if your data is
* an array, this function will need to be called to render any changes.
* @return {?}
*/
CdkTable.prototype.renderRows = /**
* Renders rows based on the table's latest set of data, which was either provided directly as an
* input or retrieved through an Observable stream (directly or from a DataSource).
* Checks for differences in the data since the last diff to perform only the necessary
* changes (add/remove/move rows).
*
* If the table's data source is a DataSource or Observable, this will be invoked automatically
* each time the provided Observable stream emits a new data array. Otherwise if your data is
* an array, this function will need to be called to render any changes.
* @return {?}
*/
function () {
var _this = this;
this._renderRows = this._getAllRenderRows();
/** @type {?} */
var changes = this._dataDiffer.diff(this._renderRows);
if (!changes) {
return;
}
/** @type {?} */
var viewContainer = this._rowOutlet.viewContainer;
changes.forEachOperation((/**
* @param {?} record
* @param {?} prevIndex
* @param {?} currentIndex
* @return {?}
*/
function (record, prevIndex, currentIndex) {
if (record.previousIndex == null) {
_this._insertRow(record.item, (/** @type {?} */ (currentIndex)));
}
else if (currentIndex == null) {
viewContainer.remove((/** @type {?} */ (prevIndex)));
}
else {
/** @type {?} */
var view = (/** @type {?} */ (viewContainer.get((/** @type {?} */ (prevIndex)))));
viewContainer.move((/** @type {?} */ (view)), currentIndex);
}
}));
// Update the meta context of a row's context data (index, count, first, last, ...)
this._updateRowIndexContext();
// Update rows that did not get added/removed/moved but may have had their identity changed,
// e.g. if trackBy matched data on some property but the actual data reference changed.
changes.forEachIdentityChange((/**
* @param {?} record
* @return {?}
*/
function (record) {
/** @type {?} */
var rowView = (/** @type {?} */ (viewContainer.get((/** @type {?} */ (record.currentIndex)))));
rowView.context.$implicit = record.item.data;
}));
this.updateStickyColumnStyles();
};
/**
* Sets the header row definition to be used. Overrides the header row definition gathered by
* using `ContentChild`, if one exists. Sets a flag that will re-render the header row after the
* table's content is checked.
* @docs-private
* @deprecated Use `addHeaderRowDef` and `removeHeaderRowDef` instead
* @breaking-change 8.0.0
*/
/**
* Sets the header row definition to be used. Overrides the header row definition gathered by
* using `ContentChild`, if one exists. Sets a flag that will re-render the header row after the
* table's content is checked.
* \@docs-private
* @deprecated Use `addHeaderRowDef` and `removeHeaderRowDef` instead
* \@breaking-change 8.0.0
* @param {?} headerRowDef
* @return {?}
*/
CdkTable.prototype.setHeaderRowDef = /**
* Sets the header row definition to be used. Overrides the header row definition gathered by
* using `ContentChild`, if one exists. Sets a flag that will re-render the header row after the
* table's content is checked.
* \@docs-private
* @deprecated Use `addHeaderRowDef` and `removeHeaderRowDef` instead
* \@breaking-change 8.0.0
* @param {?} headerRowDef
* @return {?}
*/
function (headerRowDef) {
this._customHeaderRowDefs = new Set([headerRowDef]);
this._headerRowDefChanged = true;
};
/**
* Sets the footer row definition to be used. Overrides the footer row definition gathered by
* using `ContentChild`, if one exists. Sets a flag that will re-render the footer row after the
* table's content is checked.
* @docs-private
* @deprecated Use `addFooterRowDef` and `removeFooterRowDef` instead
* @breaking-change 8.0.0
*/
/**
* Sets the footer row definition to be used. Overrides the footer row definition gathered by
* using `ContentChild`, if one exists. Sets a flag that will re-render the footer row after the
* table's content is checked.
* \@docs-private
* @deprecated Use `addFooterRowDef` and `removeFooterRowDef` instead
* \@breaking-change 8.0.0
* @param {?} footerRowDef
* @return {?}
*/
CdkTable.prototype.setFooterRowDef = /**
* Sets the footer row definition to be used. Overrides the footer row definition gathered by
* using `ContentChild`, if one exists. Sets a flag that will re-render the footer row after the
* table's content is checked.
* \@docs-private
* @deprecated Use `addFooterRowDef` and `removeFooterRowDef` instead
* \@breaking-change 8.0.0
* @param {?} footerRowDef
* @return {?}
*/
function (footerRowDef) {
this._customFooterRowDefs = new Set([footerRowDef]);
this._footerRowDefChanged = true;
};
/** Adds a column definition that was not included as part of the content children. */
/**
* Adds a column definition that was not included as part of the content children.
* @param {?} columnDef
* @return {?}
*/
CdkTable.prototype.addColumnDef = /**
* Adds a column definition that was not included as part of the content children.
* @param {?} columnDef
* @return {?}
*/
function (columnDef) {
this._customColumnDefs.add(columnDef);
};
/** Removes a column definition that was not included as part of the content children. */
/**
* Removes a column definition that was not included as part of the content children.
* @param {?} columnDef
* @return {?}
*/
CdkTable.prototype.removeColumnDef = /**
* Removes a column definition that was not included as part of the content children.
* @param {?} columnDef
* @return {?}
*/
function (columnDef) {
this._customColumnDefs.delete(columnDef);
};
/** Adds a row definition that was not included as part of the content children. */
/**
* Adds a row definition that was not included as part of the content children.
* @param {?} rowDef
* @return {?}
*/
CdkTable.prototype.addRowDef = /**
* Adds a row definition that was not included as part of the content children.
* @param {?} rowDef
* @return {?}
*/
function (rowDef) {
this._customRowDefs.add(rowDef);
};
/** Removes a row definition that was not included as part of the content children. */
/**
* Removes a row definition that was not included as part of the content children.
* @param {?} rowDef
* @return {?}
*/
CdkTable.prototype.removeRowDef = /**
* Removes a row definition that was not included as part of the content children.
* @param {?} rowDef
* @return {?}
*/
function (rowDef) {
this._customRowDefs.delete(rowDef);
};
/** Adds a header row definition that was not included as part of the content children. */
/**
* Adds a header row definition that was not included as part of the content children.
* @param {?} headerRowDef
* @return {?}
*/
CdkTable.prototype.addHeaderRowDef = /**
* Adds a header row definition that was not included as part of the content children.
* @param {?} headerRowDef
* @return {?}
*/
function (headerRowDef) {
this._customHeaderRowDefs.add(headerRowDef);
this._headerRowDefChanged = true;
};
/** Removes a header row definition that was not included as part of the content children. */
/**
* Removes a header row definition that was not included as part of the content children.
* @param {?} headerRowDef
* @return {?}
*/
CdkTable.prototype.removeHeaderRowDef = /**
* Removes a header row definition that was not included as part of the content children.
* @param {?} headerRowDef
* @return {?}
*/
function (headerRowDef) {
this._customHeaderRowDefs.delete(headerRowDef);
this._headerRowDefChanged = true;
};
/** Adds a footer row definition that was not included as part of the content children. */
/**
* Adds a footer row definition that was not included as part of the content children.
* @param {?} footerRowDef
* @return {?}
*/
CdkTable.prototype.addFooterRowDef = /**
* Adds a footer row definition that was not included as part of the content children.
* @param {?} footerRowDef
* @return {?}
*/
function (footerRowDef) {
this._customFooterRowDefs.add(footerRowDef);
this._footerRowDefChanged = true;
};
/** Removes a footer row definition that was not included as part of the content children. */
/**
* Removes a footer row definition that was not included as part of the content children.
* @param {?} footerRowDef
* @return {?}
*/
CdkTable.prototype.removeFooterRowDef = /**
* Removes a footer row definition that was not included as part of the content children.
* @param {?} footerRowDef
* @return {?}
*/
function (footerRowDef) {
this._customFooterRowDefs.delete(footerRowDef);
this._footerRowDefChanged = true;
};
/**
* Updates the header sticky styles. First resets all applied styles with respect to the cells
* sticking to the top. Then, evaluating which cells need to be stuck to the top. This is
* automatically called when the header row changes its displayed set of columns, or if its
* sticky input changes. May be called manually for cases where the cell content changes outside
* of these events.
*/
/**
* Updates the header sticky styles. First resets all applied styles with respect to the cells
* sticking to the top. Then, evaluating which cells need to be stuck to the top. This is
* automatically called when the header row changes its displayed set of columns, or if its
* sticky input changes. May be called manually for cases where the cell content changes outside
* of these events.
* @return {?}
*/
CdkTable.prototype.updateStickyHeaderRowStyles = /**
* Updates the header sticky styles. First resets all applied styles with respect to the cells
* sticking to the top. Then, evaluating which cells need to be stuck to the top. This is
* automatically called when the header row changes its displayed set of columns, or if its
* sticky input changes. May be called manually for cases where the cell content changes outside
* of these events.
* @return {?}
*/
function () {
/** @type {?} */
var headerRows = this._getRenderedRows(this._headerRowOutlet);
/** @type {?} */
var tableElement = (/** @type {?} */ (this._elementRef.nativeElement));
// Hide the thead element if there are no header rows. This is necessary to satisfy
// overzealous a11y checkers that fail because the `rowgroup` element does not contain
// required child `row`.
/** @type {?} */
var thead = tableElement.querySelector('thead');
if (thead) {
thead.style.display = headerRows.length ? '' : 'none';
}
/** @type {?} */
var stickyStates = this._headerRowDefs.map((/**
* @param {?} def
* @return {?}
*/
function (def) { return def.sticky; }));
this._stickyStyler.clearStickyPositioning(headerRows, ['top']);
this._stickyStyler.stickRows(headerRows, stickyStates, 'top');
// Reset the dirty state of the sticky input change since it has been used.
this._headerRowDefs.forEach((/**
* @param {?} def
* @return {?}
*/
function (def) { return def.resetStickyChanged(); }));
};
/**
* Updates the footer sticky styles. First resets all applied styles with respect to the cells
* sticking to the bottom. Then, evaluating which cells need to be stuck to the bottom. This is
* automatically called when the footer row changes its displayed set of columns, or if its
* sticky input changes. May be called manually for cases where the cell content changes outside
* of these events.
*/
/**
* Updates the footer sticky styles. First resets all applied styles with respect to the cells
* sticking to the bottom. Then, evaluating which cells need to be stuck to the bottom. This is
* automatically called when the footer row changes its displayed set of columns, or if its
* sticky input changes. May be called manually for cases where the cell content changes outside
* of these events.
* @return {?}
*/
CdkTable.prototype.updateStickyFooterRowStyles = /**
* Updates the footer sticky styles. First resets all applied styles with respect to the cells
* sticking to the bottom. Then, evaluating which cells need to be stuck to the bottom. This is
* automatically called when the footer row changes its displayed set of columns, or if its
* sticky input changes. May be called manually for cases where the cell content changes outside
* of these events.
* @return {?}
*/
function () {
/** @type {?} */
var footerRows = this._getRenderedRows(this._footerRowOutlet);
/** @type {?} */
var tableElement = (/** @type {?} */ (this._elementRef.nativeElement));
// Hide the tfoot element if there are no footer rows. This is necessary to satisfy
// overzealous a11y checkers that fail because the `rowgroup` element does not contain
// required child `row`.
/** @type {?} */
var tfoot = tableElement.querySelector('tfoot');
if (tfoot) {
tfoot.style.display = footerRows.length ? '' : 'none';
}
/** @type {?} */
var stickyStates = this._footerRowDefs.map((/**
* @param {?} def
* @return {?}
*/
function (def) { return def.sticky; }));
this._stickyStyler.clearStickyPositioning(footerRows, ['bottom']);
this._stickyStyler.stickRows(footerRows, stickyStates, 'bottom');
this._stickyStyler.updateStickyFooterContainer(this._elementRef.nativeElement, stickyStates);
// Reset the dirty state of the sticky input change since it has been used.
this._footerRowDefs.forEach((/**
* @param {?} def
* @return {?}
*/
function (def) { return def.resetStickyChanged(); }));
};
/**
* Updates the column sticky styles. First resets all applied styles with respect to the cells
* sticking to the left and right. Then sticky styles are added for the left and right according
* to the column definitions for each cell in each row. This is automatically called when
* the data source provides a new set of data or when a column definition changes its sticky
* input. May be called manually for cases where the cell content changes outside of these events.
*/
/**
* Updates the column sticky styles. First resets all applied styles with respect to the cells
* sticking to the left and right. Then sticky styles are added for the left and right according
* to the column definitions for each cell in each row. This is automatically called when
* the data source provides a new set of data or when a column definition changes its sticky
* input. May be called manually for cases where the cell content changes outside of these events.
* @return {?}
*/
CdkTable.prototype.updateStickyColumnStyles = /**
* Updates the column sticky styles. First resets all applied styles with respect to the cells
* sticking to the left and right. Then sticky styles are added for the left and right according
* to the column definitions for each cell in each row. This is automatically called when
* the data source provides a new set of data or when a column definition changes its sticky
* input. May be called manually for cases where the cell content changes outside of these events.
* @return {?}
*/
function () {
var _this = this;
/** @type {?} */
var headerRows = this._getRenderedRows(this._headerRowOutlet);
/** @type {?} */
var dataRows = this._getRenderedRows(this._rowOutlet);
/** @type {?} */
var footerRows = this._getRenderedRows(this._footerRowOutlet);
// Clear the left and right positioning from all columns in the table across all rows since
// sticky columns span across all table sections (header, data, footer)
this._stickyStyler.clearStickyPositioning(headerRows.concat(dataRows, footerRows), ['left', 'right']);
// Update the sticky styles for each header row depending on the def's sticky state
headerRows.forEach((/**
* @param {?} headerRow
* @param {?} i
* @return {?}
*/
function (headerRow, i) {
_this._addStickyColumnStyles([headerRow], _this._headerRowDefs[i]);
}));
// Update the sticky styles for each data row depending on its def's sticky state
this._rowDefs.forEach((/**
* @param {?} rowDef
* @return {?}
*/
function (rowDef) {
// Collect all the rows rendered with this row definition.
/** @type {?} */
var rows = [];
for (var i = 0; i < dataRows.length; i++) {
if (_this._renderRows[i].rowDef === rowDef) {
rows.push(dataRows[i]);
}
}
_this._addStickyColumnStyles(rows, rowDef);
}));
// Update the sticky styles for each footer row depending on the def's sticky state
footerRows.forEach((/**
* @param {?} footerRow
* @param {?} i
* @return {?}
*/
function (footerRow, i) {
_this._addStickyColumnStyles([footerRow], _this._footerRowDefs[i]);
}));
// Reset the dirty state of the sticky input change since it has been used.
Array.from(this._columnDefsByName.values()).forEach((/**
* @param {?} def
* @return {?}
*/
function (def) { return def.resetStickyChanged(); }));
};
/**
* Get the list of RenderRow objects to render according to the current list of data and defined
* row definitions. If the previous list already contained a particular pair, it should be reused
* so that the differ equates their references.
*/
/**
* Get the list of RenderRow objects to render according to the current list of data and defined
* row definitions. If the previous list already contained a particular pair, it should be reused
* so that the differ equates their references.
* @private
* @return {?}
*/
CdkTable.prototype._getAllRenderRows = /**
* Get the list of RenderRow objects to render according to the current list of data and defined
* row definitions. If the previous list already contained a particular pair, it should be reused
* so that the differ equates their references.
* @private
* @return {?}
*/
function () {
/** @type {?} */
var renderRows = [];
// Store the cache and create a new one. Any re-used RenderRow objects will be moved into the
// new cache while unused ones can be picked up by garbage collection.
/** @type {?} */
var prevCachedRenderRows = this._cachedRenderRowsMap;
this._cachedRenderRowsMap = new Map();
// For each data object, get the list of rows that should be rendered, represented by the
// respective `RenderRow` object which is the pair of `data` and `CdkRowDef`.
for (var i = 0; i < this._data.length; i++) {
/** @type {?} */
var data = this._data[i];
/** @type {?} */
var renderRowsForData = this._getRenderRowsForData(data, i, prevCachedRenderRows.get(data));
if (!this._cachedRenderRowsMap.has(data)) {
this._cachedRenderRowsMap.set(data, new WeakMap());
}
for (var j = 0; j < renderRowsForData.length; j++) {
/** @type {?} */
var renderRow = renderRowsForData[j];
/** @type {?} */
var cache = (/** @type {?} */ (this._cachedRenderRowsMap.get(renderRow.data)));
if (cache.has(renderRow.rowDef)) {
(/** @type {?} */ (cache.get(renderRow.rowDef))).push(renderRow);
}
else {
cache.set(renderRow.rowDef, [renderRow]);
}
renderRows.push(renderRow);
}
}
return renderRows;
};
/**
* Gets a list of `RenderRow<T>` for the provided data object and any `CdkRowDef` objects that
* should be rendered for this data. Reuses the cached RenderRow objects if they match the same
* `(T, CdkRowDef)` pair.
*/
/**
* Gets a list of `RenderRow<T>` for the provided data object and any `CdkRowDef` objects that
* should be rendered for this data. Reuses the cached RenderRow objects if they match the same
* `(T, CdkRowDef)` pair.
* @private
* @param {?} data
* @param {?} dataIndex
* @param {?=} cache
* @return {?}
*/
CdkTable.prototype._getRenderRowsForData = /**
* Gets a list of `RenderRow<T>` for the provided data object and any `CdkRowDef` objects that
* should be rendered for this data. Reuses the cached RenderRow objects if they match the same
* `(T, CdkRowDef)` pair.
* @private
* @param {?} data
* @param {?} dataIndex
* @param {?=} cache
* @return {?}
*/
function (data, dataIndex, cache) {
/** @type {?} */
var rowDefs = this._getRowDefs(data, dataIndex);
return rowDefs.map((/**
* @param {?} rowDef
* @return {?}
*/
function (rowDef) {
/** @type {?} */
var cachedRenderRows = (cache && cache.has(rowDef)) ? (/** @type {?} */ (cache.get(rowDef))) : [];
if (cachedRenderRows.length) {
/** @type {?} */
var dataRow = (/** @type {?} */ (cachedRenderRows.shift()));
dataRow.dataIndex = dataIndex;
return dataRow;
}
else {
return { data: data, rowDef: rowDef, dataIndex: dataIndex };
}
}));
};
/** Update the map containing the content's column definitions. */
/**
* Update the map containing the content's column definitions.
* @private
* @return {?}
*/
CdkTable.prototype._cacheColumnDefs = /**
* Update the map containing the content's column definitions.
* @private
* @return {?}
*/
function () {
var _this = this;
this._columnDefsByName.clear();
/** @type {?} */
var columnDefs = mergeQueryListAndSet(this._contentColumnDefs, this._customColumnDefs);
columnDefs.forEach((/**
* @param {?} columnDef
* @return {?}
*/
function (columnDef) {
if (_this._columnDefsByName.has(columnDef.name)) {
throw getTableDuplicateColumnNameError(columnDef.name);
}
_this._columnDefsByName.set(columnDef.name, columnDef);
}));
};
/** Update the list of all available row definitions that can be used. */
/**
* Update the list of all available row definitions that can be used.
* @private
* @return {?}
*/
CdkTable.prototype._cacheRowDefs = /**
* Update the list of all available row definitions that can be used.
* @private
* @return {?}
*/
function () {
this._headerRowDefs =
mergeQueryListAndSet(this._contentHeaderRowDefs, this._customHeaderRowDefs);
this._footerRowDefs =
mergeQueryListAndSet(this._contentFooterRowDefs, this._customFooterRowDefs);
this._rowDefs = mergeQueryListAndSet(this._contentRowDefs, this._customRowDefs);
// After all row definitions are determined, find the row definition to be considered default.
/** @type {?} */
var defaultRowDefs = this._rowDefs.filter((/**
* @param {?} def
* @return {?}
*/
function (def) { return !def.when; }));
if (!this.multiTemplateDataRows && defaultRowDefs.length > 1) {
throw getTableMultipleDefaultRowDefsError();
}
this._defaultRowDef = defaultRowDefs[0];
};
/**
* Check if the header, data, or footer rows have changed what columns they want to display or
* whether the sticky states have changed for the header or footer. If there is a diff, then
* re-render that section.
*/
/**
* Check if the header, data, or footer rows have changed what columns they want to display or
* whether the sticky states have changed for the header or footer. If there is a diff, then
* re-render that section.
* @private
* @return {?}
*/
CdkTable.prototype._renderUpdatedColumns = /**
* Check if the header, data, or footer rows have changed what columns they want to display or
* whether the sticky states have changed for the header or footer. If there is a diff, then
* re-render that section.
* @private
* @return {?}
*/
function () {
/** @type {?} */
var columnsDiffReducer = (/**
* @param {?} acc
* @param {?} def
* @return {?}
*/
function (acc, def) { return acc || !!def.getColumnsDiff(); });
// Force re-render data rows if the list of column definitions have changed.
if (this._rowDefs.reduce(columnsDiffReducer, false)) {
this._forceRenderDataRows();
}
// Force re-render header/footer rows if the list of column definitions have changed..
if (this._headerRowDefs.reduce(columnsDiffReducer, false)) {
this._forceRenderHeaderRows();
}
if (this._footerRowDefs.reduce(columnsDiffReducer, false)) {
this._forceRenderFooterRows();
}
};
/**
* Switch to the provided data source by resetting the data and unsubscribing from the current
* render change subscription if one exists. If the data source is null, interpret this by
* clearing the row outlet. Otherwise start listening for new data.
*/
/**
* Switch to the provided data source by resetting the data and unsubscribing from the current
* render change subscription if one exists. If the data source is null, interpret this by
* clearing the row outlet. Otherwise start listening for new data.
* @private
* @param {?} dataSource
* @return {?}
*/
CdkTable.prototype._switchDataSource = /**
* Switch to the provided data source by resetting the data and unsubscribing from the current
* render change subscription if one exists. If the data source is null, interpret this by
* clearing the row outlet. Otherwise start listening for new data.
* @private
* @param {?} dataSource
* @return {?}
*/
function (dataSource) {
this._data = [];
if (isDataSource(this.dataSource)) {
this.dataSource.disconnect(this);
}
// Stop listening for data from the previous data source.
if (this._renderChangeSubscription) {
this._renderChangeSubscription.unsubscribe();
this._renderChangeSubscription = null;
}
if (!dataSource) {
if (this._dataDiffer) {
this._dataDiffer.diff([]);
}
this._rowOutlet.viewContainer.clear();
}
this._dataSource = dataSource;
};
/** Set up a subscription for the data provided by the data source. */
/**
* Set up a subscription for the data provided by the data source.
* @private
* @return {?}
*/
CdkTable.prototype._observeRenderChanges = /**
* Set up a subscription for the data provided by the data source.
* @private
* @return {?}
*/
function () {
var _this = this;
// If no data source has been set, there is nothing to observe for changes.
if (!this.dataSource) {
return;
}
/** @type {?} */
var dataStream;
if (isDataSource(this.dataSource)) {
dataStream = this.dataSource.connect(this);
}
else if (this.dataSource instanceof Observable) {
dataStream = this.dataSource;
}
else if (Array.isArray(this.dataSource)) {
dataStream = of(this.dataSource);
}
if (dataStream === undefined) {
throw getTableUnknownDataSourceError();
}
this._renderChangeSubscription = dataStream.pipe(takeUntil(this._onDestroy)).subscribe((/**
* @param {?} data
* @return {?}
*/
function (data) {
_this._data = data || [];
_this.renderRows();
}));
};
/**
* Clears any existing content in the header row outlet and creates a new embedded view
* in the outlet using the header row definition.
*/
/**
* Clears any existing content in the header row outlet and creates a new embedded view
* in the outlet using the header row definition.
* @private
* @return {?}
*/
CdkTable.prototype._forceRenderHeaderRows = /**
* Clears any existing content in the header row outlet and creates a new embedded view
* in the outlet using the header row definition.
* @private
* @return {?}
*/
function () {
var _this = this;
// Clear the header row outlet if any content exists.
if (this._headerRowOutlet.viewContainer.length > 0) {
this._headerRowOutlet.viewContainer.clear();
}
this._headerRowDefs.forEach((/**
* @param {?} def
* @param {?} i
* @return {?}
*/
function (def, i) { return _this._renderRow(_this._headerRowOutlet, def, i); }));
this.updateStickyHeaderRowStyles();
this.updateStickyColumnStyles();
};
/**
* Clears any existing content in the footer row outlet and creates a new embedded view
* in the outlet using the footer row definition.
*/
/**
* Clears any existing content in the footer row outlet and creates a new embedded view
* in the outlet using the footer row definition.
* @private
* @return {?}
*/
CdkTable.prototype._forceRenderFooterRows = /**
* Clears any existing content in the footer row outlet and creates a new embedded view
* in the outlet using the footer row definition.
* @private
* @return {?}
*/
function () {
var _this = this;
// Clear the footer row outlet if any content exists.
if (this._footerRowOutlet.viewContainer.length > 0) {
this._footerRowOutlet.viewContainer.clear();
}
this._footerRowDefs.forEach((/**
* @param {?} def
* @param {?} i
* @return {?}
*/
function (def, i) { return _this._renderRow(_this._footerRowOutlet, def, i); }));
this.updateStickyFooterRowStyles();
this.updateStickyColumnStyles();
};
/** Adds the sticky column styles for the rows according to the columns' stick states. */
/**
* Adds the sticky column styles for the rows according to the columns' stick states.
* @private
* @param {?} rows
* @param {?} rowDef
* @return {?}
*/
CdkTable.prototype._addStickyColumnStyles = /**
* Adds the sticky column styles for the rows according to the columns' stick states.
* @private
* @param {?} rows
* @param {?} rowDef
* @return {?}
*/
function (rows, rowDef) {
var _this = this;
/** @type {?} */
var columnDefs = Array.from(rowDef.columns || []).map((/**
* @param {?} columnName
* @return {?}
*/
function (columnName) {
/** @type {?} */
var columnDef = _this._columnDefsByName.get(columnName);
if (!columnDef) {
throw getTableUnknownColumnError(columnName);
}
return (/** @type {?} */ (columnDef));
}));
/** @type {?} */
var stickyStartStates = columnDefs.map((/**
* @param {?} columnDef
* @return {?}
*/
function (columnDef) { return columnDef.sticky; }));
/** @type {?} */
var stickyEndStates = columnDefs.map((/**
* @param {?} columnDef
* @return {?}
*/
function (columnDef) { return columnDef.stickyEnd; }));
this._stickyStyler.updateStickyColumns(rows, stickyStartStates, stickyEndStates);
};
/** Gets the list of rows that have been rendered in the row outlet. */
/**
* Gets the list of rows that have been rendered in the row outlet.
* @param {?} rowOutlet
* @return {?}
*/
CdkTable.prototype._getRenderedRows = /**
* Gets the list of rows that have been rendered in the row outlet.
* @param {?} rowOutlet
* @return {?}
*/
function (rowOutlet) {
/** @type {?} */
var renderedRows = [];
for (var i = 0; i < rowOutlet.viewContainer.length; i++) {
/** @type {?} */
var viewRef = ((/** @type {?} */ ((/** @type {?} */ (rowOutlet.viewContainer.get(i))))));
renderedRows.push(viewRef.rootNodes[0]);
}
return renderedRows;
};
/**
* Get the matching row definitions that should be used for this row data. If there is only
* one row definition, it is returned. Otherwise, find the row definitions that has a when
* predicate that returns true with the data. If none return true, return the default row
* definition.
*/
/**
* Get the matching row definitions that should be used for this row data. If there is only
* one row definition, it is returned. Otherwise, find the row definitions that has a when
* predicate that returns true with the data. If none return true, return the default row
* definition.
* @param {?} data
* @param {?} dataIndex
* @return {?}
*/
CdkTable.prototype._getRowDefs = /**
* Get the matching row definitions that should be used for this row data. If there is only
* one row definition, it is returned. Otherwise, find the row definitions that has a when
* predicate that returns true with the data. If none return true, return the default row
* definition.
* @param {?} data
* @param {?} dataIndex
* @return {?}
*/
function (data, dataIndex) {
if (this._rowDefs.length == 1) {
return [this._rowDefs[0]];
}
/** @type {?} */
var rowDefs = [];
if (this.multiTemplateDataRows) {
rowDefs = this._rowDefs.filter((/**
* @param {?} def
* @return {?}
*/
function (def) { return !def.when || def.when(dataIndex, data); }));
}
else {
/** @type {?} */
var rowDef = this._rowDefs.find((/**
* @param {?} def
* @return {?}
*/
function (def) { return def.when && def.when(dataIndex, data); })) || this._defaultRowDef;
if (rowDef) {
rowDefs.push(rowDef);
}
}
if (!rowDefs.length) {
throw getTableMissingMatchingRowDefError(data);
}
return rowDefs;
};
/**
* Create the embedded view for the data row template and place it in the correct index location
* within the data row view container.
*/
/**
* Create the embedded view for the data row template and place it in the correct index location
* within the data row view container.
* @private
* @param {?} renderRow
* @param {?} renderIndex
* @return {?}
*/
CdkTable.prototype._insertRow = /**
* Create the embedded view for the data row template and place it in the correct index location
* within the data row view container.
* @private
* @param {?} renderRow
* @param {?} renderIndex
* @return {?}
*/
function (renderRow, renderIndex) {
/** @type {?} */
var rowDef = renderRow.rowDef;
/** @type {?} */
var context = { $implicit: renderRow.data };
this._renderRow(this._rowOutlet, rowDef, renderIndex, context);
};
/**
* Creates a new row template in the outlet and fills it with the set of cell templates.
* Optionally takes a context to provide to the row and cells, as well as an optional index
* of where to place the new row template in the outlet.
*/
/**
* Creates a new row template in the outlet and fills it with the set of cell templates.
* Optionally takes a context to provide to the row and cells, as well as an optional index
* of where to place the new row template in the outlet.
* @private
* @param {?} outlet
* @param {?} rowDef
* @param {?} index
* @param {?=} context
* @return {?}
*/
CdkTable.prototype._renderRow = /**
* Creates a new row template in the outlet and fills it with the set of cell templates.
* Optionally takes a context to provide to the row and cells, as well as an optional index
* of where to place the new row template in the outlet.
* @private
* @param {?} outlet
* @param {?} rowDef
* @param {?} index
* @param {?=} context
* @return {?}
*/
function (outlet, rowDef, index, context) {
if (context === void 0) { context = {}; }
// TODO(andrewseguin): enforce that one outlet was instantiated from createEmbeddedView
outlet.viewContainer.createEmbeddedView(rowDef.template, context, index);
for (var _a = 0, _b = this._getCellTemplates(rowDef); _a < _b.length; _a++) {
var cellTemplate = _b[_a];
if (CdkCellOutlet.mostRecentCellOutlet) {
CdkCellOutlet.mostRecentCellOutlet._viewContainer.createEmbeddedView(cellTemplate, context);
}
}
this._changeDetectorRef.markForCheck();
};
/**
* Updates the index-related context for each row to reflect any changes in the index of the rows,
* e.g. first/last/even/odd.
*/
/**
* Updates the index-related context for each row to reflect any changes in the index of the rows,
* e.g. first/last/even/odd.
* @private
* @return {?}
*/
CdkTable.prototype._updateRowIndexContext = /**
* Updates the index-related context for each row to reflect any changes in the index of the rows,
* e.g. first/last/even/odd.
* @private
* @return {?}
*/
function () {
/** @type {?} */
var viewContainer = this._rowOutlet.viewContainer;
for (var renderIndex = 0, count = viewContainer.length; renderIndex < count; renderIndex++) {
/** @type {?} */
var viewRef = (/** @type {?} */ (viewContainer.get(renderIndex)));
/** @type {?} */
var context = (/** @type {?} */ (viewRef.context));
context.count = count;
context.first = renderIndex === 0;
context.last = renderIndex === count - 1;
context.even = renderIndex % 2 === 0;
context.odd = !context.even;
if (this.multiTemplateDataRows) {
context.dataIndex = this._renderRows[renderIndex].dataIndex;
context.renderIndex = renderIndex;
}
else {
context.index = this._renderRows[renderIndex].dataIndex;
}
}
};
/** Gets the column definitions for the provided row def. */
/**
* Gets the column definitions for the provided row def.
* @private
* @param {?} rowDef
* @return {?}
*/
CdkTable.prototype._getCellTemplates = /**
* Gets the column definitions for the provided row def.
* @private
* @param {?} rowDef
* @return {?}
*/
function (rowDef) {
var _this = this;
if (!rowDef || !rowDef.columns) {
return [];
}
return Array.from(rowDef.columns, (/**
* @param {?} columnId
* @return {?}
*/
function (columnId) {
/** @type {?} */
var column = _this._columnDefsByName.get(columnId);
if (!column) {
throw getTableUnknownColumnError(columnId);
}
return rowDef.extractCellTemplate(column);
}));
};
/** Adds native table sections (e.g. tbody) and moves the row outlets into them. */
/**
* Adds native table sections (e.g. tbody) and moves the row outlets into them.
* @private
* @return {?}
*/
CdkTable.prototype._applyNativeTableSections = /**
* Adds native table sections (e.g. tbody) and moves the row outlets into them.
* @private
* @return {?}
*/
function () {
/** @type {?} */
var documentFragment = this._document.createDocumentFragment();
/** @type {?} */
var sections = [
{ tag: 'thead', outlet: this._headerRowOutlet },
{ tag: 'tbody', outlet: this._rowOutlet },
{ tag: 'tfoot', outlet: this._footerRowOutlet },
];
for (var _a = 0, sections_1 = sections; _a < sections_1.length; _a++) {
var section = sections_1[_a];
/** @type {?} */
var element = this._document.createElement(section.tag);
element.setAttribute('role', 'rowgroup');
element.appendChild(section.outlet.elementRef.nativeElement);
documentFragment.appendChild(element);
}
// Use a DocumentFragment so we don't hit the DOM on each iteration.
this._elementRef.nativeElement.appendChild(documentFragment);
};
/**
* Forces a re-render of the data rows. Should be called in cases where there has been an input
* change that affects the evaluation of which rows should be rendered, e.g. toggling
* `multiTemplateDataRows` or adding/removing row definitions.
*/
/**
* Forces a re-render of the data rows. Should be called in cases where there has been an input
* change that affects the evaluation of which rows should be rendered, e.g. toggling
* `multiTemplateDataRows` or adding/removing row definitions.
* @private
* @return {?}
*/
CdkTable.prototype._forceRenderDataRows = /**
* Forces a re-render of the data rows. Should be called in cases where there has been an input
* change that affects the evaluation of which rows should be rendered, e.g. toggling
* `multiTemplateDataRows` or adding/removing row definitions.
* @private
* @return {?}
*/
function () {
this._dataDiffer.diff([]);
this._rowOutlet.viewContainer.clear();
this.renderRows();
this.updateStickyColumnStyles();
};
/**
* Checks if there has been a change in sticky states since last check and applies the correct
* sticky styles. Since checking resets the "dirty" state, this should only be performed once
* during a change detection and after the inputs are settled (after content check).
*/
/**
* Checks if there has been a change in sticky states since last check and applies the correct
* sticky styles. Since checking resets the "dirty" state, this should only be performed once
* during a change detection and after the inputs are settled (after content check).
* @private
* @return {?}
*/
CdkTable.prototype._checkStickyStates = /**
* Checks if there has been a change in sticky states since last check and applies the correct
* sticky styles. Since checking resets the "dirty" state, this should only be performed once
* during a change detection and after the inputs are settled (after content check).
* @private
* @return {?}
*/
function () {
/** @type {?} */
var stickyCheckReducer = (/**
* @param {?} acc
* @param {?} d
* @return {?}
*/
function (acc, d) {
return acc || d.hasStickyChanged();
});
// Note that the check needs to occur for every definition since it notifies the definition
// that it can reset its dirty state. Using another operator like `some` may short-circuit
// remaining definitions and leave them in an unchecked state.
if (this._headerRowDefs.reduce(stickyCheckReducer, false)) {
this.updateStickyHeaderRowStyles();
}
if (this._footerRowDefs.reduce(stickyCheckReducer, false)) {
this.updateStickyFooterRowStyles();
}
if (Array.from(this._columnDefsByName.values()).reduce(stickyCheckReducer, false)) {
this.updateStickyColumnStyles();
}
};
/**
* Creates the sticky styler that will be used for sticky rows and columns. Listens
* for directionality changes and provides the latest direction to the styler. Re-applies column
* stickiness when directionality changes.
*/
/**
* Creates the sticky styler that will be used for sticky rows and columns. Listens
* for directionality changes and provides the latest direction to the styler. Re-applies column
* stickiness when directionality changes.
* @private
* @return {?}
*/
CdkTable.prototype._setupStickyStyler = /**
* Creates the sticky styler that will be used for sticky rows and columns. Listens
* for directionality changes and provides the latest direction to the styler. Re-applies column
* stickiness when directionality changes.
* @private
* @return {?}
*/
function () {
var _this = this;
/** @type {?} */
var direction = this._dir ? this._dir.value : 'ltr';
this._stickyStyler = new StickyStyler(this._isNativeHtmlTable, this.stickyCssClass, direction, this._platform.isBrowser);
(this._dir ? this._dir.change : of())
.pipe(takeUntil(this._onDestroy))
.subscribe((/**
* @param {?} value
* @return {?}
*/
function (value) {
_this._stickyStyler.direction = value;
_this.updateStickyColumnStyles();
}));
};
CdkTable.decorators = [
{ type: Component, args: [{selector: 'cdk-table, table[cdk-table]',
exportAs: 'cdkTable',
template: CDK_TABLE_TEMPLATE,
host: {
'class': 'cdk-table',
},
encapsulation: ViewEncapsulation.None,
// The "OnPush" status for the `MatTable` component is effectively a noop, so we are removing it.
// The view for `MatTable` consists entirely of templates declared in other views. As they are
// declared elsewhere, they are checked when their declaration points are checked.
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
},] },
];
/** @nocollapse */
CdkTable.ctorParameters = function () { return [
{ type: IterableDiffers },
{ type: ChangeDetectorRef },
{ type: ElementRef },
{ type: String, decorators: [{ type: Attribute, args: ['role',] }] },
{ type: Directionality, decorators: [{ type: Optional }] },
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
{ type: Platform }
]; };
CdkTable.propDecorators = {
trackBy: [{ type: Input }],
dataSource: [{ type: Input }],
multiTemplateDataRows: [{ type: Input }],
_rowOutlet: [{ type: ViewChild, args: [DataRowOutlet, { static: true },] }],
_headerRowOutlet: [{ type: ViewChild, args: [HeaderRowOutlet, { static: true },] }],
_footerRowOutlet: [{ type: ViewChild, args: [FooterRowOutlet, { static: true },] }],
_contentColumnDefs: [{ type: ContentChildren, args: [CdkColumnDef,] }],
_contentRowDefs: [{ type: ContentChildren, args: [CdkRowDef,] }],
_contentHeaderRowDefs: [{ type: ContentChildren, args: [CdkHeaderRowDef,] }],
_contentFooterRowDefs: [{ type: ContentChildren, args: [CdkFooterRowDef,] }]
};
return CdkTable;
}());
/**
* Utility function that gets a merged list of the entries in a QueryList and values of a Set.
* @template T
* @param {?} queryList
* @param {?} set
* @return {?}
*/
function mergeQueryListAndSet(queryList, set) {
return queryList.toArray().concat(Array.from(set));
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Injection token that can be used to specify the text column options.
* @type {?}
*/
var TEXT_COLUMN_OPTIONS = new InjectionToken('text-column-options');
/**
* Column that simply shows text content for the header and row cells. Assumes that the table
* is using the native table implementation (`<table>`).
*
* By default, the name of this column will be the header text and data property accessor.
* The header text can be overridden with the `headerText` input. Cell values can be overridden with
* the `dataAccessor` input. Change the text justification to the start or end using the `justify`
* input.
* @template T
*/
var CdkTextColumn = /** @class */ (function () {
function CdkTextColumn(_table, _options) {
this._table = _table;
this._options = _options;
/**
* Alignment of the cell values.
*/
this.justify = 'start';
this._options = _options || {};
}
Object.defineProperty(CdkTextColumn.prototype, "name", {
/** Column name that should be used to reference this column. */
get: /**
* Column name that should be used to reference this column.
* @return {?}
*/
function () {
return this._name;
},
set: /**
* @param {?} name
* @return {?}
*/
function (name) {
this._name = name;
// With Ivy, inputs can be initialized before static query results are
// available. In that case, we defer the synchronization until "ngOnInit" fires.
this._syncColumnDefName();
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
CdkTextColumn.prototype.ngOnInit = /**
* @return {?}
*/
function () {
this._syncColumnDefName();
if (this.headerText === undefined) {
this.headerText = this._createDefaultHeaderText();
}
if (!this.dataAccessor) {
this.dataAccessor =
this._options.defaultDataAccessor || ((/**
* @param {?} data
* @param {?} name
* @return {?}
*/
function (data, name) { return ((/** @type {?} */ (data)))[name]; }));
}
if (this._table) {
// Provide the cell and headerCell directly to the table with the static `ViewChild` query,
// since the columnDef will not pick up its content by the time the table finishes checking
// its content and initializing the rows.
this.columnDef.cell = this.cell;
this.columnDef.headerCell = this.headerCell;
this._table.addColumnDef(this.columnDef);
}
else {
throw getTableTextColumnMissingParentTableError();
}
};
/**
* @return {?}
*/
CdkTextColumn.prototype.ngOnDestroy = /**
* @return {?}
*/
function () {
if (this._table) {
this._table.removeColumnDef(this.columnDef);
}
};
/**
* Creates a default header text. Use the options' header text transformation function if one
* has been provided. Otherwise simply capitalize the column name.
*/
/**
* Creates a default header text. Use the options' header text transformation function if one
* has been provided. Otherwise simply capitalize the column name.
* @return {?}
*/
CdkTextColumn.prototype._createDefaultHeaderText = /**
* Creates a default header text. Use the options' header text transformation function if one
* has been provided. Otherwise simply capitalize the column name.
* @return {?}
*/
function () {
/** @type {?} */
var name = this.name;
if (isDevMode() && !name) {
throw getTableTextColumnMissingNameError();
}
if (this._options && this._options.defaultHeaderTextTransform) {
return this._options.defaultHeaderTextTransform(name);
}
return name[0].toUpperCase() + name.slice(1);
};
/** Synchronizes the column definition name with the text column name. */
/**
* Synchronizes the column definition name with the text column name.
* @private
* @return {?}
*/
CdkTextColumn.prototype._syncColumnDefName = /**
* Synchronizes the column definition name with the text column name.
* @private
* @return {?}
*/
function () {
if (this.columnDef) {
this.columnDef.name = this.name;
}
};
CdkTextColumn.decorators = [
{ type: Component, args: [{selector: 'cdk-text-column',
template: "\n <ng-container cdkColumnDef>\n <th cdk-header-cell *cdkHeaderCellDef [style.text-align]=\"justify\">\n {{headerText}}\n </th>\n <td cdk-cell *cdkCellDef=\"let data\" [style.text-align]=\"justify\">\n {{dataAccessor(data, name)}}\n </td>\n </ng-container>\n ",
encapsulation: ViewEncapsulation.None,
// Change detection is intentionally not set to OnPush. This component's template will be provided
// to the table to be inserted into its view. This is problematic when change detection runs since
// the bindings in this template will be evaluated _after_ the table's view is evaluated, which
// mean's the template in the table's view will not have the updated value (and in fact will cause
// an ExpressionChangedAfterItHasBeenCheckedError).
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
},] },
];
/** @nocollapse */
CdkTextColumn.ctorParameters = function () { return [
{ type: CdkTable, decorators: [{ type: Optional }] },
{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [TEXT_COLUMN_OPTIONS,] }] }
]; };
CdkTextColumn.propDecorators = {
name: [{ type: Input }],
headerText: [{ type: Input }],
dataAccessor: [{ type: Input }],
justify: [{ type: Input }],
columnDef: [{ type: ViewChild, args: [CdkColumnDef, { static: true },] }],
cell: [{ type: ViewChild, args: [CdkCellDef, { static: true },] }],
headerCell: [{ type: ViewChild, args: [CdkHeaderCellDef, { static: true },] }]
};
return CdkTextColumn;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
var EXPORTED_DECLARATIONS = [
CdkTable,
CdkRowDef,
CdkCellDef,
CdkCellOutlet,
CdkHeaderCellDef,
CdkFooterCellDef,
CdkColumnDef,
CdkCell,
CdkRow,
CdkHeaderCell,
CdkFooterCell,
CdkHeaderRow,
CdkHeaderRowDef,
CdkFooterRow,
CdkFooterRowDef,
DataRowOutlet,
HeaderRowOutlet,
FooterRowOutlet,
CdkTextColumn,
];
var CdkTableModule = /** @class */ (function () {
function CdkTableModule() {
}
CdkTableModule.decorators = [
{ type: NgModule, args: [{
imports: [CommonModule],
exports: EXPORTED_DECLARATIONS,
declarations: EXPORTED_DECLARATIONS
},] },
];
return CdkTableModule;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
export { DataRowOutlet, HeaderRowOutlet, FooterRowOutlet, CDK_TABLE_TEMPLATE, CdkTable, CdkCellDef, CdkHeaderCellDef, CdkFooterCellDef, CdkColumnDef, BaseCdkCell, CdkHeaderCell, CdkFooterCell, CdkCell, CDK_ROW_TEMPLATE, BaseRowDef, CdkHeaderRowDef, CdkFooterRowDef, CdkRowDef, CdkCellOutlet, CdkHeaderRow, CdkFooterRow, CdkRow, CdkTableModule, STICKY_DIRECTIONS, StickyStyler, mixinHasStickyInput, TEXT_COLUMN_OPTIONS, CdkTextColumn };
//# sourceMappingURL=table.es5.js.map
|
require("dotenv").config();
const mongoose = require("mongoose");
const User = require("../models/user-model.js");
const bcrypt = require("bcrypt");
mongoose
.connect(
process.env.MONGODB_URI,
{ useNewUrlParser: true }
)
.then(x => {
console.log(
`Connected to Mongo! Database name: "${x.connections[0].name}"`
);
})
.catch(err => {
console.error("Error connecting to mongo", err);
});
const userData = [
{
fullName: "Admin",
email: "[email protected]",
encryptedPassword: bcrypt.hashSync("admin", 10),
role: "admin",
course: "Teacher/TA",
avatar: "https://media.giphy.com/media/3o7TKsahTSRp78uW2I/giphy.gif",
startDate: "August 2018",
about: "Admin account"
},
{
fullName: "User One",
email: "[email protected]",
encryptedPassword: bcrypt.hashSync("user", 10),
role: "normal",
course: "Teacher/TA",
avatar: "https://media.giphy.com/media/ukMiDlCmdv2og/giphy.gif",
startDate: "August 2018",
about: "User account"
}
];
User.create(userData)
.then(userResult => {
console.log(`created ${userResult.length} users`);
})
.catch(err => {
console.log("oops, there was an error", err);
});
|
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import VueRouter from 'vue-router';
import routes from './routes';
import 'font-awesome/css/font-awesome.min.css';
Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(require('vue-moment'));
const router = new VueRouter({
routes
})
router.beforeEach((to, from, next) => {
// if (to.path == '/login') {
// sessionStorage.removeItem('user');
// }
// let user = JSON.parse(sessionStorage.getItem('user'));
// if (!user && to.path != '/login') {
// next({ path: '/login' })
// } else {
next()
// }
})
new Vue({
router,
render: h => h(App)
}).$mount('#app')
|
from itertools import chain
import math
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
from .encoder import GaussianEncoderBase
from ..utils import log_sum_exp
class GaussianLSTMEncoder(GaussianEncoderBase):
"""Gaussian LSTM Encoder with constant-length input"""
def __init__(self, args, vocab_size, model_init, emb_init):
super(GaussianLSTMEncoder, self).__init__()
self.ni = args.ni
self.nh = args.enc_nh
self.nz = args.nz
self.args = args
self.embed = nn.Embedding(vocab_size, args.ni)
self.lstm = nn.LSTM(input_size=args.ni,
hidden_size=args.enc_nh,
num_layers=1,
batch_first=True,
dropout=0)
self.linear = nn.Linear(args.enc_nh, 2 * args.nz, bias=False)
self.reset_parameters(model_init, emb_init)
def reset_parameters(self, model_init, emb_init):
# for name, param in self.lstm.named_parameters():
# # self.initializer(param)
# if 'bias' in name:
# nn.init.constant_(param, 0.0)
# # model_init(param)
# elif 'weight' in name:
# model_init(param)
# model_init(self.linear.weight)
# emb_init(self.embed.weight)
for param in self.parameters():
model_init(param)
emb_init(self.embed.weight)
def forward(self, input):
"""
Args:
x: (batch_size, seq_len)
Returns: Tensor1, Tensor2
Tensor1: the mean tensor, shape (batch, nz)
Tensor2: the logvar tensor, shape (batch, nz)
"""
# (batch_size, seq_len-1, args.ni)
word_embed = self.embed(input)
_, (last_state, last_cell) = self.lstm(word_embed)
mean, logvar = self.linear(last_state).chunk(2, -1)
# fix variance as a pre-defined value
if self.args.fix_var > 0:
logvar = mean.new_tensor([[[math.log(self.args.fix_var)]]]).expand_as(mean)
return mean.squeeze(0), logvar.squeeze(0)
# def eval_inference_mode(self, x):
# """compute the mode points in the inference distribution
# (in Gaussian case)
# Returns: Tensor
# Tensor: the posterior mode points with shape (*, nz)
# """
# # (batch_size, nz)
# mu, logvar = self.forward(x)
class LSTMEncoder(GaussianEncoderBase):
"""Gaussian LSTM Encoder with constant-length batching"""
def __init__(self, args, vocab_size, model_init, emb_init):
super(LSTMEncoder, self).__init__()
self.ni = args.ni
self.nh = args.enc_nh
self.nz = args.nz
self.embed = nn.Embedding(vocab_size, args.ni)
self.lstm = nn.LSTM(input_size=args.ni,
hidden_size=args.enc_nh,
num_layers=1,
batch_first=True,
dropout=0)
# dimension transformation to z (mean and logvar)
self.linear = nn.Linear(args.enc_nh, 2 * args.nz, bias=False)
self.reset_parameters(model_init, emb_init)
def reset_parameters(self, model_init, emb_init):
# for name, param in self.lstm.named_parameters():
# # self.initializer(param)
# if 'bias' in name:
# nn.init.constant_(param, 0.0)
# # model_init(param)
# elif 'weight' in name:
# model_init(param)
# model_init(self.linear.weight)
# emb_init(self.embed.weight)
for param in self.parameters():
model_init(param)
emb_init(self.embed.weight)
def forward(self, input):
"""
Args:
x: (batch_size, seq_len)
Returns: Tensor1, Tensor2
Tensor1: the mean tensor, shape (batch, nz)
Tensor2: the logvar tensor, shape (batch, nz)
"""
# (batch_size, seq_len-1, args.ni)
word_embed = self.embed(input)
_, (last_state, last_cell) = self.lstm(word_embed)
mean, logvar = self.linear(last_state).chunk(2, -1)
# this line extract the final layer of lstm
# mean, logvar = mean[-1,:,:], logvar[-1,:,:]
return mean.squeeze(0), logvar.squeeze(0)
# def eval_inference_mode(self, x):
# """compute the mode points in the inference distribution
# (in Gaussian case)
# Returns: Tensor
# Tensor: the posterior mode points with shape (*, nz)
# """
# # (batch_size, nz)
# mu, logvar = self.forward(x)
# class VarLSTMEncoder(LSTMEncoder):
# """Gaussian LSTM Encoder with variable-length batching"""
# def __init__(self, args, vocab_size, model_init, emb_init):
# super(VarLSTMEncoder, self).__init__(args, vocab_size, model_init, emb_init)
# def forward(self, input):
# """
# Args:
# input: tuple which contains x and sents_len
# x: (batch_size, seq_len)
# sents_len: long tensor of sentence lengths
# Returns: Tensor1, Tensor2
# Tensor1: the mean tensor, shape (batch, nz)
# Tensor2: the logvar tensor, shape (batch, nz)
# """
# input, sents_len = input
# # (batch_size, seq_len, args.ni)
# word_embed = self.embed(input)
# packed_embed = pack_padded_sequence(word_embed, sents_len.tolist(), batch_first=True)
# _, (last_state, last_cell) = self.lstm(packed_embed)
# mean, logvar = self.linear(last_state).chunk(2, -1)
# return mean.squeeze(0), logvar.squeeze(0)
# def encode(self, input, nsamples):
# """perform the encoding and compute the KL term
# Args:
# input: tuple which contains x and sents_len
# Returns: Tensor1, Tensor2
# Tensor1: the tensor latent z with shape [batch, nsamples, nz]
# Tensor2: the tenor of KL for each x with shape [batch]
# """
# # (batch_size, nz)
# mu, logvar = self.forward(input)
# # (batch, nsamples, nz)
# z = self.reparameterize(mu, logvar, nsamples)
# KL = 0.5 * (mu.pow(2) + logvar.exp() - logvar - 1).sum(dim=1)
# return z, KL
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Minimal data reader for GQN TFRecord datasets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import os
import tensorflow as tf
nest = tf.contrib.framework.nest
DatasetInfo = collections.namedtuple(
'DatasetInfo',
['basepath', 'train_size', 'test_size', 'frame_size', 'sequence_size']
)
Context = collections.namedtuple('Context', ['frames', 'cameras'])
Query = collections.namedtuple('Query', ['context', 'query_camera'])
TaskData = collections.namedtuple('TaskData', ['query', 'target'])
_DATASETS = dict(
jaco=DatasetInfo(
basepath='jaco',
train_size=3600,
test_size=400,
frame_size=64,
sequence_size=11),
mazes=DatasetInfo(
basepath='mazes',
train_size=1080,
test_size=120,
frame_size=84,
sequence_size=300),
rooms_free_camera_with_object_rotations=DatasetInfo(
basepath='rooms_free_camera_with_object_rotations',
train_size=2034,
test_size=226,
frame_size=128,
sequence_size=10),
rooms_ring_camera=DatasetInfo(
basepath='rooms_ring_camera',
train_size=2160,
test_size=240,
frame_size=64,
sequence_size=10),
rooms_free_camera_no_object_rotations=DatasetInfo(
basepath='rooms_free_camera_no_object_rotations',
train_size=2160,
test_size=240,
frame_size=64,
sequence_size=10),
shepard_metzler_5_parts=DatasetInfo(
basepath='shepard_metzler_5_parts',
train_size=900,
test_size=100,
frame_size=64,
sequence_size=15),
shepard_metzler_7_parts=DatasetInfo(
basepath='shepard_metzler_7_parts',
train_size=900,
test_size=100,
frame_size=64,
sequence_size=15)
)
_NUM_CHANNELS = 3
_NUM_RAW_CAMERA_PARAMS = 5
_MODES = ('train', 'test')
def _get_dataset_files(dateset_info, mode, root):
"""Generates lists of files for a given dataset version."""
basepath = dateset_info.basepath
base = os.path.join(root, basepath, mode)
if mode == 'train':
num_files = dateset_info.train_size
else:
num_files = dateset_info.test_size
length = len(str(num_files))
template = '{:0%d}-of-{:0%d}.tfrecord' % (length, length)
return [os.path.join(base, template.format(i + 1, num_files))
for i in range(num_files)]
def _convert_frame_data(jpeg_data):
decoded_frames = tf.image.decode_jpeg(jpeg_data)
return tf.image.convert_image_dtype(decoded_frames, dtype=tf.float32)
class DataReader(object):
"""Minimal queue based TFRecord reader.
You can use this reader to load the datasets used to train Generative Query
Networks (GQNs) in the 'Neural Scene Representation and Rendering' paper.
See README.md for a description of the datasets and an example of how to use
the reader.
"""
def __init__(self,
dataset,
context_size,
root,
mode='train',
# Optionally reshape frames
custom_frame_size=None,
# Queue params
num_threads=4,
capacity=256,
min_after_dequeue=128,
seed=None):
"""Instantiates a DataReader object and sets up queues for data reading.
Args:
dataset: string, one of ['jaco', 'mazes', 'rooms_ring_camera',
'rooms_free_camera_no_object_rotations',
'rooms_free_camera_with_object_rotations', 'shepard_metzler_5_parts',
'shepard_metzler_7_parts'].
context_size: integer, number of views to be used to assemble the context.
root: string, path to the root folder of the data.
mode: (optional) string, one of ['train', 'test'].
custom_frame_size: (optional) integer, required size of the returned
frames, defaults to None.
num_threads: (optional) integer, number of threads used to feed the reader
queues, defaults to 4.
capacity: (optional) integer, capacity of the underlying
RandomShuffleQueue, defualts to 256.
min_after_dequeue: (optional) integer, min_after_dequeue of the underlying
RandomShuffleQueue, defualts to 128.
seed: (optional) integer, seed for the random number generators used in
the reader.
Raises:
ValueError: if the required version does not exist; if the required mode
is not supported; if the requested context_size is bigger than the
maximum supported for the given dataset version.
"""
if dataset not in _DATASETS:
raise ValueError('Unrecognized dataset {} requested. Available datasets '
'are {}'.format(dataset, _DATASETS.keys()))
if mode not in _MODES:
raise ValueError('Unsupported mode {} requested. Supported modes '
'are {}'.format(mode, _MODES))
self._dataset_info = _DATASETS[dataset]
if context_size >= self._dataset_info.sequence_size:
raise ValueError(
'Maximum support context size for dataset {} is {}, but '
'was {}.'.format(
dataset, self._dataset_info.sequence_size-1, context_size))
self._context_size = context_size
# Number of views in the context + target view
self._example_size = context_size + 1
self._custom_frame_size = custom_frame_size
self.seed = seed
with tf.device('/cpu'):
file_names = _get_dataset_files(self._dataset_info, mode, root)
filename_queue = tf.train.string_input_producer(file_names, seed=self.seed)
reader = tf.TFRecordReader()
read_ops = [self._make_read_op(reader, filename_queue)
for _ in range(num_threads)]
dtypes = nest.map_structure(lambda x: x.dtype, read_ops[0])
shapes = nest.map_structure(lambda x: x.shape[1:], read_ops[0])
self._queue = tf.RandomShuffleQueue(
capacity=capacity,
min_after_dequeue=min_after_dequeue,
dtypes=dtypes,
shapes=shapes,
seed=seed)
enqueue_ops = [self._queue.enqueue_many(op) for op in read_ops]
tf.train.add_queue_runner(tf.train.QueueRunner(self._queue, enqueue_ops))
def read(self, batch_size):
"""Reads batch_size (query, target) pairs."""
frames, cameras = self._queue.dequeue_many(batch_size)
context_frames = frames[:, :-1]
context_cameras = cameras[:, :-1]
target = frames[:, -1]
query_camera = cameras[:, -1]
context = Context(cameras=context_cameras, frames=context_frames)
query = Query(context=context, query_camera=query_camera)
return TaskData(query=query, target=target)
def _make_read_op(self, reader, filename_queue):
"""Instantiates the ops used to read and parse the data into tensors."""
_, raw_data = reader.read_up_to(filename_queue, num_records=16)
feature_map = {
'frames': tf.FixedLenFeature(
shape=self._dataset_info.sequence_size, dtype=tf.string),
'cameras': tf.FixedLenFeature(
shape=[self._dataset_info.sequence_size * _NUM_RAW_CAMERA_PARAMS],
dtype=tf.float32)
}
example = tf.parse_example(raw_data, feature_map)
indices = self._get_randomized_indices(self.seed)
frames = self._preprocess_frames(example, indices)
cameras = self._preprocess_cameras(example, indices)
return frames, cameras
def _get_randomized_indices(self, seed):
"""Generates randomized indices into a sequence of a specific length."""
indices = tf.range(0, self._dataset_info.sequence_size)
indices = tf.random_shuffle(indices, seed=seed)
indices = tf.slice(indices, begin=[0], size=[self._example_size])
return indices
def _preprocess_frames(self, example, indices):
"""Instantiates the ops used to preprocess the frames data."""
frames = tf.concat(example['frames'], axis=0)
frames = tf.gather(frames, indices, axis=1)
frames = tf.map_fn(
_convert_frame_data, tf.reshape(frames, [-1]),
dtype=tf.float32, back_prop=False)
dataset_image_dimensions = tuple(
[self._dataset_info.frame_size] * 2 + [_NUM_CHANNELS])
frames = tf.reshape(
frames, (-1, self._example_size) + dataset_image_dimensions)
if (self._custom_frame_size and
self._custom_frame_size != self._dataset_info.frame_size):
frames = tf.reshape(frames, (-1,) + dataset_image_dimensions)
new_frame_dimensions = (self._custom_frame_size,) * 2 + (_NUM_CHANNELS,)
frames = tf.image.resize_bilinear(
frames, new_frame_dimensions[:2], align_corners=True)
frames = tf.reshape(
frames, (-1, self._example_size) + new_frame_dimensions)
return frames
def _preprocess_cameras(self, example, indices):
"""Instantiates the ops used to preprocess the cameras data."""
raw_pose_params = example['cameras']
raw_pose_params = tf.reshape(
raw_pose_params,
[-1, self._dataset_info.sequence_size, _NUM_RAW_CAMERA_PARAMS])
raw_pose_params = tf.gather(raw_pose_params, indices, axis=1)
pos = raw_pose_params[:, :, 0:3]
yaw = raw_pose_params[:, :, 3:4]
pitch = raw_pose_params[:, :, 4:5]
cameras = tf.concat(
[pos, tf.sin(yaw), tf.cos(yaw), tf.sin(pitch), tf.cos(pitch)], axis=2)
return cameras |
/*##################################################|*/
/* #CMS.TOOLBAR# */
(function($) {
// CMS.$ will be passed for $
$(document).ready(function () {
/*!
* Toolbar
* @version: 2.0.0
* @description: Adds toolbar, sidebar, messages and modal
*/
CMS.Toolbar = new CMS.Class({
implement: [CMS.API.Helpers],
options: {
'csrf': '',
'debug': false, // not yet required
'settings': {
'toolbar': 'expanded', // expanded or collapsed
'mode': 'edit', // live, draft, edit or layout
'states': []
},
'preventSwitch': false,
'preventSwitchMessage': 'Switching is disabled.',
'clipboard': null,
'sidebarDuration': 300,
'sidebarWidth': 320,
'messageDelay': 2000,
'modalDuration': 300,
'modalWidth': 800,
'modalHeight': 400,
'urls': {
'settings': '', // url to save settings
'css_modal': '/static/cms/css/plugins/cms.toolbar.dialog.css',
'css_sideframe': '/static/cms/css/plugins/cms.toolbar.sideframe.css'
},
'lang': {
'confirm': 'Yes',
'cancel': 'Cancel'
}
},
initialize: function (container, options) {
this.container = $(container);
this.options = $.extend(true, {}, this.options, options);
this.settings = this.options.settings;
// class variables
this.toolbar = this.container.find('.cms_toolbar');
this.toolbar.hide();
this.toolbarTrigger = this.container.find('.cms_toolbar-trigger');
this.navigations = this.container.find('.cms_toolbar-item-navigation');
this.buttons = this.container.find('.cms_toolbar-item-buttons');
this.modes = this.container.find('.cms_toolbar-item-cms-mode-switcher a');
this.switcher = this.container.find('.cms_toolbar-item_switch');
this.body = $('html');
this.sideframe = this.container.find('.cms_sideframe');
this.messages = this.container.find('.cms_messages');
this.modal = this.container.find('.cms_modal');
this.tooltip = this.container.find('.cms_placeholders-tooltip');
this.menu = $('.cms_switcher');
this.bars = $('.cms_placeholder-bar');
this.plugins = $('.cms_plugin');
this.placeholders = $('.cms_placeholder');
this.lockToolbar = false;
this.minimized = false;
this.maximized = false;
this.timer = function () {};
// setup initial stuff
this._setup();
// setup events
this._events();
},
// initial methods
_setup: function () {
// set correct settings
if(this.getSettings() === null) this.setSettings();
this.settings = this.getSettings();
// setup toolbar visibility, we need to reverse the options to set the correct state
(this.settings.toolbar === 'expanded') ? this._showToolbar(0, true) : this._hideToolbar(0, true);
// setup toolbar mode
(this.settings.mode === 'drag') ? this._enableDragMode(300, true) : this._enableEditMode(300, true);
},
_events: function () {
var that = this;
// attach event to the trigger handler
this.toolbarTrigger.bind('click', function (e) {
e.preventDefault();
that.toggleToolbar(200);
});
// attach event to the navigation elements
this.navigations.each(function () {
var item = $(this);
// attach delegate event
item.find('li ul a').bind('click', function (e) {
e.preventDefault();
if(!$(this).parent().hasClass('cms_toolbar-item-navigation-disabled')) that.delegate($(this));
});
// remove events from first level
item.find('> li > a').bind('click', function (e) {
e.preventDefault();
if($(this).attr('href') !== ''
&& $(this).attr('href') !== '#'
&& !$(this).parent().hasClass('cms_toolbar-item-navigation-disabled')
&& !$(this).parent().hasClass('cms_toolbar-item-navigation-disabled')) that.delegate($(this));
});
// handle states
var states = $(['> li', '> li li', '> li li li']);
states.each(function (index, list) {
item.find(list).bind('mouseenter mouseleave', function (e) {
item.find(list).removeClass('cms_toolbar-item-navigation-hover');
if(e.type === 'mouseenter') $(this).addClass('cms_toolbar-item-navigation-hover');
});
});
});
// attach event to the switcher elements
this.switcher.each(function () {
$(this).bind('click', function (e) {
e.preventDefault();
that._setSwitcher($(e.currentTarget));
});
});
// module events
this._eventsSidebar();
this._eventsModal();
// stopper events
$(document).bind('mouseup.cms', function (e) {
that._stopSideframeResize();
that._endModalMove(e);
that._endModalResize(e);
});
// event for switching between edit and layout mode
this.menu.bind('click', function (e) {
e.stopPropagation();
// set active state
that.setActive($(this).data('id'));
// show e dit mode
that._enableEditMode(300);
});
this.modes.eq(0).bind('click', function (e) {
e.preventDefault();
that._enableEditMode(300);
});
this.modes.eq(1).bind('click', function (e) {
e.preventDefault();
that._enableDragMode(300);
});
// keyboard handling
$(document).bind('keydown', function (e) {
// check if we have an important focus
var fields = $('*:focus');
// 32 = space
if(e.keyCode === 32 && that.settings.mode === 'drag' && !fields.length) {
that._enableEditMode(300);
} else if(e.keyCode === 32 && that.settings.mode === 'edit' && !fields.length) {
that._enableDragMode(300);
}
});
},
_eventsSidebar: function () {
var that = this;
// attach event to the sidebar
this.sideframe.find('.cms_sideframe-close').bind('click', function () {
that.closeSideframe(true);
});
this.sideframe.find('.cms_sideframe-hide').bind('click', function () {
if($(this).hasClass('cms_sideframe-hidden')) {
$(this).removeClass('cms_sideframe-hidden');
that._showSideframe(that.options.sidebarWidth);
} else {
$(this).addClass('cms_sideframe-hidden');
that._hideSideframe();
}
});
this.sideframe.find('.cms_sideframe-maximize').bind('click', function () {
if($(this).hasClass('cms_sideframe-minimize')) {
$(this).removeClass('cms_sideframe-minimize');
that.sideframe.find('.cms_sideframe-hide').show();
that._showSideframe(that.options.sidebarWidth);
} else {
$(this).addClass('cms_sideframe-minimize');
that.sideframe.find('.cms_sideframe-hide').removeClass('cms_sideframe-hidden').hide();
that._showSideframe(0, true);
}
});
this.sideframe.find('.cms_sideframe-resize').bind('mousedown', function (e) {
e.preventDefault();
that._startSideframeResize();
});
},
_eventsModal: function () {
var that = this;
// attach events to window
this.modal.find('.cms_modal-close').bind('click', function (e) {
e.preventDefault();
that.closeModal();
});
this.modal.find('.cms_modal-collapse').bind('click', function (e) {
e.preventDefault();
that._minimizeModal();
});
this.modal.find('.cms_modal-title').bind('mousedown.cms', function (e) {
e.preventDefault();
that._startModalMove(e);
});
this.modal.find('.cms_modal-resize').bind('mousedown.cms', function (e) {
e.preventDefault();
that._startModalResize(e);
});
this.modal.find('.cms_modal-maximize').bind('click', function (e) {
e.preventDefault();
that._maximizeModal();
});
this.modal.find('.cms_modal-breadcrumb-items a').live('click', function (e) {
e.preventDefault();
that._changeModalContent($(this));
});
this.modal.find('.cms_modal-cancel').bind('click', function (e) {
e.preventDefault();
that.closeModal();
});
this.modal.find('.cms_modal-save').bind('click', function (e) {
e.preventDefault();
that._saveModal();
});
},
// public methods
toggleToolbar: function (speed) {
(this.settings.toolbar === 'collapsed') ? this._showToolbar(speed) : this._hideToolbar(speed);
},
setSettings: function (settings) {
// cancel if local storage is not available
if(!window.localStorage) return false;
// set settings
settings = $.extend({}, this.settings, settings);
return localStorage.setItem('cms_cookie', JSON.stringify(settings));
},
getSettings: function () {
// cancel if local storage is not available
if(!window.localStorage) return false;
// get settings
return JSON.parse(localStorage.getItem('cms_cookie'));
},
delegate: function (el) {
// save local vars
var target = el.attr('data-rel');
switch(target) {
case 'modal':
this.openModal(
el.attr('href'),
el.attr('data-name'),
[{
'title': el.attr('data-name'),
'url': el.attr('href')
}],
el.attr('data-close-url'),
el.attr('data-redirect-on-close-url')
);
break;
case 'message':
this.openMessage(el.attr('data-text'));
break;
case 'sideframe':
this.openSideframe(el.attr('href'));
break;
case 'ajax':
this.openAjax(el.attr('href'), el.attr('data-post'));
break;
default:
window.location.href = el.attr('href');
}
},
openSideframe: function (url, maximized) {
// prepare iframe
var that = this;
var holder = this.sideframe.find('.cms_sideframe-frame');
var iframe = $('<iframe src="'+url+'" class="" frameborder="0" />');
iframe.hide();
var width = this.options.sidebarWidth;
// attach load event to iframe
iframe.bind('load', function () {
iframe.show();
that.sideframe.find('.cms_sideframe-frame').removeClass('cms_loader');
});
// cancel animation if sidebar is already shown
if(this.sideframe.is(':visible')) {
// sidebar is already open
insertHolder(iframe);
// reanimate the frame
if(parseInt(this.sideframe.css('width')) <= width) this._showSideframe(width, maximized);
} else {
// load iframe after frame animation is done
setTimeout(function () {
insertHolder(iframe);
}, this.options.sidebarDuration);
// display the frame
this._showSideframe(width, maximized);
}
function insertHolder(iframe) {
// show iframe after animation
that.sideframe.find('.cms_sideframe-frame').addClass('cms_loader');
holder.html(iframe);
}
},
closeSideframe: function () {
this._hideSideframe(true);
},
openMessage: function (msg, dir, error, delay) {
// set toolbar freeze
this.lockToolbar = true;
// add content to element
this.messages.find('.cms_messages-inner').html(msg);
// clear timeout
clearTimeout(this.timer);
// determine width
var that = this;
var width = this.messages.outerWidth(true);
var height = this.messages.outerHeight(true);
var top = this.toolbar.outerHeight(true);
var close = this.messages.find('.cms_messages-close');
close.hide();
close.bind('click', function () {
that.closeMessage();
});
// set correct position and show
this.messages.css('top', -height).show();
// error handling
this.messages.removeClass('cms_messages-error');
if(error) this.messages.addClass('cms_messages-error');
// dir should be left, center, right
dir = dir || 'center';
// set correct direction and animation
switch(dir) {
case 'left':
this.messages.css({
'top': top,
'left': -width
});
this.messages.animate({ 'left': 0 });
break;
case 'right':
this.messages.css({
'top': top,
'right': -width
});
this.messages.animate({ 'right': 0 });
break;
default:
this.messages.css({
'left': '50%',
'margin-left': -(width / 2)
});
this.messages.animate({ 'top': top });
}
// cancel autohide if delay is 0
if(delay === 0) {
close.show();
return false
}
// add delay to hide
this.timer = setTimeout(function () {
that.closeMessage();
}, delay || this.options.messageDelay);
},
closeMessage: function () {
this.messages.fadeOut(300);
// unlock toolbar
this.lockToolbar = false;
},
openModal: function (url, name, breadcrumb, close_url, redirect_on_close_url) {
// prepare iframe
var that = this;
var iframe = $('<iframe src="'+url+'" frameborder="0" style="background:#fff;" />');
iframe.hide();
var holder = this.modal.find('.cms_modal-frame');
var contents = this.modal.find('.cms_modal-body, .cms_modal-foot');
contents.show();
// insure previous iframe is hidden
holder.find('iframe').hide();
// attach load event for iframe to prevent flicker effects
iframe.bind('load', function () {
// after iframe is loaded append css
iframe.contents().find('head').append($('<link rel="stylesheet" type="text/css" href="' + that.options.urls.css_modal + '" />'));
// set modal buttons
that._setModalButtons($(this));
// than show
iframe.show();
});
// attach load event to check if we have to close the modal
iframe.load(function() {
if (this.contentWindow.location.pathname == close_url) {
if (redirect_on_close_url) {
window.location.href = redirect_on_close_url;
} else {
that.closeModal();
}
}
});
// show iframe after animation
setTimeout(function () {
that.modal.find('.cms_modal-body').addClass('cms_loader');
holder.html(iframe);
}, this.options.modalDuration);
// set correct title
var title = this.modal.find('.cms_modal-title');
title.html(name || ' ');
// insure modal is not maximized
if(this.modal.find('.cms_modal-collapsed').length) this._minimizeModal();
// reset styles
this.modal.css({
'left': '50%',
'top': '50%',
'mergin-left': 0,
'margin-right': 0
});
this.modal.find('.cms_modal-body').css({
'width': this.options.modalWidth,
'height': this.options.modalHeight
});
this.modal.find('.cms_modal-body').removeClass('cms_loader');
this.modal.find('.cms_modal-maximize').removeClass('cms_modal-maximize-active');
this.maximized = false;
// we need to render the breadcrumb
this._setModalBreadcrumb(breadcrumb);
// empty buttons
this.modal.find('.cms_modal-buttons').html('');
// display modal
this._showModal(this.options.modalDuration);
},
closeModal: function () {
this._hideModal(100);
},
openAjax: function (url, post) {
var that = this;
$.ajax({
'type': 'POST',
'url': url,
'data': (post) ? JSON.parse(post) : {},
'success': function () {
window.location.reload();
},
'error': function (jqXHR) {
that.showError(jqXHR.response + ' | ' + jqXHR.status + ' ' + jqXHR.statusText);
}
});
},
setActive: function (id) {
// reset active statesdragholders
$('.cms_draggable').removeClass('cms_draggable-selected');
$('.cms_plugin').removeClass('cms_plugin-active');
// if false is provided, only remove classes
if(id === false) return false;
// attach active class to current element
var dragitem = $('#cms_draggable-' + id);
var plugin = $('#cms_plugin-' + id);
// set new classes
dragitem.addClass('cms_draggable-selected');
plugin.addClass('cms_plugin-active');
// set new position
var pos = plugin.position('body').top;
var bound = $(window).height();
var offset = 200;
if(bound - pos <= 0) $(window).scrollTop(pos - offset);
},
// private methods
_showToolbar: function (speed, init) {
this.toolbarTrigger.addClass('cms_toolbar-trigger-expanded');
this.toolbar.slideDown(speed);
this.settings.toolbar = 'expanded';
if(!init) this.setSettings();
},
_hideToolbar: function (speed, init) {
// cancel if sidebar is active
if(this.lockToolbar) return false;
this.toolbarTrigger.removeClass('cms_toolbar-trigger-expanded');
this.toolbar.slideUp(speed);
this.settings.toolbar = 'collapsed';
if(!init) this.setSettings();
},
_enableEditMode: function (speed, init) {
this.bars.hide();
this.plugins.stop(true, true).fadeIn(speed);
this.placeholders.hide();
this.menu.hide().removeClass('cms_placeholders-menu-alternate');
// set active item
this.modes.removeClass('cms_btn-active').eq(0).addClass('cms_btn-active');
this.settings.mode = 'edit';
// hide clipboard if in edit mode
this.container.find('.cms_clipboard').hide();
// set active element to online block
var active = this.plugins.filter('.cms_plugin-active');
active.css('display', 'inline-block');
if(!init) this.setSettings();
},
_enableDragMode: function (speed, init) {
this.bars.fadeIn(speed);
this.plugins.hide();
this.placeholders.stop(true, true).fadeIn(speed);
this.menu.hide();
// set active item
this.modes.removeClass('cms_btn-active').eq(1).addClass('cms_btn-active');
this.settings.mode = 'drag';
// show clipboard in build mode
this.container.find('.cms_clipboard').fadeIn(speed);
if(!init) this.setSettings();
},
_setSwitcher: function (el) {
// save local vars
var active = el.hasClass('cms_toolbar-item_switch-active');
var anchor = el.find('a');
var knob = el.find('.cms_toolbar-item_switch-knob');
var duration = 300;
// prevent if switchopstion is passed
if(this.options.preventSwitch) {
this.openMessage(this.options.preventSwitchMessage, 'right');
return false;
}
// determin what to trigger
if(active) {
knob.animate({
'right': anchor.outerWidth(true) - (knob.outerWidth(true) + 2)
}, duration);
// move anchor behind the knob
anchor.css('z-index', 1).animate({
'padding-top': 6,
'padding-right': 14,
'padding-bottom': 4,
'padding-left': 28
}, duration);
} else {
knob.animate({
'left': anchor.outerWidth(true) - (knob.outerWidth(true) + 2)
}, duration);
// move anchor behind the knob
anchor.css('z-index', 1).animate({
'padding-top': 6,
'padding-right': 28,
'padding-bottom': 4,
'padding-left': 14
}, duration);
}
// reload
setTimeout(function () {
window.location.href = anchor.attr('href');
}, duration);
},
_showSideframe: function (width, maximized) {
if(maximized) {
this.sideframe.animate({ 'width': $(window).width() }, 0);
this.body.animate({ 'margin-left': 0 }, 0);
// invert icon position
this.sideframe.find('.cms_sideframe-btn').css('right', -2);
} else {
this.sideframe.animate({ 'width': width }, this.options.sidebarDuration);
this.body.animate({ 'margin-left': width }, this.options.sidebarDuration);
this.sideframe.find('.cms_sideframe-btn').css('right', -20);
}
this.lockToolbar = true;
},
_hideSideframe: function (close) {
var duration = this.options.sidebarDuration;
// remove the iframe
if(close && this.sideframe.width() <= 0) duration = 0;
if(close) this.sideframe.find('iframe').remove();
this.sideframe.animate({ 'width': 0 }, duration, function () {
if(close) $(this).hide();
});
this.body.animate({ 'margin-left': 0 }, duration);
this.sideframe.find('.cms_sideframe-frame').removeClass('cms_loader');
this.lockToolbar = false;
},
_startSideframeResize: function () {
var that = this;
// this prevents the iframe from being focusable
this.sideframe.find('.cms_sideframe-shim').css('z-index', 20);
$(document).bind('mousemove.cms', function (e) {
if(e.clientX <= 3) e.clientX = 3;
that.sideframe.css('width', e.clientX);
that.body.css('margin-left', e.clientX);
});
},
_stopSideframeResize: function () {
this.sideframe.find('.cms_sideframe-shim').css('z-index', 1);
$(document).unbind('mousemove.cms');
},
_showModal: function (speed) {
// we need to position the modal in the center
var that = this;
var width = this.modal.width();
var height = this.modal.height();
// animates and sets the modal
this.modal.css({
'width': 0,
'height': 0,
'margin-left': 0,
'margin-top': 0
}).stop(true, true).animate({
'width': width,
'height': height,
'margin-left': -(width / 2),
'margin-top': -(height / 2)
}, speed, function () {
$(this).removeAttr('style');
that.modal.css({
'margin-left': -(width / 2),
'margin-top': -(height / 2)
});
// fade in modal window
that.modal.show();
});
},
_hideModal: function (speed) {
this.modal.fadeOut(speed);
this.modal.find('.cms_modal-frame iframe').remove();
this.modal.find('.cms_modal-body').removeClass('cms_loader');
},
_minimizeModal: function () {
var trigger = this.modal.find('.cms_modal-collapse');
var contents = this.modal.find('.cms_modal-body, .cms_modal-foot');
// cancel action if maximized
if(this.maximized) return false;
if(this.minimized === false) {
// minimize
trigger.addClass('cms_modal-collapsed');
contents.hide();
// save initial state
this.modal.data('css', {
'left': this.modal.css('left'),
'top': this.modal.css('top'),
'margin': this.modal.css('margin')
});
this.modal.css({
'left': this.toolbar.find('.cms_toolbar-left').outerWidth(true) + 50,
'top': 1,
'margin': 0
});
this.minimized = true;
} else {
// minimize
trigger.removeClass('cms_modal-collapsed');
contents.show();
// reattach css
this.modal.css(this.modal.data('css'));
this.minimized = false;
}
},
_maximizeModal: function () {
var container = this.modal.find('.cms_modal-body');
var trigger = this.modal.find('.cms_modal-maximize');
var btnCk = this.modal.find('iframe').contents().find('.cke_button__maximize');
// cancel action when minimized
if(this.minimized) return false;
if(this.maximized === false) {
// maximize
this.maximized = true;
trigger.addClass('cms_modal-maximize-active');
this.modal.data('css', {
'left': this.modal.css('left'),
'top': this.modal.css('top'),
'margin': this.modal.css('margin')
});
container.data('css', {
'width': container.width(),
'height': container.height()
});
// reset
this.modal.css({
'left': 0,
'top': 0,
'margin': 0
});
// bind resize event
$(window).bind('resize.cms.modal', function () {
container.css({
'width': $(window).width(),
'height': $(window).height() - 60
});
});
$(window).trigger('resize.cms.modal');
// trigger wysiwyg fullscreen
if(btnCk.hasClass('cke_button_off')) btnCk.trigger('click');
} else {
// minimize
this.maximized = false;
trigger.removeClass('cms_modal-maximize-active');
$(window).unbind('resize.cms.modal');
// reattach css
this.modal.css(this.modal.data('css'));
container.css(container.data('css'));
// trigger wysiwyg fullscreen
if(btnCk.hasClass('cke_button_on')) btnCk.trigger('click');
}
},
_startModalMove: function (initial) {
// cancel if maximized
if(this.maximized) return false;
// cancel action when minimized
if(this.minimized) return false;
var that = this;
var position = that.modal.position();
this.modal.find('.cms_modal-shim').show();
$(document).bind('mousemove.cms', function (e) {
var left = position.left - (initial.pageX - e.pageX) - $(window).scrollLeft();
var top = position.top - (initial.pageY - e.pageY) - $(window).scrollTop();
that.modal.css({
'left': left,
'top': top
});
});
},
_endModalMove: function () {
this.modal.find('.cms_modal-shim').hide();
$(document).unbind('mousemove.cms');
},
_startModalResize: function (initial) {
var that = this;
var container = this.modal.find('.cms_modal-body');
var width = container.width();
var height = container.height();
var modalLeft = this.modal.position().left;
var modalTop = this.modal.position().top;
this.modal.find('.cms_modal-shim').show();
$(document).bind('mousemove.cms', function (e) {
var mvX = initial.pageX - e.pageX;
var mvY = initial.pageY - e.pageY;
var w = width - (mvX * 2);
var h = height - (mvY * 2);
var max = that.modal.find('.cms_modal-breadcrumb').outerWidth(true) + that.modal.find('.cms_modal-buttons').outerWidth(true);
// add some limits
if(w <= max || h <= 100) return false;
// set centered animation
container.css({
'width': width - (mvX * 2),
'height': height - (mvY * 2)
});
that.modal.css({
'left': modalLeft + mvX,
'top': modalTop + mvY
});
});
},
_endModalResize: function () {
this.modal.find('.cms_modal-shim').hide();
$(document).unbind('mousemove.cms');
},
_setModalBreadcrumb: function (breadcrumb) {
var bread = this.modal.find('.cms_modal-breadcrumb');
var crumb = '';
// cancel if there is no breadcrumb)
if(!breadcrumb || breadcrumb.length <= 0) return false;
if(!breadcrumb[0].title) return false;
// load breadcrumb
$.each(breadcrumb, function (index, item) {
// check if the item is the last one
var last = (index >= breadcrumb.length - 1) ? 'cms_modal-breadcrumb-last' : '';
// render breadcrumb
crumb += '<a href="' + item.url + '" class="' + last + '"><span>' + item.title + '</span></a>';
});
// attach elements
bread.find('.cms_modal-breadcrumb-items').html(crumb);
// show breadcrumb
bread.show();
},
_setModalButtons: function (iframe) {
var that = this;
var row = iframe.contents().find('.submit-row');
var buttons = row.find('input, a');
var render = $('<span />');
// loop over input buttons
buttons.each(function (index, item) {
item = $(item);
// cancel if item is a hidden input
if(item.attr('type') === 'hidden') return false;
// create helper variables
var title = item.attr('value') || item.text();
var cls = 'cms_btn';
// set additional css classes
if(item.hasClass('default')) cls = 'cms_btn cms_btn-action';
if(item.hasClass('deletelink')) cls = 'cms_btn cms_btn-caution';
// create the element
var el = $('<div class="'+cls+'" data-name="'+item.attr('name')+'" data-url="'+item.attr('href')+'">'+title+'</div>');
el.bind('click', function () {
var input = row.find('input[name="'+$(this).attr('data-name')+'"]');
if(input.length) input.click();
var anchor = row.find('a[href="'+$(this).attr('data-url')+'"]');
if(anchor.length) iframe.attr('src', iframe.attr('src') + anchor.attr('href'));
});
// append element
render.append(el);
});
// manually add cancel button at the end
var cancel = $('<div class="cms_btn">'+this.options.lang.cancel+'</div>');
cancel.bind('click', function () {
that.closeModal();
});
render.append(cancel);
// unwrap helper and ide row
row.hide();
// render buttons
this.modal.find('.cms_modal-buttons').html(render);
},
_saveModal: function () {
this.modal.find('iframe').contents().find('form').submit();
},
_changeModalContent: function (el) {
var that = this;
if(el.hasClass('cms_modal-breadcrumb-last')) return false;
var parents = el.parent().find('a');
parents.removeClass('cms_modal-breadcrumb-last');
el.addClass('cms_modal-breadcrumb-last');
// now refresh the content
var iframe = $('<iframe src="'+el.attr('href')+'" class="" frameborder="0" />');
iframe.hide();
var holder = this.modal.find('.cms_modal-frame');
// insure previous iframe is hidden
holder.find('iframe').hide();
// attach load event for iframe to prevent flicker effects
iframe.bind('load', function () {
// after iframe is loaded append css
iframe.contents().find('head').append($('<link rel="stylesheet" type="text/css" href="' + that.options.urls.css_modal + '" />'));
// than show
iframe.show();
});
// inject
holder.html(iframe);
// update title
this.modal.find('.cms_modal-title').text(el.text());
},
showError: function (msg) {
this.openMessage(msg, 'center', true);
}
});
});
})(CMS.$);
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[16],{388:function(t,e,i){var n=i(2),s=i(0),r=i(42),a=i(6),o=i(28),u=i(63),c=/MSIE .\./.test(o),d=s.Function,h=function(t){return function(e,i){var n=arguments.length>2,s=n?u(arguments,2):void 0;return t(n?function(){r(a(e)?e:d(e),this,s)}:e,i)}};n({global:!0,bind:!0,forced:c},{setTimeout:h(s.setTimeout),setInterval:h(s.setInterval)})},389:function(t,e,i){var n=i(3),s=i(18),r=Date.prototype,a=n(r.toString),o=n(r.getTime);"Invalid Date"!=String(new Date(NaN))&&s(r,"toString",(function(){var t=o(this);return t==t?a(this):"Invalid Date"}))},396:function(t,e,i){"use strict";i.r(e);i(388),i(389);var n={name:"vue-disqus",props:{shortname:{type:String,required:!0},identifier:{type:String,required:!1},url:{type:String,required:!1},title:{type:String,required:!1},remote_auth_s3:{type:String,required:!1},api_key:{type:String,required:!1},sso_config:{type:Object,required:!1},language:{type:String,required:!1}},mounted:function(){window.DISQUS?this.reset(window.DISQUS):this.init()},methods:{reset:function(t){var e=this;t.reset({reload:!0,config:function(){e.setBaseConfig(this)}})},init:function(){var t=this,e=this;window.disqus_config=function(){e.setBaseConfig(this)},setTimeout((function(){var e=document,i=e.createElement("script");i.setAttribute("id","embed-disqus"),i.setAttribute("data-timestamp",+new Date),i.type="text/javascript",i.async=!0,i.src="//".concat(t.shortname,".disqus.com/embed.js"),(e.head||e.body).appendChild(i)}),0)},setBaseConfig:function(t){var e=this;t.page.identifier=this.identifier||this.$route.path||window.location.pathname,t.page.url=this.url||this.$el.baseURI,this.title&&(t.page.title=this.title),this.remote_auth_s3&&(t.page.remote_auth_s3=this.remote_auth_s3),this.api_key&&(t.page.api_key=this.api_key),this.sso_config&&(t.sso=this.sso_config),this.language&&(t.language=this.language),t.callbacks.onReady=[function(){e.$emit("ready")}],t.callbacks.onNewComment=[function(t){e.$emit("new-comment",t)}]}}},s=i(56),r=Object(s.a)(n,(function(){var t=this.$createElement;return(this._self._c||t)("div",{attrs:{id:"disqus_thread"}})}),[],!1,null,null,null);e.default=r.exports}}]); |
import { noop, retArg0 } from "../../utils";
export let streamVal = retArg0;
export let streamOn = noop;
export let streamOff = noop;
export function streamCfg(cfg) {
streamVal = cfg.val;
streamOn = cfg.on;
streamOff = cfg.off;
} |
var should = require('should'),
testUtils = require('../../utils'),
_ = require('lodash'),
// Stuff we are testing
PostAPI = require('../../../server/api/posts'),
TagAPI = require('../../../server/api/tags'),
UserAPI = require('../../../server/api/users');
describe('Advanced Browse', function () {
// Initialise the DB just once, the tests are fetch-only
before(testUtils.teardown);
before(testUtils.setup('filter'));
after(testUtils.teardown);
should.exist(PostAPI);
should.exist(TagAPI);
should.exist(UserAPI);
describe('Advanced Use Cases', function () {
describe('1. Posts - filter: "tags: [photo, video] + id: -4", limit: "3", include: "tags"', function () {
it('Will fetch 3 posts with tags which match `photo` or `video` and are not the post with id 4.', function (done) {
PostAPI.browse({
filter: 'tags: [photo, video] + id: -' + testUtils.filterData.data.posts[3].id,
limit: 3,
include: 'tags'
}).then(function (result) {
var ids;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 3 items according to the limit property
result.posts.should.be.an.Array().with.lengthOf(3);
// None of the items returned should be the post with id 4, as that was excluded
ids = _.map(result.posts, 'id');
ids.should.not.containEql(testUtils.filterData.data.posts[3].id);
// Should not contain draft
ids.should.not.containEql(testUtils.filterData.data.posts[18].id);
// The ordering specifies that any post which matches both tags should be first
// Post 2 is the first in the list to have both tags
ids[0].should.eql(testUtils.filterData.data.posts[1].id);
// Each post should have a tag which matches either 'photo' or 'video'
_.each(result.posts, function (post) {
var slugs = _.map(post.tags, 'slug');
slugs.should.matchAny(/photo|video/);
});
// TODO: match order, followed by publish date
// This isn't finished yet, as the 'special rule' ordering for matching 'in' requests hasn't been
// implemented properly.
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(3);
result.meta.pagination.pages.should.eql(3);
result.meta.pagination.total.should.eql(7);
result.meta.pagination.next.should.eql(2);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
});
describe('2. Posts - filter: "tag:photo,featured:true,image:-null", include: "tags"', function () {
it('Will fetch posts which have either a tag of `photo`, are marked `featured` or have an image.', function (done) {
PostAPI.browse({
filter: 'tag:photo,featured:true,feature_image:-null',
include: 'tags'
}).then(function (result) {
var ids;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.posts.should.be.an.Array().with.lengthOf(9);
ids = _.map(result.posts, 'id');
ids.should.eql([
testUtils.filterData.data.posts[13].id,
testUtils.filterData.data.posts[10].id,
testUtils.filterData.data.posts[8].id,
testUtils.filterData.data.posts[7].id,
testUtils.filterData.data.posts[6].id,
testUtils.filterData.data.posts[5].id,
testUtils.filterData.data.posts[4].id,
testUtils.filterData.data.posts[2].id,
testUtils.filterData.data.posts[1].id
]);
_.each(result.posts, function (post) {
post.page.should.be.false();
post.status.should.eql('published');
});
// TODO: Should be in published order
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(9);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
});
describe.skip('3. Tags - filter="count.posts:>=1" order="count.posts DESC" limit="all"', function () {
// @TODO add support for counts/aggregates in order & filter params
it('Will fetch all tags, ordered by post count, where the post count is at least 1.', function (done) {
TagAPI.browse({
filter: 'count.posts:>=1',
order: 'count.posts DESC',
limit: 'all',
include: 'count.posts'
}).then(function (result) {
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('tags');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 3 matching items
result.tags.should.be.an.Array().with.lengthOf(3);
// TODO: add the ordering
// TODO: manage the count
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
// TODO complete meta data assertions
done();
}).catch(done);
});
});
describe('4. Posts - filter="author:[leslie,pat]+(tag:hash-audio,image:-null)"', function () {
// Note that `pat` doesn't exist (it's `pat-smith`)
it('[DEPRECATED] will fetch posts by the author `leslie` or `pat` which are either have tag `hash-audio` or an image.', function (done) {
PostAPI.browse({
filter: 'author:[leslie,pat]+(tag:hash-audio,feature_image:-null)',
include: 'author,tags'
}).then(function (result) {
var ids, authors;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 2 matching items
result.posts.should.be.an.Array().with.lengthOf(6);
// Each post must either have the author 'leslie' or 'pat'
authors = _.map(result.posts, function (post) {
return post.author.slug;
});
authors.should.matchAny(/leslie|pat/);
// Each post must either be featured or have the tag 'hash-audio'
_.each(result.posts, function (post) {
var tags = _.map(post.tags, 'slug');
// This construct ensures we get an assertion or a failure
if (!_.isEmpty(post.feature_image)) {
post.feature_image.should.not.be.empty();
} else {
tags = _.map(post.tags, 'slug');
tags.should.containEql('hash-audio');
}
});
ids = _.map(result.posts, 'id');
ids.should.eql([
testUtils.filterData.data.posts[13].id,
testUtils.filterData.data.posts[11].id,
testUtils.filterData.data.posts[10].id,
testUtils.filterData.data.posts[8].id,
testUtils.filterData.data.posts[7].id,
testUtils.filterData.data.posts[6].id
]);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(6);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
it('will fetch posts by the authors `leslie` or `pat` which are either have tag `hash-audio` or an image.', function (done) {
PostAPI.browse({
filter: 'authors:[leslie,pat]+(tag:hash-audio,feature_image:-null)',
include: 'authors,tags'
}).then(function (result) {
var ids, authors;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 2 matching items
result.posts.should.be.an.Array().with.lengthOf(6);
// Each post must either have the author 'leslie' or 'pat'
authors = _.map(result.posts, function (post) {
return post.authors[0].slug;
});
authors.should.matchAny(/leslie|pat/);
// Each post must either be featured or have the tag 'hash-audio'
_.each(result.posts, function (post) {
var tags = _.map(post.tags, 'slug');
// This construct ensures we get an assertion or a failure
if (!_.isEmpty(post.feature_image)) {
post.feature_image.should.not.be.empty();
} else {
tags = _.map(post.tags, 'slug');
tags.should.containEql('hash-audio');
}
});
ids = _.map(result.posts, 'id');
// ordered by authors.id
ids.should.eql([
testUtils.filterData.data.posts[6].id,
testUtils.filterData.data.posts[13].id,
testUtils.filterData.data.posts[11].id,
testUtils.filterData.data.posts[10].id,
testUtils.filterData.data.posts[8].id,
testUtils.filterData.data.posts[7].id
]);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(6);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
});
describe.skip('5. Users - filter="posts.tags:photo" order="count.posts DESC" limit="3"', function () {
// @TODO: add support for joining through posts and tags for users
it('Will fetch the 3 most prolific users who write posts with the tag `photo` ordered by most posts.', function (done) {
UserAPI.browse({
filter: 'posts.tags:special',
order: 'count.posts DESC',
limit: 3
}).then(function (result) {
var ids;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('users');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 2 matching items
result.users.should.be.an.Array().with.lengthOf(2);
ids = _.map(result.users, 'id');
ids.should.eql([
testUtils.filterData.data.posts[0].id,
testUtils.filterData.data.posts[1].id
]);
// TODO: add the order
// TODO: manage the count
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(3);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(2);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
});
describe.skip('6. Posts filter="published_at:>\'2015-07-20\'" limit="5"}}', function () {
it('Will fetch 5 posts after a given date.', function (done) {
PostAPI.browse({
filter: 'published_at:>\'2015-07-20\'',
limit: 5,
include: 'tags'
}).then(function (result) {
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// TODO: make dates work
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
// TODO complete meta data assertions
done();
}).catch(done);
});
});
describe('7. Users filter: "website:-null", order: "website"', function () {
it('Will fetch users that have a website and order them by website', function (done) {
UserAPI.browse({filter: 'website:-null', order: 'website ASC'}).then(function (result) {
var ids;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('users');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 2 matching items
result.users.should.be.an.Array().with.lengthOf(2);
ids = _.map(result.users, 'id');
ids.should.eql([
testUtils.filterData.data.users[1].id,
testUtils.filterData.data.users[0].id
]);
should.exist(result.users[0].website);
should.exist(result.users[1].website);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(2);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
});
describe('8. Tags filter: "image:-null+description:-null"', function () {
it('Will fetch tags which have an image and a description', function (done) {
TagAPI.browse({
filter: 'feature_image:-null+description:-null',
order: 'name ASC'
}).then(function (result) {
var ids;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('tags');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 3 matching items
result.tags.should.be.an.Array().with.lengthOf(3);
ids = _.map(result.tags, 'id');
ids.should.containEql(testUtils.filterData.data.tags[3].id);
ids.should.containEql(testUtils.filterData.data.tags[2].id);
ids.should.containEql(testUtils.filterData.data.tags[1].id);
// @TODO standardise how alphabetical ordering is done across DBs (see #6104)
// ids.should.eql([4, 2, 3]);
should.exist(result.tags[0].feature_image);
should.exist(result.tags[1].feature_image);
should.exist(result.tags[2].feature_image);
should.exist(result.tags[0].description);
should.exist(result.tags[1].description);
should.exist(result.tags[2].description);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(3);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
});
});
describe('Primary Tags / Primary Authors', function () {
it('Will fetch posts which have a primary tag of photo', function (done) {
PostAPI.browse({
filter: 'primary_tag:photo',
include: 'tags'
}).then(function (result) {
var ids;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.posts.should.be.an.Array().with.lengthOf(4);
ids = _.map(result.posts, 'id');
ids.should.eql([
testUtils.filterData.data.posts[10].id,
testUtils.filterData.data.posts[8].id,
testUtils.filterData.data.posts[2].id,
testUtils.filterData.data.posts[1].id
]);
_.each(result.posts, function (post) {
post.page.should.be.false();
post.status.should.eql('published');
});
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(4);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
it('Will fetch posts which have a primary author', function (done) {
PostAPI.browse({
filter: 'primary_author:leslie',
include: 'authors'
}).then(function (result) {
var returnedIds, insertedIds, clonedInsertedPosts;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// all posts
testUtils.filterData.data.posts.length.should.eql(21);
// 15 have the primary author leslie
result.posts.should.be.an.Array().with.lengthOf(15);
returnedIds = _.map(result.posts, 'id');
insertedIds = _.filter(testUtils.filterData.data.posts, {status: 'published'});
insertedIds = _.filter(insertedIds, {page: false});
insertedIds = _.filter(insertedIds, {author_id: testUtils.filterData.data.users[0].id});
insertedIds = _.map(insertedIds, 'id');
insertedIds.length.should.eql(15);
insertedIds.reverse();
returnedIds.should.eql(insertedIds);
_.each(result.posts, function (post) {
post.page.should.be.false();
post.status.should.eql('published');
});
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(15);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
it('Will fetch empty list if no post has matching primary-tag', function (done) {
PostAPI.browse({
filter: 'primary_tag:no-posts',
include: 'tags'
}).then(function (result) {
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.posts.should.be.an.Array().with.lengthOf(0);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(0);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
it('Will fetch empty list if primary_tag is internal', function (done) {
PostAPI.browse({
filter: 'primary_tag:no-posts',
include: 'tags'
}).then(function (result) {
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.posts.should.be.an.Array().with.lengthOf(0);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(0);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
});
describe('Count capabilities', function () {
it('can fetch `count.posts` for tags (public data only)', function (done) {
TagAPI.browse({include: 'count.posts'}).then(function (result) {
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('tags');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.tags.should.be.an.Array().with.lengthOf(6);
// Each tag should have the correct count
_.find(result.tags, function (tag) {
return tag.name === 'Getting Started';
}).count.posts.should.eql(4);
_.find(result.tags, function (tag) {
return tag.name === 'photo';
}).count.posts.should.eql(4);
_.find(result.tags, function (tag) {
return tag.name === 'Video';
}).count.posts.should.eql(5);
_.find(result.tags, function (tag) {
return tag.name === '#Audio';
}).count.posts.should.eql(6);
_.find(result.tags, function (tag) {
return tag.name === 'No Posts';
}).count.posts.should.eql(0);
_.find(result.tags, function (tag) {
return tag.name === 'Special';
}).count.posts.should.eql(3);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(6);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
it('can fetch and order by `count.posts` for tags (public data only)', function (done) {
TagAPI.browse({include: 'count.posts', order: 'count.posts DESC'}).then(function (result) {
var ids;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('tags');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.tags.should.be.an.Array().with.lengthOf(6);
// Each tag should have the correct count
_.find(result.tags, function (tag) {
return tag.name === 'Getting Started';
}).count.posts.should.eql(4);
_.find(result.tags, function (tag) {
return tag.name === 'photo';
}).count.posts.should.eql(4);
_.find(result.tags, function (tag) {
return tag.name === 'Video';
}).count.posts.should.eql(5);
_.find(result.tags, function (tag) {
return tag.name === '#Audio';
}).count.posts.should.eql(6);
_.find(result.tags, function (tag) {
return tag.name === 'No Posts';
}).count.posts.should.eql(0);
_.find(result.tags, function (tag) {
return tag.name === 'Special';
}).count.posts.should.eql(3);
ids = _.map(result.tags, 'id');
ids.should.eql([
testUtils.filterData.data.tags[3].id,
testUtils.filterData.data.tags[2].id,
testUtils.filterData.data.tags[0].id,
testUtils.filterData.data.tags[1].id,
testUtils.filterData.data.tags[5].id,
testUtils.filterData.data.tags[4].id
]);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(6);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
it.skip('can fetch `count.posts` for tags (all data)', function (done) {
// This is tested elsewhere for now using user context
// No way to override it for public requests
done();
});
it('can fetch `count.posts` for users (published only)', function (done) {
UserAPI.browse({include: 'count.posts'}).then(function (result) {
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('users');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.users.should.be.an.Array().with.lengthOf(3);
// Each user should have the correct count
_.find(result.users, function (user) {
return user.slug === 'leslie';
}).count.posts.should.eql(15);
_.find(result.users, function (user) {
return user.slug === 'pat-smith';
}).count.posts.should.eql(3);
_.find(result.users, function (user) {
return user.slug === 'camhowe';
}).count.posts.should.eql(0);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(3);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
it('can fetch and order by `count.posts` for users (published only)', function (done) {
UserAPI.browse({include: 'count.posts', order: 'count.posts ASC'}).then(function (result) {
var ids;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('users');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.users.should.be.an.Array().with.lengthOf(3);
// Each user should have the correct count
_.find(result.users, function (user) {
return user.slug === 'leslie';
}).count.posts.should.eql(15);
_.find(result.users, function (user) {
return user.slug === 'pat-smith';
}).count.posts.should.eql(3);
_.find(result.users, function (user) {
return user.slug === 'camhowe';
}).count.posts.should.eql(0);
ids = _.map(result.users, 'id');
ids.should.eql([
testUtils.filterData.data.users[2].id,
testUtils.filterData.data.users[1].id,
testUtils.filterData.data.users[0].id
]);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(3);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
done();
}).catch(done);
});
it.skip('can fetch `posts.all.count` for users (all posts)', function (done) {
done();
});
it.skip('can fetch `tags.count` for posts', function (done) {
done();
});
});
describe('Old Use Cases', function () {
// Please note: these tests are mostly here to help prove certain things whilst building out new behaviour
describe('Old post "filters"', function () {
it('Will fetch posts with a given tag', function (done) {
PostAPI.browse({filter: 'tag:photo', include: 'tag,author'}).then(function (result) {
var ids;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 4 matching items
result.posts.should.be.an.Array().with.lengthOf(4);
ids = _.map(result.posts, 'id');
ids.should.eql([
testUtils.filterData.data.posts[10].id,
testUtils.filterData.data.posts[8].id,
testUtils.filterData.data.posts[2].id,
testUtils.filterData.data.posts[1].id
]);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(4);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
// NOTE: new query does not have meta filter
result.meta.should.not.have.property('filters');
done();
}).catch(done);
});
it('[DEPRECATED] Will fetch posts with a given author', function (done) {
PostAPI.browse({
filter: 'author:leslie',
include: 'tag,author',
limit: 5,
page: 2
}).then(function (result) {
var ids;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.posts.should.be.an.Array().with.lengthOf(5);
ids = _.map(result.posts, 'id');
ids.should.eql([
testUtils.filterData.data.posts[12].id,
testUtils.filterData.data.posts[11].id,
testUtils.filterData.data.posts[10].id,
testUtils.filterData.data.posts[9].id,
testUtils.filterData.data.posts[8].id
]);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(2);
result.meta.pagination.limit.should.eql(5);
result.meta.pagination.pages.should.eql(3);
result.meta.pagination.total.should.eql(15);
result.meta.pagination.next.should.eql(3);
result.meta.pagination.prev.should.eql(1);
// NOTE: old query has meta filter
result.meta.should.not.have.property('filters');
done();
}).catch(done);
});
});
describe('Handling "featured"', function () {
it('Will fetch all posts regardless of featured status by default', function (done) {
PostAPI.browse({}).then(function (result) {
var ids;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.posts.should.be.an.Array().with.lengthOf(15);
ids = _.map(result.posts, 'id');
ids.should.eql([
testUtils.filterData.data.posts[19].id,
testUtils.filterData.data.posts[17].id,
testUtils.filterData.data.posts[16].id,
testUtils.filterData.data.posts[15].id,
testUtils.filterData.data.posts[13].id,
testUtils.filterData.data.posts[12].id,
testUtils.filterData.data.posts[11].id,
testUtils.filterData.data.posts[10].id,
testUtils.filterData.data.posts[9].id,
testUtils.filterData.data.posts[8].id,
testUtils.filterData.data.posts[7].id,
testUtils.filterData.data.posts[6].id,
testUtils.filterData.data.posts[5].id,
testUtils.filterData.data.posts[4].id,
testUtils.filterData.data.posts[3].id
]);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(2);
result.meta.pagination.total.should.eql(18);
result.meta.pagination.next.should.eql(2);
should.equal(result.meta.pagination.prev, null);
// NOTE: old query has meta filter
result.meta.should.not.have.property('filters');
done();
}).catch(done);
});
it('Will fetch only featured posts when requested', function (done) {
PostAPI.browse({filter: 'featured:true'}).then(function (result) {
var ids, featured;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.posts.should.be.an.Array().with.lengthOf(3);
// All posts should be marked as featured 'true'
featured = _.map(result.posts, 'featured');
featured.should.matchEach(true);
// Match exact items
ids = _.map(result.posts, 'id');
ids.should.eql([
testUtils.filterData.data.posts[13].id,
testUtils.filterData.data.posts[7].id,
testUtils.filterData.data.posts[4].id
]);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(3);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
// NOTE: old query has meta filter
result.meta.should.not.have.property('filters');
done();
}).catch(done);
});
it('Will fetch only non-featured posts when requested', function (done) {
PostAPI.browse({filter: 'featured:false'}).then(function (result) {
var ids, featured;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.posts.should.be.an.Array().with.lengthOf(15);
// All posts should be marked as featured 'false'
featured = _.map(result.posts, 'featured');
featured.should.matchEach(false);
// Match exact items
ids = _.map(result.posts, 'id');
ids.should.eql([
testUtils.filterData.data.posts[19].id,
testUtils.filterData.data.posts[17].id,
testUtils.filterData.data.posts[16].id,
testUtils.filterData.data.posts[15].id,
testUtils.filterData.data.posts[12].id,
testUtils.filterData.data.posts[11].id,
testUtils.filterData.data.posts[10].id,
testUtils.filterData.data.posts[9].id,
testUtils.filterData.data.posts[8].id,
testUtils.filterData.data.posts[6].id,
testUtils.filterData.data.posts[5].id,
testUtils.filterData.data.posts[3].id,
testUtils.filterData.data.posts[2].id,
testUtils.filterData.data.posts[1].id,
testUtils.filterData.data.posts[0].id
]);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(15);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
// NOTE: old query has meta filter
result.meta.should.not.have.property('filters');
done();
}).catch(done);
});
});
describe('Handling "page" (staticPages)', function () {
it('Will return only published posts by default', function (done) {
PostAPI.browse({limit: 'all'}).then(function (result) {
var ids, page;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.posts.should.be.an.Array().with.lengthOf(18);
// All posts should be marked as page 'false'
page = _.map(result.posts, 'page');
page.should.matchEach(false);
// Match exact items
ids = _.map(result.posts, 'id');
ids.should.eql([
testUtils.filterData.data.posts[19].id,
testUtils.filterData.data.posts[17].id,
testUtils.filterData.data.posts[16].id,
testUtils.filterData.data.posts[15].id,
testUtils.filterData.data.posts[13].id,
testUtils.filterData.data.posts[12].id,
testUtils.filterData.data.posts[11].id,
testUtils.filterData.data.posts[10].id,
testUtils.filterData.data.posts[9].id,
testUtils.filterData.data.posts[8].id,
testUtils.filterData.data.posts[7].id,
testUtils.filterData.data.posts[6].id,
testUtils.filterData.data.posts[5].id,
testUtils.filterData.data.posts[4].id,
testUtils.filterData.data.posts[3].id,
testUtils.filterData.data.posts[2].id,
testUtils.filterData.data.posts[1].id,
testUtils.filterData.data.posts[0].id
]);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql('all');
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(18);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
// NOTE: old query has meta filter
result.meta.should.not.have.property('filters');
done();
}).catch(done);
});
// @TODO: determine if this should be supported via filter, or whether it should only be available via a 'PageAPI'
it('Will return only pages when requested', function (done) {
PostAPI.browse({filter: 'page:true'}).then(function (result) {
var ids, page;
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 5 matching items
result.posts.should.be.an.Array().with.lengthOf(2);
// All posts should be marked as page 'true'
page = _.map(result.posts, 'page');
page.should.matchEach(true);
// Match exact items
ids = _.map(result.posts, 'id');
ids.should.eql([
testUtils.filterData.data.posts[20].id,
testUtils.filterData.data.posts[14].id
]);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(2);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
// NOTE: old query has meta filter
result.meta.should.not.have.property('filters');
done();
}).catch(done);
});
it.skip('Will NOT return both posts and pages from post API', function (done) {
done();
});
});
describe('Empty results', function () {
it('Will return empty result if tag has no posts', function (done) {
PostAPI.browse({filter: 'tag:no-posts', include: 'tag,author'}).then(function (result) {
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
// 2. The data part of the response should be correct
// We should have 4 matching items
result.posts.should.be.an.Array().with.lengthOf(0);
// 3. The meta object should contain the right details
result.meta.should.have.property('pagination');
result.meta.pagination.should.be.an.Object().with.properties(['page', 'limit', 'pages', 'total', 'next', 'prev']);
result.meta.pagination.page.should.eql(1);
result.meta.pagination.limit.should.eql(15);
result.meta.pagination.pages.should.eql(1);
result.meta.pagination.total.should.eql(0);
should.equal(result.meta.pagination.next, null);
should.equal(result.meta.pagination.prev, null);
// NOTE: new query does not have meta filter
result.meta.should.not.have.property('filters');
done();
}).catch(done);
});
});
});
describe('Bad behaviour', function () {
it('Try to get draft posts (filter with or)', function (done) {
PostAPI.browse({filter: 'status:published,status:draft', limit: 'all'}).then(function (result) {
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
_.each(result.posts, function (post) {
post.page.should.be.false();
post.status.should.eql('published');
});
done();
}).catch(done);
});
it('Try to get draft posts (filter with in)', function (done) {
PostAPI.browse({filter: 'status:[published,draft]', limit: 'all'}).then(function (result) {
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
_.each(result.posts, function (post) {
post.page.should.be.false();
post.status.should.eql('published');
});
done();
}).catch(done);
});
it('Try to get draft posts (filter with group)', function (done) {
PostAPI.browse({filter: 'page:false,(status:draft)', limit: 'all'}).then(function (result) {
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
_.each(result.posts, function (post) {
post.page.should.be.false();
post.status.should.eql('published');
});
done();
}).catch(done);
});
it('Try to get draft posts (filter with group and in)', function (done) {
PostAPI.browse({filter: 'page:false,(status:[draft,published])', limit: 'all'}).then(function (result) {
// 1. Result should have the correct base structure
should.exist(result);
result.should.have.property('posts');
result.should.have.property('meta');
_.each(result.posts, function (post) {
post.page.should.be.false();
post.status.should.eql('published');
});
done();
}).catch(done);
});
});
});
|
// @ts-check
const configHelpers = require('@fluentui/eslint-plugin/src/utils/configHelpers');
/** @type {import("eslint").Linter.Config} */
module.exports = {
extends: ['plugin:@fluentui/eslint-plugin/react'],
root: true,
overrides: [
// This rule requires type info, so only enable for TS files under src
// (and turn off while running lint-staged due to excessive cost)
...configHelpers.getTypeInfoRuleOverrides({
'@fluentui/deprecated-keyboard-event-props': 'error',
}),
],
};
|
importScripts("cell.js");
var a = 0;
onmessage = function(e) {
// TODO: perform bounds checking and pruning here?
var items, time;
items = e.data.items;
time = e.data.time;
//console.log("before",e.data.items[0]);
if( items ){
workOnCells(items, time);
}
}
function workOnCells(items, time) {
var i, end = items.length, /*item,*/ p;
for (i = 0; i < end; i++) {
p = new Particle();
p.merge(items[i]);
p.tick(time);
items[i] = p;
if(p.x === NaN || items[i].x === NaN)debugger;
}
postMessage({"items":items});
}
|
import tensorflow as tf
def create_mask(pred_mask):
'''
Get the channel with the highest probability to create the segmentation mask. Recall that the output of
our UNet has 2 channels. Thus, for each pixel, the predicition will be the channel with the highest probability.
'''
pred_mask = tf.argmax(pred_mask, axis=-1)
pred_mask = pred_mask[..., tf.newaxis]
return pred_mask
|
# -*- coding: utf-8 -*-
"""Advent of Code 2020 - Day 15 - Rambunctious Recitation."""
import argparse
import pdb
import traceback
from re import findall
def extract_ints(line):
return [int(x) for x in findall(r"-?\d+", line)]
def find_offsets(values, target):
offsets = []
for idx, value in enumerate(values):
if value == target:
offsets.append(idx)
return offsets
def solve(numbers, limit):
last = {}
for i, x in enumerate(numbers[:-1]):
last[x] = i
seen = numbers[-1]
for i in range(len(numbers) - 1, limit - 1):
x = i - last[seen] if seen in last else 0
last[seen] = i
seen = x
return seen
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Advent of Code - 2020 - Day 15 - Rambunctious Recitation."
)
parser.add_argument(
"input",
type=str,
default="input.txt",
nargs="?",
help="The puzzle input. (Default %(default)s)",
)
args = parser.parse_args()
try:
numbers = []
with open(args.input, "rt") as inf:
for line in inf:
numbers += extract_ints(line)
print((solve(numbers, 2020), solve(numbers, 30_000_000)))
except Exception:
traceback.print_exc()
pdb.post_mortem()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.