text
stringlengths 3
1.05M
|
---|
const { user_list } = require('./userMgt_data.js')
const { role_list } = require('./roleMgt_data.js')
const { meuns_list } = require('./menuMgt_data.js')
const menusList = {
code: 20000,
total: meuns_list.length,
data: meuns_list
}
const userList = {
code: 20000,
total: user_list.length,
data: user_list
}
const roleList = {
code: 20000,
total: role_list.length,
data: role_list
}
module.exports = [
{
url: '/vue-element-admin/menuMgt/list',
type: 'post',
response: _ => {
return menusList
}
},
{
url: '/vue-element-admin/menuMgt/handleAction',
type: 'post',
response: _ => {
return {
code: 20000,
msg: '操作成功'
}
}
},
{
url: '/vue-element-admin/menuMgt/handleDelete',
type: 'post',
response: _ => {
return {
code: 20000,
msg: '操作成功'
}
}
},
{
url: '/vue-element-admin/userMgt/getUserlist',
type: 'post',
response: _ => {
return userList
}
},
{
url: '/vue-element-admin/userMgt/handleAction',
type: 'post',
response: _ => {
return {
code: 20000,
msg: '操作成功'
}
}
},
{
url: '/vue-element-admin/userMgt/handleDelete',
type: 'post',
response: _ => {
return {
code: 20000,
msg: '操作成功'
}
}
},
{
url: '/vue-element-admin/sysRole/getRolelist',
type: 'post',
response: _ => {
return roleList
}
},
{
url: '/vue-element-admin/sysRole/setRolemenus',
type: 'post',
response: _ => {
return {
code: 20000,
msg: '操作成功'
}
}
},
{
url: '/vue-element-admin/sysRole/handleAction',
type: 'post',
response: _ => {
return {
code: 20000,
msg: '操作成功'
}
}
},
{
url: '/vue-element-admin/sysRole/handleDelete',
type: 'post',
response: _ => {
return {
code: 20000,
msg: '操作成功'
}
}
}
]
|
### Copyright (C) 2002-2006 Stephen Kennedy <[email protected]>
### This program is free software; you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation; either version 2 of the License, or
### (at your option) any later version.
### This program is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
### GNU General Public License for more details.
### You should have received a copy of the GNU General Public License
### along with this program; if not, write to the Free Software
### Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
from __future__ import generators
import difflib
def _null_or_space(s):
return len(s.strip()) == 0
if 0:
def _not_equal(s):
return filter(lambda x: x[0] != "equal", s)
else:
def _not_equal(s):
return s
################################################################################
#
# Differ
#
################################################################################
class IncrementalSequenceMatcher(difflib.SequenceMatcher):
def __init__(self, isjunk=None, a="", b=""):
difflib.SequenceMatcher.__init__(self, isjunk, a, b)
def initialise(self):
la, lb = len(self.a), len(self.b)
todo = [(0, la, 0, lb)]
done = []
while len(todo):
alo, ahi, blo, bhi = todo.pop(0)
i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
if k:
yield None
done.append((i, x))
if alo < i and blo < j:
todo.append((alo, i, blo, j))
if i + k < ahi and j + k < bhi:
todo.append((i + k, ahi, j + k, bhi))
done.append((la, (la, lb, 0)))
done.sort()
self.matching_blocks = [x[1] for x in done]
yield 1
def get_difference_opcodes(self):
return filter(lambda x: x[0] != "equal", self.get_opcodes())
################################################################################
#
# Differ
#
################################################################################
class Differ(object):
"""Utility class to hold diff2 or diff3 chunks"""
reversemap = {
"replace": "replace",
"insert": "delete",
"delete": "insert",
"conflict": "conflict",
"equal": "equal"}
def __init__(self, *sequences):
"""Initialise with 1,2 or 3 sequences to compare"""
# Internally, diffs are stored from text1 -> text0 and text1 -> text2.
self.num_sequences = len(sequences)
self.seqlength = [0, 0, 0]
for i, s in enumerate(sequences):
self.seqlength[i] = len(s)
if len(sequences) == 0 or len(sequences) == 1:
self.diffs = [[], []]
elif len(sequences) == 2:
seq0 = IncrementalSequenceMatcher(
None, sequences[1], sequences[0]).get_difference_opcodes()
self.diffs = [seq0, []]
elif len(sequences) == 3:
seq0 = IncrementalSequenceMatcher(
None, sequences[1], sequences[0]).get_difference_opcodes()
seq1 = IncrementalSequenceMatcher(
None, sequences[1], sequences[2]).get_difference_opcodes()
self.diffs = seq0, seq1
else:
raise ValueError("Bad number of arguments to Differ constructor (%i)" % len(sequences))
def change_sequence(self, sequence, startidx, sizechange, texts):
assert sequence in (0, 1, 2)
changes = [[0, 0], [0, 0]]
if sequence != 1: # 0 or 2
which = sequence / 2
changes[which] = self._change_sequence(
which, sequence, startidx, sizechange, texts)
else: # sequence==1:
changes[0] = self._change_sequence(
0, sequence, startidx, sizechange, texts)
if self.num_sequences == 3:
changes[1] = self._change_sequence(
1, sequence, startidx, sizechange, texts)
return changes
def _locate_chunk(self, whichdiffs, sequence, line):
"""Find the index of the chunk which contains line."""
idx = 1 + 2 * (sequence != 1)
line_in_chunk = lambda x: line < x[idx + 1]
i = 0
for c in self.diffs[whichdiffs]:
if line_in_chunk(c):
break
else:
i += 1
return i
def _change_sequence(self, which, sequence, startidx, sizechange, texts):
diffs = self.diffs[which]
lines_added = [0, 0, 0]
lines_added[sequence] = sizechange
loidx = self._locate_chunk(which, sequence, startidx)
if sizechange < 0:
hiidx = self._locate_chunk(which, sequence, startidx - sizechange)
else:
hiidx = loidx
if loidx > 0:
loidx -= 1
lorange = diffs[loidx][3], diffs[loidx][1]
else:
lorange = (0, 0)
x = which * 2
if hiidx < len(diffs):
hiidx += 1
hirange = diffs[hiidx - 1][4], diffs[hiidx - 1][2]
else:
hirange = self.seqlength[x], self.seqlength[1]
#print "diffs", loidx, hiidx, len(diffs), lorange, hirange #diffs[loidx], diffs[hiidx-1]
rangex = lorange[0], hirange[0] + lines_added[x]
range1 = lorange[1], hirange[1] + lines_added[1]
#print "^^^^^", rangex, range1
assert rangex[0] <= rangex[1] and range1[0] <= range1[1]
linesx = texts[x][rangex[0]:rangex[1]]
lines1 = texts[1][range1[0]:range1[1]]
#print "<<<\n%s\n===\n%s\n>>>" % ("\n".join(linesx),"\n".join(lines1))
newdiffs = IncrementalSequenceMatcher(
None, lines1, linesx).get_difference_opcodes()
newdiffs = [(c[0], c[1] + range1[0], c[2] + range1[0], c[3]
+ rangex[0], c[4] + rangex[0]) for c in newdiffs]
if hiidx < len(self.diffs[which]):
self.diffs[which][hiidx:] = [(c[0],
c[1] + lines_added[
1], c[2] + lines_added[1],
c[3] + lines_added[x], c[4] + lines_added[x])
for c in self.diffs[which][hiidx:]]
self.diffs[which][loidx:hiidx] = newdiffs
self.seqlength[sequence] += sizechange
return loidx, hiidx
def reverse(self, c):
return self.reversemap[c[0]], c[3], c[4], c[1], c[2]
def all_changes(self, texts):
for c in self._merge_diffs(self.diffs[0], self.diffs[1], texts):
yield c
def all_changes_in_range(self, texts, l0, h0, l1, h1):
for c in self._merge_diffs(self.diffs[0][l0:h0], self.diffs[1][l0:h0], texts):
yield c
def pair_changes(self, fromindex, toindex, texts):
"""Give all changes between file1 and either file0 or file2.
"""
if fromindex == 1:
seq = toindex / 2
for c in self.all_changes(texts):
if c[seq]:
yield c[seq]
else:
seq = fromindex / 2
for c in self.all_changes(texts):
if c[seq]:
yield self.reverse(c[seq])
def single_changes(self, textindex, texts):
"""Give changes for single file only. do not return 'equal' hunks.
"""
if textindex in (0, 2):
seq = textindex / 2
for cs in self.all_changes(texts):
c = cs[seq]
if c:
yield self.reversemap[c[0]], c[3], c[4], c[1], c[2], 1
else:
for cs in self.all_changes(texts):
if cs[0]:
c = cs[0]
yield c[0], c[1], c[2], c[3], c[4], 0
elif cs[1]:
c = cs[1]
yield c[0], c[1], c[2], c[3], c[4], 2
def _merge_blocks(self, using, low_seq, high_seq, last_diff):
LO, HI = 1, 2
lowc = using[low_seq][0][LO]
highc = using[low_seq][-1][HI]
if len(using[not low_seq]):
lowc = min(lowc, using[not low_seq][0][LO])
highc = max(highc, using[not low_seq][-1][HI])
low = []
high = []
for i in (0, 1):
if len(using[i]):
d = using[i][0]
low.append(lowc - d[LO] + d[2 + LO])
d = using[i][-1]
high.append(highc - d[HI] + d[2 + HI])
else:
d = last_diff
low.append(lowc - d[LO] + d[2 + LO])
high.append(highc - d[HI] + d[2 + HI])
return low[0], high[0], lowc, highc, low[1], high[1]
def _merge_diffs(self, seq0, seq1, texts):
seq0, seq1 = seq0[:], seq1[:]
seq = seq0, seq1
LO, HI = 1, 2
block = [0, 0, 0, 0, 0, 0]
while len(seq0) or len(seq1):
if len(seq0) == 0:
base_seq = 1
elif len(seq1) == 0:
base_seq = 0
else:
base_seq = seq0[0][LO] > seq1[0][LO]
high_seq = base_seq
high_diff = seq[high_seq].pop(0)
high_mark = high_diff[HI]
using = [[], []]
using[high_seq].append(high_diff)
while 1:
other_seq = high_seq ^ 1
try:
other_diff = seq[other_seq][0]
except IndexError:
break
else:
if high_mark < other_diff[LO]:
break
using[other_seq].append(other_diff)
seq[other_seq].pop(0)
if high_mark < other_diff[HI]:
high_seq ^= 1
high_diff = other_diff
high_mark = other_diff[HI]
block = self._merge_blocks(using, base_seq, high_seq, block)
if len(using[0]) == 0:
assert len(using[1]) == 1
yield None, using[1][0]
elif len(using[1]) == 0:
assert len(using[0]) == 1
yield using[0][0], None
else:
l0, h0, l1, h1, l2, h2 = block
if h0 - l0 == h2 - l2 and texts[0][l0:h0] == texts[2][l2:h2]:
if l1 != h1:
out0 = (
'replace', block[2], block[3], block[0], block[1])
out1 = (
'replace', block[2], block[3], block[4], block[5])
else:
out0 = (
'insert', block[2], block[3], block[0], block[1])
out1 = (
'insert', block[2], block[3], block[4], block[5])
else:
out0 = ('conflict', block[2], block[3], block[0], block[1])
out1 = ('conflict', block[2], block[3], block[4], block[5])
yield out0, out1
def set_sequences_iter(self, *sequences):
if len(sequences) == 0 or len(sequences) == 1:
diffs = [[], []]
elif len(sequences) == 2:
matcher = IncrementalSequenceMatcher(
None, sequences[1], sequences[0])
work = matcher.initialise()
while work.next() is None:
yield None
diffs = [matcher.get_difference_opcodes(), []]
elif len(sequences) == 3:
diffs = [[], []]
for i in range(2):
matcher = IncrementalSequenceMatcher(
None, sequences[1], sequences[i * 2])
work = matcher.initialise()
while work.next() is None:
yield None
diffs[i] = matcher.get_difference_opcodes()
else:
raise ValueError("Bad number of arguments to Differ constructor (%i)" % len(sequences))
self.diffs = diffs
self.num_sequences = len(sequences)
self.seqlength = [0, 0, 0]
for i, s in enumerate(sequences):
self.seqlength[i] = len(s)
yield 1
def main():
pass
# t0 = open("test/lao").readlines()
# tc = open("test/tzu").readlines()
# t1 = open("test/tao").readlines()
#
# thread0 = IncrementalSequenceMatcher(None, tc, t0).get_difference_opcodes()
# thread1 = IncrementalSequenceMatcher(None, tc, t1).get_difference_opcodes()
#
# texts = (t0,tc,t1)
if __name__ == "__main__":
main()
|
const _countWords = text => text.split(" ").length
const _stripPostHtml = html => {
const withoutStyleTag = html.split("<style")[0]
const strippedString = withoutStyleTag.replace(/(<([^>]+)>)/gi, "")
return strippedString
}
const getTimeToRead = text => {
const strippedText = _stripPostHtml(text)
const wpm = 220 // human word reading speed
const estimatedRaw = _countWords(strippedText) / wpm
const minutes = Math.round(estimatedRaw)
const readingTime = minutes < 1 ? "less than a min" : minutes + " min read"
return readingTime
}
export default getTimeToRead; |
'use strict';
const Joi = require('joi');
const abslog = require('abslog');
const { hashArray } = require('@asset-pipe/common');
const Metrics = require('@metrics/client');
const Bundler = require('./bundler');
const Storage = require('./storage');
const schemas = require('../lib/schemas');
const { hashContent } = require('./hasher');
module.exports = class OptimisticBundler extends Bundler {
constructor({ bundleInProcess, ...options }) {
super({ bundleInProcess });
const opts = {
sourceMaps: false,
minify: false,
...options,
};
this.storage = new Storage(options.sink);
this.metrics = new Metrics();
this.log = abslog(options.logger);
this.options = opts;
this.overrides = {};
this.bundleSizeGaugeMetric = this.metrics.gauge({
name: 'asset_server_bundle_size_gauge',
description: 'Measures the size of bundles created',
});
this.bundlingTimerMetric = this.metrics.histogram({
name: 'asset_server_bundling_timer',
description: 'Time taken to bundle assets',
buckets: [1, 5, 10, 15, 20, 30, 60, 120],
});
this.retrieveFromStorageTimerMetric = this.metrics.histogram({
name: 'asset_server_retrieve_from_storage_timer',
description: 'Time taken for a retrieve operation from storage',
buckets: [1, 5, 10, 15, 20, 30, 60, 120],
});
this.existsInStorageTimerMetric = this.metrics.histogram({
name: 'asset_server_exists_in_storage_timer',
description:
'Time taken for a check for existence operation from storage',
buckets: [1, 5, 10, 15, 20, 30, 60, 120],
});
this.persistToStorageTimerMetric = this.metrics.histogram({
name: 'asset_server_persist_to_storage_timer',
description: 'Time taken for a persist operation to storage',
buckets: [1, 5, 10, 15, 20, 30, 60, 120],
});
this.publishAssetsTimerMetric = this.metrics.histogram({
name: 'asset_server_publish_assets_timer',
description:
'Time taken for a publish assets operation to complete',
buckets: [1, 5, 10, 15, 20, 30, 60, 120],
});
this.saveFeedTimerMetric = this.metrics.histogram({
name: 'asset_server_save_feed_timer',
description: 'Time taken for a feed to be saved to storage',
buckets: [1, 5, 10, 15, 20, 30, 60, 120],
});
this.fallbackBundleSizeGaugeMetric = this.metrics.gauge({
name: 'asset_server_fallback_bundle_size_gauge',
description: 'Measures the size of fallback bundles created',
});
this.saveFallbackBundleTimerMetric = this.metrics.histogram({
name: 'asset_server_save_fallback_bundle_timer',
description:
'Time taken for a fallback bundle to be bundled and saved',
buckets: [1, 5, 10, 15, 20, 30, 60, 120],
});
this.publishInstructionsTimerMetric = this.metrics.histogram({
name: 'asset_server_publish_instructions_timer',
description: 'Time taken for publishInstructions() to complete',
buckets: [1, 5, 10, 15, 20, 30, 60, 120],
});
this.rebundleInstructionsTimerMetric = this.metrics.histogram({
name: 'asset_server_rebundle_instructions_timer',
description: 'Time taken to rebundle all instructions for a tag',
buckets: [1, 5, 10, 15, 20, 30, 60, 120],
});
}
async assetsPublished(tags, hashes, type) {
const hasFeeds = await this.hasFeeds(hashes);
const isPublished =
hasFeeds && tags.length === hashes.length && hashes.length > 0;
this.log.info(
`${type} assets for tag(s) "${tags.join(
', ',
)}" all published and ready for bundling?: ${isPublished}`,
);
return isPublished;
}
async getTags(tags, type) {
const end = this.retrieveFromStorageTimerMetric.timer();
const storageTags = await this.storage.getTags(tags, type);
end({ labels: { method: 'getTags' } });
return storageTags;
}
async getFeed(hash) {
const end = this.retrieveFromStorageTimerMetric.timer();
const feed = await this.storage.getFeed(hash);
end({ labels: { method: 'getFeed' } });
return feed;
}
async hasFeed(hash) {
const end = this.existsInStorageTimerMetric.timer();
const hasFeed = await this.storage.hasFeed(hash);
end({ labels: { method: 'hasFeed' } });
return hasFeed;
}
async hasBundle(hash, type) {
const end = this.existsInStorageTimerMetric.timer();
const hasBundle = await this.storage.hasBundle(hash, type);
end({ labels: { method: 'hasBundle' } });
return hasBundle;
}
async setBundle(hash, type, content) {
const end = this.persistToStorageTimerMetric.timer();
await this.storage.setBundle(hash, type, content);
end({ labels: { method: 'setBundle' } });
}
async getInstructions(tag, type) {
const end = this.retrieveFromStorageTimerMetric.timer();
const instructions = await this.storage.getInstructions(tag, type);
end({ labels: { method: 'getInstructions' } });
return instructions;
}
async setInstruction(tag, type, instruction) {
const end = this.persistToStorageTimerMetric.timer();
await this.storage.setInstruction(tag, type, instruction);
end({ labels: { method: 'setInstruction' } });
}
async setFeed(feedHash, assetFeed) {
const end = this.persistToStorageTimerMetric.timer();
await this.storage.setFeed(feedHash, assetFeed);
end({ labels: { method: 'setFeed' } });
}
async setTag(tag, assetType, feedHash) {
const end = this.persistToStorageTimerMetric.timer();
await this.storage.setTag(tag, assetType, feedHash);
end({ labels: { method: 'setTag' } });
}
async bundleExists(tags, hashes, type) {
const hash = hashArray(hashes);
const exists = await this.hasBundle(hash, type);
this.log.info(
`${type} bundle (for tag(s) "${tags.join(
', ',
)}" using hashes "${hashes.join(
',',
)} to produce file ${hash}.${type}") already exists?: ${exists}`,
);
return exists;
}
async getFeeds(hashes) {
return Promise.all(hashes.map(hash => this.getFeed(hash)));
}
async hasFeeds(hashes) {
const result = await Promise.all(
hashes.map(hash => this.storage.hasFeed(hash)),
);
return result.every(hasFeed => hasFeed === true);
}
async bundle(tag, tags, hashes, type) {
const feeds = await this.getFeeds(hashes);
const end = this.bundlingTimerMetric.timer({
labels: {
sources: JSON.stringify(tags),
assetType: type,
publisher: tag,
},
});
const content = await super.bundleFeeds(feeds, type, {
...this.options,
...this.overrides,
});
const hash = hashArray(hashes);
end();
this.bundleSizeGaugeMetric.set(Buffer.byteLength(content, 'utf8'), {
labels: {
sources: JSON.stringify(tags),
assetType: type,
publisher: tag,
},
});
return { content, hash };
}
async bundleIfNeeded(instruction) {
const { data: tags, type, tag } = instruction;
const hashes = await this.getTags(tags, type);
if (
(await this.assetsPublished(tags, hashes, type)) &&
!(await this.bundleExists(tags, hashes, type))
) {
this.log.debug(
`${type} bundle for instruction: "[${tags.join(
', ',
)}]" using hashes: "[${hashes.join(
', ',
)}]" will be produced: true`,
);
const { content, hash } = await this.bundle(
tag,
tags,
hashes,
type,
);
await this.setBundle(hash, type, content);
this.log.info(
`${type} bundle for instruction: "[${tags.join(
', ',
)}]" completed and saved as: "${hash}.${type}"`,
);
} else {
this.log.debug(
`${type} bundle for instruction: "[${tags.join(
', ',
)}]" using hashes: "[${hashes.join(
', ',
)}]" will be produced: false`,
);
}
}
async bundleInstructions(instructions) {
return Promise.all(
instructions.map(instruction => this.bundleIfNeeded(instruction)),
);
}
async rebundle(tag, type) {
const end = this.rebundleInstructionsTimerMetric.timer({
labels: {
assetType: type,
publisher: tag,
},
});
const instructions = await this.getInstructions(tag, type);
if (instructions.length) {
await this.bundleInstructions(instructions);
}
end();
}
async publishInstructions(instruction, options = {}) {
const { tag, type, data: tags } = Joi.attempt(
instruction,
schemas.instruction,
`Invalid 'instruction' object given when attempting to publish instructions.`,
);
const end = this.publishAssetsTimerMetric.timer({
labels: {
assetType: type,
publisher: tag,
},
});
this.overrides = options;
await this.setInstruction(tag, type, instruction);
this.log.info(
`${type} bundling instruction "[${tags.join(
', ',
)}]" published to "/instructions/${type}/${tag}.json"`,
);
await this.bundleIfNeeded(instruction);
end();
}
async saveFallbackBundle(tag, hash, type, feed) {
const end = this.saveFallbackBundleTimerMetric.timer({
labels: {
assetType: type,
publisher: tag,
},
});
if (await this.hasBundle(hash, type)) {
this.log.info(
`${type} fallback bundle for tag "${tag}" already exists as "${hash}.${type}" and will not be published`,
);
} else {
const bundle = await super.bundleFeeds([feed], type);
await this.setBundle(hash, type, bundle);
this.fallbackBundleSizeGaugeMetric.set(
Buffer.byteLength(bundle, 'utf8'),
{
labels: {
assetType: type,
publisher: tag,
},
},
);
this.log.info(
`${type} fallback bundle for tag "${tag}" published as "${hash}.${type}"`,
);
}
end();
}
async saveFeed(tag, hash, type, feed) {
const end = this.saveFeedTimerMetric.timer({
labels: {
assetType: type,
publisher: tag,
},
});
if (await this.hasFeed(hash)) {
this.log.info(
`${type} asset feed for tag "${tag}" already exists as "${hash}.json" and will not be published`,
);
} else {
this.log.info(
`${type} asset feed for tag "${tag}" published as "${hash}.json"`,
);
await this.setFeed(hash, feed);
}
end();
}
async publishAssets(assets, options) {
const { tag, type, data: assetFeed } = Joi.attempt(
assets,
schemas.assets,
`Invalid 'assets' object given when attempting to publish assets.`,
);
const end = this.publishAssetsTimerMetric.timer({
labels: {
assetType: type,
publisher: tag,
},
});
const opts = { rebundle: true, ...options };
this.log.debug(
`request to publish ${type} asset feed for tag "${tag}" received`,
);
this.overrides = opts;
const feedHash = hashContent(assetFeed);
await Promise.all([
this.saveFeed(tag, feedHash, type, assetFeed),
this.saveFallbackBundle(tag, feedHash, type, assetFeed),
]);
if (opts.rebundle) {
await this.setTag(tag, type, feedHash);
this.log.debug(
`${type} tag metadata updated. Wrote "${feedHash}" to "/tags/${type}/${tag}.txt"`,
);
await this.rebundle(tag, type);
this.log.debug(`${type} rebundling for tag "${tag}" complete`);
}
end();
return { id: feedHash, file: `${feedHash}.json` };
}
};
|
// Copyright 2008 The Closure Library Authors. 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.
/**
* @fileoverview Renderer for {@link goog.ui.Button}s in App style.
*
* Based on ImagelessButtonRender. Uses even more CSS voodoo than the default
* implementation to render custom buttons with fake rounded corners and
* dimensionality (via a subtle flat shadow on the bottom half of the button)
* without the use of images.
*
* Based on the Custom Buttons 3.1 visual specification, see
* http://go/custombuttons
*
* @author [email protected] (Emil A Eklund)
*/
goog.provide('goog.ui.style.app.ButtonRenderer');
goog.require('goog.dom.classes');
goog.require('goog.ui.Button');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.CustomButtonRenderer');
goog.require('goog.ui.INLINE_BLOCK_CLASSNAME');
goog.require('goog.ui.registry');
/**
* Custom renderer for {@link goog.ui.Button}s. Imageless buttons can contain
* almost arbitrary HTML content, will flow like inline elements, but can be
* styled like block-level elements.
*
* @constructor
* @extends {goog.ui.CustomButtonRenderer}
*/
goog.ui.style.app.ButtonRenderer = function() {
goog.ui.CustomButtonRenderer.call(this);
};
goog.inherits(goog.ui.style.app.ButtonRenderer, goog.ui.CustomButtonRenderer);
goog.addSingletonGetter(goog.ui.style.app.ButtonRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.style.app.ButtonRenderer.CSS_CLASS = goog.getCssName('goog-button');
/**
* Array of arrays of CSS classes that we want composite classes added and
* removed for in IE6 and lower as a workaround for lack of multi-class CSS
* selector support.
* @type {Array.<Array.<string>>}
*/
goog.ui.style.app.ButtonRenderer.IE6_CLASS_COMBINATIONS = [];
/**
* Returns the button's contents wrapped in the following DOM structure:
* <div class="goog-inline-block goog-button-base goog-button">
* <div class="goog-inline-block goog-button-base-outer-box">
* <div class="goog-button-base-inner-box">
* <div class="goog-button-base-pos">
* <div class="goog-button-base-top-shadow"> </div>
* <div class="goog-button-base-content">Contents...</div>
* </div>
* </div>
* </div>
* </div>
* Overrides {@link goog.ui.ButtonRenderer#createDom}.
* @param {goog.ui.Button} button Button to render.
* @return {Element} Root element for the button.
* @override
*/
goog.ui.style.app.ButtonRenderer.prototype.createDom =
goog.ui.style.app.ButtonRenderer.superClass_.createDom;
/** @override */
goog.ui.style.app.ButtonRenderer.prototype.getContentElement = function(
element) {
return element && /** @type {Element} */(
element.firstChild.firstChild.firstChild.lastChild);
};
/**
* Takes a text caption or existing DOM structure, and returns the content
* wrapped in a pseudo-rounded-corner box. Creates the following DOM structure:
* <div class="goog-inline-block goog-button-base-outer-box">
* <div class="goog-inline-block goog-button-base-inner-box">
* <div class="goog-button-base-pos">
* <div class="goog-button-base-top-shadow"> </div>
* <div class="goog-button-base-content">Contents...</div>
* </div>
* </div>
* </div>
* Used by both {@link #createDom} and {@link #decorate}. To be overridden
* by subclasses.
* @param {goog.ui.ControlContent} content Text caption or DOM structure to wrap
* in a box.
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Pseudo-rounded-corner box containing the content.
* @override
*/
goog.ui.style.app.ButtonRenderer.prototype.createButton = function(content,
dom) {
var baseClass = this.getStructuralCssClass();
var inlineBlock = goog.ui.INLINE_BLOCK_CLASSNAME + ' ';
return dom.createDom(
'div', inlineBlock + goog.getCssName(baseClass, 'outer-box'),
dom.createDom(
'div', inlineBlock + goog.getCssName(baseClass, 'inner-box'),
dom.createDom('div', goog.getCssName(baseClass, 'pos'),
dom.createDom(
'div', goog.getCssName(baseClass, 'top-shadow'), '\u00A0'),
dom.createDom(
'div', goog.getCssName(baseClass, 'content'), content))));
};
/**
* Check if the button's element has a box structure.
* @param {goog.ui.Button} button Button instance whose structure is being
* checked.
* @param {Element} element Element of the button.
* @return {boolean} Whether the element has a box structure.
* @protected
* @override
*/
goog.ui.style.app.ButtonRenderer.prototype.hasBoxStructure = function(
button, element) {
var baseClass = this.getStructuralCssClass();
var outer = button.getDomHelper().getFirstElementChild(element);
var outerClassName = goog.getCssName(baseClass, 'outer-box');
if (outer && goog.dom.classes.has(outer, outerClassName)) {
var inner = button.getDomHelper().getFirstElementChild(outer);
var innerClassName = goog.getCssName(baseClass, 'inner-box');
if (inner && goog.dom.classes.has(inner, innerClassName)) {
var pos = button.getDomHelper().getFirstElementChild(inner);
var posClassName = goog.getCssName(baseClass, 'pos');
if (pos && goog.dom.classes.has(pos, posClassName)) {
var shadow = button.getDomHelper().getFirstElementChild(pos);
var shadowClassName = goog.getCssName(baseClass, 'top-shadow');
if (shadow && goog.dom.classes.has(shadow, shadowClassName)) {
var content = button.getDomHelper().getNextElementSibling(shadow);
var contentClassName = goog.getCssName(baseClass, 'content');
if (content && goog.dom.classes.has(content, contentClassName)) {
// We have a proper box structure.
return true;
}
}
}
}
}
return false;
};
/** @override */
goog.ui.style.app.ButtonRenderer.prototype.getCssClass = function() {
return goog.ui.style.app.ButtonRenderer.CSS_CLASS;
};
/** @override */
goog.ui.style.app.ButtonRenderer.prototype.getStructuralCssClass = function() {
// TODO(user): extract to a constant.
return goog.getCssName('goog-button-base');
};
/** @override */
goog.ui.style.app.ButtonRenderer.prototype.getIe6ClassCombinations =
function() {
return goog.ui.style.app.ButtonRenderer.IE6_CLASS_COMBINATIONS;
};
// Register a decorator factory function for goog.ui.style.app.ButtonRenderer.
goog.ui.registry.setDecoratorByClassName(
goog.ui.style.app.ButtonRenderer.CSS_CLASS,
function() {
return new goog.ui.Button(null,
goog.ui.style.app.ButtonRenderer.getInstance());
});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _default = {
'@context': 'http://iiif.io/api/presentation/3/context.json',
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/mahler-symphony-3.json',
type: 'Manifest',
label: {
en: ['Symphony no. 3 - Mahler, Gustav, 1860-1911']
},
description: 'Published by the Indiana University School of Music. Recorded Jan. 17-18, 1995, in the Musical Arts Center, Bloomington, Ind. Compact disc',
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/1',
type: 'Canvas',
duration: 1985,
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/annopage/1',
type: 'AnnotationPage',
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/annopage/1/1',
type: 'Annotation',
motivation: 'painting',
target: 'https://dlib.indiana.edu/iiif_av/canvas/1',
body: [{
type: 'Choice',
choiceHint: 'user',
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/CD1/high/320Kbps.mp4',
type: 'Video',
format: 'video/mp4',
label: {
en: ['High']
}
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/CD1/medium/128Kbps.mp4',
type: 'Video',
format: 'video/mp4',
label: {
en: ['Medium']
}
}]
}]
}]
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/2',
type: 'Canvas',
duration: 3829,
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/annopage/2',
type: 'AnnotationPage',
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/annopage/2/2',
type: 'Annotation',
motivation: 'painting',
target: 'https://dlib.indiana.edu/iiif_av/canvas/2',
body: [{
type: 'Choice',
choiceHint: 'user',
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/CD2/high/320Kbps.mp4',
type: 'Video',
format: 'video/mp4; codec..xxxxx',
label: {
en: ['High']
}
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/CD2/medium/128Kbps.mp4',
type: 'Video',
format: 'video/mp4; codec..xxxxx',
label: {
en: ['Medium']
}
}]
}]
}]
}]
}],
seeAlso: [{
id: 'http://localhost:3001/src/json/upc-video-subtitles-en.vtt',
type: 'Text',
format: 'application/webvtt',
label: 'subtitles'
}],
structures: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/0',
type: 'Range',
behavior: 'top',
label: {
en: ['Symphony no. 3 - Mahler, Gustav']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/1',
type: 'Range',
behavior: 'no-nav',
label: {
en: ['CD1 - Mahler, Symphony No.3']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/1-1',
type: 'Range',
label: {
en: ['Track 1. I. Kraftig']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/1#t=0,374',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/1-2',
type: 'Range',
label: {
en: ['Track 2. Langsam. Schwer']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/1#t=374,525',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/1-3',
type: 'Range',
label: {
en: ['Track 3. Tempo I']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/1#t=525,711',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/1-4',
type: 'Range',
label: {
en: ['Track 4. Schwungvoll']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/1#t=711,1188',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/1-5',
type: 'Range',
label: {
en: ['Track 5. Immer dasselbe Tempo']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/1#t=1188,1406',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/1-6',
type: 'Range',
label: {
en: ['Track 6. Wie zu Anfang']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/1#t=1406,1693',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/1-7',
type: 'Range',
label: {
en: ['Track 7. Tempo I']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/1#t=01693,1985',
type: 'Canvas'
}]
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/2',
type: 'Range',
label: {
en: ['CD2 - Mahler, Symphony No.3 (cont.)']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/2-1',
type: 'Range',
label: {
en: ['Track 1. II. Tempo di Menuetto']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/2#t=0,566',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/2-2',
type: 'Range',
label: {
en: ['Track 2. III. Comodo']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/2#t=566,1183',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/2-3',
type: 'Range',
label: {
en: ['Track 3. Tempo I']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/2#t=1183,1635',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/2-4',
type: 'Range',
label: {
en: ['Track 4. IV. Misterioso']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/2#t=1635,2204',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/2-5',
type: 'Range',
label: {
en: ['Track 5. V. Lustig im Tempo']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/2#t=2204,2475',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/2-6',
type: 'Range',
label: {
en: ['Track 6. VI. Langsam']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/2#t=2475,3047',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/2-7',
type: 'Range',
label: {
en: ['Track 7. Nicht mehr so breit']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/2#t=3047,3287',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/2-8',
type: 'Range',
label: {
en: ['Track 8. Tempo I']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/2#t=3287,3451',
type: 'Canvas'
}]
}, {
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/range/2-9',
type: 'Range',
label: {
en: ['Track 9. Tempo I']
},
items: [{
id: 'https://dlib.indiana.edu/iiif_av/mahler-symphony-3/canvas/2#t=3451,3829',
type: 'Canvas'
}]
}]
}]
}]
};
exports["default"] = _default; |
import typer
from prompt_toolkit.formatted_text import HTML
from .dialog import radiolist_dialog, ansired
from .utils import no_traceback as nt, repo
app = typer.Typer(help='start/submit/delete a feature branch')
@app.command()
def start(name: str = typer.Argument(..., help='branch name')):
"""create a branch from main branch
"""
nt(repo.git.checkout)('develop')
branch = repo.create_head(f"f-{name}")
repo.head.reference = branch
typer.echo(f'start feature {branch}')
@app.command()
def submit(name: str = typer.Argument(repo.head.reference.name, help='branch name')):
""" submit branch to Test branch.
"""
nt(repo.git.checkout)('test')
nt(repo.git.merge)(name)
@app.command()
def delete():
values = [(head, head.name) for head in repo.heads if head.name.startswith('f')]
result = radiolist_dialog(
title=HTML(f'Choose a branch to delete (Press {ansired("Enter")} to confirm, {ansired("Esc")} to cancel):'),
values=values)
if not result:
raise typer.Abort()
if repo.head.reference == result:
nt(repo.git.checkout)('develop')
nt(repo.delete_head)(result)
@app.command()
def finish(name: str = typer.Argument(repo.head.reference.name, help='branch name')):
""" publish branch to release
"""
nt(repo.git.checkout)('main')
nt(repo.git.merge(name))
|
(this.webpackJsonpweb_frontend=this.webpackJsonpweb_frontend||[]).push([[0],{405:function(e,t,n){"use strict";n.r(t);var i=n(8),r=n.n(i),o=n(31),c=n.n(o),s=(n(80),n(46)),a=n(75),d=n.n(a),l=n(9);function b(){return Object(l.jsx)(d.a,{height:window.outerHeight,params:u})}var u={particles:{number:{value:160,density:{enable:!1}},size:{value:3,random:!0,anim:{speed:4,size_min:.3}},line_linked:{enable:!1},move:{random:!0,speed:1,direction:"top",out_mode:"out"}},interactivity:{events:{onhover:{enable:!0,mode:"bubble"},onclick:{enable:!0,mode:"repulse"}},modes:{bubble:{distance:250,duration:2,size:0,opacity:0},repulse:{distance:400,duration:4}}}},p=n.p+"static/media/title.71eb2cc8.svg";n(404);function j(){var e="".concat(p,"#svgView(preserveAspectRatio(none))");return Object(l.jsx)(s.a,{top:!0,style:{borderRadius:"10px",padding:"5px 20px"},trigger:"hover",content:Object(l.jsx)(h,{}),children:Object(l.jsx)("img",{src:e,alt:"",height:"35%",style:{cursor:"pointer"},onClick:function(){window.open("https://github.com/irfan-zahir/runchit-app","_blank").focus()}})})}function h(){return Object(l.jsxs)("div",{style:{display:"flex",flexDirection:"row",alignItems:"center",fontSize:"1.15rem"},children:[Object(l.jsx)("i",{className:"fab fa-github-square",style:{marginRight:"15px",fontSize:"2rem"}}),"View on GitHub"]})}var m=function(){return Object(l.jsxs)(l.Fragment,{children:[Object(l.jsx)(j,{}),Object(l.jsxs)("div",{children:["An open source inventory management system by",Object(l.jsx)(s.a,{bottom:!0,trigger:"hover",content:"Visit profile page",children:Object(l.jsx)("a",{id:"myportfolio",target:"_blank",rel:"noopenner noreferrer",href:"http://irfanzhr.me/",children:" Irfan Zahir"})})]}),Object(l.jsx)("div",{className:"particles-background-container",children:Object(l.jsx)(b,{})})]})};c.a.render(Object(l.jsx)(r.a.StrictMode,{children:Object(l.jsx)(m,{})}),document.getElementById("root"))},80:function(e,t,n){}},[[405,1,2]]]);
//# sourceMappingURL=main.ccc2879f.chunk.js.map |
const { gql } = require('apollo-server-express');
const typeDefs = gql`
scalar Date
type Note {
id: ID!
content: String!
htmlContent: String!
author: User!
favoriteCount: Int!
favoritedBy: [User!]
createdAt: Date!
updatedAt: Date!
}
type NoteFeed {
page: Int!
pages: Int!
total: Int!
notes: [Note!]!
}
type User {
id: ID!
name: String
avatar: String
notes: [Note!]!
favorites: [Note!]!
}
type Query {
singleNote(id: ID!): Note
notes: [Note!]!
noteFeed(page: Int): NoteFeed
myNotes: [Note!]
myFavorites: [Note!]
userFavorites(id: ID!): [Note!]
singleUser(id: ID!): User
allUsers: [User!]!
me: User!
}
type Mutation {
newNote(content: String!): Note
updateNote(id: ID!, content: String!): Note!
deleteNote(id: ID!): Boolean!
toggleFavorite(id: ID!): Note
}
`;
module.exports = typeDefs;
|
# Author : Rajanikant Tenguria
def kapnum(i):
f=len(list(str(i)))
mod=10**(f)
l=i*i
j=l/mod
k=l%mod
#print i,j,k,j+k,l
if (j+k)==i:
return 1
else:
return 0
n=int(raw_input())
m=int(raw_input())
cnt=0
for i in range(n,m+1):
if kapnum(i):
print i,
cnt+=1
if cnt==0:
print "INVALID RANGE"
|
const Component = require('react').Component
const connect = require('react-redux').connect
const h = require('react-hyperscript')
const inherits = require('util').inherits
const TokenBalance = require('./token-balance')
const Identicon = require('./identicon')
const currencyFormatter = require('currency-formatter')
const currencies = require('currency-formatter/currencies')
const { formatBalance, generateBalanceObject } = require('../util')
module.exports = connect(mapStateToProps)(BalanceComponent)
function mapStateToProps (state) {
const accounts = state.metamask.accounts
const network = state.metamask.network
const selectedAddress = state.metamask.selectedAddress || Object.keys(accounts)[0]
const account = accounts[selectedAddress]
return {
account,
network,
conversionRate: state.metamask.conversionRate,
currentCurrency: state.metamask.currentCurrency,
}
}
inherits(BalanceComponent, Component)
function BalanceComponent () {
Component.call(this)
}
BalanceComponent.prototype.render = function () {
const props = this.props
const { token, network } = props
return h('div.balance-container', {}, [
// TODO: balance icon needs to be passed in
// h('img.balance-icon', {
// src: '../images/eth_logo.svg',
// style: {},
// }),
h(Identicon, {
diameter: 50,
address: token && token.address,
network,
}),
token ? this.renderTokenBalance() : this.renderBalance(),
])
}
BalanceComponent.prototype.renderTokenBalance = function () {
const { token } = this.props
return h('div.flex-column.balance-display', [
h('div.token-amount', [ h(TokenBalance, { token }) ]),
])
}
BalanceComponent.prototype.renderBalance = function () {
const props = this.props
const { shorten, account } = props
const balanceValue = account && account.balance
const needsParse = 'needsParse' in props ? props.needsParse : true
const formattedBalance = balanceValue ? formatBalance(balanceValue, 6, needsParse) : '...'
const showFiat = 'showFiat' in props ? props.showFiat : true
if (formattedBalance === 'None' || formattedBalance === '...') {
return h('div.flex-column.balance-display', {}, [
h('div.token-amount', {
style: {},
}, formattedBalance),
])
}
return h('div.flex-column.balance-display', {}, [
h('div.token-amount', {
style: {},
}, this.getTokenBalance(formattedBalance, shorten)),
showFiat ? this.renderFiatValue(formattedBalance) : null,
])
}
BalanceComponent.prototype.renderFiatValue = function (formattedBalance) {
const { conversionRate, currentCurrency } = this.props
const fiatDisplayNumber = this.getFiatDisplayNumber(formattedBalance, conversionRate)
const fiatPrefix = currentCurrency === 'USD' ? '$' : ''
return this.renderFiatAmount(fiatDisplayNumber, currentCurrency, fiatPrefix)
}
BalanceComponent.prototype.renderFiatAmount = function (fiatDisplayNumber, fiatSuffix, fiatPrefix) {
const shouldNotRenderFiat = fiatDisplayNumber === 'N/A' || Number(fiatDisplayNumber) === 0
if (shouldNotRenderFiat) return null
const upperCaseFiatSuffix = fiatSuffix.toUpperCase()
const display = currencies.find(currency => currency.code === upperCaseFiatSuffix)
? currencyFormatter.format(Number(fiatDisplayNumber), {
code: upperCaseFiatSuffix,
})
: `${fiatPrefix}${fiatDisplayNumber} ${upperCaseFiatSuffix}`
return h('div.fiat-amount', {
style: {},
}, display)
}
BalanceComponent.prototype.getTokenBalance = function (formattedBalance, shorten) {
const balanceObj = generateBalanceObject(formattedBalance, shorten ? 1 : 3)
const balanceValue = shorten ? balanceObj.shortBalance : balanceObj.balance
const label = balanceObj.label
return `${balanceValue} ${label}`
}
BalanceComponent.prototype.getFiatDisplayNumber = function (formattedBalance, conversionRate) {
if (formattedBalance === 'None') return formattedBalance
if (conversionRate === 0) return 'N/A'
const splitBalance = formattedBalance.split(' ')
const convertedNumber = (Number(splitBalance[0]) * conversionRate)
const wholePart = Math.floor(convertedNumber)
const decimalPart = convertedNumber - wholePart
return wholePart + Number(decimalPart.toPrecision(2))
}
|
/*
Copyright 2019 Politica para Todos
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.
*/
import React, { PureComponent, Fragment } from "react";
import Layout from 'antd/es/layout';
const Sider = Layout.Sider;
import MetaTags from "../../MetaTags";
import LayoutHeader from "../../common/LayoutHeader";
import LayoutFooter from "../../common/LayoutFooter";
import ManifestoSider from "./ManifestoSider";
import ManifestoSection from "./ManifestoSection";
import PartyHeader from "../PartyHeader";
import { slugify } from "../../../utils";
class PartyManifesto extends PureComponent {
constructor() {
super()
this.state = {
title: "",
sections: [],
section: undefined,
party: {}
}
}
getItems() {
const { section_id } = this.props.match.params;
if (section_id) {
return fetch(`/manifesto_sections/${section_id}.json`)
.then(res => res.json())
.catch((error) => {
console.log(error);
});
}
return []
}
getManifestoData() {
const { party_acronym } = this.props.match.params;
// party_acronym is already encoded
return fetch(`/parties/${party_acronym}/manifesto.json`)
.then(res => res.json())
.catch((error) => {
console.log(error);
});
}
getParty() {
const { party_acronym } = this.props.match.params;
// party_acronym is already encoded
return fetch(`/parties/${party_acronym}.json`)
.then(res => res.json())
.catch((error) => {
console.log(error);
});
}
componentDidMount() {
const itemsPromise = this.getItems()
const manifestoDataPromise = this.getManifestoData()
const partyPromise = this.getParty()
Promise.all([itemsPromise, manifestoDataPromise, partyPromise]).then((results) => {
const [section, manifesto, party] = results;
this.setState({
title: manifesto.title,
sections: manifesto.sections,
section: section,
party: party
});
});
}
getSelectedKey(sections, section_id) {
return section_id ? [section_id] : []
}
getOpenKey(sections, section_id) {
let openKey = []
sections.forEach((section) => {
if (section.subsections.length > 0) {
section.subsections.forEach((subsection) => {
if (subsection.id.toString() === section_id) {
openKey = [section.id.toString()]
}
})
}
})
return openKey.length ? openKey : [];
}
render() {
const { sections, title, section, party } = this.state;
const { section_id, party_acronym } = this.props.match.params;
return (
<Layout className="party-manifesto">
{party.name && (
<MetaTags
pageTitle={`Programa Eleitoral - ${party.name}`}
pageDescription={`Informações sobre o programa eleitoral do ${party.acronym}`}
pageTitle={`Programa Eleitoral - ${party.name}`}
socialDescription={`Informações sobre o programa eleitoral do ${party.acronym}`}
socialImage={`/images/share/banner-${slugify(party.acronym)}.jpg`}
/>
)}
<LayoutHeader />
<Layout.Content>
<PartyHeader
party={party}
subtitle={`${party.acronym} - Programa`}
/>
<Layout>
<Sider width={400} className="party-manifesto-sider">
{sections.length && (
<ManifestoSider
sections={sections}
party_acronym={party_acronym}
section_id={section_id}
selectedKey={this.getSelectedKey(sections, section_id)}
openKey={this.getOpenKey(sections, section_id)}
/>
)}
</Sider>
<Layout.Content>
{section && (
<ManifestoSection title={title} section={section} section_id={section_id} />
)}
</Layout.Content>
</Layout>
</Layout.Content>
<LayoutFooter />
</Layout>
);
}
}
export default PartyManifesto;
|
""""
Tools for models
@ load original resnet18 detector with load_original
@ Optimized model with trt_converter
@ load optimized model using load_optz
author: nakmuayoder
date 10/2021
"""
import json
import trt_pose.coco
import torch2trt
import torch
import trt_pose.models
import os
from google_drive_downloader import GoogleDriveDownloader as gdd
from torch2trt import TRTModule
from trt_pose.parse_objects import ParseObjects
__path = os.path.dirname(os.path.abspath(__file__))
__original_model = "resnet18_baseline_att_224x224_A_epoch_249.pth"
__optimized_model = "resnet18_{}_224x224_optz.pth"
def download_model():
"""
Download pose estimation model from google drive
"""
gdd.download_file_from_google_drive(file_id='1XYDdCUdiF2xxx4rznmLb62SdOUZuoNbd', dest_path=os.path.join(__path, __original_model))
def load_original():
"""
Load original model
"""
path = os.path.join(__path, __original_model)
if not os.path.exists(path):
download_model()
return torch.load(path)
def trt_converter(batch_size=1):
"""
Convert torch model to trt
"""
mdl = os.path.join(__path, __optimized_model.format(batch_size))
if os.path.exists(mdl):
return
with open(os.path.join(__path, "person.json"), 'r') as f:
human_pose = json.load(f)
num_parts = len(human_pose['keypoints'])
num_links = len(human_pose['skeleton'])
print("Dl info")
model = trt_pose.models.resnet18_baseline_att(num_parts, 2 * num_links).cuda().eval()
print("Load model")
model.load_state_dict(load_original())
print("Start conversion")
model_trt = torch2trt.torch2trt(model, [torch.zeros((batch_size, 3, 224, 224)).cuda()], fp16_mode=True, max_workspace_size=1<<25)
print("Save model")
torch.save(model_trt.state_dict(), mdl)
def load_optz(batch_size=1):
"""
Load opptimized model
"""
path = os.path.join(__path, __optimized_model.format(batch_size))
model_trt = TRTModule()
model_trt.load_state_dict(torch.load(path))
return model_trt
def get_parse_objects():
"""
return a parse object
"""
path = os.path.join(__path, "person.json")
with open(path, 'r') as f:
human_pose = json.load(f)
topology = trt_pose.coco.coco_category_to_topology(human_pose)
return ParseObjects(topology) |
# -*- coding: utf-8 -*-
"""ardublocklyserver package.
Copyright (c) 2017 carlosperate https://github.com/carlosperate/
Licensed under the Apache License, Version 2.0 (the "License"):
http://www.apache.org/licenses/LICENSE-2.0
There is a specific requirements for this Python project to not need external
module dependencies, so all third-party modules have been carefully chosen with
this purpose in mind and included in a folder named 'local-packages'.
The sys.path has to be expanded to be able to import these.
"""
import os
import sys
# Adding the local-packages to the sys path
local_packages_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'local-packages')
sys.path.insert(0, local_packages_path)
# Follows Semantic Versioning 2.0.0 http://semver.org/spec/v2.0.0.html
__version__ = '0.1.3-a'
__author__ = 'carlosperate'
__copyright__ = 'Copyright 2017, carlosperate https://github.com/carlosperate/'
__license__ = 'Apache License, Version 2.0'
|
/**
* Kendo UI v2016.1.118 (http://www.telerik.com/kendo-ui)
* Copyright 2016 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
!function(o,define){define("util/main.min",["kendo.core.min"],o)}(function(){return function(){function o(o){return typeof o!==S}function e(o,e){var l=r(e);return M.round(o*l)/l}function r(o){return o?M.pow(10,o):1}function l(o,e,r){return M.max(M.min(o,r),e)}function c(o){return o*W}function a(o){return o/W}function t(o){return"number"==typeof o&&!isNaN(o)}function n(e,r){return o(e)?e:r}function i(o){return o*o}function f(o){var e,r=[];for(e in o)r.push(e+o[e]);return r.sort().join("")}function s(o){var e,r=2166136261;for(e=0;o.length>e;++e)r+=(r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24),r^=o.charCodeAt(e);return r>>>0}function d(o){return s(f(o))}function b(o){var e,r=o.length,l=I,c=N;for(e=0;r>e;e++)c=M.max(c,o[e]),l=M.min(l,o[e]);return{min:l,max:c}}function u(o){return b(o).min}function h(o){return b(o).max}function k(o){return m(o).min}function g(o){return m(o).max}function m(o){var e,r,l,c=I,a=N;for(e=0,r=o.length;r>e;e++)l=o[e],null!==l&&isFinite(l)&&(c=M.min(c,l),a=M.max(a,l));return{min:c===I?void 0:c,max:a===N?void 0:a}}function p(o){return o?o[o.length-1]:void 0}function v(o,e){return o.push.apply(o,e),o}function w(o){return G.template(o,{useWithBlock:!1,paramName:"d"})}function C(e,r){return o(r)&&null!==r?" "+e+"='"+r+"' ":""}function y(o){var e,r="";for(e=0;o.length>e;e++)r+=C(o[e][0],o[e][1]);return r}function D(e){var r,l,c="";for(r=0;e.length>r;r++)l=e[r][1],o(l)&&(c+=e[r][0]+":"+l+";");return""!==c?c:void 0}function B(o){return"string"!=typeof o&&(o+="px"),o}function x(o){var e,r,l=[];if(o)for(e=G.toHyphens(o).split("-"),r=0;e.length>r;r++)l.push("k-pos-"+e[r]);return l.join(" ")}function _(e){return""===e||null===e||"none"===e||"transparent"===e||!o(e)}function A(o){for(var e={1:"i",10:"x",100:"c",2:"ii",20:"xx",200:"cc",3:"iii",30:"xxx",300:"ccc",4:"iv",40:"xl",400:"cd",5:"v",50:"l",500:"d",6:"vi",60:"lx",600:"dc",7:"vii",70:"lxx",700:"dcc",8:"viii",80:"lxxx",800:"dccc",9:"ix",90:"xc",900:"cm",1e3:"m"},r=[1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],l="";o>0;)r[0]>o?r.shift():(l+=e[r[0]],o-=r[0]);return l}function L(o){var e,r,l,c,a;for(o=o.toLowerCase(),e={i:1,v:5,x:10,l:50,c:100,d:500,m:1e3},r=0,l=0,c=0;o.length>c;++c){if(a=e[o.charAt(c)],!a)return null;r+=a,a>l&&(r-=2*l),l=a}return r}function z(o){var e=Object.create(null);return function(){var r,l="";for(r=arguments.length;--r>=0;)l+=":"+arguments[r];return l in e?e[l]:o.apply(this,arguments)}}function T(o){for(var e,r,l=[],c=0,a=o.length;a>c;)e=o.charCodeAt(c++),e>=55296&&56319>=e&&a>c?(r=o.charCodeAt(c++),56320==(64512&r)?l.push(((1023&e)<<10)+(1023&r)+65536):(l.push(e),c--)):l.push(e);return l}function j(o){return o.map(function(o){var e="";return o>65535&&(o-=65536,e+=String.fromCharCode(o>>>10&1023|55296),o=56320|1023&o),e+=String.fromCharCode(o)}).join("")}var M=Math,G=window.kendo,P=G.deepExtend,W=M.PI/180,I=Number.MAX_VALUE,N=-Number.MAX_VALUE,S="undefined",O=Date.now;O||(O=function(){return(new Date).getTime()}),P(G,{util:{MAX_NUM:I,MIN_NUM:N,append:v,arrayLimits:b,arrayMin:u,arrayMax:h,defined:o,deg:a,hashKey:s,hashObject:d,isNumber:t,isTransparent:_,last:p,limitValue:l,now:O,objectKey:f,round:e,rad:c,renderAttr:C,renderAllAttr:y,renderPos:x,renderSize:B,renderStyle:D,renderTemplate:w,sparseArrayLimits:m,sparseArrayMin:k,sparseArrayMax:g,sqr:i,valueOrDefault:n,romanToArabic:L,arabicToRoman:A,memoize:z,ucs2encode:j,ucs2decode:T}}),G.drawing.util=G.util,G.dataviz.util=G.util}(),window.kendo},"function"==typeof define&&define.amd?define:function(o,e,r){(r||e)()}),function(o,define){define("util/text-metrics.min",["kendo.core.min","util/main.min"],o)}(function(){!function(o){function e(o,e,r){return f.current.measure(o,e,r)}var r=document,l=window.kendo,c=l.Class,a=l.util,t=a.defined,n=c.extend({init:function(o){this._size=o,this._length=0,this._map={}},put:function(o,e){var r=this,l=r._map,c={key:o,value:e};l[o]=c,r._head?(r._tail.newer=c,c.older=r._tail,r._tail=c):r._head=r._tail=c,r._length>=r._size?(l[r._head.key]=null,r._head=r._head.newer,r._head.older=null):r._length++},get:function(o){var e=this,r=e._map[o];return r?(r===e._head&&r!==e._tail&&(e._head=r.newer,e._head.older=null),r!==e._tail&&(r.older&&(r.older.newer=r.newer,r.newer.older=r.older),r.older=e._tail,r.newer=null,e._tail.newer=r,e._tail=r),r.value):void 0}}),i=o("<div style='position: absolute !important; top: -4000px !important; width: auto !important; height: auto !important;padding: 0 !important; margin: 0 !important; border: 0 !important;line-height: normal !important; visibility: hidden !important; white-space: nowrap!important;' />")[0],f=c.extend({init:function(o){this._cache=new n(1e3),this._initOptions(o)},options:{baselineMarkerSize:1},measure:function(e,l,c){var n,f,s,d,b,u=a.objectKey(l),h=a.hashKey(e+u),k=this._cache.get(h);if(k)return k;n={width:0,height:0,baseline:0},f=c?c:i,s=this._baselineMarker().cloneNode(!1);for(d in l)b=l[d],t(b)&&(f.style[d]=b);return o(f).text(e),f.appendChild(s),r.body.appendChild(f),(e+"").length&&(n.width=f.offsetWidth-this.options.baselineMarkerSize,n.height=f.offsetHeight,n.baseline=s.offsetTop+this.options.baselineMarkerSize),n.width>0&&n.height>0&&this._cache.put(h,n),f.parentNode.removeChild(f),n},_baselineMarker:function(){return o("<div class='k-baseline-marker' style='display: inline-block; vertical-align: baseline;width: "+this.options.baselineMarkerSize+"px; height: "+this.options.baselineMarkerSize+"px;overflow: hidden;' />")[0]}});f.current=new f,l.util.TextMetrics=f,l.util.LRUCache=n,l.util.measureText=e}(window.kendo.jQuery)},"function"==typeof define&&define.amd?define:function(o,e,r){(r||e)()}),function(o,define){define("util/base64.min",["util/main.min"],o)}(function(){return function(){function o(o){var r,l,c,t,n,i,f,s="",d=0;for(o=e(o);o.length>d;)r=o.charCodeAt(d++),l=o.charCodeAt(d++),c=o.charCodeAt(d++),t=r>>2,n=(3&r)<<4|l>>4,i=(15&l)<<2|c>>6,f=63&c,isNaN(l)?i=f=64:isNaN(c)&&(f=64),s=s+a.charAt(t)+a.charAt(n)+a.charAt(i)+a.charAt(f);return s}function e(o){var e,r,l="";for(e=0;o.length>e;e++)r=o.charCodeAt(e),128>r?l+=c(r):2048>r?(l+=c(192|r>>>6),l+=c(128|63&r)):65536>r&&(l+=c(224|r>>>12),l+=c(128|r>>>6&63),l+=c(128|63&r));return l}var r=window.kendo,l=r.deepExtend,c=String.fromCharCode,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";l(r.util,{encodeBase64:o,encodeUTF8:e})}(),window.kendo},"function"==typeof define&&define.amd?define:function(o,e,r){(r||e)()}),function(o,define){define("mixins/observers.min",["kendo.core.min"],o)}(function(){return function(o){var e=Math,r=window.kendo,l=r.deepExtend,c=o.inArray,a={observers:function(){return this._observers=this._observers||[]},addObserver:function(o){return this._observers?this._observers.push(o):this._observers=[o],this},removeObserver:function(o){var e=this.observers(),r=c(o,e);return-1!=r&&e.splice(r,1),this},trigger:function(o,e){var r,l,c=this._observers;if(c&&!this._suspended)for(l=0;c.length>l;l++)r=c[l],r[o]&&r[o](e);return this},optionsChange:function(o){this.trigger("optionsChange",o)},geometryChange:function(o){this.trigger("geometryChange",o)},suspend:function(){return this._suspended=(this._suspended||0)+1,this},resume:function(){return this._suspended=e.max((this._suspended||0)-1,0),this},_observerField:function(o,e){this[o]&&this[o].removeObserver(this),this[o]=e,e.addObserver(this)}};l(r,{mixins:{ObserversMixin:a}})}(window.kendo.jQuery),window.kendo},"function"==typeof define&&define.amd?define:function(o,e,r){(r||e)()}),function(o,define){define("kendo.dataviz.themes.min",["kendo.dataviz.core.min"],o)}(function(){return function(o){function e(e,r){return o.map(e,function(o,e){return[[o,r[e]]]})}var r=window.kendo,l=r.dataviz.ui,c=r.deepExtend,a=1.5,t=.4,n="#000",i="Arial,Helvetica,sans-serif",f="11px "+i,s="12px "+i,d="16px "+i,b="#fff",u={title:{font:d},legend:{labels:{font:s}},seriesDefaults:{visible:!0,labels:{font:f},donut:{margin:1},line:{width:2},vericalLine:{width:2},scatterLine:{width:1},area:{opacity:.4,markers:{visible:!1,size:6},highlight:{markers:{border:{color:"#fff",opacity:1,width:1}}},line:{opacity:1,width:0}},verticalArea:{opacity:.4,markers:{visible:!1,size:6},line:{opacity:1,width:0}},radarLine:{width:2,markers:{visible:!1}},radarArea:{opacity:.5,markers:{visible:!1,size:6},line:{opacity:1,width:0}},candlestick:{line:{width:1,color:n},border:{width:1,_brightness:.8},gap:1,spacing:.3,downColor:b,highlight:{line:{width:2},border:{width:2,opacity:1}}},ohlc:{line:{width:1},gap:1,spacing:.3,highlight:{line:{width:3,opacity:1}}},bubble:{opacity:.6,border:{width:0},labels:{background:"transparent"}},bar:{gap:a,spacing:t},column:{gap:a,spacing:t},rangeColumn:{gap:a,spacing:t},rangeBar:{gap:a,spacing:t},waterfall:{gap:.5,spacing:t,line:{width:1,color:n}},horizontalWaterfall:{gap:.5,spacing:t,line:{width:1,color:n}},bullet:{gap:a,spacing:t,target:{color:"#ff0000"}},verticalBullet:{gap:a,spacing:t,target:{color:"#ff0000"}},boxPlot:{outliersField:"",meanField:"",whiskers:{width:1,color:n},mean:{width:1,color:n},median:{width:1,color:n},border:{width:1,_brightness:.8},gap:1,spacing:.3,downColor:b,highlight:{whiskers:{width:2},border:{width:2,opacity:1}}},funnel:{labels:{color:"",background:""}},notes:{icon:{border:{width:1}},label:{padding:3,font:s},line:{length:10,width:1},visible:!0}},categoryAxis:{majorGridLines:{visible:!0}},axisDefaults:{labels:{font:s},title:{font:d,margin:5},crosshair:{tooltip:{font:s}},notes:{icon:{size:7,border:{width:1}},label:{padding:3,font:s},line:{length:10,width:1},visible:!0}},tooltip:{font:s},navigator:{pane:{height:90,margin:{top:10}}}},h={scale:{labels:{font:s}}},k={shapeDefaults:{hover:{opacity:.2},stroke:{width:0}},editable:{resize:{handles:{width:7,height:7}}},selectable:{stroke:{width:1,dashType:"dot"}},connectionDefaults:{stroke:{width:2},selection:{handles:{width:8,height:8}},editable:{tools:["edit","delete"]}}},g=l.themes,m=l.registerTheme=function(o,e){var r,l={};l.chart=c({},u,e.chart),l.gauge=c({},h,e.gauge),l.diagram=c({},k,e.diagram),l.treeMap=c({},e.treeMap),r=l.chart.seriesDefaults,r.verticalLine=c({},r.line),r.verticalArea=c({},r.area),r.polarArea=c({},r.radarArea),r.polarLine=c({},r.radarLine),g[o]=l};m("black",{chart:{title:{color:b},legend:{labels:{color:b},inactiveItems:{labels:{color:"#919191"},markers:{color:"#919191"}}},seriesDefaults:{labels:{color:b},errorBars:{color:b},notes:{icon:{background:"#3b3b3b",border:{color:"#8e8e8e"}},label:{color:b},line:{color:"#8e8e8e"}},pie:{overlay:{gradient:"sharpBevel"}},donut:{overlay:{gradient:"sharpGlass"}},line:{markers:{background:"#3d3d3d"}},scatter:{markers:{background:"#3d3d3d"}},scatterLine:{markers:{background:"#3d3d3d"}},waterfall:{line:{color:"#8e8e8e"}},horizontalWaterfall:{line:{color:"#8e8e8e"}},candlestick:{downColor:"#555",line:{color:b},border:{_brightness:1.5,opacity:1},highlight:{border:{color:b,opacity:.2}}},ohlc:{line:{color:b}}},chartArea:{background:"#3d3d3d"},seriesColors:["#0081da","#3aafff","#99c900","#ffeb3d","#b20753","#ff4195"],axisDefaults:{line:{color:"#8e8e8e"},labels:{color:b},majorGridLines:{color:"#545454"},minorGridLines:{color:"#454545"},title:{color:b},crosshair:{color:"#8e8e8e"},notes:{icon:{background:"#3b3b3b",border:{color:"#8e8e8e"}},label:{color:b},line:{color:"#8e8e8e"}}}},gauge:{pointer:{color:"#0070e4"},scale:{rangePlaceholderColor:"#1d1d1d",labels:{color:b},minorTicks:{color:b},majorTicks:{color:b},line:{color:b}}},diagram:{shapeDefaults:{fill:{color:"#0066cc"},connectorDefaults:{fill:{color:b},stroke:{color:"#384049"},hover:{fill:{color:"#3d3d3d"},stroke:{color:"#efefef"}}},content:{color:b}},editable:{resize:{handles:{fill:{color:"#3d3d3d"},stroke:{color:b},hover:{fill:{color:b},stroke:{color:b}}}},rotate:{thumb:{stroke:{color:b},fill:{color:b}}}},selectable:{stroke:{color:b}},connectionDefaults:{stroke:{color:b},content:{color:b},selection:{handles:{fill:{color:"#3d3d3d"},stroke:{color:"#efefef"}}}}},treeMap:{colors:[["#0081da","#314b5c"],["#3aafff","#3c5464"],["#99c900","#4f5931"],["#ffeb3d","#64603d"],["#b20753","#543241"],["#ff4195","#643e4f"]]}}),m("blueopal",{chart:{title:{color:"#293135"},legend:{labels:{color:"#293135"},inactiveItems:{labels:{color:"#27A5BA"},markers:{color:"#27A5BA"}}},seriesDefaults:{labels:{color:n,background:b,opacity:.5},errorBars:{color:"#293135"},candlestick:{downColor:"#c4d0d5",line:{color:"#9aabb2"}},waterfall:{line:{color:"#9aabb2"}},horizontalWaterfall:{line:{color:"#9aabb2"}},notes:{icon:{background:"transparent",border:{color:"#9aabb2"}},label:{color:"#293135"},line:{color:"#9aabb2"}}},seriesColors:["#0069a5","#0098ee","#7bd2f6","#ffb800","#ff8517","#e34a00"],axisDefaults:{line:{color:"#9aabb2"},labels:{color:"#293135"},majorGridLines:{color:"#c4d0d5"},minorGridLines:{color:"#edf1f2"},title:{color:"#293135"},crosshair:{color:"#9aabb2"},notes:{icon:{background:"transparent",border:{color:"#9aabb2"}},label:{color:"#293135"},line:{color:"#9aabb2"}}}},gauge:{pointer:{color:"#005c83"},scale:{rangePlaceholderColor:"#daecf4",labels:{color:"#293135"},minorTicks:{color:"#293135"},majorTicks:{color:"#293135"},line:{color:"#293135"}}},diagram:{shapeDefaults:{fill:{color:"#7ec6e3"},connectorDefaults:{fill:{color:"#003f59"},stroke:{color:b},hover:{fill:{color:b},stroke:{color:"#003f59"}}},content:{color:"#293135"}},editable:{resize:{handles:{fill:{color:b},stroke:{color:"#003f59"},hover:{fill:{color:"#003f59"},stroke:{color:"#003f59"}}}},rotate:{thumb:{stroke:{color:"#003f59"},fill:{color:"#003f59"}}}},selectable:{stroke:{color:"#003f59"}},connectionDefaults:{stroke:{color:"#003f59"},content:{color:"#293135"},selection:{handles:{fill:{color:"#3d3d3d"},stroke:{color:"#efefef"}}}}},treeMap:{colors:[["#0069a5","#bad7e7"],["#0098ee","#b9e0f5"],["#7bd2f6","#ceeaf6"],["#ffb800","#e6e3c4"],["#ff8517","#e4d8c8"],["#e34a00","#ddccc2"]]}}),m("highcontrast",{chart:{title:{color:"#ffffff"},legend:{labels:{color:"#ffffff"},inactiveItems:{labels:{color:"#66465B"},markers:{color:"#66465B"}}},seriesDefaults:{labels:{color:"#ffffff"},errorBars:{color:"#ffffff"},notes:{icon:{background:"transparent",border:{color:"#ffffff"}},label:{color:"#ffffff"},line:{color:"#ffffff"}},pie:{overlay:{gradient:"sharpGlass"}},donut:{overlay:{gradient:"sharpGlass"}},line:{markers:{background:"#2c232b"}},scatter:{markers:{background:"#2c232b"}},scatterLine:{markers:{background:"#2c232b"}},area:{opacity:.5},waterfall:{line:{color:"#ffffff"}},horizontalWaterfall:{line:{color:"#ffffff"}},candlestick:{downColor:"#664e62",line:{color:"#ffffff"},border:{_brightness:1.5,opacity:1},highlight:{border:{color:"#ffffff",opacity:1}}},ohlc:{line:{color:"#ffffff"}}},chartArea:{background:"#2c232b"},seriesColors:["#a7008f","#ffb800","#3aafff","#99c900","#b20753","#ff4195"],axisDefaults:{line:{color:"#ffffff"},labels:{color:"#ffffff"},majorGridLines:{color:"#664e62"},minorGridLines:{color:"#4f394b"},title:{color:"#ffffff"},crosshair:{color:"#ffffff"},notes:{icon:{background:"transparent",border:{color:"#ffffff"}},label:{color:"#ffffff"},line:{color:"#ffffff"}}}},gauge:{pointer:{color:"#a7008f"},scale:{rangePlaceholderColor:"#2c232b",labels:{color:"#ffffff"},minorTicks:{color:"#2c232b"},majorTicks:{color:"#664e62"},line:{color:"#ffffff"}}},diagram:{shapeDefaults:{fill:{color:"#a7018f"},connectorDefaults:{fill:{color:b},stroke:{color:"#2c232b"},hover:{fill:{color:"#2c232b"},stroke:{color:b}}},content:{color:b}},editable:{resize:{handles:{fill:{color:"#2c232b"},stroke:{color:b},hover:{fill:{color:b},stroke:{color:b}}}},rotate:{thumb:{stroke:{color:b},fill:{color:b}}}},selectable:{stroke:{color:b}},connectionDefaults:{stroke:{color:b},content:{color:b},selection:{handles:{fill:{color:"#2c232b"},stroke:{color:b}}}}},treeMap:{colors:[["#a7008f","#451c3f"],["#ffb800","#564122"],["#3aafff","#2f3f55"],["#99c900","#424422"],["#b20753","#471d33"],["#ff4195","#562940"]]}}),m("default",{chart:{title:{color:"#8e8e8e"},legend:{labels:{color:"#232323"},inactiveItems:{labels:{color:"#919191"},markers:{color:"#919191"}}},seriesDefaults:{labels:{color:n,background:b,opacity:.5},errorBars:{color:"#232323"},candlestick:{downColor:"#dedede",line:{color:"#8d8d8d"}},waterfall:{line:{color:"#8e8e8e"}},horizontalWaterfall:{line:{color:"#8e8e8e"}},notes:{icon:{background:"transparent",border:{color:"#8e8e8e"}},label:{color:"#232323"},line:{color:"#8e8e8e"}}},seriesColors:["#ff6800","#a0a700","#ff8d00","#678900","#ffb53c","#396000"],axisDefaults:{line:{color:"#8e8e8e"},labels:{color:"#232323"},minorGridLines:{color:"#f0f0f0"},majorGridLines:{color:"#dfdfdf"},title:{color:"#232323"},crosshair:{color:"#8e8e8e"},notes:{icon:{background:"transparent",border:{color:"#8e8e8e"}},label:{color:"#232323"},line:{color:"#8e8e8e"}}}},gauge:{pointer:{color:"#ea7001"},scale:{rangePlaceholderColor:"#dedede",labels:{color:"#2e2e2e"},minorTicks:{color:"#2e2e2e"},majorTicks:{color:"#2e2e2e"},line:{color:"#2e2e2e"}}},diagram:{shapeDefaults:{fill:{color:"#e15613"},connectorDefaults:{fill:{color:"#282828"},stroke:{color:b},hover:{fill:{color:b},stroke:{color:"#282828"}}},content:{color:"#2e2e2e"}},editable:{resize:{handles:{fill:{color:b},stroke:{color:"#282828"},hover:{fill:{color:"#282828"},stroke:{color:"#282828"}}}},rotate:{thumb:{stroke:{color:"#282828"},fill:{color:"#282828"}}}},selectable:{stroke:{color:"#a7018f"}},connectionDefaults:{stroke:{color:"#282828"},content:{color:"#2e2e2e"},selection:{handles:{fill:{color:b},stroke:{color:"#282828"}}}}},treeMap:{colors:[["#ff6800","#edcfba"],["#a0a700","#dadcba"],["#ff8d00","#edd7ba"],["#678900","#cfd6ba"],["#ffb53c","#eddfc6"],["#396000","#c6ceba"]]}}),m("silver",{chart:{title:{color:"#4e5968"},legend:{labels:{color:"#4e5968"},inactiveItems:{labels:{color:"#B1BCC8"},markers:{color:"#B1BCC8"}}},seriesDefaults:{labels:{color:"#293135",background:"#eaeaec",opacity:.5},errorBars:{color:"#4e5968"},notes:{icon:{background:"transparent",border:{color:"#4e5968"}},label:{color:"#4e5968"},line:{color:"#4e5968"}},line:{markers:{background:"#eaeaec"}},scatter:{markers:{background:"#eaeaec"}},scatterLine:{markers:{background:"#eaeaec"}},pie:{connectors:{color:"#A6B1C0"}},donut:{connectors:{color:"#A6B1C0"}},waterfall:{line:{color:"#a6b1c0"}},horizontalWaterfall:{line:{color:"#a6b1c0"}},candlestick:{downColor:"#a6afbe"}},chartArea:{background:"#eaeaec"},seriesColors:["#007bc3","#76b800","#ffae00","#ef4c00","#a419b7","#430B62"],axisDefaults:{line:{color:"#a6b1c0"},labels:{color:"#4e5968"},majorGridLines:{color:"#dcdcdf"},minorGridLines:{color:"#eeeeef"},title:{color:"#4e5968"},crosshair:{color:"#a6b1c0"},notes:{icon:{background:"transparent",border:{color:"#4e5968"}},label:{color:"#4e5968"},line:{color:"#4e5968"}}}},gauge:{pointer:{color:"#0879c0"},scale:{rangePlaceholderColor:"#f3f3f4",labels:{color:"#515967"},minorTicks:{color:"#515967"},majorTicks:{color:"#515967"},line:{color:"#515967"}}},diagram:{shapeDefaults:{fill:{color:"#1c82c2"},connectorDefaults:{fill:{color:"#515967"},stroke:{color:b},hover:{fill:{color:b},stroke:{color:"#282828"}}},content:{color:"#515967"}},editable:{resize:{handles:{fill:{color:b},stroke:{color:"#515967"},hover:{fill:{color:"#515967"},stroke:{color:"#515967"}}}},rotate:{thumb:{stroke:{color:"#515967"},fill:{color:"#515967"}}}},selectable:{stroke:{color:"#515967"}},connectionDefaults:{stroke:{color:"#515967"},content:{color:"#515967"},selection:{handles:{fill:{color:b},stroke:{color:"#515967"}}}}},treeMap:{colors:[["#007bc3","#c2dbea"],["#76b800","#dae7c3"],["#ffae00","#f5e5c3"],["#ef4c00","#f2d2c3"],["#a419b7","#e3c7e8"],["#430b62","#d0c5d7"]]}}),m("metro",{chart:{title:{color:"#777777"},legend:{labels:{color:"#777777"},inactiveItems:{labels:{color:"#CBCBCB"},markers:{color:"#CBCBCB"}}},seriesDefaults:{labels:{color:n},errorBars:{color:"#777777"},notes:{icon:{background:"transparent",border:{color:"#777777"}},label:{color:"#777777"},line:{color:"#777777"}},candlestick:{downColor:"#c7c7c7",line:{color:"#787878"}},waterfall:{line:{color:"#c7c7c7"}},horizontalWaterfall:{line:{color:"#c7c7c7"}},overlay:{gradient:"none"},border:{_brightness:1}},seriesColors:["#8ebc00","#309b46","#25a0da","#ff6900","#e61e26","#d8e404","#16aba9","#7e51a1","#313131","#ed1691"],axisDefaults:{line:{color:"#c7c7c7"},labels:{color:"#777777"},minorGridLines:{color:"#c7c7c7"},majorGridLines:{color:"#c7c7c7"},title:{color:"#777777"},crosshair:{color:"#c7c7c7"},notes:{icon:{background:"transparent",border:{color:"#777777"}},label:{color:"#777777"},line:{color:"#777777"}}}},gauge:{pointer:{color:"#8ebc00"},scale:{rangePlaceholderColor:"#e6e6e6",labels:{color:"#777"},minorTicks:{color:"#777"},majorTicks:{color:"#777"},line:{color:"#777"}}},diagram:{shapeDefaults:{fill:{color:"#8ebc00"},connectorDefaults:{fill:{color:n},stroke:{color:b},hover:{fill:{color:b},stroke:{color:n}}},content:{color:"#777"}},editable:{resize:{handles:{fill:{color:b},stroke:{color:"#787878"},hover:{fill:{color:"#787878"},stroke:{color:"#787878"}}}},rotate:{thumb:{stroke:{color:"#787878"},fill:{color:"#787878"}}}},selectable:{stroke:{color:"#515967"}},connectionDefaults:{stroke:{color:"#787878"},content:{color:"#777"},selection:{handles:{fill:{color:b},stroke:{color:"#787878"}}}}},treeMap:{colors:[["#8ebc00","#e8f2cc"],["#309b46","#d6ebda"],["#25a0da","#d3ecf8"],["#ff6900","#ffe1cc"],["#e61e26","#fad2d4"],["#d8e404","#f7facd"],["#16aba9","#d0eeee"],["#7e51a1","#e5dcec"],["#313131","#d6d6d6"],["#ed1691","#fbd0e9"]]}}),m("metroblack",{chart:{title:{color:"#ffffff"},legend:{labels:{color:"#ffffff"},inactiveItems:{labels:{color:"#797979"},markers:{color:"#797979"}}},seriesDefaults:{border:{_brightness:1},labels:{color:"#ffffff"},errorBars:{color:"#ffffff"},notes:{icon:{background:"transparent",border:{color:"#cecece"}},label:{color:"#ffffff"},line:{color:"#cecece"}},line:{markers:{background:"#0e0e0e"}},bubble:{opacity:.6},scatter:{markers:{background:"#0e0e0e"}},scatterLine:{markers:{background:"#0e0e0e"}},candlestick:{downColor:"#828282",line:{color:"#ffffff"}},waterfall:{line:{color:"#cecece"}},horizontalWaterfall:{line:{color:"#cecece"}},overlay:{gradient:"none"}},chartArea:{background:"#0e0e0e"},seriesColors:["#00aba9","#309b46","#8ebc00","#ff6900","#e61e26","#d8e404","#25a0da","#7e51a1","#313131","#ed1691"],axisDefaults:{line:{color:"#cecece"},labels:{color:"#ffffff"},minorGridLines:{color:"#2d2d2d"},majorGridLines:{color:"#333333"},title:{color:"#ffffff"},crosshair:{color:"#cecece"},notes:{icon:{background:"transparent",border:{color:"#cecece"}},label:{color:"#ffffff"},line:{color:"#cecece"}}}},gauge:{pointer:{color:"#00aba9"},scale:{rangePlaceholderColor:"#2d2d2d",labels:{color:"#ffffff"},minorTicks:{color:"#333333"},majorTicks:{color:"#cecece"},line:{color:"#cecece"}}},diagram:{shapeDefaults:{fill:{color:"#00aba9"},connectorDefaults:{fill:{color:b},stroke:{color:"#0e0e0e"},hover:{fill:{color:"#0e0e0e"},stroke:{color:b}}},content:{color:b}},editable:{resize:{handles:{fill:{color:"#0e0e0e"},stroke:{color:"#787878"},hover:{fill:{color:"#787878"},stroke:{color:"#787878"}}}},rotate:{thumb:{stroke:{color:b},fill:{color:b}}}},selectable:{stroke:{color:"#787878"}},connectionDefaults:{stroke:{color:b},content:{color:b},selection:{handles:{fill:{color:"#0e0e0e"},stroke:{color:b}}}}},treeMap:{colors:[["#00aba9","#0b2d2d"],["#309b46","#152a19"],["#8ebc00","#28310b"],["#ff6900","#3e200b"],["#e61e26","#391113"],["#d8e404","#36390c"],["#25a0da","#132b37"],["#7e51a1","#241b2b"],["#313131","#151515"],["#ed1691","#3b1028"]]}}),m("moonlight",{chart:{title:{color:"#ffffff"},legend:{labels:{color:"#ffffff"},inactiveItems:{labels:{color:"#A1A7AB"},markers:{color:"#A1A7AB"}}},seriesDefaults:{labels:{color:"#ffffff"},errorBars:{color:"#ffffff"},notes:{icon:{background:"transparent",border:{color:"#8c909e"}},label:{color:"#ffffff"},line:{color:"#8c909e"}},pie:{overlay:{gradient:"sharpBevel"}},donut:{overlay:{gradient:"sharpGlass"}},line:{markers:{background:"#212a33"}},bubble:{opacity:.6},scatter:{markers:{background:"#212a33"}},scatterLine:{markers:{background:"#212a33"}},area:{opacity:.3},candlestick:{downColor:"#757d87",line:{color:"#ea9d06"},border:{_brightness:1.5,opacity:1},highlight:{border:{color:b,opacity:.2}}},waterfall:{line:{color:"#8c909e"}},horizontalWaterfall:{line:{color:"#8c909e"}},ohlc:{line:{color:"#ea9d06"}}},chartArea:{background:"#212a33"},seriesColors:["#ffca08","#ff710f","#ed2e24","#ff9f03","#e13c02","#a00201"],axisDefaults:{line:{color:"#8c909e"},minorTicks:{color:"#8c909e"},majorTicks:{color:"#8c909e"},labels:{color:"#ffffff"},majorGridLines:{color:"#3e424d"},minorGridLines:{color:"#2f3640"},title:{color:"#ffffff"},crosshair:{color:"#8c909e"},notes:{icon:{background:"transparent",border:{color:"#8c909e"}},label:{color:"#ffffff"},line:{color:"#8c909e"}}}},gauge:{pointer:{color:"#f4af03"},scale:{rangePlaceholderColor:"#2f3640",labels:{color:b},minorTicks:{color:"#8c909e"},majorTicks:{color:"#8c909e"},line:{color:"#8c909e"}}},diagram:{shapeDefaults:{fill:{color:"#f3ae03"},connectorDefaults:{fill:{color:b},stroke:{color:"#414550"},hover:{fill:{color:"#414550"},stroke:{color:b}}},content:{color:b}},editable:{resize:{handles:{fill:{color:"#414550"},stroke:{color:b},hover:{fill:{color:b},stroke:{color:b}}}},rotate:{thumb:{stroke:{color:b},fill:{color:b}}}},selectable:{stroke:{color:b}},connectionDefaults:{stroke:{color:b},content:{color:b},selection:{handles:{fill:{color:"#414550"},stroke:{color:b}}}}},treeMap:{colors:[["#ffca08","#4e4b2b"],["#ff710f","#4e392d"],["#ed2e24","#4b2c31"],["#ff9f03","#4e422a"],["#e13c02","#482e2a"],["#a00201","#3b232a"]]}}),m("uniform",{chart:{title:{color:"#686868"},legend:{labels:{color:"#686868"},inactiveItems:{labels:{color:"#B6B6B6"},markers:{color:"#B6B6B6"}}},seriesDefaults:{labels:{color:"#686868"},errorBars:{color:"#686868"},notes:{icon:{background:"transparent",border:{color:"#9e9e9e"}},label:{color:"#686868"},line:{color:"#9e9e9e"}},pie:{overlay:{gradient:"sharpBevel"}},donut:{overlay:{gradient:"sharpGlass"}},line:{markers:{background:"#ffffff"}},bubble:{opacity:.6},scatter:{markers:{background:"#ffffff"}},scatterLine:{markers:{background:"#ffffff"}},area:{opacity:.3},candlestick:{downColor:"#cccccc",line:{color:"#cccccc"},border:{_brightness:1.5,opacity:1},highlight:{border:{color:"#cccccc",opacity:.2}}},waterfall:{line:{color:"#9e9e9e"}},horizontalWaterfall:{line:{color:"#9e9e9e"}},ohlc:{line:{color:"#cccccc"}}},chartArea:{background:"#ffffff"},seriesColors:["#527aa3","#6f91b3","#8ca7c2","#a8bdd1","#c5d3e0","#e2e9f0"],axisDefaults:{line:{color:"#9e9e9e"},minorTicks:{color:"#aaaaaa"},majorTicks:{color:"#888888"},labels:{color:"#686868"},majorGridLines:{color:"#dadada"},minorGridLines:{color:"#e7e7e7"},title:{color:"#686868"},crosshair:{color:"#9e9e9e"},notes:{icon:{background:"transparent",border:{color:"#9e9e9e"}},label:{color:"#686868"},line:{color:"#9e9e9e"}}}},gauge:{pointer:{color:"#527aa3"},scale:{rangePlaceholderColor:"#e7e7e7",labels:{color:"#686868"},minorTicks:{color:"#aaaaaa"},majorTicks:{color:"#888888"},line:{color:"#9e9e9e"}}},diagram:{shapeDefaults:{fill:{color:"#d1d1d1"},connectorDefaults:{fill:{color:"#686868"},stroke:{color:b},hover:{fill:{color:b},stroke:{color:"#686868"}}},content:{color:"#686868"}},editable:{resize:{handles:{fill:{color:b},stroke:{color:"#686868"},hover:{fill:{color:"#686868"},stroke:{color:"#686868"}}}},rotate:{thumb:{stroke:{color:"#686868"},fill:{color:"#686868"}}}},selectable:{stroke:{color:"#686868"}},connectionDefaults:{stroke:{color:"#686868"},content:{color:"#686868"},selection:{handles:{fill:{color:b},stroke:{color:"#686868"}}}}},treeMap:{colors:[["#527aa3","#d0d8e1"],["#6f91b3","#d6dde4"],["#8ca7c2","#dce1e7"],["#a8bdd1","#e2e6ea"],["#c5d3e0","#e7eaed"],["#e2e9f0","#edeff0"]]}}),m("bootstrap",{chart:{title:{color:"#333333"},legend:{labels:{color:"#333333"},inactiveItems:{labels:{color:"#999999"},markers:{color:"#9A9A9A"}}},seriesDefaults:{labels:{color:"#333333"},overlay:{gradient:"none"},errorBars:{color:"#343434"},notes:{icon:{background:"#000000",border:{color:"#000000"}},label:{color:"#333333"},line:{color:"#000000"}},pie:{overlay:{gradient:"none"}},donut:{overlay:{gradient:"none"}},line:{markers:{background:"#ffffff"}},bubble:{opacity:.6},scatter:{markers:{background:"#ffffff"}},scatterLine:{markers:{background:"#ffffff"}},area:{opacity:.8},candlestick:{downColor:"#d0d0d0",line:{color:"#333333"},border:{_brightness:1.5,opacity:1},highlight:{border:{color:"#b8b8b8",opacity:.2}}},waterfall:{line:{color:"#cccccc"}},horizontalWaterfall:{line:{color:"#cccccc"}},ohlc:{line:{color:"#333333"}}},chartArea:{background:"#ffffff"},seriesColors:["#428bca","#5bc0de","#5cb85c","#f2b661","#e67d4a","#da3b36"],axisDefaults:{line:{color:"#cccccc"},minorTicks:{color:"#ebebeb"},majorTicks:{color:"#cccccc"},labels:{color:"#333333"},majorGridLines:{color:"#cccccc"},minorGridLines:{color:"#ebebeb"},title:{color:"#333333"},crosshair:{color:"#000000"},notes:{icon:{background:"#000000",border:{color:"#000000"}},label:{color:"#ffffff"},line:{color:"#000000"}}}},gauge:{pointer:{color:"#428bca"},scale:{rangePlaceholderColor:"#cccccc",labels:{color:"#333333"},minorTicks:{color:"#ebebeb"},majorTicks:{color:"#cccccc"},line:{color:"#cccccc"}}},diagram:{shapeDefaults:{fill:{color:"#428bca"},connectorDefaults:{fill:{color:"#333333"},stroke:{color:b},hover:{fill:{color:b},stroke:{color:"#333333"}}},content:{color:"#333333"}},editable:{resize:{handles:{fill:{color:b},stroke:{color:"#333333"},hover:{fill:{color:"#333333"},stroke:{color:"#333333"}}}},rotate:{thumb:{stroke:{color:"#333333"},fill:{color:"#333333"}}}},selectable:{stroke:{color:"#333333"}},connectionDefaults:{stroke:{color:"#c4c4c4"},content:{color:"#333333"},selection:{handles:{fill:{color:b},stroke:{color:"#333333"}},stroke:{color:"#333333"}}}},treeMap:{colors:[["#428bca","#d1e0ec"],["#5bc0de","#d6eaf0"],["#5cb85c","#d6e9d6"],["#5cb85c","#f4e8d7"],["#e67d4a","#f2ddd3"],["#da3b36","#f0d0cf"]]}}),m("flat",{chart:{title:{color:"#4c5356"},legend:{labels:{color:"#4c5356"},inactiveItems:{labels:{color:"#CBCBCB"},markers:{color:"#CBCBCB"}}},seriesDefaults:{labels:{color:"#4c5356"},errorBars:{color:"#4c5356"},notes:{icon:{background:"transparent",border:{color:"#cdcdcd"}},label:{color:"#4c5356"},line:{color:"#cdcdcd"}},candlestick:{downColor:"#c7c7c7",line:{color:"#787878"}},area:{opacity:.9},waterfall:{line:{color:"#cdcdcd"}},horizontalWaterfall:{line:{color:"#cdcdcd"}},overlay:{gradient:"none"},border:{_brightness:1}},seriesColors:["#10c4b2","#ff7663","#ffb74f","#a2df53","#1c9ec4","#ff63a5","#1cc47b"],axisDefaults:{line:{color:"#cdcdcd"},labels:{color:"#4c5356"},minorGridLines:{color:"#cdcdcd"},majorGridLines:{color:"#cdcdcd"},title:{color:"#4c5356"},crosshair:{color:"#cdcdcd"},notes:{icon:{background:"transparent",border:{color:"#cdcdcd"}},label:{color:"#4c5356"},line:{color:"#cdcdcd"}}}},gauge:{pointer:{color:"#10c4b2"},scale:{rangePlaceholderColor:"#cdcdcd",labels:{color:"#4c5356"},minorTicks:{color:"#4c5356"},majorTicks:{color:"#4c5356"},line:{color:"#4c5356"}}},diagram:{shapeDefaults:{fill:{color:"#10c4b2"},connectorDefaults:{fill:{color:"#363940"},stroke:{color:b},hover:{fill:{color:b},stroke:{color:"#363940"}}},content:{color:"#4c5356"}},editable:{resize:{handles:{fill:{color:b},stroke:{color:"#363940"},hover:{fill:{color:"#363940"},stroke:{color:"#363940"}}}},rotate:{thumb:{stroke:{color:"#363940"},fill:{color:"#363940"}}}},selectable:{stroke:{color:"#363940"}},connectionDefaults:{stroke:{color:"#cdcdcd"},content:{color:"#4c5356"},selection:{handles:{fill:{color:b},stroke:{color:"#363940"}},stroke:{color:"#363940"}}}},treeMap:{colors:[["#10c4b2","#cff3f0"],["#ff7663","#ffe4e0"],["#ffb74f","#fff1dc"],["#a2df53","#ecf9dd"],["#1c9ec4","#d2ecf3"],["#ff63a5","#ffe0ed"],["#1cc47b","#d2f3e5"]]}}),m("material",{chart:{title:{color:"#444444"},legend:{labels:{color:"#444444"},inactiveItems:{labels:{color:"#CBCBCB"},markers:{color:"#CBCBCB"}}},seriesDefaults:{labels:{color:"#444444"},errorBars:{color:"#444444"},notes:{icon:{background:"transparent",border:{color:"#e5e5e5"}},label:{color:"#444444"},line:{color:"#e5e5e5"}},candlestick:{downColor:"#c7c7c7",line:{color:"#787878"}},area:{opacity:.9},waterfall:{
line:{color:"#e5e5e5"}},horizontalWaterfall:{line:{color:"#e5e5e5"}},overlay:{gradient:"none"},border:{_brightness:1}},seriesColors:["#3f51b5","#03a9f4","#4caf50","#f9ce1d","#ff9800","#ff5722"],axisDefaults:{line:{color:"#e5e5e5"},labels:{color:"#444444"},minorGridLines:{color:"#e5e5e5"},majorGridLines:{color:"#e5e5e5"},title:{color:"#444444"},crosshair:{color:"#7f7f7f"},notes:{icon:{background:"transparent",border:{color:"#e5e5e5"}},label:{color:"#444444"},line:{color:"#e5e5e5"}}}},gauge:{pointer:{color:"#3f51b5"},scale:{rangePlaceholderColor:"#e5e5e5",labels:{color:"#444444"},minorTicks:{color:"#444444"},majorTicks:{color:"#444444"},line:{color:"#444444"}}},diagram:{shapeDefaults:{fill:{color:"#3f51b5"},connectorDefaults:{fill:{color:"#7f7f7f"},stroke:{color:b},hover:{fill:{color:b},stroke:{color:"#7f7f7f"}}},content:{color:"#444444"}},editable:{resize:{handles:{fill:{color:b},stroke:{color:"#444444"},hover:{fill:{color:"#444444"},stroke:{color:"#444444"}}}},rotate:{thumb:{stroke:{color:"#444444"},fill:{color:"#444444"}}}},selectable:{stroke:{color:"#444444"}},connectionDefaults:{stroke:{color:"#7f7f7f"},content:{color:"#444444"},selection:{handles:{fill:{color:b},stroke:{color:"#444444"}},stroke:{color:"#444444"}}}},treeMap:{colors:[["#3f51b5","#cff3f0"],["#03a9f4","#e5f6fe"],["#4caf50","#edf7ed"],["#f9ce1d","#fefae8"],["#ff9800","#fff4e5"],["#ff5722","#ffeee8"]]}}),m("materialblack",{chart:{title:{color:"#fff"},legend:{labels:{color:"#fff"},inactiveItems:{labels:{color:"#CBCBCB"},markers:{color:"#CBCBCB"}}},seriesDefaults:{labels:{color:"#fff"},errorBars:{color:"#fff"},notes:{icon:{background:"transparent",border:{color:"#e5e5e5"}},label:{color:"#fff"},line:{color:"#e5e5e5"}},candlestick:{downColor:"#c7c7c7",line:{color:"#787878"}},area:{opacity:.9},waterfall:{line:{color:"#4d4d4d"}},horizontalWaterfall:{line:{color:"#4d4d4d"}},overlay:{gradient:"none"},border:{_brightness:1}},chartArea:{background:"#1c1c1c"},seriesColors:["#3f51b5","#03a9f4","#4caf50","#f9ce1d","#ff9800","#ff5722"],axisDefaults:{line:{color:"#4d4d4d"},labels:{color:"#fff"},minorGridLines:{color:"#4d4d4d"},majorGridLines:{color:"#4d4d4d"},title:{color:"#fff"},crosshair:{color:"#7f7f7f"},notes:{icon:{background:"transparent",border:{color:"#4d4d4d"}},label:{color:"#fff"},line:{color:"#4d4d4d"}}}},gauge:{pointer:{color:"#3f51b5"},scale:{rangePlaceholderColor:"#4d4d4d",labels:{color:"#fff"},minorTicks:{color:"#fff"},majorTicks:{color:"#fff"},line:{color:"#fff"}}},diagram:{shapeDefaults:{fill:{color:"#3f51b5"},connectorDefaults:{fill:{color:"#7f7f7f"},stroke:{color:b},hover:{fill:{color:b},stroke:{color:"#7f7f7f"}}},content:{color:"#fff"}},editable:{resize:{handles:{fill:{color:b},stroke:{color:"#fff"},hover:{fill:{color:"#fff"},stroke:{color:"#fff"}}}},rotate:{thumb:{stroke:{color:"#fff"},fill:{color:"#fff"}}}},selectable:{stroke:{color:"#fff"}},connectionDefaults:{stroke:{color:"#7f7f7f"},content:{color:"#fff"},selection:{handles:{fill:{color:b},stroke:{color:"#fff"}},stroke:{color:"#fff"}}}},treeMap:{colors:[["#3f51b5","#cff3f0"],["#03a9f4","#e5f6fe"],["#4caf50","#edf7ed"],["#f9ce1d","#fefae8"],["#ff9800","#fff4e5"],["#ff5722","#ffeee8"]]}}),function(){function o(){return{icon:{background:"#007cc0",border:{color:"#007cc0"}},label:{color:"#ffffff"},line:{color:a}}}var r="#333333",l="#7f7f7f",c="#bdbdbd",a="#c8c8c8",t="#dddddd",n=["#008fd3","#99d101","#f39b02","#f05662","#c03c53","#acacac"],i=["#cbe8f5","#eaf5cb","#fceacc","#fbdcdf","#f2d7dc","#eeeeee"],f=n[0],s=b;m("fiori",{chart:{title:{color:r},legend:{labels:{color:r},inactiveItems:{labels:{color:l},markers:{color:l}}},seriesDefaults:{labels:{color:r},errorBars:{color:r},notes:o(),candlestick:{downColor:a,line:{color:c}},area:{opacity:.8},waterfall:{line:{color:a}},horizontalWaterfall:{line:{color:a}},overlay:{gradient:"none"},border:{_brightness:1}},seriesColors:n,axisDefaults:{line:{color:a},labels:{color:r},minorGridLines:{color:t},majorGridLines:{color:a},title:{color:r},crosshair:{color:l},notes:o()}},gauge:{pointer:{color:f},scale:{rangePlaceholderColor:a,labels:{color:r},minorTicks:{color:r},majorTicks:{color:r},line:{color:r}}},diagram:{shapeDefaults:{fill:{color:f},connectorDefaults:{fill:{color:r},stroke:{color:s},hover:{fill:{color:s},stroke:{color:r}}},content:{color:r}},editable:{resize:{handles:{fill:{color:s},stroke:{color:c},hover:{fill:{color:c},stroke:{color:c}}}},rotate:{thumb:{stroke:{color:c},fill:{color:c}}}},selectable:{stroke:{color:c}},connectionDefaults:{stroke:{color:c},content:{color:c},selection:{handles:{fill:{color:s},stroke:{color:c}},stroke:{color:c}}}},treeMap:{colors:e(n,i)}})}(),function(){function o(){return{icon:{background:"#00b0ff",border:{color:"#00b0ff"}},label:{color:"#ffffff"},line:{color:a}}}var r="#4e4e4e",l="#7f7f7f",c="#bdbdbd",a="#c8c8c8",t="#e5e5e5",n=["#0072c6","#5db2ff","#008a17","#82ba00","#ff8f32","#ac193d"],i=["#cbe2f3","#deeffe","#cbe7d0","#e5f0cb","#fee8d5","#eed0d7"],f=n[0],s=b;m("office365",{chart:{title:{color:r},legend:{labels:{color:r},inactiveItems:{labels:{color:l},markers:{color:l}}},seriesDefaults:{labels:{color:r},errorBars:{color:r},notes:o(),candlestick:{downColor:a,line:{color:c}},area:{opacity:.8},waterfall:{line:{color:a}},horizontalWaterfall:{line:{color:a}},overlay:{gradient:"none"},border:{_brightness:1}},seriesColors:n,axisDefaults:{line:{color:a},labels:{color:r},minorGridLines:{color:t},majorGridLines:{color:a},title:{color:r},crosshair:{color:l},notes:o()}},gauge:{pointer:{color:f},scale:{rangePlaceholderColor:a,labels:{color:r},minorTicks:{color:r},majorTicks:{color:r},line:{color:r}}},diagram:{shapeDefaults:{fill:{color:f},connectorDefaults:{fill:{color:r},stroke:{color:s},hover:{fill:{color:s},stroke:{color:r}}},content:{color:r}},editable:{resize:{handles:{fill:{color:s},stroke:{color:c},hover:{fill:{color:c},stroke:{color:c}}}},rotate:{thumb:{stroke:{color:c},fill:{color:c}}}},selectable:{stroke:{color:c}},connectionDefaults:{stroke:{color:c},content:{color:c},selection:{handles:{fill:{color:s},stroke:{color:c}},stroke:{color:c}}}},treeMap:{colors:e(n,i)}})}(),function(){function o(){return{icon:{background:"#007cc0",border:{color:"#007cc0"}},label:{color:"#ffffff"},line:{color:a}}}var r="#32364c",l="#7f7f7f",c="#bdbdbd",a="#dfe0e1",t="#dfe0e1",n=["#ff4350","#ff9ea5","#00acc1","#80deea","#ffbf46","#ffd78c"],i=["#ffd9dc","#ffeced","#cceef3","#e6f8fb","#fff2da","#fff7e8"],f=n[0],s=b;m("nova",{chart:{title:{color:r},legend:{labels:{color:r},inactiveItems:{labels:{color:l},markers:{color:l}}},seriesDefaults:{labels:{color:r},errorBars:{color:r},notes:o(),candlestick:{downColor:a,line:{color:c}},area:{opacity:.8},waterfall:{line:{color:a}},horizontalWaterfall:{line:{color:a}},overlay:{gradient:"none"},border:{_brightness:1}},seriesColors:n,axisDefaults:{line:{color:a},labels:{color:r},minorGridLines:{color:t},majorGridLines:{color:a},title:{color:r},crosshair:{color:r},notes:o()}},gauge:{pointer:{color:f},scale:{rangePlaceholderColor:a,labels:{color:r},minorTicks:{color:r},majorTicks:{color:r},line:{color:r}}},diagram:{shapeDefaults:{fill:{color:f},connectorDefaults:{fill:{color:r},stroke:{color:s},hover:{fill:{color:s},stroke:{color:r}}},content:{color:r}},editable:{resize:{handles:{fill:{color:s},stroke:{color:c},hover:{fill:{color:c},stroke:{color:c}}}},rotate:{thumb:{stroke:{color:c},fill:{color:c}}}},selectable:{stroke:{color:c}},connectionDefaults:{stroke:{color:c},content:{color:c},selection:{handles:{fill:{color:s},stroke:{color:c}},stroke:{color:c}}}},treeMap:{colors:e(n,i)}})}()}(window.kendo.jQuery),window.kendo},"function"==typeof define&&define.amd?define:function(o,e,r){(r||e)()});
//# sourceMappingURL=kendo.dataviz.themes.min.js.map
|
/**
* flowground :- Telekom iPaaS / ornl-gov-daymet-connector
* Copyright © 2019, Deutsche Telekom AG
* contact: [email protected]
*
* All files of this connector are licensed under the Apache 2.0 License. For details
* see the file LICENSE on the toplevel directory.
*/
const elasticio = require('elasticio-node');
const messages = elasticio.messages;
/**
* Receives an action process function and returns a wrapper around it
* Extra functionality:
* - this.emitData(data)
*
* Usage:
* const processWrapper = require('../services/process-wrapper.js');
* exports.process = processWrapper(processAction);
*
* @param {function} processFn - the function to wrap
* @returns {function} - the wrapper with additional functionality
*/
module.exports = function processWrapper(processFn) {
let num_emit = 0;
return function() {
let originalEmit = this.emit;
this.emit = (type, msg) => {
console.log('---EMIT', ++num_emit, type, JSON.stringify(msg));
return originalEmit.call(this, type, msg);
};
this.emitData = (data) => this.emit('data', messages.newMessageWithBody(data));
return Promise.resolve()
.then(() => processFn.apply(this, arguments))
.then(() => undefined);
};
}; |
'use strict';
exports.__esModule = true;
var _Formats;
exports.default = viewLabel;
var _constants = require('./constants');
var _formats = require('../formats');
var _formats2 = _interopRequireDefault(_formats);
var _localizer = require('../localizer');
var _localizer2 = _interopRequireDefault(_localizer);
var _Views = require('../Views');
var _Views2 = _interopRequireDefault(_Views);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Formats = (_Formats = {}, _Formats[_constants.views.MONTH] = 'monthHeaderFormat', _Formats[_constants.views.WEEK] = 'dayRangeHeaderFormat', _Formats[_constants.views.WORK_WEEK] = 'dayRangeHeaderFormat', _Formats[_constants.views.DAY] = 'dayHeaderFormat', _Formats[_constants.views.AGENDA] = 'agendaHeaderFormat', _Formats);
function getRangeBounds(range) {
if (Array.isArray(range)) {
var start = range[0];
var end = range[range.length - 1];
return { start: start, end: end };
}
return range;
}
function viewLabel(date, view, formats, culture) {
var View = _Views2.default[view];
var headerSingle = view === _constants.views.MONTH || view === _constants.views.DAY;
formats = (0, _formats2.default)(formats || {});
var headerFormat = formats[Formats[view]];
return headerSingle ? _localizer2.default.format(date, headerFormat, culture) : _localizer2.default.format(getRangeBounds(View.range(date, { culture: culture })), headerFormat, culture);
} |
(function() {
'use strict';
angular
.module('courses', ['ngResource', 'ui.router', 'ui.bootstrap',
'LocalStorageModule', 'courses.Filters', 'ngMockE2E', 'ngMessages'])
})();
|
import Icon from 'vue-awesome/components/Icon'
Icon.register({
assignment_ind_two_tone: {
paths: [
{
opacity: '.3',
d: 'M19 5H5v14h14V5zm-7 1c1.65 0 3 1.35 3 3s-1.35 3-3 3-3-1.35-3-3 1.35-3 3-3zm6 12H6v-1.53c0-2.5 3.97-3.58 6-3.58s6 1.08 6 3.58V18z'
},
{
d: 'M20.66 3.88c-.14-.21-.33-.4-.54-.54-.11-.07-.22-.13-.34-.18-.24-.1-.5-.16-.78-.16h-4.18C14.4 1.84 13.3 1 12 1s-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c.28 0 .54-.06.78-.16.12-.05.23-.11.34-.18.21-.14.4-.33.54-.54.21-.32.34-.71.34-1.12V5c0-.41-.13-.8-.34-1.12zM12 2.75c.22 0 .41.1.55.25.12.13.2.31.2.5 0 .41-.34.75-.75.75s-.75-.34-.75-.75c0-.19.08-.37.2-.5.14-.15.33-.25.55-.25zM19 19H5V5h14v14z'
},
{
d: 'M12 12c1.65 0 3-1.35 3-3s-1.35-3-3-3-3 1.35-3 3 1.35 3 3 3zm0-2c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm0 2.88c-2.03 0-6 1.08-6 3.58V18h12v-1.53c0-2.51-3.97-3.59-6-3.59zM8.31 16c.69-.56 2.38-1.12 3.69-1.12s3.01.56 3.69 1.12H8.31z'
}
],
width: '24',
height: '24'
}
})
|
const http = require('http');
var str_hello = '';
for ( let i = 0; i < 1024 * 1024 ; i++) {
str_hello += 'a';
}
var buff_hello = Buffer.from(str_hello);
http.createServer( (req, res) => {
res.writeHead(200);
res.end(buff_hello);
}).listen(8010);
console.log('http_server starting ok...'); |
/**
* dijit - A version of dijit.js framework that ported to running on skylarkjs.
* @author Hudaokeji, Inc.
* @version v0.9.0
* @link https://github.com/skylark-integration/dijit/
* @license MIT
*/
define(["dojo/_base/declare","dojo/dom-class","dojo/has","dojo/keys","dojo/_base/lang","dojo/on","./focus","./layout/ContentPane","./_DialogMixin","./form/_FormMixin","./_TemplatedMixin","dojo/text!./templates/TooltipDialog.html","./_dijit"],function(t,o,i,e,s,n,r,l,d,c,h,a,p){var f=t("dijit.TooltipDialog",[l,h,c,d],{title:"",doLayout:!1,autofocus:!0,baseClass:"dijitTooltipDialog",_firstFocusItem:null,_lastFocusItem:null,templateString:a,_setTitleAttr:"containerNode",postCreate:function(){this.inherited(arguments),this.own(n(this.domNode,"keydown",s.hitch(this,"_onKey")))},orient:function(t,i,e){var s={"MR-ML":"dijitTooltipRight","ML-MR":"dijitTooltipLeft","TM-BM":"dijitTooltipAbove","BM-TM":"dijitTooltipBelow","BL-TL":"dijitTooltipBelow dijitTooltipABLeft","TL-BL":"dijitTooltipAbove dijitTooltipABLeft","BR-TR":"dijitTooltipBelow dijitTooltipABRight","TR-BR":"dijitTooltipAbove dijitTooltipABRight","BR-BL":"dijitTooltipRight","BL-BR":"dijitTooltipLeft","BR-TL":"dijitTooltipBelow dijitTooltipABLeft","BL-TR":"dijitTooltipBelow dijitTooltipABRight","TL-BR":"dijitTooltipAbove dijitTooltipABRight","TR-BL":"dijitTooltipAbove dijitTooltipABLeft"}[i+"-"+e];o.replace(this.domNode,s,this._currentOrientClass||""),this._currentOrientClass=s},focus:function(){this._getFocusItems(),r.focus(this._firstFocusItem)},onOpen:function(t){this.orient(this.domNode,t.aroundCorner,t.corner);var o=t.aroundNodePos;"M"==t.corner.charAt(0)&&"M"==t.aroundCorner.charAt(0)?(this.connectorNode.style.top=o.y+(o.h-this.connectorNode.offsetHeight>>1)-t.y+"px",this.connectorNode.style.left=""):"M"==t.corner.charAt(1)&&"M"==t.aroundCorner.charAt(1)&&(this.connectorNode.style.left=o.x+(o.w-this.connectorNode.offsetWidth>>1)-t.x+"px"),this._onShow()},onClose:function(){this.onHide()},_onKey:function(t){if(t.keyCode==e.ESCAPE)this.defer("onCancel"),t.stopPropagation(),t.preventDefault();else if(t.keyCode==e.TAB){var o=t.target;this._getFocusItems(),this._firstFocusItem==this._lastFocusItem?(t.stopPropagation(),t.preventDefault()):o==this._firstFocusItem&&t.shiftKey?(r.focus(this._lastFocusItem),t.stopPropagation(),t.preventDefault()):o!=this._lastFocusItem||t.shiftKey?t.stopPropagation():(r.focus(this._firstFocusItem),t.stopPropagation(),t.preventDefault())}}});return i("dojo-bidi")&&f.extend({_setTitleAttr:function(t){this.containerNode.title=this.textDir&&this.enforceTextDirWithUcc?this.enforceTextDirWithUcc(null,t):t,this._set("title",t)},_setTextDirAttr:function(t){this._created&&this.textDir==t||(this._set("textDir",t),this.textDir&&this.title&&(this.containerNode.title=this.enforceTextDirWithUcc(null,this.title)))}}),f});
//# sourceMappingURL=sourcemaps/TooltipDialog.js.map
|
const url = require('url');
const axios = require('axios').default;
const fileType = require('file-type');
/**
* @param {string} siteUrl
*/
function getSiteDomain(siteUrl) {
return url.parse(siteUrl).hostname;
}
/**
* @param {string} iconUrl
*/
async function downloadIcon(iconUrl) {
let iconResponse;
try {
iconResponse = await axios.get(iconUrl, {
responseType: 'arraybuffer',
//'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'
});
} catch (error) {
if (error.response && error.response.status === 404) {
return null;
}
throw error;
}
const iconData = await iconResponse.data;
if (!iconData) {
return null;
}
const fileDetails = await fileType.fromBuffer(iconData);
if (!fileDetails) {
return null;
}
return {
source: iconUrl,
name: getSiteDomain(iconUrl),
data: iconData,
size: iconData.length,
ext: `.${fileDetails.ext}`, // add `.` to ext
mime: fileDetails.mime,
};
}
module.exports = downloadIcon;
|
import { jobsService, doctorsService } from 'barracao-digital/services'
export const handler = async (user) => {
const currentUser = await doctorsService.getOneByUsername(user.username)
if (currentUser.active) await doctorsService.alternateActive(user.username)
await jobsService.removeAlternateDoctorJobSchedule(user)
}
|
! function(a, b) {
"function" == typeof define && (define.amd || define.cmd) ? define(function() {
return b(a)
}) : b(a, !0)
}(this, function(a, b) {
function c(b, c, d) {
a.WeixinJSBridge ? WeixinJSBridge.invoke(b, e(c), function(a) {
g(b, a, d)
}) : j(b, d)
}
function d(b, c, d) {
a.WeixinJSBridge ? WeixinJSBridge.on(b, function(a) {
d && d.trigger && d.trigger(a), g(b, a, c)
}) : d ? j(b, d) : j(b, c)
}
function e(a) {
return a = a || {}, a.appId = E.appId, a.verifyAppId = E.appId, a.verifySignType = "sha1", a.verifyTimestamp = E.timestamp + "", a.verifyNonceStr = E.nonceStr, a.verifySignature = E.signature, a
}
function f(a) {
return {
timeStamp: a.timestamp + "",
nonceStr: a.nonceStr,
"package": a.package,
paySign: a.paySign,
signType: a.signType || "SHA1"
}
}
function g(a, b, c) {
var d, e, f;
switch (delete b.err_code, delete b.err_desc, delete b.err_detail, d = b.errMsg, d || (d = b.err_msg, delete b.err_msg, d = h(a, d), b.errMsg = d), c = c || {}, c._complete && (c._complete(b), delete c._complete), d = b.errMsg || "", E.debug && !c.isInnerInvoke && alert(JSON.stringify(b)), e = d.indexOf(":"), f = d.substring(e + 1)) {
case "ok":
c.success && c.success(b);
break;
case "cancel":
c.cancel && c.cancel(b);
break;
default:
c.fail && c.fail(b)
}
c.complete && c.complete(b)
}
function h(a, b) {
var e, f, c = a,
d = p[c];
return d && (c = d), e = "ok", b && (f = b.indexOf(":"), e = b.substring(f + 1), "confirm" == e && (e = "ok"), "failed" == e && (e = "fail"), -1 != e.indexOf("failed_") && (e = e.substring(7)), -1 != e.indexOf("fail_") && (e = e.substring(5)), e = e.replace(/_/g, " "), e = e.toLowerCase(), ("access denied" == e || "no permission to execute" == e) && (e = "permission denied"), "config" == c && "function not exist" == e && (e = "ok"), "" == e && (e = "fail")), b = c + ":" + e
}
function i(a) {
var b, c, d, e;
if (a) {
for (b = 0, c = a.length; c > b; ++b) d = a[b], e = o[d], e && (a[b] = e);
return a
}
}
function j(a, b) {
if (!(!E.debug || b && b.isInnerInvoke)) {
var c = p[a];
c && (a = c), b && b._complete && delete b._complete, console.log('"' + a + '",', b || "")
}
}
function k() {
0 != D.preVerifyState && (u || v || E.debug || "6.0.2" > z || D.systemType < 0 || A || (A = !0, D.appId = E.appId, D.initTime = C.initEndTime - C.initStartTime, D.preVerifyTime = C.preVerifyEndTime - C.preVerifyStartTime, H.getNetworkType({
isInnerInvoke: !0,
success: function(a) {
var b, c;
D.networkType = a.networkType, b = "http://open.weixin.qq.com/sdk/report?v=" + D.version + "&o=" + D.preVerifyState + "&s=" + D.systemType + "&c=" + D.clientVersion + "&a=" + D.appId + "&n=" + D.networkType + "&i=" + D.initTime + "&p=" + D.preVerifyTime + "&u=" + D.url, c = new Image, c.src = b
}
})))
}
function l() {
return (new Date).getTime()
}
function m(b) {
w && (a.WeixinJSBridge ? b() : q.addEventListener && q.addEventListener("WeixinJSBridgeReady", b, !1))
}
function n() {
H.invoke || (H.invoke = function(b, c, d) {
a.WeixinJSBridge && WeixinJSBridge.invoke(b, e(c), d)
}, H.on = function(b, c) {
a.WeixinJSBridge && WeixinJSBridge.on(b, c)
})
}
var o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H;
if (!a.jWeixin) return o = {
config: "preVerifyJSAPI",
onMenuShareTimeline: "menu:share:timeline",
onMenuShareAppMessage: "menu:share:appmessage",
onMenuShareQQ: "menu:share:qq",
onMenuShareWeibo: "menu:share:weiboApp",
onMenuShareQZone: "menu:share:QZone",
previewImage: "imagePreview",
getLocation: "geoLocation",
openProductSpecificView: "openProductViewWithPid",
addCard: "batchAddCard",
openCard: "batchViewCard",
chooseWXPay: "getBrandWCPayRequest"
}, p = function() {
var b, a = {};
for (b in o) a[o[b]] = b;
return a
}(), q = a.document, r = q.title, s = navigator.userAgent.toLowerCase(), t = navigator.platform.toLowerCase(), u = !(!t.match("mac") && !t.match("win")), v = -1 != s.indexOf("wxdebugger"), w = -1 != s.indexOf("micromessenger"), x = -1 != s.indexOf("android"), y = -1 != s.indexOf("iphone") || -1 != s.indexOf("ipad"), z = function() {
var a = s.match(/micromessenger\/(\d+\.\d+\.\d+)/) || s.match(/micromessenger\/(\d+\.\d+)/);
return a ? a[1] : ""
}(), A = !1, B = !1, C = {
initStartTime: l(),
initEndTime: 0,
preVerifyStartTime: 0,
preVerifyEndTime: 0
}, D = {
version: 1,
appId: "",
initTime: 0,
preVerifyTime: 0,
networkType: "",
preVerifyState: 1,
systemType: y ? 1 : x ? 2 : -1,
clientVersion: z,
url: encodeURIComponent(location.href)
}, E = {}, F = {
_completes: []
}, G = {
state: 0,
data: {}
}, m(function() {
C.initEndTime = l()
}), H = {
config: function(a) {
E = a, j("config", a);
var b = E.check === !1 ? !1 : !0;
m(function() {
var a, d, e;
if (b) c(o.config, {
verifyJsApiList: i(E.jsApiList)
}, function() {
F._complete = function(a) {
C.preVerifyEndTime = l(), G.state = 1, G.data = a
}, F.success = function() {
D.preVerifyState = 0
}, F.fail = function(a) {
F._fail ? F._fail(a) : G.state = -1
};
var a = F._completes;
return a.push(function() {
k()
}), F.complete = function() {
for (var c = 0, d = a.length; d > c; ++c) a[c]();
F._completes = []
}, F
}()), C.preVerifyStartTime = l();
else {
for (G.state = 1, a = F._completes, d = 0, e = a.length; e > d; ++d) a[d]();
F._completes = []
}
}), E.beta && n()
},
ready: function(a) {
0 != G.state ? a() : (F._completes.push(a), !w && E.debug && a())
},
error: function(a) {
"6.0.2" > z || B || (B = !0, -1 == G.state ? a(G.data) : F._fail = a)
},
checkJsApi: function(a) {
var b = function(a) {
var c, d, b = a.checkResult;
for (c in b) d = p[c], d && (b[d] = b[c], delete b[c]);
return a
};
c("checkJsApi", {
jsApiList: i(a.jsApiList)
}, function() {
return a._complete = function(a) {
if (x) {
var c = a.checkResult;
c && (a.checkResult = JSON.parse(c))
}
a = b(a)
}, a
}())
},
onMenuShareTimeline: function(a) {
d(o.onMenuShareTimeline, {
complete: function() {
c("shareTimeline", {
title: a.title || r,
desc: a.title || r,
img_url: a.imgUrl || "",
link: a.link || location.href,
type: a.type || "link",
data_url: a.dataUrl || ""
}, a)
}
}, a)
},
onMenuShareAppMessage: function(a) {
d(o.onMenuShareAppMessage, {
complete: function() {
c("sendAppMessage", {
title: a.title || r,
desc: a.desc || "",
link: a.link || location.href,
img_url: a.imgUrl || "",
type: a.type || "link",
data_url: a.dataUrl || ""
}, a)
}
}, a)
},
onMenuShareQQ: function(a) {
d(o.onMenuShareQQ, {
complete: function() {
c("shareQQ", {
title: a.title || r,
desc: a.desc || "",
img_url: a.imgUrl || "",
link: a.link || location.href
}, a)
}
}, a)
},
onMenuShareWeibo: function(a) {
d(o.onMenuShareWeibo, {
complete: function() {
c("shareWeiboApp", {
title: a.title || r,
desc: a.desc || "",
img_url: a.imgUrl || "",
link: a.link || location.href
}, a)
}
}, a)
},
onMenuShareQZone: function(a) {
d(o.onMenuShareQZone, {
complete: function() {
c("shareQZone", {
title: a.title || r,
desc: a.desc || "",
img_url: a.imgUrl || "",
link: a.link || location.href
}, a)
}
}, a)
},
startRecord: function(a) {
c("startRecord", {}, a)
},
stopRecord: function(a) {
c("stopRecord", {}, a)
},
onVoiceRecordEnd: function(a) {
d("onVoiceRecordEnd", a)
},
playVoice: function(a) {
c("playVoice", {
localId: a.localId
}, a)
},
pauseVoice: function(a) {
c("pauseVoice", {
localId: a.localId
}, a)
},
stopVoice: function(a) {
c("stopVoice", {
localId: a.localId
}, a)
},
onVoicePlayEnd: function(a) {
d("onVoicePlayEnd", a)
},
uploadVoice: function(a) {
c("uploadVoice", {
localId: a.localId,
isShowProgressTips: 0 == a.isShowProgressTips ? 0 : 1
}, a)
},
downloadVoice: function(a) {
c("downloadVoice", {
serverId: a.serverId,
isShowProgressTips: 0 == a.isShowProgressTips ? 0 : 1
}, a)
},
translateVoice: function(a) {
c("translateVoice", {
localId: a.localId,
isShowProgressTips: 0 == a.isShowProgressTips ? 0 : 1
}, a)
},
chooseImage: function(a) {
c("chooseImage", {
scene: "1|2",
count: a.count || 9,
sizeType: a.sizeType || ["original", "compressed"],
sourceType: a.sourceType || ["album", "camera"]
}, function() {
return a._complete = function(a) {
if (x) {
var b = a.localIds;
b && (a.localIds = JSON.parse(b))
}
}, a
}())
},
previewImage: function(a) {
c(o.previewImage, {
current: a.current,
urls: a.urls
}, a)
},
uploadImage: function(a) {
c("uploadImage", {
localId: a.localId,
isShowProgressTips: 0 == a.isShowProgressTips ? 0 : 1
}, a)
},
downloadImage: function(a) {
c("downloadImage", {
serverId: a.serverId,
isShowProgressTips: 0 == a.isShowProgressTips ? 0 : 1
}, a)
},
getNetworkType: function(a) {
var b = function(a) {
var c, d, e, b = a.errMsg;
if (a.errMsg = "getNetworkType:ok", c = a.subtype, delete a.subtype, c) a.networkType = c;
else switch (d = b.indexOf(":"), e = b.substring(d + 1)) {
case "wifi":
case "edge":
case "wwan":
a.networkType = e;
break;
default:
a.errMsg = "getNetworkType:fail"
}
return a
};
c("getNetworkType", {}, function() {
return a._complete = function(a) {
a = b(a)
}, a
}())
},
openLocation: function(a) {
c("openLocation", {
latitude: a.latitude,
longitude: a.longitude,
name: a.name || "",
address: a.address || "",
scale: a.scale || 28,
infoUrl: a.infoUrl || ""
}, a)
},
getLocation: function(a) {
a = a || {}, c(o.getLocation, {
type: a.type || "wgs84"
}, function() {
return a._complete = function(a) {
delete a.type
}, a
}())
},
hideOptionMenu: function(a) {
c("hideOptionMenu", {}, a)
},
showOptionMenu: function(a) {
c("showOptionMenu", {}, a)
},
closeWindow: function(a) {
a = a || {}, c("closeWindow", {}, a)
},
hideMenuItems: function(a) {
c("hideMenuItems", {
menuList: a.menuList
}, a)
},
showMenuItems: function(a) {
c("showMenuItems", {
menuList: a.menuList
}, a)
},
hideAllNonBaseMenuItem: function(a) {
c("hideAllNonBaseMenuItem", {}, a)
},
showAllNonBaseMenuItem: function(a) {
c("showAllNonBaseMenuItem", {}, a)
},
scanQRCode: function(a) {
a = a || {}, c("scanQRCode", {
needResult: a.needResult || 0,
scanType: a.scanType || ["qrCode", "barCode"]
}, function() {
return a._complete = function(a) {
var b, c;
y && (b = a.resultStr, b && (c = JSON.parse(b), a.resultStr = c && c.scan_code && c.scan_code.scan_result))
}, a
}())
},
openProductSpecificView: function(a) {
c(o.openProductSpecificView, {
pid: a.productId,
view_type: a.viewType || 0,
ext_info: a.extInfo
}, a)
},
addCard: function(a) {
var e, f, g, h, b = a.cardList,
d = [];
for (e = 0, f = b.length; f > e; ++e) g = b[e], h = {
card_id: g.cardId,
card_ext: g.cardExt
}, d.push(h);
c(o.addCard, {
card_list: d
}, function() {
return a._complete = function(a) {
var c, d, e, b = a.card_list;
if (b) {
for (b = JSON.parse(b), c = 0, d = b.length; d > c; ++c) e = b[c], e.cardId = e.card_id, e.cardExt = e.card_ext, e.isSuccess = e.is_succ ? !0 : !1, delete e.card_id, delete e.card_ext, delete e.is_succ;
a.cardList = b, delete a.card_list
}
}, a
}())
},
chooseCard: function(a) {
c("chooseCard", {
app_id: E.appId,
location_id: a.shopId || "",
sign_type: a.signType || "SHA1",
card_id: a.cardId || "",
card_type: a.cardType || "",
card_sign: a.cardSign,
time_stamp: a.timestamp + "",
nonce_str: a.nonceStr
}, function() {
return a._complete = function(a) {
a.cardList = a.choose_card_info, delete a.choose_card_info
}, a
}())
},
openCard: function(a) {
var e, f, g, h, b = a.cardList,
d = [];
for (e = 0, f = b.length; f > e; ++e) g = b[e], h = {
card_id: g.cardId,
code: g.code
}, d.push(h);
c(o.openCard, {
card_list: d
}, a)
},
chooseWXPay: function(a) {
c(o.chooseWXPay, f(a), a)
}
}, b && (a.wx = a.jWeixin = H), H
}); |
// Transpile all code following this line with babel and use '@babel/preset-env' (aka ES6) preset.
require("@babel/register")({
presets: ["@babel/preset-env"]
});
// Import the rest of our application.
module.exports = require('./index.js')
module.exports = require('./babylon/babylon-functions.js') |
var mongoose = require('mongoose');
var UserSchema = new mongoose.Schema({
userCode: String,
password: String,
Avatar: String,
backgroundImg: String,
ImgList: String,
realName: String,
sex: Number,//0女,1男
identityCardNum: String,
phone: Number,
qq: String,
nickName: String,
birthday: Date,
relationshipStatus: Number,//0保密,1单身,2恋爱中,3已婚,4同性
personSign: String,//个人签名
address: String,
career: String,//职业
school: String,//学校
tags: String,//标签
personRemark: String,//个人说明
movies: String,
bookes: String,
music: String,
lastLoginDate: Date,
registerDate: Date,
});
mongoose.model('User',UserSchema); |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class TenantSettingsOperations(object):
"""TenantSettingsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.apimanagement.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list_by_service(
self,
resource_group_name, # type: str
service_name, # type: str
filter=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.TenantSettingsCollection"]
"""Public settings.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:param filter: Not used.
:type filter: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either TenantSettingsCollection or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.apimanagement.models.TenantSettingsCollection]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.TenantSettingsCollection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-12-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_service.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
if filter is not None:
query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('TenantSettingsCollection', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_service.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/settings'} # type: ignore
def get(
self,
resource_group_name, # type: str
service_name, # type: str
settings_type, # type: Union[str, "_models.SettingsTypeName"]
**kwargs # type: Any
):
# type: (...) -> "_models.TenantSettingsContract"
"""Get tenant settings.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param service_name: The name of the API Management service.
:type service_name: str
:param settings_type: The identifier of the settings.
:type settings_type: str or ~azure.mgmt.apimanagement.models.SettingsTypeName
:keyword callable cls: A custom type or function that will be passed the direct response
:return: TenantSettingsContract, or the result of cls(response)
:rtype: ~azure.mgmt.apimanagement.models.TenantSettingsContract
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.TenantSettingsContract"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-12-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'serviceName': self._serialize.url("service_name", service_name, 'str', max_length=50, min_length=1, pattern=r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'settingsType': self._serialize.url("settings_type", settings_type, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
response_headers = {}
response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
deserialized = self._deserialize('TenantSettingsContract', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/settings/{settingsType}'} # type: ignore
|
function solve(tokens = []) {
let movies = [];
while (tokens.length !== 0) {
let movieData = tokens.shift();
if (movieData.includes('addMovie')) {
movieData = movieData.replace('addMovie ', '');
let movie = { name: movieData };
movies.push(movie);
} else if (movieData.includes('directedBy')) {
movieData = movieData.replace(' directedBy ', '|').split('|');
let movie = movies.find(x => x.name === movieData[0]);
if (movie !== undefined) {
movie.director = movieData[1];
}
} else {
movieData = movieData.replace(' onDate ', '|').split('|');
let movie = movies.find(x => x.name === movieData[0]);
if (movie !== undefined) {
movie.date = movieData[1];
}
}
}
movies.filter(x => Object.keys(x).length === 3).forEach(x => console.log(JSON.stringify(x)));
}
|
var class_a_r_k_1_1_util_1_1_matrix33 =
[
[ "Matrix33", "class_a_r_k_1_1_util_1_1_matrix33.html#a70e4ce2c882eb7ea884d4b72baf6c728", null ],
[ "Matrix33", "class_a_r_k_1_1_util_1_1_matrix33.html#a511c2745c754ce18638f722f0f6dee03", null ],
[ "Matrix33", "class_a_r_k_1_1_util_1_1_matrix33.html#ac617cf530710eaf515b40180cf39c3ac", null ],
[ "determinant", "class_a_r_k_1_1_util_1_1_matrix33.html#a69ed7d36dbdc586939e8e53c7bdf6a14", null ],
[ "identity", "class_a_r_k_1_1_util_1_1_matrix33.html#a0c5a14693de9eb4355cc5959a323ef95", null ],
[ "inverse", "class_a_r_k_1_1_util_1_1_matrix33.html#a5555c7c6c59387fd0b83edfeb75864bc", null ],
[ "operator[]", "class_a_r_k_1_1_util_1_1_matrix33.html#ad50a3f758cbd953cb4220eb18508ccf0", null ],
[ "operator[]", "class_a_r_k_1_1_util_1_1_matrix33.html#afe1837f3f52e5e907fb295fbf368c982", null ],
[ "pointer", "class_a_r_k_1_1_util_1_1_matrix33.html#af737a0f826f0a27a86a430cb0ab24b55", null ],
[ "pointer", "class_a_r_k_1_1_util_1_1_matrix33.html#a9a655d0b6f4a487503a2290a53b7840b", null ],
[ "transpose", "class_a_r_k_1_1_util_1_1_matrix33.html#aff41c521941910e2186e9dede2082661", null ],
[ "col", "class_a_r_k_1_1_util_1_1_matrix33.html#ad003f8120c7948baa490536856dc3891", null ],
[ "x", "class_a_r_k_1_1_util_1_1_matrix33.html#a3b59ba89df1344c97c652fa542c7de8b", null ],
[ "y", "class_a_r_k_1_1_util_1_1_matrix33.html#aa486059e72757279d0de4bbbacd1d4bf", null ],
[ "z", "class_a_r_k_1_1_util_1_1_matrix33.html#a75ba6bca8efddf4412ca1c3e096d91ae", null ]
]; |
'use strict';
var chai = require('chai')
, Sequelize = require('../../index')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../lib/data-types')
, datetime = require('chai-datetime');
chai.use(datetime);
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser('Model'), function() {
beforeEach(function() {
return Support.prepareTransactionTest(this.sequelize).bind(this).then(function(sequelize) {
this.sequelize = sequelize;
this.User = this.sequelize.define('User', {
username: DataTypes.STRING,
secretValue: DataTypes.STRING,
data: DataTypes.STRING,
intVal: DataTypes.INTEGER,
theDate: DataTypes.DATE,
aBool: DataTypes.BOOLEAN
});
return this.User.sync({ force: true });
});
});
describe('scopes', function() {
beforeEach(function() {
this.ScopeMe = this.sequelize.define('ScopeMe', {
username: Sequelize.STRING,
email: Sequelize.STRING,
access_level: Sequelize.INTEGER,
other_value: Sequelize.INTEGER,
parent_id: Sequelize.INTEGER
}, {
defaultScope: {
where: {
access_level: {
gte: 5
}
}
},
scopes: {
orderScope: {
order: 'access_level DESC'
},
limitScope: {
limit: 2
},
sequelizeTeam: {
where: ['email LIKE \'%@sequelizejs.com\'']
},
fakeEmail: {
where: ['email LIKE \'%@fakeemail.com\'']
},
highValue: {
where: {
other_value: {
gte: 10
}
}
},
isTony: {
where: {
username: 'tony'
}
},
canBeTony: {
where: {
username: ['tony']
}
},
canBeDan: {
where: {
username: {
in : 'dan'
}
}
},
actualValue: function(value) {
return {
where: {
other_value: value
}
};
},
complexFunction: function(email, accessLevel) {
return {
where: ['email like ? AND access_level >= ?', email + '%', accessLevel]
};
},
lowAccess: {
where: {
access_level: {
lte: 5
}
}
},
escape: {
where: {
username: "escape'd"
}
}
}
});
return this.sequelize.sync({force: true}).then(function() {
var records = [
{username: 'dan', email: '[email protected]', access_level: 5, other_value: 10, parent_id: 1},
{username: 'tobi', email: '[email protected]', access_level: 10, other_value: 11, parent_id: 2},
{username: 'tony', email: '[email protected]', access_level: 3, other_value: 7, parent_id: 1},
{username: 'fred', email: '[email protected]', access_level: 3, other_value: 7, parent_id: 1}
];
return this.ScopeMe.bulkCreate(records);
}.bind(this));
});
it('should be able use where in scope', function() {
return this.ScopeMe.scope({where: { parent_id: 2 }}).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
expect(users[0].username).to.equal('tobi');
});
});
it('should be able to combine scope and findAll where clauses', function() {
return this.ScopeMe.scope({where: { parent_id: 1 }}).findAll({ where: {access_level: 3}}).then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2);
expect(['tony', 'fred'].indexOf(users[0].username) !== -1).to.be.true;
expect(['tony', 'fred'].indexOf(users[1].username) !== -1).to.be.true;
});
});
it('should have no problems with escaping SQL', function() {
var self = this;
return this.ScopeMe.create({username: 'escape\'d', email: '[email protected]'}).then(function() {
return self.ScopeMe.scope('escape').all().then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
expect(users[0].username).to.equal('escape\'d');
});
});
});
it('should be able to use a defaultScope if declared', function() {
return this.ScopeMe.all().then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2);
expect([10, 5].indexOf(users[0].access_level) !== -1).to.be.true;
expect([10, 5].indexOf(users[1].access_level) !== -1).to.be.true;
expect(['dan', 'tobi'].indexOf(users[0].username) !== -1).to.be.true;
expect(['dan', 'tobi'].indexOf(users[1].username) !== -1).to.be.true;
});
});
it('should be able to amend the default scope with a find object', function() {
return this.ScopeMe.findAll({where: {username: 'dan'}}).then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
expect(users[0].username).to.equal('dan');
});
});
it('should be able to override the default scope', function() {
return this.ScopeMe.scope('fakeEmail').findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
expect(users[0].username).to.equal('tobi');
});
});
it('should be able to combine two scopes', function() {
return this.ScopeMe.scope(['sequelizeTeam', 'highValue']).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
expect(users[0].username).to.equal('dan');
});
});
it("should be able to call a scope that's a function", function() {
return this.ScopeMe.scope({method: ['actualValue', 11]}).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
expect(users[0].username).to.equal('tobi');
});
});
it('should be able to handle multiple function scopes', function() {
return this.ScopeMe.scope([{method: ['actualValue', 10]}, {method: ['complexFunction', 'dan', '5']}]).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
expect(users[0].username).to.equal('dan');
});
});
it('should be able to stack the same field in the where clause', function() {
return this.ScopeMe.scope(['canBeDan', 'canBeTony']).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2);
expect(['dan', 'tony'].indexOf(users[0].username) !== -1).to.be.true;
expect(['dan', 'tony'].indexOf(users[1].username) !== -1).to.be.true;
});
});
it('should be able to merge scopes', function() {
return this.ScopeMe.scope(['highValue', 'isTony', {merge: true, method: ['actualValue', 7]}]).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
expect(users[0].username).to.equal('tony');
});
});
describe('should not overwrite', function() {
it('default scope with values from previous finds', function() {
return this.ScopeMe.findAll({ where: { other_value: 10 }}).bind(this).then(function(users) {
expect(users).to.have.length(1);
return this.ScopeMe.findAll();
}).then(function(users) {
// This should not have other_value: 10
expect(users).to.have.length(2);
});
});
it('other scopes with values from previous finds', function() {
return this.ScopeMe.scope('highValue').findAll({ where: { access_level: 10 }}).bind(this).then(function(users) {
expect(users).to.have.length(1);
return this.ScopeMe.scope('highValue').findAll();
}).then(function(users) {
// This should not have other_value: 10
expect(users).to.have.length(2);
});
});
it('function scopes', function() {
return this.ScopeMe.scope({method: ['actualValue', 11]}).findAll().bind(this).then(function(users) {
expect(users).to.have.length(1);
expect(users[0].other_value).to.equal(11);
return this.ScopeMe.scope({method: ['actualValue', 10]}).findAll();
}).then(function(users) {
expect(users).to.have.length(1);
expect(users[0].other_value).to.equal(10);
});
});
});
it('should give us the correct order if we declare an order in our scope', function() {
return this.ScopeMe.scope('sequelizeTeam', 'orderScope').findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2);
expect(users[0].username).to.equal('dan');
expect(users[1].username).to.equal('tony');
});
});
it('should give us the correct order as well as a limit if we declare such in our scope', function() {
return this.ScopeMe.scope(['orderScope', 'limitScope']).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2);
expect(users[0].username).to.equal('tobi');
expect(users[1].username).to.equal('dan');
});
});
it('should have no problems combining scopes and traditional where object', function() {
return this.ScopeMe.scope('sequelizeTeam').findAll({where: {other_value: 10}}).then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
expect(users[0].username).to.equal('dan');
expect(users[0].access_level).to.equal(5);
expect(users[0].other_value).to.equal(10);
});
});
it('should be able to remove all scopes', function() {
return this.ScopeMe.scope(null).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(4);
});
});
it('should have no problem performing findOrCreate', function() {
return this.ScopeMe.findOrCreate({ where: {username: 'fake'}}).spread(function(user) {
expect(user.username).to.equal('fake');
});
});
it('should be able to hold multiple scope objects', function() {
var sequelizeTeam = this.ScopeMe.scope('sequelizeTeam', 'orderScope')
, tobi = this.ScopeMe.scope({method: ['actualValue', 11]});
return sequelizeTeam.all().then(function(team) {
return tobi.all().then(function(t) {
expect(team).to.be.an.instanceof(Array);
expect(team.length).to.equal(2);
expect(team[0].username).to.equal('dan');
expect(team[1].username).to.equal('tony');
expect(t).to.be.an.instanceof(Array);
expect(t.length).to.equal(1);
expect(t[0].username).to.equal('tobi');
});
});
});
it("should gracefully omit any scopes that don't exist", function() {
return this.ScopeMe.scope('sequelizeTeam', 'orderScope', 'doesntexist').all().then(function(team) {
expect(team).to.be.an.instanceof(Array);
expect(team.length).to.equal(2);
expect(team[0].username).to.equal('dan');
expect(team[1].username).to.equal('tony');
});
});
it("should gracefully omit any scopes that don't exist through an array", function() {
return this.ScopeMe.scope(['sequelizeTeam', 'orderScope', 'doesntexist']).all().then(function(team) {
expect(team).to.be.an.instanceof(Array);
expect(team.length).to.equal(2);
expect(team[0].username).to.equal('dan');
expect(team[1].username).to.equal('tony');
});
});
it("should gracefully omit any scopes that don't exist through an object", function() {
return this.ScopeMe.scope('sequelizeTeam', 'orderScope', {method: 'doesntexist'}).all().then(function(team) {
expect(team).to.be.an.instanceof(Array);
expect(team.length).to.equal(2);
expect(team[0].username).to.equal('dan');
expect(team[1].username).to.equal('tony');
});
});
it("should emit an error for scopes that don't exist with silent: false", function() {
expect(this.ScopeMe.scope.bind(this.ScopeMe, 'doesntexist', {silent: false})).to.throw('Invalid scope doesntexist called.');
});
});
});
|
(function($) {
'use strict';
var table = $('#asignacions');
const inf = $('#inf');
$(document).ready(function () {
table.DataTable({
search: {
smart: true
},
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
responsive: true,
processing: true,
serverSide: true,
select: true,
sDom: '<"text-right mb-md"T><"row"<"col-lg-6"l><"col-lg-6"f>><"table-responsive"t>p',
ajax: inf.data('urltabla'),
dom: 'Bfrtip',
columns: [
{data: null, defaultContent: '', className: 'control', orderable: false, searchable: false },
{data: "id", name: "id", className: 'never', orderable: false, visible: false, searchable: false},
{ data: "name", name:"name",orderable: true, searchable: true },
{ data: "address", name:"address",orderable: true, searchable: true },
{ data: "votantes", name:"votantes",orderable: false, searchable: false },
{
data: "id", render: function (data, type, row) {
return '<a href="' + inf.data('url') + "/campain/points/" + data + '/edit"' + ' class="on-default edit-row simple-ajax-modal"><i class="fas fa-pencil-alt"></i></a>' +
'<a href="' + inf.data('url') + "/campain/points/" + data + '"' + ' class="on-default show-row ml-1 "><i class="fas fa-eye"></i></a> ' +
'<a href="#modalEliminar" data-nasg ="'+row.name+'" data-urldestroy = "' + inf.data('url') + '/campain/points/' + data +'" class="on-default ml-1 remove-row modal-basic " >' +
'<i class="far fa-trash-alt"></i>' +
'</a>';
},
}
],
buttons: [
{
extend: 'collection',
text: 'Export',
buttons: [
'copy',
'excel',
'csv',
'pdf',
'print'
],
className: 'dropdown-toggle btn-primary'
}
],
language: {
lengthMenu: "_MENU_ Grupos por página",
search: "_INPUT_",
searchPlaceholder: "Buscar...",
zeroRecords: "Nada encontrado, lo sentimos",
info: "Mostrando página _PAGE_ de _PAGES_",
infoEmpty: "No hay registros disponibles",
infoFiltered: "(filtrado de _MAX_ registros totales)"
}
});
$.fn.dataTable.ext.errMode = 'throw';
$(document).on('click', '.edit-row', function (e) {
e.preventDefault();
$('.simple-ajax-modal').magnificPopup({
type: 'ajax',
modal: true
});
});
$(document).on('click', '.remove-row', function (e) {
$("#form-delete").attr('action', $(this).data('urldestroy') );
$("#Nombreasg").text( $(this).data('nasg') );
$('.modal-basic').magnificPopup({
type: 'inline',
preloader: false,
modal: true
});
});
}
);
}).apply(this, [jQuery]);
|
import React, {useState} from 'react';
const DropdownMenuItem = ({ ingredient, handleClick }) => {
return (
<div >
<p onClick={handleClick}>{ingredient}</p>
</div>
);
};
export default DropdownMenuItem;
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[379],{3802:function(e,t,n){"use strict";n.r(t),n.d(t,"icon",(function(){return o}));n(13),n(3),n(4),n(9),n(2),n(10);var r=n(0),a=n.n(r);function l(){return(l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function i(e,t){if(null==e)return{};var n,r,a=function(e,t){if(null==e)return{};var n,r,a={},l=Object.keys(e);for(r=0;r<l.length;r++)n=l[r],t.indexOf(n)>=0||(a[n]=e[n]);return a}(e,t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(e);for(r=0;r<l.length;r++)n=l[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}var o=function(e){var t=e.title,n=e.titleId,r=i(e,["title","titleId"]);return a.a.createElement("svg",l({width:16,height:16,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":n},r),t?a.a.createElement("title",{id:n},t):null,a.a.createElement("path",{fillRule:"evenodd",d:"M5.482 4.344a2 2 0 10-2.963 0c-.08.042-.156.087-.23.136-.457.305-.75.704-.933 1.073A3.457 3.457 0 001 6.978V9a1 1 0 001 1h2.5a3.69 3.69 0 01.684-.962L5.171 9H2V7s0-2 2-2c1.007 0 1.507.507 1.755 1.01.225-.254.493-.47.793-.636a2.717 2.717 0 00-1.066-1.03zM4 4a1 1 0 100-2 1 1 0 000 2zm10 6h-2.5a3.684 3.684 0 00-.684-.962L10.829 9H14V7s0-2-2-2c-1.007 0-1.507.507-1.755 1.01a3.012 3.012 0 00-.793-.636 2.716 2.716 0 011.066-1.03 2 2 0 112.963 0c.08.042.156.087.23.136.457.305.75.704.933 1.073A3.453 3.453 0 0115 6.944V9a1 1 0 01-1 1zm-2-6a1 1 0 100-2 1 1 0 000 2z"}),a.a.createElement("path",{fillRule:"evenodd",d:"M10 8c0 .517-.196.989-.518 1.344a2.755 2.755 0 011.163 1.21A3.453 3.453 0 0111 11.977V14a1 1 0 01-1 1H6a1 1 0 01-1-1v-2.022a2.005 2.005 0 01.006-.135 3.456 3.456 0 01.35-1.29 2.755 2.755 0 011.162-1.21A2 2 0 1110 8zm-4 4v2h4v-2s0-2-2-2-2 2-2 2zm3-4a1 1 0 11-2 0 1 1 0 012 0z"}))}}}]);
//# sourceMappingURL=icon.users-js.min.js.map |
/*
########################################
MIT License
Copyright (c) 2019 Marc Espin Sanz
License > https://github.com/Graviton-Code-Editor/Graviton-App/blob/master/LICENSE.md
#########################################
*/
"use strict";
const fallbackProperties = {
'editor-background-color':'editorBackgroundColor',
'white-black' : 'primaryText',
'black-white' : 'secondaryText',
'widget-color':'widgetColor',
'buttons-roundness':'buttonsRoundness',
'dropmenu-background-color':'dropmenuBackgroundColor',
'dropmenu-span-color':'dropmenuSpanColor',
'titleBar-icons-color':'titleBarIconsColor',
'window-radius':'windowsRadius',
"window-border-color":"windowsBorderColor",
"notifications-background-color":"notificationsBackgroundColor",
"notifications-window-radius":"notificationsRadius",
"scroll-color":"scrollColor",
"scroll-color-hover":"scrollColorHovering"
}
function setProperties(current_config) {
const colors = themes[i]["colors"]; //Take the colors object inside the json file of the selected theme
for (i = 0; i < Object.keys(colors).length; i++) {
if (
current_config.accentColorPreferences === "system" &&
Object.keys(colors)[i] === "accentColor"
) {
try {
document.documentElement.style.setProperty(
"--accentColor",
"#" + systemPreferences.getAccentColor()
);
document.documentElement.style.setProperty(
"--accentDarkColor",
tinycolor(systemPreferences.getAccentColor())
.darken()
.toString()
);
document.documentElement.style.setProperty(
"--accentLightColor",
tinycolor(systemPreferences.getAccentColor())
.brighten()
.toString()
);
i += 2;
} catch {}
continue;
}
if (
(current_config.animationsPreferences === "desactivated" &&
Object.keys(colors)[i] !== "scalation") ||
current_config.animationsPreferences === "activated" ||
Object.keys(colors)[i] !== "blur"
) {
document.documentElement.style.setProperty(
`--${Object.keys(colors)[i]}`,
colors[Object.keys(colors)[i]]
); //Update the CSS variables
}
}
}
function filterColors(colors){
Object.keys(colors).map(function(color){
if(color in fallbackProperties) {
colors[fallbackProperties[color]] = colors[color]
delete colors[color]
}
})
}
module.exports = {
setTheme: function(name) {
if (graviton.getCurrentTheme() === name) return;
for (i = 0; i < themes.length; i++) {
if (themes[i]["name"] === name) {
if (themeObject.type === "custom_theme") {
Plugins.disableCSS(themeObject);
}
current_config["theme"] = themes[i].name;
if (themes[i].type === "custom_theme") {
themes[i].colors;
}
filterColors(themes[i].colors)
Plugins.enableCSS(themes[i]);
themeObject = themes[i];
setProperties(current_config);
const explorer_icons = document.getElementsByClassName(
"explorer_file_icon"
);
for (i = 0; i < explorer_icons.length; i++) {
const format = getFormat(
explorer_icons[i].getAttribute("file")
);
explorer_icons[i].src = (function() {
if (
explorer_icons[i].getAttribute("elementType") ===
"directory"
) {
return directories.getCustomIcon(
explorer_icons[i].getAttribute("file"),
explorer_icons[
i
].parentElement.parentElement.getAttribute(
"opened"
) === "false"
? "close"
: "open"
);
} else {
if (
themeObject.icons === undefined ||
(themeObject.icons[format.lang] === undefined &&
format.trust === true)
) {
return `src/icons/files/${format.lang}.svg`;
} else {
if (
themeObject.icons[format.lang] ===
undefined &&
themeObject.icons[format.format] ===
undefined
) {
return `src/icons/files/${format.lang}.svg`;
}
if (format.trust === true) {
return path.join(
plugins_folder,
themeObject.name,
themeObject.icons[format.lang]
);
} else {
return path.join(
plugins_folder,
themeObject.name,
themeObject.icons[format.format]
);
}
}
}
})();
}
editors.forEach(current_editor => {
if (
current_editor.editor !== undefined &&
current_editor.editor !== null
) {
current_editor.editor.setOption(
"theme",
themeObject["highlight"]
);
}
});
if (terminal != null) {
terminal.xterm.setOption("theme", {
background:
themeObject.colors["editorBackgroundColor"],
foreground: themeObject.colors["primaryText"],
cursor: themeObject.colors["primaryText"],
selection: themeObject.colors["scrollColor"]
});
}
document.body.setAttribute("theme", themeObject.name);
return;
}
}
}
};
|
var ctx = $("#myChart").get(0).getContext("2d");
var data = {
labels: ["Jan 09", "Feb 09", "Mar 09", "Apr 09", "May 09", "Jun 09", "Jul 09", "Aug 09", "Sep 09", "Oct 09", "Nov 09", "Dec 09",
"Jan 10", "Feb 10", "Mar 10", "Apr 10", "May 10", "Jun 10", "Jul 10", "Aug 10", "Sep 10", "Oct 10", "Nov 10", "Dec 10",
"Jan 11", "Feb 11", "Mar 11", "Apr 11", "May 11", "Jun 11", "Jul 11", "Aug 11", "Sep 11", "Oct 11", "Nov 11", "Dec 11",
"Jan 12", "Feb 12", "Mar 12", "Apr 12", "May 12", "Jun 12", "Jul 12", "Aug 12", "Sep 12", "Oct 12", "Nov 12", "Dec 12",
"Jan 13", "Feb 13", "Mar 13", "Apr 13", "May 13", "Jun 13", "Jul 13", "Aug 13", "Sep 13", "Oct 13", "Nov 13", "Dec 13",
"Jan 14", "Feb 14", "Mar 14", "Apr 14", "May 14"],
datasets: [
// First dataset: SW18
{
label: "SW18",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,.2)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [399000, 409000, 417000, 426000, 435000, 443000, 450000,
458000, 465000, 471000, 477000, 483000, 488000, 493000, 496000,
500000, 504000, 507000, 510000, 513000, 515000, 516000, 517000,
516000, 516000, 515000, 514000, 513000, 513000, 514000, 514000,
515000, 515000, 515000, 516000, 516000, 518000, 519000, 521000,
524000, 526000, 529000, 532000, 536000, 539000, 542000, 546000,
550000, 554000, 558000, 562000, 567000, 572000, 577000, 582000,
588000, 594000, 600000, 607000, 613000, 620000, 627000, 634000,
641000, 649000]
},
{
label: "All",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [266000, 271000, 275000, 279000, 283000, 287000, 291000,
295000, 298000, 302000, 305000, 308000, 310000, 313000, 315000,
317000, 319000, 321000, 323000, 325000, 326000, 327000, 328000,
328000, 329000, 329000, 330000, 330000, 330000, 330000, 330000,
329000, 329000, 328000, 328000, 329000, 329000, 330000, 330000,
331000, 332000, 333000, 334000, 334000, 335000, 336000, 337000,
339000, 340000, 341000, 342000, 343000, 344000, 345000, 346000,
347000, 349000, 350000, 351000, 352000, 353000, 354000, 356000,
357000, 358000]
}
]
};
var myNewChart = new Chart(ctx);
Chart.defaults.global = {
// Boolean - Whether to animate the chart
animation: true,
// Number - Number of animation steps
animationSteps: 60,
// String - Animation easing effect
animationEasing: "easeOutQuart",
// Boolean - If we should show the scale at all
showScale: true,
// Boolean - If we want to override with a hard coded scale
scaleOverride: false,
// ** Required if scaleOverride is true **
// Number - The number of steps in a hard coded scale
scaleSteps: null,
// Number - The value jump in the hard coded scale
scaleStepWidth: null,
// Number - The scale starting value
scaleStartValue: null,
// String - Colour of the scale line
scaleLineColor: "rgba(0,0,0,.1)",
// Number - Pixel width of the scale line
scaleLineWidth: 1,
// Boolean - Whether to show labels on the scale
scaleShowLabels: true,
// Interpolated JS string - can access value
scaleLabel: "<%=value%>",
// Boolean - Whether the scale should stick to integers, not floats even if drawing space is there
scaleIntegersOnly: true,
// Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero: false,
// String - Scale label font declaration for the scale label
scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Scale label font size in pixels
scaleFontSize: 12,
// String - Scale label font weight style
scaleFontStyle: "normal",
// String - Scale label font colour
scaleFontColor: "#666",
// Boolean - whether or not the chart should be responsive and resize when the browser does.
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true,
// Boolean - Determines whether to draw tooltips on the canvas or not
showTooltips: true,
// Array - Array of string names to attach tooltip events
tooltipEvents: ["mousemove", "touchstart", "touchmove"],
// String - Tooltip background colour
tooltipFillColor: "rgba(0,0,0,0.8)",
// String - Tooltip label font declaration for the scale label
tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip label font size in pixels
tooltipFontSize: 14,
// String - Tooltip font weight style
tooltipFontStyle: "normal",
// String - Tooltip label font colour
tooltipFontColor: "#fff",
// String - Tooltip title font declaration for the scale label
tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip title font size in pixels
tooltipTitleFontSize: 14,
// String - Tooltip title font weight style
tooltipTitleFontStyle: "bold",
// String - Tooltip title font colour
tooltipTitleFontColor: "#fff",
// Number - pixel width of padding around tooltip text
tooltipYPadding: 6,
// Number - pixel width of padding around tooltip text
tooltipXPadding: 6,
// Number - Size of the caret on the tooltip
tooltipCaretSize: 8,
// Number - Pixel radius of the tooltip border
tooltipCornerRadius: 6,
// Number - Pixel offset from point x to tooltip edge
tooltipXOffset: 10,
// String - Template string for single tooltips
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
// String - Template string for single tooltips
multiTooltipTemplate: "<%= value %>",
// Function - Will fire on animation progression.
onAnimationProgress: function(){},
// Function - Will fire on animation completion.
onAnimationComplete: function(){}
}
var myLineChart = new Chart(ctx).Line(data, {
///Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : false,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether the line is curved between points
bezierCurve : true,
//Number - Tension of the bezier curve between points
bezierCurveTension : 0.4,
//Boolean - Whether to show a dot for each point
pointDot : true,
//Number - Radius of each point dot in pixels
pointDotRadius : 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth : 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius : 1,
//Boolean - Whether to show a stroke for datasets
datasetStroke : true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth : 2,
//Boolean - Whether to fill the dataset with a colour
datasetFill : true,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
});
|
import unittest
from unittest.mock import Mock
import amaxa
from amaxa import constants
from .MockFileStore import MockFileStore
class test_LoadOperation(unittest.TestCase):
def test_maps_record_ids(self):
connection = Mock()
op = amaxa.LoadOperation(connection)
op.file_store = MockFileStore()
op.register_new_id(
"Account",
amaxa.SalesforceId("001000000000000"),
amaxa.SalesforceId("001000000000001"),
)
self.assertEqual(
amaxa.SalesforceId("001000000000001"),
op.get_new_id(amaxa.SalesforceId("001000000000000")),
)
def test_register_new_id_writes_result_entries(self):
connection = Mock()
op = amaxa.LoadOperation(connection)
op.file_store = MockFileStore()
op.register_new_id(
"Account",
amaxa.SalesforceId("001000000000000"),
amaxa.SalesforceId("001000000000001"),
)
op.file_store.get_csv(
"Account", amaxa.FileType.RESULT
).writerow.assert_called_once_with(
{
constants.ORIGINAL_ID: str(amaxa.SalesforceId("001000000000000")),
constants.NEW_ID: str(amaxa.SalesforceId("001000000000001")),
}
)
def test_execute_runs_all_passes(self):
connection = Mock()
first_step = Mock(sobjectname="Account")
second_step = Mock(sobjectname="Contact")
op = amaxa.LoadOperation(connection)
op.file_store = MockFileStore()
op.add_step(first_step)
op.add_step(second_step)
self.assertEqual(0, op.execute())
first_step.execute.assert_called_once_with()
first_step.execute_dependent_updates.assert_called_once_with()
second_step.execute.assert_called_once_with()
second_step.execute_dependent_updates.assert_called_once_with()
def test_execute_stops_after_first_error_in_step_execute(self):
connection = Mock()
op = amaxa.LoadOperation(connection)
op.file_store = MockFileStore()
first_step = Mock(sobjectname="Account")
second_step = Mock(sobjectname="Contact")
first_step.execute.side_effect = lambda: op.register_error(
"Account", "001000000000000", "err"
)
op.add_step(first_step)
op.add_step(second_step)
self.assertEqual(-1, op.execute())
first_step.execute.assert_called_once_with()
first_step.execute_dependent_updates.assert_not_called()
second_step.execute.assert_not_called()
second_step.execute_dependent_updates.assert_not_called()
def test_execute_stops_after_first_error_in_step_execute_dependent_updates(self):
connection = Mock()
op = amaxa.LoadOperation(connection)
op.file_store = MockFileStore()
first_step = Mock(sobjectname="Account")
second_step = Mock(sobjectname="Contact")
first_step.execute_dependent_updates.side_effect = lambda: op.register_error(
"Account", "001000000000000", "err"
)
op.add_step(first_step)
op.add_step(second_step)
self.assertEqual(-1, op.execute())
first_step.execute.assert_called_once_with()
first_step.execute_dependent_updates.assert_called_once_with()
second_step.execute.assert_called_once_with()
second_step.execute_dependent_updates.assert_not_called()
def test_register_error_logs_to_result_file(self):
connection = Mock()
first_step = Mock()
first_step.sobjectname = "Account"
op = amaxa.LoadOperation(connection)
op.file_store = MockFileStore()
op.add_step(first_step)
first_step.execute.side_effect = lambda: op.register_error(
"Account", "001000000000000", "err"
)
self.assertEqual(-1, op.execute())
op.file_store.get_csv(
"Account", amaxa.FileType.RESULT
).writerow.assert_called_once_with(
{constants.ORIGINAL_ID: "001000000000000", constants.ERROR: "err"}
)
def test_execute_resumes_with_dependent_updates_if_stage_set(self):
connection = Mock()
first_step = Mock(sobjectname="Account")
second_step = Mock(sobjectname="Contact")
op = amaxa.LoadOperation(connection)
op.file_store = MockFileStore()
op.stage = amaxa.LoadStage.DEPENDENTS
op.add_step(first_step)
op.add_step(second_step)
self.assertEqual(0, op.execute())
first_step.execute.assert_not_called()
second_step.execute.assert_not_called()
first_step.execute_dependent_updates.assert_called_once_with()
second_step.execute_dependent_updates.assert_called_once_with()
|
/**
* Created by ShriRam on 2/17/2017.
*/
import React from 'react';
const Comments = React.createClass ({
renderComment(comment,i){
return(
<div className="comment" key={i}>
<p>
<strong>{comment.user}</strong>
{comment.text}
<button className="remove-comment">x</button>
</p>
</div>
)
},
handleSubmit(e) {
e.preventDefault();
const { postId } = this.props.params;
const author = this.refs.author.value;
const comment = this.refs.comment.value;
this.props.addComment(postId, author, comment);
this.refs.commentForm.reset();
},
render () {
return (
<div className="comment">
{this.props.postComments.map(this.renderComment)}
<form ref="commentForm" className="comment-form" onSubmit={this.handleSubmit}>
<input type="text" ref="author" placeholder="author"/>
<input type="text" ref="comment" placeholder="comment"/>
<input type="submit" hidden />
</form>
</div>
)
}
});
export default Comments; |
import torch
import torch.nn as nn
import torchvision.models as models
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
super(EncoderCNN, self).__init__()
resnet = models.resnet50(pretrained=True)
for param in resnet.parameters():
param.requires_grad_(False)
modules = list(resnet.children())[:-1]
self.resnet = nn.Sequential(*modules)
self.embed = nn.Linear(resnet.fc.in_features, embed_size)
def forward(self, images):
features = self.resnet(images)
features = features.view(features.size(0), -1)
features = self.embed(features)
return features
class DecoderRNN(nn.Module):
def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):
super(DecoderRNN, self).__init__()
self.embeddings = nn.Embedding(vocab_size, embed_size)
self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True)
self.linear = nn.Linear(hidden_size, vocab_size)
def forward(self, features, captions):
captions = captions[:, :-1]
embedding = self.embeddings(captions)
embedding = torch.cat((features.unsqueeze(dim=1), embedding), dim=1)
lstm_out, hidden = self.lstm(embedding)
outputs = self.linear(lstm_out)
return outputs
def sample(self, inputs, states=None, max_len=20):
predicted_sentence = []
for i in range(max_len):
lstm_out, states = self.lstm(inputs, states)
lstm_out = lstm_out.squeeze(1)
outputs = self.linear(lstm_out)
predicted = outputs.max(1)[1]
predicted_sentence.append(predicted.item())
inputs = self.embeddings(predicted).unsqueeze(1)
return predicted_sentence |
// Copyright 2021 Kuei-chun Chen. All rights reserved.
removeTTL();
// db.eventlog.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 3600 } )
// db.serverlog.createIndex( { "expired_at": 1 }, { expireAfterSeconds: 0 } )
function removeTTL() {
var removeCommands = [];
var createCommands = [];
var doc = db.adminCommand( { listDatabases: 1 } );
var dbnames = doc["databases"];
dbnames.forEach(function(database) {
if(database["name"] == "admin" || database["name"] == "config" || database["name"] == "local") {
// skip
} else {
var dbname = database["name"];
var names = db.getSisterDB(dbname).getCollectionNames();
names.sort();
names.forEach(function(name) {
var indexes = db.getSisterDB(dbname).getCollection(name).getIndexes();
indexes.forEach(function(index) {
if( index.hasOwnProperty("expireAfterSeconds") ) {
var cmd = 'db.getSisterDB("'+dbname+'").'+name+'.dropIndex("'+index['name']+'");';
removeCommands.push(cmd);
cmd = 'db.getSisterDB("'+dbname+'").'+name+'.createIndex(' +JSON.stringify(index['key'])+', { "expireAfterSeconds": '+index["expireAfterSeconds"]+' } );';
createCommands.push(cmd);
}
});
});
}
});
print(); print("remove commands"); print();
removeCommands.forEach(function(cmd) {
print(cmd);
});
print(); print("create commands"); print();
createCommands.forEach(function(cmd) {
print(cmd);
});
}
|
from .base import *
ALLOWED_HOSTS = ['stats.czechelib.cz']
LIVE_ERMS_AUTHENTICATION = True
DEBUG = False
STATIC_ROOT = '/var/www/celus/static/'
MEDIA_ROOT = '/var/www/celus/media/'
ADMINS = (
("Beda Kosata", "[email protected]"),
)
EMAIL_HOST = 'smtp.ntkcz.cz'
SERVER_EMAIL = '[email protected]'
|
class SlackError(Exception):
"""Base Slack Exception"""
def __init__(self, msg):
"""Return error message to user
:param msg: the error message to return
"""
self.msg = msg
|
// Defining angularjs module
var app = angular.module('demoModule', []);
// Defining angularjs Controller and injecting ProductsService
app.controller('demoCtrl', function ($scope, $http, ProductsService) {
$scope.productsData = null;
$scope.message = '';
// Fetching records from the factory created at the bottom of the script file
ProductsService.GetAllRecords().then(function (d) {
$scope.productsData = d.data; // Success
}, function () {
$scope.message = 'Error Occured !!!'; // Failed
//alert('Error Occured !!!');
});
// Calculate Total of Price After Initialization
$scope.total = function () {
var total = 0;
angular.forEach($scope.productsData, function (item) {
total += item.Price;
})
return total;
}
$scope.Product = {
Id: '',
Name: '',
Price: '',
Category: ''
};
// Reset product details
$scope.clear = function () {
$scope.Product.Id = '';
$scope.Product.Name = '';
$scope.Product.Price = '';
$scope.Product.Category = '';
}
//Add New Item
$scope.save = function () {
if ($scope.Product.Name != "" &&
$scope.Product.Price != "" && $scope.Product.Category != "") {
// Call Http request using $.ajax
//$.ajax({
// type: 'POST',
// contentType: 'application/json; charset=utf-8',
// data: JSON.stringify($scope.Product),
// url: 'api/Product/PostProduct',
// success: function (data, status) {
// $scope.$apply(function () {
// $scope.productsData.push(data);
// alert("Product Added Successfully !!!");
// $scope.clear();
// });
// },
// error: function (status) { }
//});
// or you can call Http request using $http
$scope.message = '';
$http({
method: 'POST',
url: 'api/Product/PostProduct/',
data: $scope.Product
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.productsData.push(response.data);
$scope.clear();
$scope.message = 'Product Added Successfully !!!';
//alert("Product Added Successfully !!!");
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.message = 'Error : ' + response.data.ExceptionMessa;
//alert("Error : " + response.data.ExceptionMessage);
});
}
else {
alert('Please Enter All the Values !!');
}
};
// Edit product details
$scope.edit = function (data) {
$scope.Product = { Id: data.Id, Name: data.Name, Price: data.Price, Category: data.Category };
}
// Cancel product details
$scope.cancel = function () {
$scope.clear();
}
// Update product details
$scope.update = function () {
if ($scope.Product.Name != "" &&
$scope.Product.Price != "" && $scope.Product.Category != "") {
$scope.message = '';
$http({
method: 'PUT',
url: 'api/Product/PutProduct/' + $scope.Product.Id,
data: $scope.Product
}).then(function successCallback(response) {
$scope.productsData = response.data;
$scope.clear();
//alert("Product Updated Successfully !!!");
$scope.message = 'Product Updated Successfully !!!';
}, function errorCallback(response) {
$scope.message = 'Error : ' + response.data.ExceptionMes;
//alert("Error : " + response.data.ExceptionMessage);
});
}
else {
alert('Please Enter All the Values !!');
}
};
// Delete product details
$scope.delete = function (index) {
$scope.message = '';
$http({
method: 'DELETE',
url: 'api/Product/DeleteProduct/' + $scope.productsData[index].Id,
}).then(function successCallback(response) {
$scope.productsData.splice(index, 1);
$scope.message = 'Product Deleted Successfully !!!';
//alert("Product Deleted Successfully !!!");
}, function errorCallback(response) {
$scope.message = 'Error : ' + response.data.ExceptionMessage;
//alert("Error : " + response.data.ExceptionMessage);
});
};
});
// Here I have created a factory which is a populer way to create and configure services. You may also create the factories in another script file which is best practice.
// You can also write above codes for POST,PUT,DELETE in this factory instead of controller, so that our controller will look clean and exhibits proper Separation of Concern.
app.factory('ProductsService', function ($http) {
var fac = {};
fac.GetAllRecords = function () {
return $http.get('api/Product/GetAllProducts');
}
return fac;
}); |
from rest_framework import viewsets, mixins, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from rest_framework.response import Response
from core.models import Tag, Ingredient, Recipe
from receipe import serializers
class BaseRecipeAttrViewSet(viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.CreateModelMixin):
"""Take all common atrributes of below classes into
one to reduce duplication"""
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def get_queryset(self):
"""Return objects for current authenticated user only"""
assigned_only = bool(
int(self.request.query_params.get('assigned_only', 0))
)
queryset = self.queryset
if assigned_only:
queryset = queryset.filter(recipe__isnull=False)
return queryset.filter(
user=self.request.user
).order_by('-name').distinct()
def perform_create(self, serializer):
"""Create New Ingredient"""
serializer.save(user=self.request.user)
class TagViewSet(BaseRecipeAttrViewSet):
"""Manage Tag in the database"""
queryset = Tag.objects.all()
serializer_class = serializers.TagSerializer
class IngredientViewSet(BaseRecipeAttrViewSet):
"""Manage Ingredient in database"""
queryset = Ingredient.objects.all()
serializer_class = serializers.IngredientSerializer
class RecipeViewSet(viewsets.ModelViewSet):
"""Manage Recipe in the database"""
serializer_class = serializers.RecipeSerializer
queryset = Recipe.objects.all()
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def _params_to_ints(self, qs):
"""Convert a list of string ids to a list of integers.Using _ before
the function we are considering it as a private function.However it
can be access as public"""
return [int(str_id) for str_id in qs.split(',')]
def get_queryset(self):
"""Retrieve rcipes for authenticated user"""
tags = self.request.query_params.get('tags')
ingredients = self.request.query_params.get('ingredients')
queryset = self.queryset
if tags:
tag_ids = self._params_to_ints(tags)
queryset = queryset.filter(tags__id__in=tag_ids)
'''__ is a django syntax for filtering foreign key.Here we are
filtering tags in recipe queryset which has an foreign key tags
table which is id and then we using a function called in by another
__'''
if ingredients:
ingredient_ids = self._params_to_ints(ingredients)
queryset = queryset.filter(ingredients__id__in=ingredient_ids)
return queryset.filter(user=self.request.user)
def get_serializer_class(self):
"""Return appropiate serializer class"""
if self.action == 'retrieve':
return serializers.RecipeDetailSerializer
elif self.action == 'upload_image':
return serializers.RecipeImageSerializer
return self.serializer_class
def perform_create(self, serializer):
"""Create a new recipe"""
serializer.save(user=self.request.user)
@action(methods=['POST'], detail=True, url_path='upload-image')
def upload_image(self, request, pk=None):
"""Upload an image to a recipe"""
recipe = self.get_object()
serializer = self.get_serializer(
recipe,
data=request.data
)
if serializer.is_valid():
serializer.save()
return Response(
serializer.data,
status=status.HTTP_200_OK
)
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST
)
|
import logging
from nose2 import session
from nose2.plugins import logcapture
from nose2.tests._common import TestCase
log = logging.getLogger(__name__)
class StubLogging(object):
def __init__(self, name=None):
self.name = name
self.handlers = []
self.level = None
def getLogger(self, _name=None):
return self
def addHandler(self, handler):
self.handlers.append(handler)
def setLevel(self, level):
self.level = level
def debug(self, message, *arg):
# import pdb; pdb.set_trace()
for handler in self.handlers:
handler.emit(StubRecord(message % arg))
class StubRecord(object):
def __init__(self, message):
self.message = message
self.name = "stub"
self.levelname = "stub"
self.exc_info = None
self.exc_text = None
self.stack_info = None
def getMessage(self):
return self.message
class LogCaptureUnitTest(TestCase):
tags = ["unit"]
def setUp(self):
self.session = session.Session()
self.plugin = logcapture.LogCapture(session=self.session)
self.logging = logcapture.logging
logcapture.logging = StubLogging()
def tearDown(self):
logcapture.logging = self.logging
def event(self, error=True, failed=False):
e = Event()
e.metadata = {}
return e
def test_buffer_cleared_after_each_test(self):
self.plugin.startTestRun(None)
self.plugin.startTest(None)
logcapture.logging.getLogger("test").debug("hello")
assert self.plugin.handler.buffer
self.plugin.setTestOutcome(self.event())
assert self.plugin.handler.buffer
self.plugin.stopTest(None)
assert not self.plugin.handler.buffer
def test_buffered_logs_attached_to_event(self):
self.plugin.startTestRun(None)
self.plugin.startTest(None)
logcapture.logging.getLogger("test").debug("hello")
assert self.plugin.handler.buffer
e = self.event()
self.plugin.setTestOutcome(e)
assert "logs" in e.metadata, "No log in %s" % e.metadata
class Event:
pass
|
'use strict';
var platform = require('os').platform();
var spawnSync = require('child_process').spawnSync;
var readdirSync = require('fs').readdirSync;
var GLIBC = 'glibc';
var MUSL = 'musl';
var spawnOptions = {
encoding: 'utf8',
env: process.env
};
if (!spawnSync) {
spawnSync = function spawnSync() {
return { status: 126, stdout: '', stderr: '' };
};
}
function contains(needle) {
return function (haystack) {
return haystack.indexOf(needle) !== -1;
};
}
function versionFromMuslLdd(out) {
return out.split(/[\r\n]+/)[1].trim().split(/\s/)[1];
}
function safeReaddirSync(path) {
try {
return readdirSync(path);
} catch (e) {}
return [];
}
var family = '';
var version = '';
var method = '';
if (platform === 'linux') {
// Try getconf
var glibc = spawnSync('getconf', ['GNU_LIBC_VERSION'], spawnOptions);
if (glibc.status === 0) {
family = GLIBC;
version = glibc.stdout.trim().split(' ')[1];
method = 'getconf';
} else {
// Try ldd
var ldd = spawnSync('ldd', ['--version'], spawnOptions);
if (ldd.status === 0 && ldd.stdout.indexOf(MUSL) !== -1) {
family = MUSL;
version = versionFromMuslLdd(ldd.stdout);
method = 'ldd';
} else if (ldd.status === 1 && ldd.stderr.indexOf(MUSL) !== -1) {
family = MUSL;
version = versionFromMuslLdd(ldd.stderr);
method = 'ldd';
} else {
// Try filesystem (family only)
var lib = safeReaddirSync('/lib');
if (lib.some(contains('-linux-gnu'))) {
family = GLIBC;
method = 'filesystem';
} else if (lib.some(contains('libc.musl-'))) {
family = MUSL;
method = 'filesystem';
} else if (lib.some(contains('ld-musl-'))) {
family = MUSL;
method = 'filesystem';
} else {
var usrSbin = safeReaddirSync('/usr/sbin');
if (usrSbin.some(contains('glibc'))) {
family = GLIBC;
method = 'filesystem';
}
}
}
}
}
var isNonGlibcLinux = family !== '' && family !== GLIBC;
module.exports = {
GLIBC: GLIBC,
MUSL: MUSL,
family: family,
version: version,
method: method,
isNonGlibcLinux: isNonGlibcLinux
}; |
import { Injectable } from '@angular/core';
import { zip } from 'rxjs';
import { SourceDispatcher } from '../domain/source.dispatcher';
import { StructureEditSourceItemParams } from '../domain/origin/edit/structure.edit-source-item.params';
import { FieldWarehouse } from '../../../field/core/api/field.warehouse';
import { CommandDispatcher, fromRxJsObservable, hermesMap, hermesTake, toRxJsObservable } from '@generic-ui/hermes';
import { DeleteOriginItemCommand } from '../domain/origin/delete/delete-origin-item.command';
import { SourceWarehouse } from '../api/source.warehouse';
import { SourceCommandInvoker } from '../api/source.command-invoker';
export class SourceDomainCommandInvoker extends SourceCommandInvoker {
constructor(commandDispatcher, sourceDispatcher, fieldWarehouse, sourceReadModelService) {
super();
this.commandDispatcher = commandDispatcher;
this.sourceDispatcher = sourceDispatcher;
this.fieldWarehouse = fieldWarehouse;
this.sourceReadModelService = sourceReadModelService;
}
setOrigin(items, structureId) {
this.sourceDispatcher.setOrigin(structureId, items);
}
setLoading(enabled, structureId) {
this.sourceDispatcher.setLoading(structureId, enabled);
}
editItem(params, structureId) {
this.sourceDispatcher.editItem(structureId, params);
}
editItemByIndex(itemIndex, fieldIndex, value, structureId) {
const itemId$ = toRxJsObservable(this.sourceReadModelService
.onceEntities(structureId)
.pipe(hermesMap((entities) => {
return entities[itemIndex].getId();
})));
const fieldId$ = toRxJsObservable(this.fieldWarehouse.onFields(structureId));
fromRxJsObservable(zip(itemId$, fieldId$))
.pipe(hermesTake(1))
.subscribe((array) => {
const itemId = array[0], fields = array[1];
this.editItem(new StructureEditSourceItemParams(itemId, fields[fieldIndex], value), structureId);
});
}
deleteRow(row, structureId) {
if (row.getItemId() !== undefined) {
this.deleteItemById(row.getItemId(), structureId);
}
else if (row.getIndex() !== undefined) {
this.deleteItemByIndex(row.getIndex(), structureId);
}
}
deleteRows(rows, structureId) {
if (rows.length > 0) {
if (rows[0].getItemId() !== undefined) {
this.deleteManyItemsByItemIds(rows.map(r => r.getItemId()), structureId);
}
else if (rows[0].getIndex() !== undefined) {
this.deleteManyItemsByIndex(rows.map(r => r.getIndex()), structureId);
}
}
}
deleteItemByIndex(index, structureId) {
this.commandDispatcher.dispatch(DeleteOriginItemCommand.byIndex(structureId, index));
}
deleteItemById(itemId, structureId) {
this.commandDispatcher.dispatch(DeleteOriginItemCommand.byItemId(structureId, itemId));
}
deleteManyItemsByIndex(indexes, structureId) {
this.commandDispatcher.dispatch(DeleteOriginItemCommand.byManyIndex(structureId, indexes));
}
deleteManyItemsByItemIds(itemIds, structureId) {
this.commandDispatcher.dispatch(DeleteOriginItemCommand.byManyItemId(structureId, itemIds));
}
}
SourceDomainCommandInvoker.decorators = [
{ type: Injectable }
];
SourceDomainCommandInvoker.ctorParameters = () => [
{ type: CommandDispatcher },
{ type: SourceDispatcher },
{ type: FieldWarehouse },
{ type: SourceWarehouse }
];
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic291cmNlLmRvbWFpbi5jb21tYW5kLWludm9rZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi8uLi9idWlsZC1jbGkvcHJvamVjdHMvbmd4LWdyaWQvc3JjL3N0cnVjdHVyZS9zb3VyY2UvY29yZS9kb21haW4vc291cmNlLmRvbWFpbi5jb21tYW5kLWludm9rZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxFQUFFLFVBQVUsRUFBRSxNQUFNLGVBQWUsQ0FBQztBQUMzQyxPQUFPLEVBQUUsR0FBRyxFQUFFLE1BQU0sTUFBTSxDQUFDO0FBRTNCLE9BQU8sRUFBRSxnQkFBZ0IsRUFBRSxNQUFNLDZCQUE2QixDQUFDO0FBRS9ELE9BQU8sRUFBRSw2QkFBNkIsRUFBRSxNQUFNLHlEQUF5RCxDQUFDO0FBRXhHLE9BQU8sRUFBRSxjQUFjLEVBQUUsTUFBTSx5Q0FBeUMsQ0FBQztBQUV6RSxPQUFPLEVBQUUsaUJBQWlCLEVBQUUsa0JBQWtCLEVBQUUsU0FBUyxFQUFFLFVBQVUsRUFBRSxnQkFBZ0IsRUFBRSxNQUFNLG9CQUFvQixDQUFDO0FBQ3BILE9BQU8sRUFBRSx1QkFBdUIsRUFBRSxNQUFNLG9EQUFvRCxDQUFDO0FBQzdGLE9BQU8sRUFBRSxlQUFlLEVBQUUsTUFBTSx5QkFBeUIsQ0FBQztBQUUxRCxPQUFPLEVBQUUsb0JBQW9CLEVBQUUsTUFBTSwrQkFBK0IsQ0FBQztBQUlyRSxNQUFNLE9BQU8sMEJBQTJCLFNBQVEsb0JBQW9CO0lBRW5FLFlBQTZCLGlCQUFvQyxFQUM3QyxnQkFBa0MsRUFDbEMsY0FBOEIsRUFDOUIsc0JBQXVDO1FBQzFELEtBQUssRUFBRSxDQUFDO1FBSm9CLHNCQUFpQixHQUFqQixpQkFBaUIsQ0FBbUI7UUFDN0MscUJBQWdCLEdBQWhCLGdCQUFnQixDQUFrQjtRQUNsQyxtQkFBYyxHQUFkLGNBQWMsQ0FBZ0I7UUFDOUIsMkJBQXNCLEdBQXRCLHNCQUFzQixDQUFpQjtJQUUzRCxDQUFDO0lBRUQsU0FBUyxDQUFDLEtBQWlCLEVBQUUsV0FBd0I7UUFDcEQsSUFBSSxDQUFDLGdCQUFnQixDQUFDLFNBQVMsQ0FBQyxXQUFXLEVBQUUsS0FBSyxDQUFDLENBQUM7SUFDckQsQ0FBQztJQUVELFVBQVUsQ0FBQyxPQUFnQixFQUFFLFdBQXdCO1FBQ3BELElBQUksQ0FBQyxnQkFBZ0IsQ0FBQyxVQUFVLENBQUMsV0FBVyxFQUFFLE9BQU8sQ0FBQyxDQUFDO0lBQ3hELENBQUM7SUFFRCxRQUFRLENBQUMsTUFBcUMsRUFBRSxXQUF3QjtRQUN2RSxJQUFJLENBQUMsZ0JBQWdCLENBQUMsUUFBUSxDQUFDLFdBQVcsRUFBRSxNQUFNLENBQUMsQ0FBQztJQUNyRCxDQUFDO0lBRUQsZUFBZSxDQUFDLFNBQWlCLEVBQUUsVUFBa0IsRUFBRSxLQUFVLEVBQUUsV0FBd0I7UUFFMUYsTUFBTSxPQUFPLEdBQ1osZ0JBQWdCLENBQ2YsSUFBSSxDQUFDLHNCQUFzQjthQUN6QixZQUFZLENBQUMsV0FBVyxDQUFDO2FBQ3pCLElBQUksQ0FDSixTQUFTLENBQUMsQ0FBQyxRQUEyQixFQUFFLEVBQUU7WUFDekMsT0FBTyxRQUFRLENBQUMsU0FBUyxDQUFDLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDcEMsQ0FBQyxDQUFDLENBQ0YsQ0FDRixDQUFDO1FBRUgsTUFBTSxRQUFRLEdBQUcsZ0JBQWdCLENBQ2hDLElBQUksQ0FBQyxjQUFjLENBQUMsUUFBUSxDQUFDLFdBQVcsQ0FBQyxDQUN6QyxDQUFDO1FBRUYsa0JBQWtCLENBQ2pCLEdBQUcsQ0FBQyxPQUFPLEVBQUUsUUFBUSxDQUFDLENBQ3RCO2FBQ0MsSUFBSSxDQUNKLFVBQVUsQ0FBQyxDQUFDLENBQUMsQ0FDYjthQUNBLFNBQVMsQ0FBQyxDQUFDLEtBQWlCLEVBQUUsRUFBRTtZQUVoQyxNQUFNLE1BQU0sR0FBRyxLQUFLLENBQUMsQ0FBQyxDQUFDLEVBQ3RCLE1BQU0sR0FBRyxLQUFLLENBQUMsQ0FBQyxDQUFDLENBQUM7WUFFbkIsSUFBSSxDQUFDLFFBQVEsQ0FDWixJQUFJLDZCQUE2QixDQUFDLE1BQU0sRUFBRSxNQUFNLENBQUMsVUFBVSxDQUFDLEVBQUUsS0FBSyxDQUFDLEVBQ3BFLFdBQVcsQ0FDWCxDQUFDO1FBQ0gsQ0FBQyxDQUFDLENBQUM7SUFDTCxDQUFDO0lBRUQsU0FBUyxDQUFDLEdBQWdCLEVBQUUsV0FBd0I7UUFFbkQsSUFBSSxHQUFHLENBQUMsU0FBUyxFQUFFLEtBQUssU0FBUyxFQUFFO1lBQ2xDLElBQUksQ0FBQyxjQUFjLENBQUMsR0FBRyxDQUFDLFNBQVMsRUFBRSxFQUFFLFdBQVcsQ0FBQyxDQUFDO1NBQ2xEO2FBQU0sSUFBSSxHQUFHLENBQUMsUUFBUSxFQUFFLEtBQUssU0FBUyxFQUFFO1lBQ3hDLElBQUksQ0FBQyxpQkFBaUIsQ0FBQyxHQUFHLENBQUMsUUFBUSxFQUFFLEVBQUUsV0FBVyxDQUFDLENBQUM7U0FDcEQ7SUFDRixDQUFDO0lBRUQsVUFBVSxDQUFDLElBQXdCLEVBQUUsV0FBd0I7UUFFNUQsSUFBSSxJQUFJLENBQUMsTUFBTSxHQUFHLENBQUMsRUFBRTtZQUNwQixJQUFJLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQyxTQUFTLEVBQUUsS0FBSyxTQUFTLEVBQUU7Z0JBQ3RDLElBQUksQ0FBQyx3QkFBd0IsQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxDQUFDLFNBQVMsRUFBRSxDQUFDLEVBQUUsV0FBVyxDQUFDLENBQUM7YUFDekU7aUJBQU0sSUFBSSxJQUFJLENBQUMsQ0FBQyxDQUFDLENBQUMsUUFBUSxFQUFFLEtBQUssU0FBUyxFQUFFO2dCQUM1QyxJQUFJLENBQUMsc0JBQXNCLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsQ0FBQyxRQUFRLEVBQUUsQ0FBQyxFQUFFLFdBQVcsQ0FBQyxDQUFDO2FBQ3RFO1NBQ0Q7SUFDRixDQUFDO0lBRUQsaUJBQWlCLENBQUMsS0FBYSxFQUFFLFdBQXdCO1FBQ3hELElBQUksQ0FBQyxpQkFBaUIsQ0FBQyxRQUFRLENBQUMsdUJBQXVCLENBQUMsT0FBTyxDQUFDLFdBQVcsRUFBRSxLQUFLLENBQUMsQ0FBQyxDQUFDO0lBQ3RGLENBQUM7SUFFRCxjQUFjLENBQUMsTUFBZ0IsRUFBRSxXQUF3QjtRQUN4RCxJQUFJLENBQUMsaUJBQWlCLENBQUMsUUFBUSxDQUFDLHVCQUF1QixDQUFDLFFBQVEsQ0FBQyxXQUFXLEVBQUUsTUFBTSxDQUFDLENBQUMsQ0FBQztJQUN4RixDQUFDO0lBRUQsc0JBQXNCLENBQUMsT0FBc0IsRUFBRSxXQUF3QjtRQUN0RSxJQUFJLENBQUMsaUJBQWlCLENBQUMsUUFBUSxDQUFDLHVCQUF1QixDQUFDLFdBQVcsQ0FBQyxXQUFXLEVBQUUsT0FBTyxDQUFDLENBQUMsQ0FBQztJQUM1RixDQUFDO0lBRUQsd0JBQXdCLENBQUMsT0FBd0IsRUFBRSxXQUF3QjtRQUMxRSxJQUFJLENBQUMsaUJBQWlCLENBQUMsUUFBUSxDQUFDLHVCQUF1QixDQUFDLFlBQVksQ0FBQyxXQUFXLEVBQUUsT0FBTyxDQUFDLENBQUMsQ0FBQztJQUM3RixDQUFDOzs7WUEzRkQsVUFBVTs7O1lBUEYsaUJBQWlCO1lBTmpCLGdCQUFnQjtZQUloQixjQUFjO1lBSWQsZUFBZSIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7IEluamVjdGFibGUgfSBmcm9tICdAYW5ndWxhci9jb3JlJztcbmltcG9ydCB7IHppcCB9IGZyb20gJ3J4anMnO1xuXG5pbXBvcnQgeyBTb3VyY2VEaXNwYXRjaGVyIH0gZnJvbSAnLi4vZG9tYWluL3NvdXJjZS5kaXNwYXRjaGVyJztcbmltcG9ydCB7IFN0cnVjdHVyZUlkIH0gZnJvbSAnLi4vLi4vLi4vY29yZS9hcGkvc3RydWN0dXJlLmlkJztcbmltcG9ydCB7IFN0cnVjdHVyZUVkaXRTb3VyY2VJdGVtUGFyYW1zIH0gZnJvbSAnLi4vZG9tYWluL29yaWdpbi9lZGl0L3N0cnVjdHVyZS5lZGl0LXNvdXJjZS1pdGVtLnBhcmFtcyc7XG5pbXBvcnQgeyBJdGVtRW50aXR5IH0gZnJvbSAnLi4vZG9tYWluL2NvcmUvaXRlbS9pdGVtLmVudGl0eSc7XG5pbXBvcnQgeyBGaWVsZFdhcmVob3VzZSB9IGZyb20gJy4uLy4uLy4uL2ZpZWxkL2NvcmUvYXBpL2ZpZWxkLndhcmVob3VzZSc7XG5pbXBvcnQgeyBPcmlnaW5JZCB9IGZyb20gJy4uL2RvbWFpbi9vcmlnaW4vb3JpZ2luLWlkJztcbmltcG9ydCB7IENvbW1hbmREaXNwYXRjaGVyLCBmcm9tUnhKc09ic2VydmFibGUsIGhlcm1lc01hcCwgaGVybWVzVGFrZSwgdG9SeEpzT2JzZXJ2YWJsZSB9IGZyb20gJ0BnZW5lcmljLXVpL2hlcm1lcyc7XG5pbXBvcnQgeyBEZWxldGVPcmlnaW5JdGVtQ29tbWFuZCB9IGZyb20gJy4uL2RvbWFpbi9vcmlnaW4vZGVsZXRlL2RlbGV0ZS1vcmlnaW4taXRlbS5jb21tYW5kJztcbmltcG9ydCB7IFNvdXJjZVdhcmVob3VzZSB9IGZyb20gJy4uL2FwaS9zb3VyY2Uud2FyZWhvdXNlJztcbmltcG9ydCB7IFNlbGVjdGVkUm93IH0gZnJvbSAnLi4vLi4vLi4vZm9ybWF0aW9uL2NvcmUvYXBpL3Jvdy1zZWxlY3RlZC9zZWxlY3RlZC1yb3cnO1xuaW1wb3J0IHsgU291cmNlQ29tbWFuZEludm9rZXIgfSBmcm9tICcuLi9hcGkvc291cmNlLmNvbW1hbmQtaW52b2tlcic7XG5cblxuQEluamVjdGFibGUoKVxuZXhwb3J0IGNsYXNzIFNvdXJjZURvbWFpbkNvbW1hbmRJbnZva2VyIGV4dGVuZHMgU291cmNlQ29tbWFuZEludm9rZXIge1xuXG5cdGNvbnN0cnVjdG9yKHByaXZhdGUgcmVhZG9ubHkgY29tbWFuZERpc3BhdGNoZXI6IENvbW1hbmREaXNwYXRjaGVyLFxuXHRcdFx0XHRwcml2YXRlIHJlYWRvbmx5IHNvdXJjZURpc3BhdGNoZXI6IFNvdXJjZURpc3BhdGNoZXIsXG5cdFx0XHRcdHByaXZhdGUgcmVhZG9ubHkgZmllbGRXYXJlaG91c2U6IEZpZWxkV2FyZWhvdXNlLFxuXHRcdFx0XHRwcml2YXRlIHJlYWRvbmx5IHNvdXJjZVJlYWRNb2RlbFNlcnZpY2U6IFNvdXJjZVdhcmVob3VzZSkge1xuXHRcdHN1cGVyKCk7XG5cdH1cblxuXHRzZXRPcmlnaW4oaXRlbXM6IEFycmF5PGFueT4sIHN0cnVjdHVyZUlkOiBTdHJ1Y3R1cmVJZCk6IHZvaWQge1xuXHRcdHRoaXMuc291cmNlRGlzcGF0Y2hlci5zZXRPcmlnaW4oc3RydWN0dXJlSWQsIGl0ZW1zKTtcblx0fVxuXG5cdHNldExvYWRpbmcoZW5hYmxlZDogYm9vbGVhbiwgc3RydWN0dXJlSWQ6IFN0cnVjdHVyZUlkKTogdm9pZCB7XG5cdFx0dGhpcy5zb3VyY2VEaXNwYXRjaGVyLnNldExvYWRpbmcoc3RydWN0dXJlSWQsIGVuYWJsZWQpO1xuXHR9XG5cblx0ZWRpdEl0ZW0ocGFyYW1zOiBTdHJ1Y3R1cmVFZGl0U291cmNlSXRlbVBhcmFtcywgc3RydWN0dXJlSWQ6IFN0cnVjdHVyZUlkKTogdm9pZCB7XG5cdFx0dGhpcy5zb3VyY2VEaXNwYXRjaGVyLmVkaXRJdGVtKHN0cnVjdHVyZUlkLCBwYXJhbXMpO1xuXHR9XG5cblx0ZWRpdEl0ZW1CeUluZGV4KGl0ZW1JbmRleDogbnVtYmVyLCBmaWVsZEluZGV4OiBudW1iZXIsIHZhbHVlOiBhbnksIHN0cnVjdHVyZUlkOiBTdHJ1Y3R1cmVJZCk6IHZvaWQge1xuXG5cdFx0Y29uc3QgaXRlbUlkJCA9XG5cdFx0XHR0b1J4SnNPYnNlcnZhYmxlKFxuXHRcdFx0XHR0aGlzLnNvdXJjZVJlYWRNb2RlbFNlcnZpY2Vcblx0XHRcdFx0XHQub25jZUVudGl0aWVzKHN0cnVjdHVyZUlkKVxuXHRcdFx0XHRcdC5waXBlKFxuXHRcdFx0XHRcdFx0aGVybWVzTWFwKChlbnRpdGllczogQXJyYXk8SXRlbUVudGl0eT4pID0+IHtcblx0XHRcdFx0XHRcdFx0cmV0dXJuIGVudGl0aWVzW2l0ZW1JbmRleF0uZ2V0SWQoKTtcblx0XHRcdFx0XHRcdH0pXG5cdFx0XHRcdFx0KVxuXHRcdFx0KTtcblxuXHRcdGNvbnN0IGZpZWxkSWQkID0gdG9SeEpzT2JzZXJ2YWJsZShcblx0XHRcdHRoaXMuZmllbGRXYXJlaG91c2Uub25GaWVsZHMoc3RydWN0dXJlSWQpXG5cdFx0KTtcblxuXHRcdGZyb21SeEpzT2JzZXJ2YWJsZShcblx0XHRcdHppcChpdGVtSWQkLCBmaWVsZElkJClcblx0XHQpXG5cdFx0XHQucGlwZShcblx0XHRcdFx0aGVybWVzVGFrZSgxKVxuXHRcdFx0KVxuXHRcdFx0LnN1YnNjcmliZSgoYXJyYXk6IEFycmF5PGFueT4pID0+IHtcblxuXHRcdFx0XHRjb25zdCBpdGVtSWQgPSBhcnJheVswXSxcblx0XHRcdFx0XHRmaWVsZHMgPSBhcnJheVsxXTtcblxuXHRcdFx0XHR0aGlzLmVkaXRJdGVtKFxuXHRcdFx0XHRcdG5ldyBTdHJ1Y3R1cmVFZGl0U291cmNlSXRlbVBhcmFtcyhpdGVtSWQsIGZpZWxkc1tmaWVsZEluZGV4XSwgdmFsdWUpLFxuXHRcdFx0XHRcdHN0cnVjdHVyZUlkXG5cdFx0XHRcdCk7XG5cdFx0XHR9KTtcblx0fVxuXG5cdGRlbGV0ZVJvdyhyb3c6IFNlbGVjdGVkUm93LCBzdHJ1Y3R1cmVJZDogU3RydWN0dXJlSWQpOiB2b2lkIHtcblxuXHRcdGlmIChyb3cuZ2V0SXRlbUlkKCkgIT09IHVuZGVmaW5lZCkge1xuXHRcdFx0dGhpcy5kZWxldGVJdGVtQnlJZChyb3cuZ2V0SXRlbUlkKCksIHN0cnVjdHVyZUlkKTtcblx0XHR9IGVsc2UgaWYgKHJvdy5nZXRJbmRleCgpICE9PSB1bmRlZmluZWQpIHtcblx0XHRcdHRoaXMuZGVsZXRlSXRlbUJ5SW5kZXgocm93LmdldEluZGV4KCksIHN0cnVjdHVyZUlkKTtcblx0XHR9XG5cdH1cblxuXHRkZWxldGVSb3dzKHJvd3M6IEFycmF5PFNlbGVjdGVkUm93Piwgc3RydWN0dXJlSWQ6IFN0cnVjdHVyZUlkKTogdm9pZCB7XG5cblx0XHRpZiAocm93cy5sZW5ndGggPiAwKSB7XG5cdFx0XHRpZiAocm93c1swXS5nZXRJdGVtSWQoKSAhPT0gdW5kZWZpbmVkKSB7XG5cdFx0XHRcdHRoaXMuZGVsZXRlTWFueUl0ZW1zQnlJdGVtSWRzKHJvd3MubWFwKHIgPT4gci5nZXRJdGVtSWQoKSksIHN0cnVjdHVyZUlkKTtcblx0XHRcdH0gZWxzZSBpZiAocm93c1swXS5nZXRJbmRleCgpICE9PSB1bmRlZmluZWQpIHtcblx0XHRcdFx0dGhpcy5kZWxldGVNYW55SXRlbXNCeUluZGV4KHJvd3MubWFwKHIgPT4gci5nZXRJbmRleCgpKSwgc3RydWN0dXJlSWQpO1xuXHRcdFx0fVxuXHRcdH1cblx0fVxuXG5cdGRlbGV0ZUl0ZW1CeUluZGV4KGluZGV4OiBudW1iZXIsIHN0cnVjdHVyZUlkOiBTdHJ1Y3R1cmVJZCk6IHZvaWQge1xuXHRcdHRoaXMuY29tbWFuZERpc3BhdGNoZXIuZGlzcGF0Y2goRGVsZXRlT3JpZ2luSXRlbUNvbW1hbmQuYnlJbmRleChzdHJ1Y3R1cmVJZCwgaW5kZXgpKTtcblx0fVxuXG5cdGRlbGV0ZUl0ZW1CeUlkKGl0ZW1JZDogT3JpZ2luSWQsIHN0cnVjdHVyZUlkOiBTdHJ1Y3R1cmVJZCk6IHZvaWQge1xuXHRcdHRoaXMuY29tbWFuZERpc3BhdGNoZXIuZGlzcGF0Y2goRGVsZXRlT3JpZ2luSXRlbUNvbW1hbmQuYnlJdGVtSWQoc3RydWN0dXJlSWQsIGl0ZW1JZCkpO1xuXHR9XG5cblx0ZGVsZXRlTWFueUl0ZW1zQnlJbmRleChpbmRleGVzOiBBcnJheTxudW1iZXI+LCBzdHJ1Y3R1cmVJZDogU3RydWN0dXJlSWQpOiB2b2lkIHtcblx0XHR0aGlzLmNvbW1hbmREaXNwYXRjaGVyLmRpc3BhdGNoKERlbGV0ZU9yaWdpbkl0ZW1Db21tYW5kLmJ5TWFueUluZGV4KHN0cnVjdHVyZUlkLCBpbmRleGVzKSk7XG5cdH1cblxuXHRkZWxldGVNYW55SXRlbXNCeUl0ZW1JZHMoaXRlbUlkczogQXJyYXk8T3JpZ2luSWQ+LCBzdHJ1Y3R1cmVJZDogU3RydWN0dXJlSWQpOiB2b2lkIHtcblx0XHR0aGlzLmNvbW1hbmREaXNwYXRjaGVyLmRpc3BhdGNoKERlbGV0ZU9yaWdpbkl0ZW1Db21tYW5kLmJ5TWFueUl0ZW1JZChzdHJ1Y3R1cmVJZCwgaXRlbUlkcykpO1xuXHR9XG5cbn1cbiJdfQ== |
/*!
=========================================================
* Material Kit React - v1.9.0 based on Material Kit - v2.0.2
=========================================================
* Product Page: https://www.creative-tim.com/product/material-kit-react
* Copyright 2020 Creative Tim (https://www.creative-tim.com)
* Licensed under MIT (https://github.com/creativetimofficial/material-kit-react/blob/master/LICENSE.md)
=========================================================
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
// ##############################
// // // Variables - Styles that are used on more than one component
// #############################
const drawerWidth = 260;
const transition = {
transition: "all 0.33s cubic-bezier(0.685, 0.0473, 0.346, 1)"
};
const containerFluid = {
paddingRight: "15px",
paddingLeft: "15px",
marginRight: "auto",
marginLeft: "auto",
width: "100%"
};
const container = {
...containerFluid,
"@media (min-width: 576px)": {
maxWidth: "540px"
},
"@media (min-width: 768px)": {
maxWidth: "720px"
},
"@media (min-width: 992px)": {
maxWidth: "960px"
},
"@media (min-width: 1200px)": {
maxWidth: "1140px"
}
};
const boxShadow = {
boxShadow:
"0 10px 30px -12px rgba(0, 0, 0, 0.42), 0 4px 25px 0px rgba(0, 0, 0, 0.12), 0 8px 10px -5px rgba(0, 0, 0, 0.2)"
};
const card = {
display: "inline-block",
position: "relative",
width: "100%",
margin: "25px 0",
boxShadow: "0 1px 4px 0 rgba(0, 0, 0, 0.14)",
borderRadius: "3px",
color: "rgba(0, 0, 0, 0.87)",
background: "#fff"
};
const defaultFont = {
fontFamily: `"Playfair Display", "Garamond", "Helvetica", serif`,
fontWeight: "300",
lineHeight: "1.5em"
};
const primaryColor = "#e69296";
const warningColor = "#ff9800";
const dangerColor = "#f44336";
const successColor = "#4caf50";
const infoColor = "#00acc1";
const roseColor = "#e91e63";
const grayColor = "#999999";
const primaryBoxShadow = {
boxShadow:
"0 12px 20px -10px rgba(156, 39, 176, 0.28), 0 4px 20px 0px rgba(0, 0, 0, 0.12), 0 7px 8px -5px rgba(156, 39, 176, 0.2)"
};
const infoBoxShadow = {
boxShadow:
"0 12px 20px -10px rgba(0, 188, 212, 0.28), 0 4px 20px 0px rgba(0, 0, 0, 0.12), 0 7px 8px -5px rgba(0, 188, 212, 0.2)"
};
const successBoxShadow = {
boxShadow:
"0 12px 20px -10px rgba(76, 175, 80, 0.28), 0 4px 20px 0px rgba(0, 0, 0, 0.12), 0 7px 8px -5px rgba(76, 175, 80, 0.2)"
};
const warningBoxShadow = {
boxShadow:
"0 12px 20px -10px rgba(255, 152, 0, 0.28), 0 4px 20px 0px rgba(0, 0, 0, 0.12), 0 7px 8px -5px rgba(255, 152, 0, 0.2)"
};
const dangerBoxShadow = {
boxShadow:
"0 12px 20px -10px rgba(244, 67, 54, 0.28), 0 4px 20px 0px rgba(0, 0, 0, 0.12), 0 7px 8px -5px rgba(244, 67, 54, 0.2)"
};
const roseBoxShadow = {
boxShadow:
"0 4px 20px 0px rgba(0, 0, 0, 0.14), 0 7px 10px -5px rgba(233, 30, 99, 0.4)"
};
const warningCardHeader = {
color: "#fff",
background: "linear-gradient(60deg, #ffa726, #fb8c00)",
...warningBoxShadow
};
const successCardHeader = {
color: "#fff",
background: "linear-gradient(60deg, #66bb6a, #43a047)",
...successBoxShadow
};
const dangerCardHeader = {
color: "#fff",
background: "linear-gradient(60deg, #ef5350, #e53935)",
...dangerBoxShadow
};
const infoCardHeader = {
color: "#fff",
background: "linear-gradient(60deg, #26c6da, #00acc1)",
...infoBoxShadow
};
const primaryCardHeader = {
color: "#fff",
background: "linear-gradient(60deg, #ab47bc, #8e24aa)",
...primaryBoxShadow
};
const roseCardHeader = {
color: "#fff",
background: "linear-gradient(60deg, #ec407a, #d81b60)",
...roseBoxShadow
};
const cardActions = {
margin: "0 20px 10px",
paddingTop: "10px",
borderTop: "1px solid #eeeeee",
height: "auto",
...defaultFont
};
const cardHeader = {
margin: "-30px 15px 0",
borderRadius: "3px",
padding: "15px"
};
const defaultBoxShadow = {
border: "0",
borderRadius: "3px",
boxShadow:
"0 10px 20px -12px rgba(0, 0, 0, 0.42), 0 3px 20px 0px rgba(0, 0, 0, 0.12), 0 8px 10px -5px rgba(0, 0, 0, 0.2)",
padding: "10px 0",
transition: "all 150ms ease 0s"
};
const title = {
color: "#3C4858",
margin: "1.75rem 0 0.875rem",
textDecoration: "none",
fontWeight: "700",
fontFamily: `"Playfair Display", "Garamond", serif`
};
const cardTitle = {
...title,
marginTop: ".625rem"
};
const cardLink = {
"& + $cardLink": {
marginLeft: "1.25rem"
}
};
const cardSubtitle = {
marginBottom: "0",
marginTop: "-.375rem"
};
export {
//variables
drawerWidth,
transition,
container,
containerFluid,
boxShadow,
card,
defaultFont,
primaryColor,
warningColor,
dangerColor,
successColor,
infoColor,
roseColor,
grayColor,
primaryBoxShadow,
infoBoxShadow,
successBoxShadow,
warningBoxShadow,
dangerBoxShadow,
roseBoxShadow,
warningCardHeader,
successCardHeader,
dangerCardHeader,
infoCardHeader,
primaryCardHeader,
roseCardHeader,
cardActions,
cardHeader,
defaultBoxShadow,
title,
cardTitle,
cardLink,
cardSubtitle
};
|
# Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Workflow UI facade."""
from lib import url, users
from lib.constants import object_states
from lib.entities import cycle_entity_population, ui_dict_convert
from lib.page import dashboard
from lib.page.widget import (
workflow_tabs, task_group_info_panel, workflow_page, object_modal)
from lib.ui import internal_ui_operations, ui_facade
from lib.utils import selenium_utils
def create_workflow(workflow):
"""Creates a workflow `workflow`."""
selenium_utils.open_url(url.dashboard())
dashboard.Dashboard().start_workflow()
internal_ui_operations.submit_obj(workflow)
def open_create_task_group_task_popup(task_group):
"""Opens task group task popup."""
# pylint: disable=invalid-name
setup_tab = workflow_tabs.SetupTab()
setup_tab.open_via_url(task_group.workflow)
setup_tab.open_create_task_group_task_modal(task_group)
def create_task_group_task(task_group_task):
"""Creates a task group task."""
setup_tab = workflow_tabs.SetupTab()
setup_tab.open_via_url(task_group_task.task_group.workflow)
setup_tab.create_task_group_task(task_group_task)
def task_group_objs(workflow):
"""Returns task group titles of `workflow`."""
setup_tab = workflow_tabs.SetupTab()
setup_tab.open_via_url(workflow)
return [ui_dict_convert.task_group_ui_to_app(task_group_row.obj_dict())
for task_group_row in setup_tab.task_group_rows()]
def get_task_group_tasks_objs():
"""Returns task group tasks."""
return [ui_dict_convert.task_group_task_ui_to_app(task_row.obj_dict())
for task_row
in task_group_info_panel.TaskGroupInfoPanel().task_rows()]
def add_obj_to_task_group(obj, task_group):
"""Map existing object `obj` to the task group `task_group`."""
setup_tab = workflow_tabs.SetupTab()
setup_tab.open_via_url(task_group.workflow)
setup_tab.add_obj_to_task_group(obj=obj, task_group=task_group)
def get_objs_added_to_task_group(task_group):
"""Returns list of objects mapped to the task group."""
setup_tab = workflow_tabs.SetupTab()
setup_tab.open_via_url(task_group.workflow)
return setup_tab.get_objs_added_to_task_group(task_group)
def add_task_group(workflow, task_group):
"""Adds task group."""
workflow_tabs.SetupTab().open_via_url(workflow)
dashboard.Dashboard().start_task_group()
object_modal.get_modal_obj("task_group").submit_obj(task_group)
def delete_task_group(task_group):
"""Deletes task group."""
setup_tab = workflow_tabs.SetupTab()
setup_tab.open_via_url(task_group.workflow)
setup_tab.delete_task_group(task_group)
def activate_workflow(workflow):
"""Activates workflow."""
setup_tab = workflow_tabs.SetupTab()
setup_tab.open_via_url(workflow)
workflow_page.WorkflowPage().activate_workflow(
is_workflow_repeat=bool(workflow.repeat_unit))
def get_workflow_cycles(workflow):
"""Builds and returns a tree of workflow cycles / cycle task groups
/ cycle tasks.
"""
active_cycles_tab = workflow_tabs.ActiveCyclesTab()
active_cycles_tab.open_via_url(workflow)
return active_cycles_tab.get_workflow_cycles()
def map_obj_to_cycle_task(obj, cycle_task):
"""Maps object to the cycle task."""
active_cycles_tab = workflow_tabs.ActiveCyclesTab()
active_cycles_tab.open_using_cycle_task(cycle_task)
active_cycles_tab.map_obj_to_cycle_task(obj=obj, cycle_task=cycle_task)
def get_objs_mapped_to_cycle_task(cycle_task):
"""Get objects mapped to the cycle task."""
active_cycles_tab = workflow_tabs.ActiveCyclesTab()
active_cycles_tab.open_using_cycle_task(cycle_task)
return active_cycles_tab.get_objs_mapped_to_cycle_task(cycle_task)
def add_assignee_to_cycle_task(assignee, cycle_task):
"""Adds the assignee to the cycle task."""
active_cycles_tab = workflow_tabs.ActiveCyclesTab()
active_cycles_tab.open_using_cycle_task(cycle_task)
active_cycles_tab.add_assignee_to_cycle_task(
assignee=assignee, cycle_task=cycle_task)
cycle_task.assignees.append(assignee)
def add_comment_to_cycle_task(comment, cycle_task):
"""Adds a comment to the cycle task."""
active_cycles_tab = workflow_tabs.ActiveCyclesTab()
active_cycles_tab.open_using_cycle_task(cycle_task)
active_cycles_tab.add_comment_to_cycle_task(
comment=comment, cycle_task=cycle_task)
comment.modified_by = users.current_person()
cycle_task.comments.append(comment)
def get_cycle_task(cycle_task):
"""Returns Task Assignees of cycle task."""
active_cycles_tab = workflow_tabs.ActiveCyclesTab()
active_cycles_tab.open_using_cycle_task(cycle_task)
return active_cycles_tab.get_cycle_task(cycle_task)
def start_cycle_task(cycle_task):
"""Starts the cycle task."""
active_cycles_tab = workflow_tabs.ActiveCyclesTab()
active_cycles_tab.open_using_cycle_task(cycle_task)
active_cycles_tab.start_cycle_task(cycle_task)
cycle_task.state = object_states.IN_PROGRESS
cycle_entity_population.propagate_task_state_change(cycle_task)
def archive_workflow(workflow):
"""Archives workflow."""
ui_facade.open_obj(workflow)
info_widget = internal_ui_operations.info_widget_page(workflow)
info_widget.archive()
workflow.is_archived = True
workflow.recurrences_started = False
workflow.modified_by = users.current_person()
|
import { Subscriber } from '../Subscriber';
/* tslint:enable:max-line-length */
/**
* Emits a given value if the source Observable completes without emitting any
* `next` value, otherwise mirrors the source Observable.
*
* <span class="informal">If the source Observable turns out to be empty, then
* this operator will emit a default value.</span>
*
* <img src="./img/defaultIfEmpty.png" width="100%">
*
* `defaultIfEmpty` emits the values emitted by the source Observable or a
* specified default value if the source Observable is empty (completes without
* having emitted any `next` value).
*
* @example <caption>If no clicks happen in 5 seconds, then emit "no clicks"</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var clicksBeforeFive = clicks.takeUntil(Rx.Observable.interval(5000));
* var result = clicksBeforeFive.defaultIfEmpty('no clicks');
* result.subscribe(x => console.log(x));
*
* @see {@link empty}
* @see {@link last}
*
* @param {any} [defaultValue=null] The default value used if the source
* Observable is empty.
* @return {Observable} An Observable that emits either the specified
* `defaultValue` if the source Observable emits no items, or the values emitted
* by the source Observable.
* @method defaultIfEmpty
* @owner Observable
*/
export function defaultIfEmpty(defaultValue = null) {
return (source) => source.lift(new DefaultIfEmptyOperator(defaultValue));
}
class DefaultIfEmptyOperator {
constructor(defaultValue) {
this.defaultValue = defaultValue;
}
call(subscriber, source) {
return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class DefaultIfEmptySubscriber extends Subscriber {
constructor(destination, defaultValue) {
super(destination);
this.defaultValue = defaultValue;
this.isEmpty = true;
}
_next(value) {
this.isEmpty = false;
this.destination.next(value);
}
_complete() {
if (this.isEmpty) {
this.destination.next(this.defaultValue);
}
this.destination.complete();
}
}
//# sourceMappingURL=defaultIfEmpty.js.map |
const main = process.platform === 'darwin' ? require('bindings')('main.node') : undefined;
const getIcon = async (input, output, size) => {
if (process.platform !== 'darwin') {
throw new Error('node-mac-file-icon only works on macOS')
}
return new Promise((resolve, reject) => {
main.getFileIcon(input, output, size, (result) => {
resolve(result);
});
})
};
module.exports = {
getIcon,
};
|
import React from 'react';
import { theme as chakraTheme } from '@chakra-ui/core';
const fonts = {
...chakraTheme.fonts,
mono: `'Menlo', monospace`,
heading: `'Oswald', sans-serif`,
body: `'Montserrat', sans-serif`
};
const breakpoints = ['48em', '62em', '80em'];
const theme = {
...chakraTheme,
colors: {
transparent: 'transparent',
...chakraTheme.colors,
black: '#16161D',
brand: {
yellow: '#F0EB70',
blue_primary: '#1E85C3',
blue_accent: '#7690B9',
lightgray: '#ebf1f1'
}
},
fonts,
breakpoints,
icons: {
...chakraTheme.icons,
logo: {
path: (
<svg
width="3000"
height="3163"
viewBox="0 0 3000 3163"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<rect width="3000" height="3162.95" fill="none" />
<path
d="M1470.89 1448.81L2170 2488.19H820V706.392H2170L1470.89 1448.81ZM1408.21 1515.37L909.196 2045.3V2393.46H1998.84L1408.21 1515.37Z"
fill="currentColor"
/>
</svg>
),
viewBox: '0 0 3000 3163'
},
google: {
path: (
<svg width="118" height="120" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fillRule="evenodd">
<path
d="M117.6 61.364c0-4.255-.382-8.346-1.09-12.273H60V72.3h32.29c-1.39 7.5-5.617 13.855-11.972 18.11v15.054H99.71c11.346-10.446 17.891-25.828 17.891-44.1z"
fill="#4285F4"
/>
<path
d="M60 120c16.2 0 29.782-5.373 39.71-14.536L80.317 90.409c-5.373 3.6-12.245 5.727-20.318 5.727-15.627 0-28.855-10.554-33.573-24.736H6.382v15.545C16.255 106.555 36.545 120 60 120z"
fill="#34A853"
/>
<path
d="M26.427 71.4c-1.2-3.6-1.882-7.445-1.882-11.4s.682-7.8 1.882-11.4V33.055H6.382A59.976 59.976 0 0 0 0 60a59.976 59.976 0 0 0 6.382 26.945L26.427 71.4z"
fill="#FBBC05"
/>
<path
d="M60 23.864c8.81 0 16.718 3.027 22.936 8.972l17.21-17.209C89.754 5.945 76.172 0 60 0 36.545 0 16.255 13.445 6.382 33.055L26.427 48.6C31.145 34.418 44.373 23.864 60 23.864z"
fill="#EA4335"
/>
<path d="M0 0h120v120H0V0z" />
</g>
</svg>
),
viewBox: '0 0 120 120'
},
circle: {
path: <circle cx="12" cy="12" r="10"></circle>,
viewBox: '0 0 24 24'
},
open_circle: {
path: (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="10"></circle>
</svg>
)
},
prev: {
path: (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="15 18 9 12 15 6"></polyline>
</svg>
),
viewBox: '0 0 24 24'
},
next: {
path: (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="9 18 15 12 9 6"></polyline>
</svg>
),
viewBox: '0 0 24 24'
}
}
};
export default theme;
|
// Group array of objects together according to a specific key
// `key` can a string (the object key), an array (several object keys) or
// a function returning a string.
export const groupBy = function(array, key) {
return array.reduce(groupByReducer.bind(null, key), {})
}
const groupByReducer = function(key, groups, obj) {
const groupName = getGroupName(key, obj)
const { [groupName]: currentGroup = [] } = groups
const newGroup = [...currentGroup, obj]
return { ...groups, [groupName]: newGroup }
}
const getGroupName = function(key, obj) {
if (typeof key === 'function') {
return key(obj)
}
if (Array.isArray(key)) {
return key.map(name => obj[name]).join(',')
}
return obj[key]
}
export const groupValuesBy = function(array, key) {
const groups = groupBy(array, key)
return Object.values(groups)
}
|
"""The tests for Device Tracker device triggers."""
import pytest
import voluptuous_serialize
import homeassistant.components.automation as automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.device_tracker import DOMAIN, device_trigger
import homeassistant.components.zone as zone
from homeassistant.helpers import config_validation as cv, device_registry
from homeassistant.helpers.entity import EntityCategory
from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component
from tests.common import (
MockConfigEntry,
assert_lists_same,
async_get_device_automations,
async_mock_service,
mock_device_registry,
mock_registry,
)
from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401
AWAY_LATITUDE = 32.881011
AWAY_LONGITUDE = -117.234758
HOME_LATITUDE = 32.880837
HOME_LONGITUDE = -117.237561
@pytest.fixture
def device_reg(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
@pytest.fixture
def entity_reg(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass)
@pytest.fixture
def calls(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
@pytest.fixture(autouse=True)
def setup_zone(hass):
"""Create test zone."""
hass.loop.run_until_complete(
async_setup_component(
hass,
zone.DOMAIN,
{
"zone": {
"name": "test",
"latitude": HOME_LATITUDE,
"longitude": HOME_LONGITUDE,
"radius": 250,
}
},
)
)
async def test_get_triggers(hass, device_reg, entity_reg):
"""Test we get the expected triggers from a device_tracker."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_reg.async_get_or_create(DOMAIN, "test", "5678", device_id=device_entry.id)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": trigger,
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
"metadata": {"secondary": False},
}
for trigger in ["leaves", "enters"]
]
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert_lists_same(triggers, expected_triggers)
@pytest.mark.parametrize(
"hidden_by,entity_category",
(
(RegistryEntryHider.INTEGRATION, None),
(RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
),
)
async def test_get_triggers_hidden_auxiliary(
hass,
device_reg,
entity_reg,
hidden_by,
entity_category,
):
"""Test we get the expected triggers from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_reg.async_get_or_create(
DOMAIN,
"test",
"5678",
device_id=device_entry.id,
entity_category=entity_category,
hidden_by=hidden_by,
)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": trigger,
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
"metadata": {"secondary": True},
}
for trigger in ["leaves", "enters"]
]
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, device_entry.id
)
assert_lists_same(triggers, expected_triggers)
async def test_if_fires_on_zone_change(hass, calls):
"""Test for enter and leave triggers firing."""
hass.states.async_set(
"device_tracker.entity",
"state",
{"latitude": AWAY_LATITUDE, "longitude": AWAY_LONGITUDE},
)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "device_tracker.entity",
"type": "enters",
"zone": "zone.test",
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"enter - {{ trigger.platform}} - "
"{{ trigger.entity_id}} - {{ trigger.from_state.attributes.longitude|round(3)}} - "
"{{ trigger.to_state.attributes.longitude|round(3)}}"
)
},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "device_tracker.entity",
"type": "leaves",
"zone": "zone.test",
},
"action": {
"service": "test.automation",
"data_template": {
"some": (
"leave - {{ trigger.platform}} - "
"{{ trigger.entity_id}} - {{ trigger.from_state.attributes.longitude|round(3)}} - "
"{{ trigger.to_state.attributes.longitude|round(3)}}"
)
},
},
},
]
},
)
# Fake that the entity is entering.
hass.states.async_set(
"device_tracker.entity",
"state",
{"latitude": HOME_LATITUDE, "longitude": HOME_LONGITUDE},
)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["some"] == "enter - device - {} - -117.235 - -117.238".format(
"device_tracker.entity"
)
# Fake that the entity is leaving.
hass.states.async_set(
"device_tracker.entity",
"state",
{"latitude": AWAY_LATITUDE, "longitude": AWAY_LONGITUDE},
)
await hass.async_block_till_done()
assert len(calls) == 2
assert calls[1].data["some"] == "leave - device - {} - -117.238 - -117.235".format(
"device_tracker.entity"
)
async def test_get_trigger_capabilities(hass, device_reg, entity_reg):
"""Test we get the expected capabilities from a device_tracker trigger."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_reg.async_get_or_create(DOMAIN, "test", "5678", device_id=device_entry.id)
capabilities = await device_trigger.async_get_trigger_capabilities(
hass,
{
"platform": "device",
"domain": DOMAIN,
"type": "enters",
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
},
)
assert capabilities and "extra_fields" in capabilities
assert voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
) == [
{
"name": "zone",
"required": True,
"type": "select",
"options": [("zone.test", "test"), ("zone.home", "test home")],
}
]
|
#!/usr/bin/env python3
import matplotlib
matplotlib.use('Agg')
import sys
import os
import numpy as np
from funque.config import FunqueConfig, DisplayConfig
from funque.core.asset import Asset
from funque.core.quality_runner import FunqueQualityRunner
from funque.tools.misc import get_file_name_without_extension, get_cmd_option, \
cmd_option_exists
from funque.tools.stats import ListStats
__copyright__ = "Copyright 2016-2020, Netflix, Inc."
__license__ = "BSD+Patent"
FMTS = ['yuv420p', 'yuv422p', 'yuv444p',
'yuv420p10le', 'yuv422p10le', 'yuv444p10le',
'yuv420p12le', 'yuv422p12le', 'yuv444p12le',
'yuv420p16le', 'yuv422p16le', 'yuv444p16le',
]
OUT_FMTS = ['text (default)', 'xml', 'json']
POOL_METHODS = ['mean', 'harmonic_mean', 'min', 'median', 'perc5', 'perc10', 'perc20']
def print_usage():
print("usage: " + os.path.basename(sys.argv[0]) \
+ " fmt width height ref_path dis_path [--model model_path] [--out-fmt out_fmt] " \
"[--phone-model] [--ci] [--save-plot plot_dir]\n")
print("fmt:\n\t" + "\n\t".join(FMTS) + "\n")
print("out_fmt:\n\t" + "\n\t".join(OUT_FMTS) + "\n")
def main():
if len(sys.argv) < 6:
print_usage()
return 2
try:
fmt = sys.argv[1]
width = int(sys.argv[2])
height = int(sys.argv[3])
ref_file = sys.argv[4]
dis_file = sys.argv[5]
except ValueError:
print_usage()
return 2
if width < 0 or height < 0:
print("width and height must be non-negative, but are {w} and {h}".format(w=width, h=height))
print_usage()
return 2
if fmt not in FMTS:
print_usage()
return 2
model_path = get_cmd_option(sys.argv, 6, len(sys.argv), '--model')
out_fmt = get_cmd_option(sys.argv, 6, len(sys.argv), '--out-fmt')
if not (out_fmt is None
or out_fmt == 'xml'
or out_fmt == 'json'
or out_fmt == 'text'):
print_usage()
return 2
pool_method = get_cmd_option(sys.argv, 6, len(sys.argv), '--pool')
if not (pool_method is None
or pool_method in POOL_METHODS):
print('--pool can only have option among {}'.format(', '.join(POOL_METHODS)))
return 2
show_local_explanation = cmd_option_exists(sys.argv, 6, len(sys.argv), '--local-explain')
phone_model = cmd_option_exists(sys.argv, 6, len(sys.argv), '--phone-model')
enable_conf_interval = cmd_option_exists(sys.argv, 6, len(sys.argv), '--ci')
save_plot_dir = get_cmd_option(sys.argv, 6, len(sys.argv), '--save-plot')
if show_local_explanation and enable_conf_interval:
print('cannot set both --local-explain and --ci flags')
return 2
asset = Asset(dataset="cmd",
content_id=abs(hash(get_file_name_without_extension(ref_file))) % (10 ** 16),
asset_id=abs(hash(get_file_name_without_extension(ref_file))) % (10 ** 16),
workdir_root=FunqueConfig.workdir_path(),
ref_path=ref_file,
dis_path=dis_file,
asset_dict={'width':width, 'height':height, 'yuv_type':fmt}
)
assets = [asset]
if show_local_explanation:
from funque.core.quality_runner_extra import FunqueQualityRunnerWithLocalExplainer
runner_class = FunqueQualityRunnerWithLocalExplainer
elif enable_conf_interval:
from funque.core.quality_runner import BootstrapFunqueQualityRunner
runner_class = BootstrapFunqueQualityRunner
else:
runner_class = FunqueQualityRunner
if model_path is None:
optional_dict = None
else:
optional_dict = {'model_filepath':model_path}
if phone_model:
if optional_dict is None:
optional_dict = {}
optional_dict['enable_transform_score'] = True
runner = runner_class(
assets, None, fifo_mode=True,
delete_workdir=True,
result_store=None,
optional_dict=optional_dict,
optional_dict2=None,
)
# run
runner.run()
result = runner.results[0]
# pooling
if pool_method == 'harmonic_mean':
result.set_score_aggregate_method(ListStats.harmonic_mean)
elif pool_method == 'min':
result.set_score_aggregate_method(np.min)
elif pool_method == 'median':
result.set_score_aggregate_method(np.median)
elif pool_method == 'perc5':
result.set_score_aggregate_method(ListStats.perc5)
elif pool_method == 'perc10':
result.set_score_aggregate_method(ListStats.perc10)
elif pool_method == 'perc20':
result.set_score_aggregate_method(ListStats.perc20)
else: # None or 'mean'
pass
# output
if out_fmt == 'xml':
print(result.to_xml())
elif out_fmt == 'json':
print(result.to_json())
else: # None or 'text'
print(str(result))
# local explanation
if show_local_explanation:
runner.show_local_explanations([result])
if save_plot_dir is None:
DisplayConfig.show()
else:
DisplayConfig.show(write_to_dir=save_plot_dir)
return 0
if __name__ == "__main__":
ret = main()
exit(ret)
|
var _ = require('underscore');
var $ = require('jquery');
var cdb = require('cartodb.js');
var errorParse = require('../../../../../helpers/error-parser');
var ENOUGH_QUOTA_QUERY = _.template("select cdb_dataservices_client.cdb_enough_quota('<%= analysis %>', <%= rows %>);");
module.exports = {
init: function (configModel) {
this.SQL = new cdb.SQL({
user: configModel.get('user_name'),
sql_api_template: configModel.get('sql_api_template'),
api_key: configModel.get('api_key')
});
},
fetch: function (service, rows) {
var query = ENOUGH_QUOTA_QUERY({
analysis: service,
rows: rows
});
if (!this.deferred || this.deferred.state() !== 'pending') {
var deferred = $.Deferred();
this.deferred = deferred;
var errorCallback = function (err) {
deferred.reject(errorParse(err));
};
var successCallback = function (data) {
// response is something like:
// {"rows":[{"cdb_enough_quota":false}],"time":0.024,"fields":{"cdb_enough_quota":{"type":"boolean"}},"total_rows":1}
deferred.resolve(data.rows[0].cdb_enough_quota);
};
this.SQL.execute(query, null, {
success: successCallback,
error: errorCallback
});
}
return this.deferred.promise();
}
};
|
#!/usr/bin/env node
var exec = require('child_process').exec;
var fs = require('fs');
var path = require('path');
console.log('Updating plugin manifest');
exec("cordova plugin list", function(error, output, code) {
var plugins = [];
var lines = output.split("\n");
var count = 0;
lines.forEach(function(line){
if(line.length < 2) {
return;
}
count++;
line = line.replace(' ', '@').replace(new RegExp(' .*'), '')
plugin = line.substring(0, line.indexOf('@'));
version = line.substring(line.indexOf('@') + 1);
fetch = JSON.parse(fs.readFileSync(path.join('plugins', plugin, '.fetch.json'), 'utf-8'));
plugins.push({ id: plugin, version: version, source: fetch['source'] });
});
if(count>1) {
console.log('Writing plugin manifest to plugins.json');
fs.writeFileSync('plugins.json', JSON.stringify(plugins, null, 2), 'utf8');
}
else {
console.log('Not overwriting the plugin manifest. Only one plugin was detected, which probably means only manhandle-cordova-plugin is installed.');
}
}); |
require('./bootstrap');
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import {routes} from './routes';
import User from './Helpers/User'
window.User = User
//Sweet alert start:
import Swal from 'sweetalert2'
window.Swal = Swal;
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
window.Toast = Toast;
window.Reload = new Vue();
//noty
import Notification from "./Helpers/Notification";
window.Notification = Notification
//sweet alert end
const router = new VueRouter({
routes,
mode:'history'
})
const app = new Vue({
el: '#app',
router
});
|
const webpack = require('webpack');
const path = require('path');
const assetsDir = path.join(__dirname, 'public/assets');
const vendorsDir = path.join(__dirname, 'src/app/vendors');
const srcInclude = path.join(__dirname, 'src/app');
const indexFile = path.join(__dirname, 'src/app/index.js');
const config = {
devtool: 'cheap-module-source-map',
entry: [
'babel-polyfill',
'react-hot-loader/patch',
'webpack-hot-middleware/client',
indexFile
],
output: {
path: assetsDir,
filename: 'bundle.js',
publicPath: '/public/assets/'
},
module: {
rules: [
{
test: /\.jsx?$/,
include: srcInclude,
exclude: [vendorsDir],
loaders: ['react-hot-loader/webpack', 'babel-loader']
},
{
test: /\.css$/,
use: [
'style-loader',
{loader: 'css-loader', options: { importLoaders: 1 }},
'postcss-loader'
]
},
{
test: /\.scss$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
query: {
modules: true,
sourceMap: true,
importLoaders: 1,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
'sass-loader',
'postcss-loader'
]
},
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpe?g|gif)(\?\S*)?$/,
use: [
{
loader: 'url-loader',
options: {
limit: 100000,
name: '[name].[ext]'
}
}
]
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
getImplicitGlobals(),
setNodeEnv()
]
};
/*
* here using hoisting so don't use `var NAME = function()...`
*/
function getImplicitGlobals() {
return new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
jquery: 'jquery'
});
}
function setNodeEnv() {
return new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('dev')
}
});
}
module.exports = config;
|
var db = require("../models");
module.exports = function (app) {
app.get("/api/allskills", (req, res) => {
db.Skill.findAll().then((data) => {
res.json(data);
});
});
app.get("/api/navprojects", (req, res) => {
db.Project.findAll({
attributes: ['title']
}).then((data) => {
res.json(data);
});
});
app.get("/api/allprojects", (req, res) => {
db.Project.findAll().then((data) => {
res.json(data);
});
});
app.get("/api/projectskills", (req, res) => {
db.ProjectSkills.findAll({
include: [{model: db.Skill, attributes: ["skill"]}]
}).then((data) => {
res.json(data);
});
});
};
|
!function(t){var e={};function n(o){if(e[o])return e[o].exports;var r=e[o]={i:o,l:!1,exports:{}};return t[o].call(r.exports,r,r.exports,n),r.l=!0,r.exports}n.m=t,n.c=e,n.d=function(t,e,o){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:o})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var o=Object.create(null);if(n.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(o,r,function(e){return t[e]}.bind(null,r));return o},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="/",n(n.s=9)}({"8oxB":function(t,e){var n,o,r=t.exports={};function i(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function s(t){if(n===setTimeout)return setTimeout(t,0);if((n===i||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:i}catch(t){n=i}try{o="function"==typeof clearTimeout?clearTimeout:a}catch(t){o=a}}();var l,c=[],u=!1,d=-1;function f(){u&&l&&(u=!1,l.length?c=l.concat(c):d=-1,c.length&&p())}function p(){if(!u){var t=s(f);u=!0;for(var e=c.length;e;){for(l=c,c=[];++d<e;)l&&l[d].run();d=-1,e=c.length}l=null,u=!1,function(t){if(o===clearTimeout)return clearTimeout(t);if((o===a||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(t);try{o(t)}catch(e){try{return o.call(null,t)}catch(e){return o.call(this,t)}}}(t)}}function m(t,e){this.fun=t,this.array=e}function g(){}r.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];c.push(new m(t,e)),1!==c.length||u||s(p)},m.prototype.run=function(){this.fun.apply(null,this.array)},r.title="browser",r.browser=!0,r.env={},r.argv=[],r.version="",r.versions={},r.on=g,r.addListener=g,r.once=g,r.off=g,r.removeListener=g,r.removeAllListeners=g,r.emit=g,r.prependListener=g,r.prependOnceListener=g,r.listeners=function(t){return[]},r.binding=function(t){throw new Error("process.binding is not supported")},r.cwd=function(){return"/"},r.chdir=function(t){throw new Error("process.chdir is not supported")},r.umask=function(){return 0}},9:function(t,e,n){t.exports=n("D6hk")},D6hk:function(t,e,n){var o=n("bquW");function r(t){var e=t.val(),n=$("textarea#html-template").val().replace("{{ CONTENT }}",e),o=t.closest(".row").find(".html-preview .content iframe")[0].contentWindow.document;o.open(),o.close(),$("body",o).html(n)}n("oBpX"),$.trumbowyg.svgPath="/trumbowyg/icons.svg",$(".trumbowyg").trumbowyg({autogrowOnEnter:!0,imageWidthModalEdit:!0}).on("tbwchange",function(){r($(this))}),$(document).ready(function(){$(".trumbowyg-modal-box input").each(function(){$(this).addClass("browser-default")}),$(".trumbowyg").each(function(){r($(this))});var t=$("#push_notification_form_schedule");t.change(function(){$(this).prop("checked")?($(".schedule").show(),$(".sendnow").hide()):($(".schedule").hide(),$(".sendnow").show())}),t.trigger("change");var e=$("#push_notification_form_test");function n(){$(".loader-container:not(.page-loader-container)").fadeIn(200);var t=translations.confirmationContent+"\n\n";$.ajax({url:notificationDeviceCountUrl,type:"post",data:{segment:$("#push_notification_form_segment").val(),test:$("#push_notification_form_test:checked").length>0,testDevices:$(".row.test table tbody input:checkbox:checked").map(function(){return $(this).val()}).get()},success:function(e){if($(".loader-container:not(.page-loader-container)").fadeOut(200),0==$("#push_notification_form_segment").val()||void 0===$("#push_notification_form_segment").val()){var n=$("#push_notification_form_test:checked").length>0?translations.selectedTestDevices:translations.allDevices;t+=translations.segment+": "+n+"\n"}else t+=translations.segment+": "+$("#push_notification_form_segment option:selected").text()+"\n";t+=translations.deviceCount+": "+e.data.recipients+"\n",o.confirm(translations.confirmTitle,t,function(){$(".loader-container:not(.page-loader-container)").fadeIn(200),$('form[name="push_notification_form"]').submit()})}})}function i(t){return $(t).filter(function(){return!$(this).val()}).length}e.change(function(){$(this).prop("checked")?$(".test").show():$(".test").hide()}),e.trigger("change"),$("#push_notification_form_sendNow, #push_notification_form_sendLater").click(function(){return forms.removeAlertsFromTabs(),function(){var t=!0;$("ul.validation-message:not(.message-inconsistent)").remove(),$("input.invalid").removeClass("invalid");var e=$(".is-fallback-language");""===e.find("input.title").val()&&(forms.markInvalid(e.find("input.title")),t=!1);$("input.title, input.content").each(function(){$(this).val().length>$(this).data("length")&&(forms.markInvalid($(this),translations.maximumCharacterCountExceeded),t=!1)});var n=$("select.click-action").val();1==n&&(""===e.find("input.click-action-url").val()&&(forms.markInvalid(e.find("input.click-action-url")),t=!1),$("input.click-action-url").each(function(){""===$(this).val()||/^https?:\/\//.test($(this).val())||$(this).val("http://"+$(this).val())}));2==n&&""===e.find("textarea.click-action-html").val()&&(forms.markInvalid(e.find(".trumbowyg-box")),t=!1);var o=$("#push_notification_form_segment");""===o.val()&&(forms.markInvalid(o.closest(".select-wrapper")),t=!1);if($("input#push_notification_form_schedule").is(":checked")){var r=$("input#push_notification_form_scheduledSending_date"),i=$("input#push_notification_form_scheduledSending_time");""===r.val()&&(forms.markInvalid(r),t=!1),""===i.val()&&(forms.markInvalid(i),t=!1);""===r.val()||/[0-3]{1}[0-9]{1}-[0-1]{1}[0-9]{1}-[2-9]{1}[0-9]{3}/.test(r.val())||(forms.markInvalid(r,translations.invalidFormat),t=!1),""===i.val()||/[0-2]{1}[0-9]{1}:[0-5]{1}[0-9]{1}/.test(i.val())||(forms.markInvalid(i,translations.invalidFormat),t=!1)}return t}()?(!function(){var t=!0;$("ul.message-inconsistent").remove();var e=$("li.tab").length,n=e-i("input.title");n>0&&n<e&&(forms.markInconsistent("input.title"),t=!1);var o=e-i("input.content");o>0&&o<e&&(forms.markInconsistent("input.content"),t=!1);var r=$("select.click-action").val();if(r>0){var a="1"===r?"input.click-action-url":"textarea.click-action-html",s="2"===r,l=e-i(a);if(l>0&&l<e){var c=s?".trumbowyg-box":a;forms.markInconsistent(c),t=!1}}return t}()?o.confirm(translations.inconsistentTitle,translations.inconsistentContent,function(){n()},void 0,translations.sendAnyway):n(),!1):(o.warning(translations.invalidFormTitle,translations.invalidFormContent),!1)})})},GUC0:function(t,e,n){(function(e,n){t.exports=function(t){function e(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return t[o].call(r.exports,r,r.exports,e),r.l=!0,r.exports}var n={};return e.m=t,e.c=n,e.d=function(t,n,o){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:o})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=8)}([function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o="swal-button";e.CLASS_NAMES={MODAL:"swal-modal",OVERLAY:"swal-overlay",SHOW_MODAL:"swal-overlay--show-modal",MODAL_TITLE:"swal-title",MODAL_TEXT:"swal-text",ICON:"swal-icon",ICON_CUSTOM:"swal-icon--custom",CONTENT:"swal-content",FOOTER:"swal-footer",BUTTON_CONTAINER:"swal-button-container",BUTTON:o,CONFIRM_BUTTON:o+"--confirm",CANCEL_BUTTON:o+"--cancel",DANGER_BUTTON:o+"--danger",BUTTON_LOADING:o+"--loading",BUTTON_LOADER:o+"__loader"},e.default=e.CLASS_NAMES},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getNode=function(t){var e="."+t;return document.querySelector(e)},e.stringToNode=function(t){var e=document.createElement("div");return e.innerHTML=t.trim(),e.firstChild},e.insertAfter=function(t,e){var n=e.nextSibling;e.parentNode.insertBefore(t,n)},e.removeNode=function(t){t.parentElement.removeChild(t)},e.throwErr=function(t){throw"SweetAlert: "+(t=(t=t.replace(/ +(?= )/g,"")).trim())},e.isPlainObject=function(t){if("[object Object]"!==Object.prototype.toString.call(t))return!1;var e=Object.getPrototypeOf(t);return null===e||e===Object.prototype},e.ordinalSuffixOf=function(t){var e=t%10,n=t%100;return 1===e&&11!==n?t+"st":2===e&&12!==n?t+"nd":3===e&&13!==n?t+"rd":t+"th"}},function(t,e,n){"use strict";function o(t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}Object.defineProperty(e,"__esModule",{value:!0}),o(n(25));var r=n(26);e.overlayMarkup=r.default,o(n(27)),o(n(28)),o(n(29));var i=n(0),a=i.default.MODAL_TITLE,s=i.default.MODAL_TEXT,l=i.default.ICON,c=i.default.FOOTER;e.iconMarkup='\n <div class="'+l+'"></div>',e.titleMarkup='\n <div class="'+a+'"></div>\n',e.textMarkup='\n <div class="'+s+'"></div>',e.footerMarkup='\n <div class="'+c+'"></div>\n'},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(1);e.CONFIRM_KEY="confirm",e.CANCEL_KEY="cancel";var r={visible:!0,text:null,value:null,className:"",closeModal:!0},i=Object.assign({},r,{visible:!1,text:"Cancel",value:null}),a=Object.assign({},r,{text:"OK",value:!0});e.defaultButtonList={cancel:i,confirm:a};var s=function(t){switch(t){case e.CONFIRM_KEY:return a;case e.CANCEL_KEY:return i;default:var n=t.charAt(0).toUpperCase()+t.slice(1);return Object.assign({},r,{text:n,value:t})}},l=function(t,e){var n=s(t);return!0===e?Object.assign({},n,{visible:!0}):"string"==typeof e?Object.assign({},n,{visible:!0,text:e}):o.isPlainObject(e)?Object.assign({visible:!0},n,e):Object.assign({},n,{visible:!1})},c=function(t){var n={};switch(t.length){case 1:n[e.CANCEL_KEY]=Object.assign({},i,{visible:!1});break;case 2:n[e.CANCEL_KEY]=l(e.CANCEL_KEY,t[0]),n[e.CONFIRM_KEY]=l(e.CONFIRM_KEY,t[1]);break;default:o.throwErr("Invalid number of 'buttons' in array ("+t.length+").\n If you want more than 2 buttons, you need to use an object!")}return n};e.getButtonListOpts=function(t){var n=e.defaultButtonList;return"string"==typeof t?n[e.CONFIRM_KEY]=l(e.CONFIRM_KEY,t):Array.isArray(t)?n=c(t):o.isPlainObject(t)?n=function(t){for(var e={},n=0,o=Object.keys(t);n<o.length;n++){var r=o[n],a=t[r],s=l(r,a);e[r]=s}return e.cancel||(e.cancel=i),e}(t):!0===t?n=c([!0,!0]):!1===t?n=c([!1,!1]):void 0===t&&(n=e.defaultButtonList),n}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(1),r=n(2),i=n(0),a=i.default.MODAL,s=i.default.OVERLAY,l=n(30),c=n(31),u=n(32),d=n(33);e.injectElIntoModal=function(t){var e=o.getNode(a),n=o.stringToNode(t);return e.appendChild(n),n};var f=function(t,e){!function(t){t.className=a,t.textContent=""}(t);var n=e.className;n&&t.classList.add(n)};e.initModalContent=function(t){var e=o.getNode(a);f(e,t),l.default(t.icon),c.initTitle(t.title),c.initText(t.text),d.default(t.content),u.default(t.buttons,t.dangerMode)},e.default=function(){var t=o.getNode(s),e=o.stringToNode(r.modalMarkup);t.appendChild(e)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(3),r={isOpen:!1,promise:null,actions:{},timer:null},i=Object.assign({},r);e.resetState=function(){i=Object.assign({},r)},e.setActionValue=function(t){if("string"==typeof t)return a(o.CONFIRM_KEY,t);for(var e in t)a(e,t[e])};var a=function(t,e){i.actions[t]||(i.actions[t]={}),Object.assign(i.actions[t],{value:e})};e.setActionOptionsFor=function(t,e){var n=(void 0===e?{}:e).closeModal,o=void 0===n||n;Object.assign(i.actions[t],{closeModal:o})},e.default=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(1),r=n(3),i=n(0),a=i.default.OVERLAY,s=i.default.SHOW_MODAL,l=i.default.BUTTON,c=i.default.BUTTON_LOADING,u=n(5);e.openModal=function(){o.getNode(a).classList.add(s),u.default.isOpen=!0},e.onAction=function(t){void 0===t&&(t=r.CANCEL_KEY);var e=u.default.actions[t],n=e.value;if(!1===e.closeModal){var i=l+"--"+t;o.getNode(i).classList.add(c)}else o.getNode(a).classList.remove(s),u.default.isOpen=!1;u.default.promise.resolve(n)},e.getState=function(){var t=Object.assign({},u.default);return delete t.promise,delete t.timer,t},e.stopLoading=function(){for(var t=document.querySelectorAll("."+l),e=0;e<t.length;e++)t[e].classList.remove(c)}},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e,n){(function(e){t.exports=e.sweetAlert=n(9)}).call(e,n(7))},function(t,e,n){(function(e){t.exports=e.swal=n(10)}).call(e,n(7))},function(t,e,n){"undefined"!=typeof window&&n(11),n(16);var o=n(23).default;t.exports=o},function(t,e,n){var o=n(12);"string"==typeof o&&(o=[[t.i,o,""]]);var r={insertAt:"top",transform:void 0};n(14)(o,r),o.locals&&(t.exports=o.locals)},function(t,e,n){(t.exports=n(13)(void 0)).push([t.i,'.swal-icon--error{border-color:#f27474;-webkit-animation:animateErrorIcon .5s;animation:animateErrorIcon .5s}.swal-icon--error__x-mark{position:relative;display:block;-webkit-animation:animateXMark .5s;animation:animateXMark .5s}.swal-icon--error__line{position:absolute;height:5px;width:47px;background-color:#f27474;display:block;top:37px;border-radius:2px}.swal-icon--error__line--left{-webkit-transform:rotate(45deg);transform:rotate(45deg);left:17px}.swal-icon--error__line--right{-webkit-transform:rotate(-45deg);transform:rotate(-45deg);right:16px}@-webkit-keyframes animateErrorIcon{0%{-webkit-transform:rotateX(100deg);transform:rotateX(100deg);opacity:0}to{-webkit-transform:rotateX(0deg);transform:rotateX(0deg);opacity:1}}@keyframes animateErrorIcon{0%{-webkit-transform:rotateX(100deg);transform:rotateX(100deg);opacity:0}to{-webkit-transform:rotateX(0deg);transform:rotateX(0deg);opacity:1}}@-webkit-keyframes animateXMark{0%{-webkit-transform:scale(.4);transform:scale(.4);margin-top:26px;opacity:0}50%{-webkit-transform:scale(.4);transform:scale(.4);margin-top:26px;opacity:0}80%{-webkit-transform:scale(1.15);transform:scale(1.15);margin-top:-6px}to{-webkit-transform:scale(1);transform:scale(1);margin-top:0;opacity:1}}@keyframes animateXMark{0%{-webkit-transform:scale(.4);transform:scale(.4);margin-top:26px;opacity:0}50%{-webkit-transform:scale(.4);transform:scale(.4);margin-top:26px;opacity:0}80%{-webkit-transform:scale(1.15);transform:scale(1.15);margin-top:-6px}to{-webkit-transform:scale(1);transform:scale(1);margin-top:0;opacity:1}}.swal-icon--warning{border-color:#f8bb86;-webkit-animation:pulseWarning .75s infinite alternate;animation:pulseWarning .75s infinite alternate}.swal-icon--warning__body{width:5px;height:47px;top:10px;border-radius:2px;margin-left:-2px}.swal-icon--warning__body,.swal-icon--warning__dot{position:absolute;left:50%;background-color:#f8bb86}.swal-icon--warning__dot{width:7px;height:7px;border-radius:50%;margin-left:-4px;bottom:-11px}@-webkit-keyframes pulseWarning{0%{border-color:#f8d486}to{border-color:#f8bb86}}@keyframes pulseWarning{0%{border-color:#f8d486}to{border-color:#f8bb86}}.swal-icon--success{border-color:#a5dc86}.swal-icon--success:after,.swal-icon--success:before{content:"";border-radius:50%;position:absolute;width:60px;height:120px;background:#fff;-webkit-transform:rotate(45deg);transform:rotate(45deg)}.swal-icon--success:before{border-radius:120px 0 0 120px;top:-7px;left:-33px;-webkit-transform:rotate(-45deg);transform:rotate(-45deg);-webkit-transform-origin:60px 60px;transform-origin:60px 60px}.swal-icon--success:after{border-radius:0 120px 120px 0;top:-11px;left:30px;-webkit-transform:rotate(-45deg);transform:rotate(-45deg);-webkit-transform-origin:0 60px;transform-origin:0 60px;-webkit-animation:rotatePlaceholder 4.25s ease-in;animation:rotatePlaceholder 4.25s ease-in}.swal-icon--success__ring{width:80px;height:80px;border:4px solid hsla(98,55%,69%,.2);border-radius:50%;box-sizing:content-box;position:absolute;left:-4px;top:-4px;z-index:2}.swal-icon--success__hide-corners{width:5px;height:90px;background-color:#fff;padding:1px;position:absolute;left:28px;top:8px;z-index:1;-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}.swal-icon--success__line{height:5px;background-color:#a5dc86;display:block;border-radius:2px;position:absolute;z-index:2}.swal-icon--success__line--tip{width:25px;left:14px;top:46px;-webkit-transform:rotate(45deg);transform:rotate(45deg);-webkit-animation:animateSuccessTip .75s;animation:animateSuccessTip .75s}.swal-icon--success__line--long{width:47px;right:8px;top:38px;-webkit-transform:rotate(-45deg);transform:rotate(-45deg);-webkit-animation:animateSuccessLong .75s;animation:animateSuccessLong .75s}@-webkit-keyframes rotatePlaceholder{0%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}5%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}12%{-webkit-transform:rotate(-405deg);transform:rotate(-405deg)}to{-webkit-transform:rotate(-405deg);transform:rotate(-405deg)}}@keyframes rotatePlaceholder{0%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}5%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}12%{-webkit-transform:rotate(-405deg);transform:rotate(-405deg)}to{-webkit-transform:rotate(-405deg);transform:rotate(-405deg)}}@-webkit-keyframes animateSuccessTip{0%{width:0;left:1px;top:19px}54%{width:0;left:1px;top:19px}70%{width:50px;left:-8px;top:37px}84%{width:17px;left:21px;top:48px}to{width:25px;left:14px;top:45px}}@keyframes animateSuccessTip{0%{width:0;left:1px;top:19px}54%{width:0;left:1px;top:19px}70%{width:50px;left:-8px;top:37px}84%{width:17px;left:21px;top:48px}to{width:25px;left:14px;top:45px}}@-webkit-keyframes animateSuccessLong{0%{width:0;right:46px;top:54px}65%{width:0;right:46px;top:54px}84%{width:55px;right:0;top:35px}to{width:47px;right:8px;top:38px}}@keyframes animateSuccessLong{0%{width:0;right:46px;top:54px}65%{width:0;right:46px;top:54px}84%{width:55px;right:0;top:35px}to{width:47px;right:8px;top:38px}}.swal-icon--info{border-color:#c9dae1}.swal-icon--info:before{width:5px;height:29px;bottom:17px;border-radius:2px;margin-left:-2px}.swal-icon--info:after,.swal-icon--info:before{content:"";position:absolute;left:50%;background-color:#c9dae1}.swal-icon--info:after{width:7px;height:7px;border-radius:50%;margin-left:-3px;top:19px}.swal-icon{width:80px;height:80px;border-width:4px;border-style:solid;border-radius:50%;padding:0;position:relative;box-sizing:content-box;margin:20px auto}.swal-icon:first-child{margin-top:32px}.swal-icon--custom{width:auto;height:auto;max-width:100%;border:none;border-radius:0}.swal-icon img{max-width:100%;max-height:100%}.swal-title{color:rgba(0,0,0,.65);font-weight:600;text-transform:none;position:relative;display:block;padding:13px 16px;font-size:27px;line-height:normal;text-align:center;margin-bottom:0}.swal-title:first-child{margin-top:26px}.swal-title:not(:first-child){padding-bottom:0}.swal-title:not(:last-child){margin-bottom:13px}.swal-text{font-size:16px;position:relative;float:none;line-height:normal;vertical-align:top;text-align:left;display:inline-block;margin:0;padding:0 10px;font-weight:400;color:rgba(0,0,0,.64);max-width:calc(100% - 20px);overflow-wrap:break-word;box-sizing:border-box}.swal-text:first-child{margin-top:45px}.swal-text:last-child{margin-bottom:45px}.swal-footer{text-align:right;padding-top:13px;margin-top:13px;padding:13px 16px;border-radius:inherit;border-top-left-radius:0;border-top-right-radius:0}.swal-button-container{margin:5px;display:inline-block;position:relative}.swal-button{background-color:#7cd1f9;color:#fff;border:none;box-shadow:none;border-radius:5px;font-weight:600;font-size:14px;padding:10px 24px;margin:0;cursor:pointer}.swal-button:not([disabled]):hover{background-color:#78cbf2}.swal-button:active{background-color:#70bce0}.swal-button:focus{outline:none;box-shadow:0 0 0 1px #fff,0 0 0 3px rgba(43,114,165,.29)}.swal-button[disabled]{opacity:.5;cursor:default}.swal-button::-moz-focus-inner{border:0}.swal-button--cancel{color:#555;background-color:#efefef}.swal-button--cancel:not([disabled]):hover{background-color:#e8e8e8}.swal-button--cancel:active{background-color:#d7d7d7}.swal-button--cancel:focus{box-shadow:0 0 0 1px #fff,0 0 0 3px rgba(116,136,150,.29)}.swal-button--danger{background-color:#e64942}.swal-button--danger:not([disabled]):hover{background-color:#df4740}.swal-button--danger:active{background-color:#cf423b}.swal-button--danger:focus{box-shadow:0 0 0 1px #fff,0 0 0 3px rgba(165,43,43,.29)}.swal-content{padding:0 20px;margin-top:20px;font-size:medium}.swal-content:last-child{margin-bottom:20px}.swal-content__input,.swal-content__textarea{-webkit-appearance:none;background-color:#fff;border:none;font-size:14px;display:block;box-sizing:border-box;width:100%;border:1px solid rgba(0,0,0,.14);padding:10px 13px;border-radius:2px;transition:border-color .2s}.swal-content__input:focus,.swal-content__textarea:focus{outline:none;border-color:#6db8ff}.swal-content__textarea{resize:vertical}.swal-button--loading{color:transparent}.swal-button--loading~.swal-button__loader{opacity:1}.swal-button__loader{position:absolute;height:auto;width:43px;z-index:2;left:50%;top:50%;-webkit-transform:translateX(-50%) translateY(-50%);transform:translateX(-50%) translateY(-50%);text-align:center;pointer-events:none;opacity:0}.swal-button__loader div{display:inline-block;float:none;vertical-align:baseline;width:9px;height:9px;padding:0;border:none;margin:2px;opacity:.4;border-radius:7px;background-color:hsla(0,0%,100%,.9);transition:background .2s;-webkit-animation:swal-loading-anim 1s infinite;animation:swal-loading-anim 1s infinite}.swal-button__loader div:nth-child(3n+2){-webkit-animation-delay:.15s;animation-delay:.15s}.swal-button__loader div:nth-child(3n+3){-webkit-animation-delay:.3s;animation-delay:.3s}@-webkit-keyframes swal-loading-anim{0%{opacity:.4}20%{opacity:.4}50%{opacity:1}to{opacity:.4}}@keyframes swal-loading-anim{0%{opacity:.4}20%{opacity:.4}50%{opacity:1}to{opacity:.4}}.swal-overlay{position:fixed;top:0;bottom:0;left:0;right:0;text-align:center;font-size:0;overflow-y:auto;background-color:rgba(0,0,0,.4);z-index:10000;pointer-events:none;opacity:0;transition:opacity .3s}.swal-overlay:before{content:" ";display:inline-block;vertical-align:middle;height:100%}.swal-overlay--show-modal{opacity:1;pointer-events:auto}.swal-overlay--show-modal .swal-modal{opacity:1;pointer-events:auto;box-sizing:border-box;-webkit-animation:showSweetAlert .3s;animation:showSweetAlert .3s;will-change:transform}.swal-modal{width:478px;opacity:0;pointer-events:none;background-color:#fff;text-align:center;border-radius:5px;position:static;margin:20px auto;display:inline-block;vertical-align:middle;-webkit-transform:scale(1);transform:scale(1);-webkit-transform-origin:50% 50%;transform-origin:50% 50%;z-index:10001;transition:opacity .2s,-webkit-transform .3s;transition:transform .3s,opacity .2s;transition:transform .3s,opacity .2s,-webkit-transform .3s}@media (max-width:500px){.swal-modal{width:calc(100% - 20px)}}@-webkit-keyframes showSweetAlert{0%{-webkit-transform:scale(1);transform:scale(1)}1%{-webkit-transform:scale(.5);transform:scale(.5)}45%{-webkit-transform:scale(1.05);transform:scale(1.05)}80%{-webkit-transform:scale(.95);transform:scale(.95)}to{-webkit-transform:scale(1);transform:scale(1)}}@keyframes showSweetAlert{0%{-webkit-transform:scale(1);transform:scale(1)}1%{-webkit-transform:scale(.5);transform:scale(.5)}45%{-webkit-transform:scale(1.05);transform:scale(1.05)}80%{-webkit-transform:scale(.95);transform:scale(.95)}to{-webkit-transform:scale(1);transform:scale(1)}}',""])},function(t,e){function n(t,e){var n=t[1]||"",o=t[3];if(!o)return n;if(e&&"function"==typeof btoa){var r=function(t){return"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(t))))+" */"}(o);return[n].concat(o.sources.map(function(t){return"/*# sourceURL="+o.sourceRoot+t+" */"})).concat([r]).join("\n")}return[n].join("\n")}t.exports=function(t){var e=[];return e.toString=function(){return this.map(function(e){var o=n(e,t);return e[2]?"@media "+e[2]+"{"+o+"}":o}).join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var o={},r=0;r<this.length;r++){var i=this[r][0];"number"==typeof i&&(o[i]=!0)}for(r=0;r<t.length;r++){var a=t[r];"number"==typeof a[0]&&o[a[0]]||(n&&!a[2]?a[2]=n:n&&(a[2]="("+a[2]+") and ("+n+")"),e.push(a))}},e}},function(t,e,n){function o(t,e){for(var n=0;n<t.length;n++){var o=t[n],r=f[o.id];if(r){r.refs++;for(var i=0;i<r.parts.length;i++)r.parts[i](o.parts[i]);for(;i<o.parts.length;i++)r.parts.push(u(o.parts[i],e))}else{for(var a=[],i=0;i<o.parts.length;i++)a.push(u(o.parts[i],e));f[o.id]={id:o.id,refs:1,parts:a}}}}function r(t,e){for(var n=[],o={},r=0;r<t.length;r++){var i=t[r],a=e.base?i[0]+e.base:i[0],s=i[1],l=i[2],c=i[3],u={css:s,media:l,sourceMap:c};o[a]?o[a].parts.push(u):n.push(o[a]={id:a,parts:[u]})}return n}function i(t,e){var n=m(t.insertInto);if(!n)throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");var o=b[b.length-1];if("top"===t.insertAt)o?o.nextSibling?n.insertBefore(e,o.nextSibling):n.appendChild(e):n.insertBefore(e,n.firstChild),b.push(e);else{if("bottom"!==t.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(e)}}function a(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t);var e=b.indexOf(t);e>=0&&b.splice(e,1)}function s(t){var e=document.createElement("style");return t.attrs.type="text/css",c(e,t.attrs),i(t,e),e}function l(t){var e=document.createElement("link");return t.attrs.type="text/css",t.attrs.rel="stylesheet",c(e,t.attrs),i(t,e),e}function c(t,e){Object.keys(e).forEach(function(n){t.setAttribute(n,e[n])})}function u(t,e){var n,o,r,i;if(e.transform&&t.css){if(!(i=e.transform(t.css)))return function(){};t.css=i}if(e.singleton){var c=h++;n=g||(g=s(e)),o=d.bind(null,n,c,!1),r=d.bind(null,n,c,!0)}else t.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=l(e),o=function(t,e,n){var o=n.css,r=n.sourceMap,i=void 0===e.convertToAbsoluteUrls&&r;(e.convertToAbsoluteUrls||i)&&(o=v(o)),r&&(o+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(r))))+" */");var a=new Blob([o],{type:"text/css"}),s=t.href;t.href=URL.createObjectURL(a),s&&URL.revokeObjectURL(s)}.bind(null,n,e),r=function(){a(n),n.href&&URL.revokeObjectURL(n.href)}):(n=s(e),o=function(t,e){var n=e.css,o=e.media;if(o&&t.setAttribute("media",o),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}.bind(null,n),r=function(){a(n)});return o(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap)return;o(t=e)}else r()}}function d(t,e,n,o){var r=n?"":o.css;if(t.styleSheet)t.styleSheet.cssText=w(e,r);else{var i=document.createTextNode(r),a=t.childNodes;a[e]&&t.removeChild(a[e]),a.length?t.insertBefore(i,a[e]):t.appendChild(i)}}var f={},p=function(t){var e;return function(){return void 0===e&&(e=function(){return window&&document&&document.all&&!window.atob}.apply(this,arguments)),e}}(),m=function(t){var e={};return function(t){return void 0===e[t]&&(e[t]=function(t){return document.querySelector(t)}.call(this,t)),e[t]}}(),g=null,h=0,b=[],v=n(15);t.exports=function(t,e){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");(e=e||{}).attrs="object"==typeof e.attrs?e.attrs:{},e.singleton||(e.singleton=p()),e.insertInto||(e.insertInto="head"),e.insertAt||(e.insertAt="bottom");var n=r(t,e);return o(n,e),function(t){for(var i=[],a=0;a<n.length;a++){var s=n[a],l=f[s.id];l.refs--,i.push(l)}t&&o(r(t,e),e);for(var a=0;a<i.length;a++){var l=i[a];if(0===l.refs){for(var c=0;c<l.parts.length;c++)l.parts[c]();delete f[l.id]}}}};var w=function(){var t=[];return function(e,n){return t[e]=n,t.filter(Boolean).join("\n")}}()},function(t,e){t.exports=function(t){var e="undefined"!=typeof window&&window.location;if(!e)throw new Error("fixUrls requires window.location");if(!t||"string"!=typeof t)return t;var n=e.protocol+"//"+e.host,o=n+e.pathname.replace(/\/[^\/]*$/,"/");return t.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi,function(t,e){var r,i=e.trim().replace(/^"(.*)"$/,function(t,e){return e}).replace(/^'(.*)'$/,function(t,e){return e});return/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/)/i.test(i)?t:(r=0===i.indexOf("//")?i:0===i.indexOf("/")?n+i:o+i.replace(/^\.\//,""),"url("+JSON.stringify(r)+")")})}},function(t,e,n){var o=n(17);"undefined"==typeof window||window.Promise||(window.Promise=o),n(21),String.prototype.includes||(String.prototype.includes=function(t,e){"use strict";return"number"!=typeof e&&(e=0),!(e+t.length>this.length)&&-1!==this.indexOf(t,e)}),Array.prototype.includes||Object.defineProperty(Array.prototype,"includes",{value:function(t,e){if(null==this)throw new TypeError('"this" is null or not defined');var n=Object(this),o=n.length>>>0;if(0===o)return!1;for(var r=0|e,i=Math.max(r>=0?r:o-Math.abs(r),0);i<o;){if(function(t,e){return t===e||"number"==typeof t&&"number"==typeof e&&isNaN(t)&&isNaN(e)}(n[i],t))return!0;i++}return!1}}),"undefined"!=typeof window&&function(t){t.forEach(function(t){t.hasOwnProperty("remove")||Object.defineProperty(t,"remove",{configurable:!0,enumerable:!0,writable:!0,value:function(){this.parentNode.removeChild(this)}})})}([Element.prototype,CharacterData.prototype,DocumentType.prototype])},function(t,e,n){(function(e){!function(n){function o(){}function r(t){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof t)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],u(t,this)}function i(t,e){for(;3===t._state;)t=t._value;0!==t._state?(t._handled=!0,r._immediateFn(function(){var n=1===t._state?e.onFulfilled:e.onRejected;if(null!==n){var o;try{o=n(t._value)}catch(t){return void s(e.promise,t)}a(e.promise,o)}else(1===t._state?a:s)(e.promise,t._value)})):t._deferreds.push(e)}function a(t,e){try{if(e===t)throw new TypeError("A promise cannot be resolved with itself.");if(e&&("object"==typeof e||"function"==typeof e)){var n=e.then;if(e instanceof r)return t._state=3,t._value=e,void l(t);if("function"==typeof n)return void u(function(t,e){return function(){t.apply(e,arguments)}}(n,e),t)}t._state=1,t._value=e,l(t)}catch(e){s(t,e)}}function s(t,e){t._state=2,t._value=e,l(t)}function l(t){2===t._state&&0===t._deferreds.length&&r._immediateFn(function(){t._handled||r._unhandledRejectionFn(t._value)});for(var e=0,n=t._deferreds.length;e<n;e++)i(t,t._deferreds[e]);t._deferreds=null}function c(t,e,n){this.onFulfilled="function"==typeof t?t:null,this.onRejected="function"==typeof e?e:null,this.promise=n}function u(t,e){var n=!1;try{t(function(t){n||(n=!0,a(e,t))},function(t){n||(n=!0,s(e,t))})}catch(t){if(n)return;n=!0,s(e,t)}}var d=setTimeout;r.prototype.catch=function(t){return this.then(null,t)},r.prototype.then=function(t,e){var n=new this.constructor(o);return i(this,new c(t,e,n)),n},r.all=function(t){var e=Array.prototype.slice.call(t);return new r(function(t,n){function o(i,a){try{if(a&&("object"==typeof a||"function"==typeof a)){var s=a.then;if("function"==typeof s)return void s.call(a,function(t){o(i,t)},n)}e[i]=a,0==--r&&t(e)}catch(t){n(t)}}if(0===e.length)return t([]);for(var r=e.length,i=0;i<e.length;i++)o(i,e[i])})},r.resolve=function(t){return t&&"object"==typeof t&&t.constructor===r?t:new r(function(e){e(t)})},r.reject=function(t){return new r(function(e,n){n(t)})},r.race=function(t){return new r(function(e,n){for(var o=0,r=t.length;o<r;o++)t[o].then(e,n)})},r._immediateFn="function"==typeof e&&function(t){e(t)}||function(t){d(t,0)},r._unhandledRejectionFn=function(t){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",t)},r._setImmediateFn=function(t){r._immediateFn=t},r._setUnhandledRejectionFn=function(t){r._unhandledRejectionFn=t},void 0!==t&&t.exports?t.exports=r:n.Promise||(n.Promise=r)}(this)}).call(e,n(18).setImmediate)},function(t,o,r){function i(t,e){this._id=t,this._clearFn=e}var a=Function.prototype.apply;o.setTimeout=function(){return new i(a.call(setTimeout,window,arguments),clearTimeout)},o.setInterval=function(){return new i(a.call(setInterval,window,arguments),clearInterval)},o.clearTimeout=o.clearInterval=function(t){t&&t.close()},i.prototype.unref=i.prototype.ref=function(){},i.prototype.close=function(){this._clearFn.call(window,this._id)},o.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},o.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},o._unrefActive=o.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function(){t._onTimeout&&t._onTimeout()},e))},r(19),o.setImmediate=e,o.clearImmediate=n},function(t,e,n){(function(t,e){!function(t,n){"use strict";function o(t){delete s[t]}function r(t){if(l)setTimeout(r,0,t);else{var e=s[t];if(e){l=!0;try{!function(t){var e=t.callback,o=t.args;switch(o.length){case 0:e();break;case 1:e(o[0]);break;case 2:e(o[0],o[1]);break;case 3:e(o[0],o[1],o[2]);break;default:e.apply(n,o)}}(e)}finally{o(t),l=!1}}}}if(!t.setImmediate){var i,a=1,s={},l=!1,c=t.document,u=Object.getPrototypeOf&&Object.getPrototypeOf(t);u=u&&u.setTimeout?u:t,"[object process]"==={}.toString.call(t.process)?i=function(t){e.nextTick(function(){r(t)})}:function(){if(t.postMessage&&!t.importScripts){var e=!0,n=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=n,e}}()?function(){var e="setImmediate$"+Math.random()+"$",n=function(n){n.source===t&&"string"==typeof n.data&&0===n.data.indexOf(e)&&r(+n.data.slice(e.length))};t.addEventListener?t.addEventListener("message",n,!1):t.attachEvent("onmessage",n),i=function(n){t.postMessage(e+n,"*")}}():t.MessageChannel?function(){var t=new MessageChannel;t.port1.onmessage=function(t){r(t.data)},i=function(e){t.port2.postMessage(e)}}():c&&"onreadystatechange"in c.createElement("script")?function(){var t=c.documentElement;i=function(e){var n=c.createElement("script");n.onreadystatechange=function(){r(e),n.onreadystatechange=null,t.removeChild(n),n=null},t.appendChild(n)}}():i=function(t){setTimeout(r,0,t)},u.setImmediate=function(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),n=0;n<e.length;n++)e[n]=arguments[n+1];var o={callback:t,args:e};return s[a]=o,i(a),a++},u.clearImmediate=o}}("undefined"==typeof self?void 0===t?this:t:self)}).call(e,n(7),n(20))},function(t,e){function n(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function r(t){if(c===setTimeout)return setTimeout(t,0);if((c===n||!c)&&setTimeout)return c=setTimeout,setTimeout(t,0);try{return c(t,0)}catch(e){try{return c.call(null,t,0)}catch(e){return c.call(this,t,0)}}}function i(){m&&f&&(m=!1,f.length?p=f.concat(p):g=-1,p.length&&a())}function a(){if(!m){var t=r(i);m=!0;for(var e=p.length;e;){for(f=p,p=[];++g<e;)f&&f[g].run();g=-1,e=p.length}f=null,m=!1,function(t){if(u===clearTimeout)return clearTimeout(t);if((u===o||!u)&&clearTimeout)return u=clearTimeout,clearTimeout(t);try{u(t)}catch(e){try{return u.call(null,t)}catch(e){return u.call(this,t)}}}(t)}}function s(t,e){this.fun=t,this.array=e}function l(){}var c,u,d=t.exports={};!function(){try{c="function"==typeof setTimeout?setTimeout:n}catch(t){c=n}try{u="function"==typeof clearTimeout?clearTimeout:o}catch(t){u=o}}();var f,p=[],m=!1,g=-1;d.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];p.push(new s(t,e)),1!==p.length||m||r(a)},s.prototype.run=function(){this.fun.apply(null,this.array)},d.title="browser",d.browser=!0,d.env={},d.argv=[],d.version="",d.versions={},d.on=l,d.addListener=l,d.once=l,d.off=l,d.removeListener=l,d.removeAllListeners=l,d.emit=l,d.prependListener=l,d.prependOnceListener=l,d.listeners=function(t){return[]},d.binding=function(t){throw new Error("process.binding is not supported")},d.cwd=function(){return"/"},d.chdir=function(t){throw new Error("process.chdir is not supported")},d.umask=function(){return 0}},function(t,e,n){"use strict";n(22).polyfill()},function(t,e,n){"use strict";function o(t,e){if(null==t)throw new TypeError("Cannot convert first argument to object");for(var n=Object(t),o=1;o<arguments.length;o++){var r=arguments[o];if(null!=r)for(var i=Object.keys(Object(r)),a=0,s=i.length;a<s;a++){var l=i[a],c=Object.getOwnPropertyDescriptor(r,l);void 0!==c&&c.enumerable&&(n[l]=r[l])}}return n}t.exports={assign:o,polyfill:function(){Object.assign||Object.defineProperty(Object,"assign",{enumerable:!1,configurable:!0,writable:!0,value:o})}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(24),r=n(6),i=n(5),a=n(36),s=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if("undefined"!=typeof window){var n=a.getOpts.apply(void 0,t);return new Promise(function(t,e){i.default.promise={resolve:t,reject:e},o.default(n),setTimeout(function(){r.openModal()})})}};s.close=r.onAction,s.getState=r.getState,s.setActionValue=i.setActionValue,s.stopLoading=r.stopLoading,s.setDefaults=a.setDefaults,e.default=s},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(1),r=n(0),i=r.default.MODAL,a=n(4),s=n(34),l=n(35),c=n(1);e.init=function(t){o.getNode(i)||(document.body||c.throwErr("You can only use SweetAlert AFTER the DOM has loaded!"),s.default(),a.default()),a.initModalContent(t),l.default(t)},e.default=e.init},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(0),r=o.default.MODAL;e.modalMarkup='\n <div class="'+r+'" role="dialog" aria-modal="true"></div>',e.default=e.modalMarkup},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(0),r=o.default.OVERLAY,i='<div \n class="'+r+'"\n tabIndex="-1">\n </div>';e.default=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(0),r=o.default.ICON;e.errorIconMarkup=function(){var t=r+"--error",e=t+"__line";return'\n <div class="'+t+'__x-mark">\n <span class="'+e+" "+e+'--left"></span>\n <span class="'+e+" "+e+'--right"></span>\n </div>\n '},e.warningIconMarkup=function(){var t=r+"--warning";return'\n <span class="'+t+'__body">\n <span class="'+t+'__dot"></span>\n </span>\n '},e.successIconMarkup=function(){var t=r+"--success";return'\n <span class="'+t+"__line "+t+'__line--long"></span>\n <span class="'+t+"__line "+t+'__line--tip"></span>\n\n <div class="'+t+'__ring"></div>\n <div class="'+t+'__hide-corners"></div>\n '}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(0),r=o.default.CONTENT;e.contentMarkup='\n <div class="'+r+'">\n\n </div>\n'},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(0),r=o.default.BUTTON_CONTAINER,i=o.default.BUTTON,a=o.default.BUTTON_LOADER;e.buttonMarkup='\n <div class="'+r+'">\n\n <button\n class="'+i+'"\n ></button>\n\n <div class="'+a+'">\n <div></div>\n <div></div>\n <div></div>\n </div>\n\n </div>\n'},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(4),r=n(2),i=n(0),a=i.default.ICON,s=i.default.ICON_CUSTOM,l=["error","warning","success","info"],c={error:r.errorIconMarkup(),warning:r.warningIconMarkup(),success:r.successIconMarkup()};e.default=function(t){if(t){var e=o.injectElIntoModal(r.iconMarkup);l.includes(t)?function(t,e){var n=a+"--"+t;e.classList.add(n);var o=c[t];o&&(e.innerHTML=o)}(t,e):function(t,e){e.classList.add(s);var n=document.createElement("img");n.src=t,e.appendChild(n)}(t,e)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(2),r=n(4),i=function(t){navigator.userAgent.includes("AppleWebKit")&&(t.style.display="none",t.offsetHeight,t.style.display="")};e.initTitle=function(t){if(t){var e=r.injectElIntoModal(o.titleMarkup);e.textContent=t,i(e)}},e.initText=function(t){if(t){var e=document.createDocumentFragment();t.split("\n").forEach(function(t,n,o){e.appendChild(document.createTextNode(t)),n<o.length-1&&e.appendChild(document.createElement("br"))});var n=r.injectElIntoModal(o.textMarkup);n.appendChild(e),i(n)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(1),r=n(4),i=n(0),a=i.default.BUTTON,s=i.default.DANGER_BUTTON,l=n(3),c=n(2),u=n(6),d=n(5),f=function(t,e,n){var r=e.text,i=e.value,f=e.className,p=e.closeModal,m=o.stringToNode(c.buttonMarkup),g=m.querySelector("."+a),h=a+"--"+t;g.classList.add(h),f&&(Array.isArray(f)?f:f.split(" ")).filter(function(t){return t.length>0}).forEach(function(t){g.classList.add(t)}),n&&t===l.CONFIRM_KEY&&g.classList.add(s),g.textContent=r;var b={};return b[t]=i,d.setActionValue(b),d.setActionOptionsFor(t,{closeModal:p}),g.addEventListener("click",function(){return u.onAction(t)}),m};e.default=function(t,e){var n=r.injectElIntoModal(c.footerMarkup);for(var o in t){var i=t[o],a=f(o,i,e);i.visible&&n.appendChild(a)}0===n.children.length&&n.remove()}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(3),r=n(4),i=n(2),a=n(5),s=n(6),l=n(0),c=l.default.CONTENT,u=function(t){t.addEventListener("input",function(t){var e=t.target,n=e.value;a.setActionValue(n)}),t.addEventListener("keyup",function(t){if("Enter"===t.key)return s.onAction(o.CONFIRM_KEY)}),setTimeout(function(){t.focus(),a.setActionValue("")},0)};e.default=function(t){if(t){var e=r.injectElIntoModal(i.contentMarkup),n=t.element,o=t.attributes;"string"==typeof n?function(t,e,n){var o=document.createElement(e),r=c+"__"+e;for(var i in o.classList.add(r),n){var a=n[i];o[i]=a}"input"===e&&u(o),t.appendChild(o)}(e,n,o):e.appendChild(n)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(1),r=n(2);e.default=function(){var t=o.stringToNode(r.overlayMarkup);document.body.appendChild(t)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(5),r=n(6),i=n(1),a=n(3),s=n(0),l=s.default.MODAL,c=s.default.BUTTON,u=s.default.OVERLAY,d=function(t){if(o.default.isOpen)switch(t.key){case"Escape":return r.onAction(a.CANCEL_KEY)}},f=function(t){if(o.default.isOpen)switch(t.key){case"Tab":return function(t){t.preventDefault(),m()}(t)}},p=function(t){if(o.default.isOpen)return"Tab"===t.key&&t.shiftKey?function(t){t.preventDefault(),g()}(t):void 0},m=function(){var t=i.getNode(c);t&&(t.tabIndex=0,t.focus())},g=function(){var t=i.getNode(l),e=t.querySelectorAll("."+c),n=e.length-1,o=e[n];o&&o.focus()},h=function(){var t=i.getNode(l),e=t.querySelectorAll("."+c);e.length&&(function(t){t[t.length-1].addEventListener("keydown",f)}(e),function(t){t[0].addEventListener("keydown",p)}(e))},b=function(t){if(i.getNode(u)===t.target)return r.onAction(a.CANCEL_KEY)};e.default=function(t){t.closeOnEsc?document.addEventListener("keyup",d):document.removeEventListener("keyup",d),t.dangerMode?m():g(),h(),function(t){var e=i.getNode(u);e.removeEventListener("click",b),t&&e.addEventListener("click",b)}(t.closeOnClickOutside),function(t){o.default.timer&&clearTimeout(o.default.timer),t&&(o.default.timer=window.setTimeout(function(){return r.onAction(a.CANCEL_KEY)},t))}(t.timer)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(1),r=n(3),i=n(37),a=n(38),s={title:null,text:null,icon:null,buttons:r.defaultButtonList,content:null,className:null,closeOnClickOutside:!0,closeOnEsc:!0,dangerMode:!1,timer:null},l=Object.assign({},s);e.setDefaults=function(t){l=Object.assign({},s,t)};var c=function(t){var e=t&&t.button,n=t&&t.buttons;return void 0!==e&&void 0!==n&&o.throwErr("Cannot set both 'button' and 'buttons' options!"),void 0!==e?{confirm:e}:n},u=function(t){return o.ordinalSuffixOf(t+1)},d=function(t,e){o.throwErr(u(e)+" argument ('"+t+"') is invalid")},f=function(t,e){var n=t+1,r=e[n];o.isPlainObject(r)||void 0===r||o.throwErr("Expected "+u(n)+" argument ('"+r+"') to be a plain object")},p=function(t,e,n,r){var i=typeof e,a="string"===i,s=e instanceof Element;if(a){if(0===n)return{text:e};if(1===n)return{text:e,title:r[0]};if(2===n)return f(n,r),{icon:e};d(e,n)}else{if(s&&0===n)return f(n,r),{content:e};if(o.isPlainObject(e))return function(t,e){var n=t+1,r=e[n];void 0!==r&&o.throwErr("Unexpected "+u(n)+" argument ("+r+")")}(n,r),e;d(e,n)}};e.getOpts=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n={};t.forEach(function(e,o){var r=p(0,e,o,t);Object.assign(n,r)});var o=c(n);n.buttons=r.getButtonListOpts(o),delete n.button,n.content=i.getContentOpts(n.content);var u=Object.assign({},s,l,n);return Object.keys(u).forEach(function(t){a.DEPRECATED_OPTS[t]&&a.logDeprecation(t)}),u}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=n(1),r={element:"input",attributes:{placeholder:""}};e.getContentOpts=function(t){return o.isPlainObject(t)?Object.assign({},t):t instanceof Element?{element:t}:"input"===t?r:null}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.logDeprecation=function(t){var n=e.DEPRECATED_OPTS[t],o=n.onlyRename,r=n.replacement,i=n.subOption,a=n.link,s=o?"renamed":"deprecated",l='SweetAlert warning: "'+t+'" option has been '+s+".";r&&(l+=" Please use"+(i?' "'+i+'" in ':" ")+'"'+r+'" instead.');var c="https://sweetalert.js.org";l+=a?" More details: "+c+a:" More details: "+c+"/guides/#upgrading-from-1x",console.warn(l)},e.DEPRECATED_OPTS={type:{replacement:"icon",link:"/docs/#icon"},imageUrl:{replacement:"icon",link:"/docs/#icon"},customClass:{replacement:"className",onlyRename:!0,link:"/docs/#classname"},imageSize:{},showCancelButton:{replacement:"buttons",link:"/docs/#buttons"},showConfirmButton:{replacement:"button",link:"/docs/#button"},confirmButtonText:{replacement:"button",link:"/docs/#button"},confirmButtonColor:{},cancelButtonText:{replacement:"buttons",link:"/docs/#buttons"},closeOnConfirm:{replacement:"button",subOption:"closeModal",link:"/docs/#button"},closeOnCancel:{replacement:"buttons",subOption:"closeModal",link:"/docs/#buttons"},showLoaderOnConfirm:{replacement:"buttons"},animation:{},inputType:{replacement:"content",link:"/docs/#content"},inputValue:{replacement:"content",link:"/docs/#content"},inputPlaceholder:{replacement:"content",link:"/docs/#content"},html:{replacement:"content",link:"/docs/#content"},allowEscapeKey:{replacement:"closeOnEsc",onlyRename:!0,link:"/docs/#closeonesc"},allowClickOutside:{replacement:"closeOnClickOutside",onlyRename:!0,link:"/docs/#closeonclickoutside"}}}])}).call(this,n("URgk").setImmediate,n("URgk").clearImmediate)},URgk:function(t,e,n){(function(t){var o=void 0!==t&&t||"undefined"!=typeof self&&self||window,r=Function.prototype.apply;function i(t,e){this._id=t,this._clearFn=e}e.setTimeout=function(){return new i(r.call(setTimeout,o,arguments),clearTimeout)},e.setInterval=function(){return new i(r.call(setInterval,o,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},i.prototype.unref=i.prototype.ref=function(){},i.prototype.close=function(){this._clearFn.call(o,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function(){t._onTimeout&&t._onTimeout()},e))},n("YBdB"),e.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==t&&t.setImmediate||this&&this.setImmediate,e.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==t&&t.clearImmediate||this&&this.clearImmediate}).call(this,n("yLpj"))},YBdB:function(t,e,n){(function(t,e){!function(t,n){"use strict";if(!t.setImmediate){var o,r,i,a,s,l=1,c={},u=!1,d=t.document,f=Object.getPrototypeOf&&Object.getPrototypeOf(t);f=f&&f.setTimeout?f:t,"[object process]"==={}.toString.call(t.process)?o=function(t){e.nextTick(function(){m(t)})}:!function(){if(t.postMessage&&!t.importScripts){var e=!0,n=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=n,e}}()?t.MessageChannel?((i=new MessageChannel).port1.onmessage=function(t){m(t.data)},o=function(t){i.port2.postMessage(t)}):d&&"onreadystatechange"in d.createElement("script")?(r=d.documentElement,o=function(t){var e=d.createElement("script");e.onreadystatechange=function(){m(t),e.onreadystatechange=null,r.removeChild(e),e=null},r.appendChild(e)}):o=function(t){setTimeout(m,0,t)}:(a="setImmediate$"+Math.random()+"$",s=function(e){e.source===t&&"string"==typeof e.data&&0===e.data.indexOf(a)&&m(+e.data.slice(a.length))},t.addEventListener?t.addEventListener("message",s,!1):t.attachEvent("onmessage",s),o=function(e){t.postMessage(a+e,"*")}),f.setImmediate=function(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),n=0;n<e.length;n++)e[n]=arguments[n+1];var r={callback:t,args:e};return c[l]=r,o(l),l++},f.clearImmediate=p}function p(t){delete c[t]}function m(t){if(u)setTimeout(m,0,t);else{var e=c[t];if(e){u=!0;try{!function(t){var e=t.callback,o=t.args;switch(o.length){case 0:e();break;case 1:e(o[0]);break;case 2:e(o[0],o[1]);break;case 3:e(o[0],o[1],o[2]);break;default:e.apply(n,o)}}(e)}finally{p(t),u=!1}}}}}("undefined"==typeof self?void 0===t?this:t:self)}).call(this,n("yLpj"),n("8oxB"))},bquW:function(t,e,n){var o=n("GUC0");t.exports={confirm:function(t,e,n,r,i,a){var s={title:t,icon:"warning",text:e,dangerMode:!0,buttons:{cancel:{text:void 0!==a?a:translations.cancel,value:null,visible:!0,className:"",closeModal:!0},confirm:{text:void 0!==i?i:translations.ok,value:!0,visible:!0,className:"",closeModal:!0}}};return o(s).then(function(t){t?void 0!==n&&n():void 0!==r&&r()}),!1},info:function(t,e){o({title:t,text:e,icon:"info"})},warning:function(t,e){o({title:t,text:e,icon:"warning",dangerMode:!0})}}},oBpX:function(t,e){jQuery.trumbowyg={langs:{en:{viewHTML:"View HTML",undo:"Undo",redo:"Redo",formatting:"Formatting",p:"Paragraph",blockquote:"Quote",code:"Code",header:"Header",bold:"Bold",italic:"Italic",strikethrough:"Stroke",underline:"Underline",strong:"Strong",em:"Emphasis",del:"Deleted",superscript:"Superscript",subscript:"Subscript",unorderedList:"Unordered list",orderedList:"Ordered list",insertImage:"Insert Image",link:"Link",createLink:"Insert link",unlink:"Remove link",justifyLeft:"Align Left",justifyCenter:"Align Center",justifyRight:"Align Right",justifyFull:"Align Justify",horizontalRule:"Insert horizontal rule",removeformat:"Remove format",fullscreen:"Fullscreen",close:"Close",submit:"Confirm",reset:"Cancel",required:"Required",description:"Description",title:"Title",text:"Text",target:"Target",width:"Width"}},plugins:{},svgPath:null,hideButtonTexts:null},Object.defineProperty(jQuery.trumbowyg,"defaultOptions",{value:{lang:"en",fixedBtnPane:!1,fixedFullWidth:!1,autogrow:!1,autogrowOnEnter:!1,imageWidthModalEdit:!1,prefix:"trumbowyg-",semantic:!0,resetCss:!1,removeformatPasted:!1,tagsToRemove:[],tagsToKeep:["hr","img","embed","iframe","input"],btns:[["viewHTML"],["undo","redo"],["formatting"],["strong","em","del"],["superscript","subscript"],["link"],["insertImage"],["justifyLeft","justifyCenter","justifyRight","justifyFull"],["unorderedList","orderedList"],["horizontalRule"],["removeformat"],["fullscreen"]],btnsDef:{},inlineElementsSelector:"a,abbr,acronym,b,caption,cite,code,col,dfn,dir,dt,dd,em,font,hr,i,kbd,li,q,span,strikeout,strong,sub,sup,u",pasteHandlers:[],plugins:{},urlProtocol:!1,minimalLinks:!1},writable:!1,enumerable:!0,configurable:!1}),function(t,e,n,o){"use strict";o.fn.trumbowyg=function(t,e){if(t===Object(t)||!t)return this.each(function(){o(this).data("trumbowyg")||o(this).data("trumbowyg",new r(this,t))});if(1===this.length)try{var n=o(this).data("trumbowyg");switch(t){case"execCmd":return n.execCmd(e.cmd,e.param,e.forceCss);case"openModal":return n.openModal(e.title,e.content);case"closeModal":return n.closeModal();case"openModalInsert":return n.openModalInsert(e.title,e.fields,e.callback);case"saveRange":return n.saveRange();case"getRange":return n.range;case"getRangeText":return n.getRangeText();case"restoreRange":return n.restoreRange();case"enable":return n.setDisabled(!1);case"disable":return n.setDisabled(!0);case"toggle":return n.toggle();case"destroy":return n.destroy();case"empty":return n.empty();case"html":return n.html(e)}}catch(t){}return!1};var r=function(r,i){var a=this,s=o.trumbowyg;a.doc=r.ownerDocument||n,a.$ta=o(r),a.$c=o(r),null!=(i=i||{}).lang||null!=s.langs[i.lang]?a.lang=o.extend(!0,{},s.langs.en,s.langs[i.lang]):a.lang=s.langs.en,a.hideButtonTexts=null!=s.hideButtonTexts?s.hideButtonTexts:i.hideButtonTexts;var l=null!=s.svgPath?s.svgPath:i.svgPath;if(a.hasSvg=!1!==l,a.svgPath=a.doc.querySelector("base")?e.location.href.split("#")[0]:"",0===o("#trumbowyg-icons",a.doc).length&&!1!==l){if(null==l){for(var c=n.getElementsByTagName("script"),u=0;u<c.length;u+=1){var d=c[u].src,f=d.match("trumbowyg(.min)?.js");null!=f&&(l=d.substring(0,d.indexOf(f[0]))+"ui/icons.svg")}null==l&&console.warn("You must define svgPath: https://goo.gl/CfTY9U")}var p=a.doc.createElement("div");p.id="trumbowyg-icons",a.doc.body.insertBefore(p,a.doc.body.childNodes[0]),o.ajax({async:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",dataType:"xml",crossDomain:!0,url:l,data:null,beforeSend:null,complete:null,success:function(t){p.innerHTML=(new XMLSerializer).serializeToString(t.documentElement)}})}var m=a.lang.header,g=function(){return(e.chrome||e.Intl&&Intl.v8BreakIterator)&&"CSS"in e};a.btnsDef={viewHTML:{fn:"toggle",class:"trumbowyg-not-disable"},undo:{isSupported:g,key:"Z"},redo:{isSupported:g,key:"Y"},p:{fn:"formatBlock"},blockquote:{fn:"formatBlock"},h1:{fn:"formatBlock",title:m+" 1"},h2:{fn:"formatBlock",title:m+" 2"},h3:{fn:"formatBlock",title:m+" 3"},h4:{fn:"formatBlock",title:m+" 4"},subscript:{tag:"sub"},superscript:{tag:"sup"},bold:{key:"B",tag:"b"},italic:{key:"I",tag:"i"},underline:{tag:"u"},strikethrough:{tag:"strike"},strong:{fn:"bold",key:"B"},em:{fn:"italic",key:"I"},del:{fn:"strikethrough"},createLink:{key:"K",tag:"a"},unlink:{},insertImage:{},justifyLeft:{tag:"left",forceCss:!0},justifyCenter:{tag:"center",forceCss:!0},justifyRight:{tag:"right",forceCss:!0},justifyFull:{tag:"justify",forceCss:!0},unorderedList:{fn:"insertUnorderedList",tag:"ul"},orderedList:{fn:"insertOrderedList",tag:"ol"},horizontalRule:{fn:"insertHorizontalRule"},removeformat:{},fullscreen:{class:"trumbowyg-not-disable"},close:{fn:"destroy",class:"trumbowyg-not-disable"},formatting:{dropdown:["p","blockquote","h1","h2","h3","h4"],ico:"p"},link:{dropdown:["createLink","unlink"]}},a.o=o.extend(!0,{},s.defaultOptions,i),a.o.hasOwnProperty("imgDblClickHandler")||(a.o.imgDblClickHandler=a.getDefaultImgDblClickHandler()),a.urlPrefix=a.setupUrlPrefix(),a.disabled=a.o.disabled||"TEXTAREA"===r.nodeName&&r.disabled,i.btns?a.o.btns=i.btns:a.o.semantic||(a.o.btns[3]=["bold","italic","underline","strikethrough"]),o.each(a.o.btnsDef,function(t,e){a.addBtnDef(t,e)}),a.eventNamespace="trumbowyg-event",a.keys=[],a.tagToButton={},a.tagHandlers=[],a.pasteHandlers=[].concat(a.o.pasteHandlers),a.isIE=-1!==t.userAgent.indexOf("MSIE")||-1!==t.appVersion.indexOf("Trident/"),a.init()};r.prototype={DEFAULT_SEMANTIC_MAP:{b:"strong",i:"em",s:"del",strike:"del",div:"p"},init:function(){var t=this;t.height=t.$ta.height(),t.initPlugins();try{t.doc.execCommand("enableObjectResizing",!1,!1),t.doc.execCommand("defaultParagraphSeparator",!1,"p")}catch(t){}t.buildEditor(),t.buildBtnPane(),t.fixedBtnPaneEvents(),t.buildOverlay(),setTimeout(function(){t.disabled&&t.setDisabled(!0),t.$c.trigger("tbwinit")})},addBtnDef:function(t,e){this.btnsDef[t]=e},setupUrlPrefix:function(){var t=this.o.urlProtocol;if(t)return"string"!=typeof t?"https://":/:\/\/$/.test(t)?t:t+"://"},buildEditor:function(){var t=this,n=t.o.prefix,r="";t.$box=o("<div/>",{class:n+"box "+n+"editor-visible "+n+t.o.lang+" trumbowyg"}),t.isTextarea=t.$ta.is("textarea"),t.isTextarea?(r=t.$ta.val(),t.$ed=o("<div/>"),t.$box.insertAfter(t.$ta).append(t.$ed,t.$ta)):(t.$ed=t.$ta,r=t.$ed.html(),t.$ta=o("<textarea/>",{name:t.$ta.attr("id"),height:t.height}).val(r),t.$box.insertAfter(t.$ed).append(t.$ta,t.$ed),t.syncCode()),t.$ta.addClass(n+"textarea").attr("tabindex",-1),t.$ed.addClass(n+"editor").attr({contenteditable:!0,dir:t.lang._dir||"ltr"}).html(r),t.o.tabindex&&t.$ed.attr("tabindex",t.o.tabindex),t.$c.is("[placeholder]")&&t.$ed.attr("placeholder",t.$c.attr("placeholder")),t.$c.is("[spellcheck]")&&t.$ed.attr("spellcheck",t.$c.attr("spellcheck")),t.o.resetCss&&t.$ed.addClass(n+"reset-css"),t.o.autogrow||t.$ta.add(t.$ed).css({height:t.height}),t.semanticCode(),t.o.autogrowOnEnter&&t.$ed.addClass(n+"autogrow-on-enter");var i,a=!1,s=!1;t.$ed.on("dblclick","img",t.o.imgDblClickHandler).on("keydown",function(e){if((e.ctrlKey||e.metaKey)&&!e.altKey){a=!0;var n=t.keys[String.fromCharCode(e.which).toUpperCase()];try{return t.execCmd(n.fn,n.param),!1}catch(t){}}}).on("compositionstart compositionupdate",function(){s=!0}).on("keyup compositionend",function(e){if("compositionend"===e.type)s=!1;else if(s)return;var n=e.which;if(!(n>=37&&n<=40)){if(!e.ctrlKey&&!e.metaKey||89!==n&&90!==n)if(a||17===n)void 0===e.which&&t.semanticCode(!1,!1,!0);else{var o=!t.isIE||"compositionend"===e.type;t.semanticCode(!1,o&&13===n),t.$c.trigger("tbwchange")}else t.semanticCode(!1,!0),t.$c.trigger("tbwchange");setTimeout(function(){a=!1},50)}}).on("mouseup keydown keyup",function(e){(!e.ctrlKey&&!e.metaKey||e.altKey)&&setTimeout(function(){a=!1},50),clearTimeout(i),i=setTimeout(function(){t.updateButtonPaneStatus()},50)}).on("focus blur",function(e){if(t.$c.trigger("tbw"+e.type),"blur"===e.type&&o("."+n+"active-button",t.$btnPane).removeClass(n+"active-button "+n+"active"),t.o.autogrowOnEnter){if(t.autogrowOnEnterDontClose)return;"focus"===e.type?(t.autogrowOnEnterWasFocused=!0,t.autogrowEditorOnEnter()):t.o.autogrow||(t.$ed.css({height:t.$ed.css("min-height")}),t.$c.trigger("tbwresize"))}}).on("cut drop",function(){setTimeout(function(){t.semanticCode(!1,!0),t.$c.trigger("tbwchange")},0)}).on("paste",function(n){if(t.o.removeformatPasted){n.preventDefault(),e.getSelection&&e.getSelection().deleteFromDocument&&e.getSelection().deleteFromDocument();try{var r=e.clipboardData.getData("Text");try{t.doc.selection.createRange().pasteHTML(r)}catch(e){t.doc.getSelection().getRangeAt(0).insertNode(t.doc.createTextNode(r))}t.$c.trigger("tbwchange",n)}catch(e){t.execCmd("insertText",(n.originalEvent||n).clipboardData.getData("text/plain"))}}o.each(t.pasteHandlers,function(t,e){e(n)}),setTimeout(function(){t.semanticCode(!1,!0),t.$c.trigger("tbwpaste",n),t.$c.trigger("tbwchange")},0)}),t.$ta.on("keyup",function(){t.$c.trigger("tbwchange")}).on("paste",function(){setTimeout(function(){t.$c.trigger("tbwchange")},0)}),t.$box.on("keydown",function(e){if(27===e.which&&1===o("."+n+"modal-box",t.$box).length)return t.closeModal(),!1})},autogrowEditorOnEnter:function(){var t=this;t.$ed.removeClass("autogrow-on-enter");var e=t.$ed[0].clientHeight;t.$ed.height("auto");var n=t.$ed[0].scrollHeight;t.$ed.addClass("autogrow-on-enter"),e!==n&&(t.$ed.height(e),setTimeout(function(){t.$ed.css({height:n}),t.$c.trigger("tbwresize")},0))},buildBtnPane:function(){var t=this,e=t.o.prefix,n=t.$btnPane=o("<div/>",{class:e+"button-pane"});o.each(t.o.btns,function(r,i){o.isArray(i)||(i=[i]);var a=o("<div/>",{class:e+"button-group "+(i.indexOf("fullscreen")>=0?e+"right":"")});o.each(i,function(e,n){try{t.isSupportedBtn(n)&&a.append(t.buildBtn(n))}catch(t){}}),a.html().trim().length>0&&n.append(a)}),t.$box.prepend(n)},buildBtn:function(t){var e=this,n=e.o.prefix,r=e.btnsDef[t],i=r.dropdown,a=null==r.hasIcon||r.hasIcon,s=e.lang[t]||t,l=o("<button/>",{type:"button",class:n+t+"-button "+(r.class||"")+(a?"":" "+n+"textual-button"),html:e.hasSvg&&a?'<svg><use xlink:href="'+e.svgPath+"#"+n+(r.ico||t).replace(/([A-Z]+)/g,"-$1").toLowerCase()+'"/></svg>':e.hideButtonTexts?"":r.text||r.title||e.lang[t]||t,title:(r.title||r.text||s)+(r.key?" (Ctrl + "+r.key+")":""),tabindex:-1,mousedown:function(){return i&&!o("."+t+"-"+n+"dropdown",e.$box).is(":hidden")||o("body",e.doc).trigger("mousedown"),!((e.$btnPane.hasClass(n+"disable")||e.$box.hasClass(n+"disabled"))&&!o(this).hasClass(n+"active")&&!o(this).hasClass(n+"not-disable"))&&(e.execCmd((!i?r.fn:"dropdown")||t,r.param||t,r.forceCss),!1)}});if(i){l.addClass(n+"open-dropdown");var c=n+"dropdown",u={class:c+"-"+t+" "+c+" "+n+"fixed-top"};u["data-"+c]=t;var d=o("<div/>",u);o.each(i,function(t,n){e.btnsDef[n]&&e.isSupportedBtn(n)&&d.append(e.buildSubBtn(n))}),e.$box.append(d.hide())}else r.key&&(e.keys[r.key]={fn:r.fn||t,param:r.param||t});return i||(e.tagToButton[(r.tag||t).toLowerCase()]=t),l},buildSubBtn:function(t){var e=this,n=e.o.prefix,r=e.btnsDef[t],i=null==r.hasIcon||r.hasIcon;return r.key&&(e.keys[r.key]={fn:r.fn||t,param:r.param||t}),e.tagToButton[(r.tag||t).toLowerCase()]=t,o("<button/>",{type:"button",class:n+t+"-dropdown-button"+(r.ico?" "+n+r.ico+"-button":""),html:e.hasSvg&&i?'<svg><use xlink:href="'+e.svgPath+"#"+n+(r.ico||t).replace(/([A-Z]+)/g,"-$1").toLowerCase()+'"/></svg>'+(r.text||r.title||e.lang[t]||t):r.text||r.title||e.lang[t]||t,title:r.key?" (Ctrl + "+r.key+")":null,style:r.style||null,mousedown:function(){return o("body",e.doc).trigger("mousedown"),e.execCmd(r.fn||t,r.param||t,r.forceCss),!1}})},isSupportedBtn:function(t){try{return this.btnsDef[t].isSupported()}catch(t){}return!0},buildOverlay:function(){var t=this;return t.$overlay=o("<div/>",{class:t.o.prefix+"overlay"}).appendTo(t.$box),t.$overlay},showOverlay:function(){var t=this;o(e).trigger("scroll"),t.$overlay.fadeIn(200),t.$box.addClass(t.o.prefix+"box-blur")},hideOverlay:function(){var t=this;t.$overlay.fadeOut(50),t.$box.removeClass(t.o.prefix+"box-blur")},fixedBtnPaneEvents:function(){var t=this,n=t.o.fixedFullWidth,r=t.$box;t.o.fixedBtnPane&&(t.isFixed=!1,o(e).on("scroll."+t.eventNamespace+" resize."+t.eventNamespace,function(){if(r){t.syncCode();var i=o(e).scrollTop(),a=r.offset().top+1,s=t.$btnPane,l=s.outerHeight()-2;i-a>0&&i-a-t.height<0?(t.isFixed||(t.isFixed=!0,s.css({position:"fixed",top:0,left:n?"0":"auto",zIndex:7}),o([t.$ta,t.$ed]).css({marginTop:s.height()})),s.css({width:n?"100%":r.width()-1+"px"}),o("."+t.o.prefix+"fixed-top",r).css({position:n?"fixed":"absolute",top:n?l:l+(i-a)+"px",zIndex:15})):t.isFixed&&(t.isFixed=!1,s.removeAttr("style"),o([t.$ta,t.$ed]).css({marginTop:0}),o("."+t.o.prefix+"fixed-top",r).css({position:"absolute",top:l}))}}))},setDisabled:function(t){var e=this,n=e.o.prefix;e.disabled=t,t?e.$ta.attr("disabled",!0):e.$ta.removeAttr("disabled"),e.$box.toggleClass(n+"disabled",t),e.$ed.attr("contenteditable",!t)},destroy:function(){var t=this,n=t.o.prefix;t.isTextarea?t.$box.after(t.$ta.css({height:""}).val(t.html()).removeClass(n+"textarea").show()):t.$box.after(t.$ed.css({height:""}).removeClass(n+"editor").removeAttr("contenteditable").removeAttr("dir").html(t.html()).show()),t.$ed.off("dblclick","img"),t.destroyPlugins(),t.$box.remove(),t.$c.removeData("trumbowyg"),o("body").removeClass(n+"body-fullscreen"),t.$c.trigger("tbwclose"),o(e).off("scroll."+t.eventNamespace+" resize."+t.eventNamespace)},empty:function(){this.$ta.val(""),this.syncCode(!0)},toggle:function(){var t=this,e=t.o.prefix;t.o.autogrowOnEnter&&(t.autogrowOnEnterDontClose=!t.$box.hasClass(e+"editor-hidden")),t.semanticCode(!1,!0),setTimeout(function(){t.doc.activeElement.blur(),t.$box.toggleClass(e+"editor-hidden "+e+"editor-visible"),t.$btnPane.toggleClass(e+"disable"),o("."+e+"viewHTML-button",t.$btnPane).toggleClass(e+"active"),t.$box.hasClass(e+"editor-visible")?t.$ta.attr("tabindex",-1):t.$ta.removeAttr("tabindex"),t.o.autogrowOnEnter&&!t.autogrowOnEnterDontClose&&t.autogrowEditorOnEnter()},0)},dropdown:function(t){var n=this,r=n.doc,i=n.o.prefix,a=o("[data-"+i+"dropdown="+t+"]",n.$box),s=o("."+i+t+"-button",n.$btnPane),l=a.is(":hidden");if(o("body",r).trigger("mousedown"),l){var c=s.offset().left;s.addClass(i+"active"),a.css({position:"absolute",top:s.offset().top-n.$btnPane.offset().top+s.outerHeight(),left:n.o.fixedFullWidth&&n.isFixed?c+"px":c-n.$btnPane.offset().left+"px"}).show(),o(e).trigger("scroll"),o("body",r).on("mousedown."+n.eventNamespace,function(t){a.is(t.target)||(o("."+i+"dropdown",n.$box).hide(),o("."+i+"active",n.$btnPane).removeClass(i+"active"),o("body",r).off("mousedown."+n.eventNamespace))})}},html:function(t){var e=this;return null!=t?(e.$ta.val(t),e.syncCode(!0),e.$c.trigger("tbwchange"),e):e.$ta.val()},syncTextarea:function(){var t=this;t.$ta.val(t.$ed.text().trim().length>0||t.$ed.find(t.o.tagsToKeep.join(",")).length>0?t.$ed.html():"")},syncCode:function(t){var e=this;if(!t&&e.$ed.is(":visible"))e.syncTextarea();else{var n=o("<div>").html(e.$ta.val()),r=o("<div>").append(n);o(e.o.tagsToRemove.join(","),r).remove(),e.$ed.html(r.contents().html())}if(e.o.autogrow&&(e.height=e.$ed.height(),e.height!==e.$ta.css("height")&&(e.$ta.css({height:e.height}),e.$c.trigger("tbwresize"))),e.o.autogrowOnEnter){e.$ed.height("auto");var i=e.autogrowOnEnterWasFocused?e.$ed[0].scrollHeight:e.$ed.css("min-height");i!==e.$ta.css("height")&&(e.$ed.css({height:i}),e.$c.trigger("tbwresize"))}},semanticCode:function(t,e,n){var r=this;if(r.saveRange(),r.syncCode(t),r.o.semantic){if(r.semanticTag("b"),r.semanticTag("i"),r.semanticTag("s"),r.semanticTag("strike"),e){var i=r.o.inlineElementsSelector,a=":not("+i+")";r.$ed.contents().filter(function(){return 3===this.nodeType&&this.nodeValue.trim().length>0}).wrap("<span data-tbw/>");var s=function(t){if(0!==t.length){var e=t.nextUntil(a).addBack().wrapAll("<p/>").parent(),n=e.nextAll(i).first();e.next("br").remove(),s(n)}};s(r.$ed.children(i).first()),r.semanticTag("div",!0),r.$ed.find("p").filter(function(){return(!r.range||this!==r.range.startContainer)&&(0===o(this).text().trim().length&&0===o(this).children().not("br,span").length)}).contents().unwrap(),o("[data-tbw]",r.$ed).contents().unwrap(),r.$ed.find("p:empty").remove()}n||r.restoreRange(),r.syncTextarea()}},semanticTag:function(t,e){var n;if(null!=this.o.semantic&&"object"==typeof this.o.semantic&&this.o.semantic.hasOwnProperty(t))n=this.o.semantic[t];else{if(!0!==this.o.semantic||!this.DEFAULT_SEMANTIC_MAP.hasOwnProperty(t))return;n=this.DEFAULT_SEMANTIC_MAP[t]}o(t,this.$ed).each(function(){var t=o(this);if(0===t.contents().length)return!1;t.wrap("<"+n+"/>"),e&&o.each(t.prop("attributes"),function(){t.parent().attr(this.name,this.value)}),t.contents().unwrap()})},createLink:function(){for(var t,e,n,r=this,i=r.doc.getSelection(),a=i.focusNode,s=(new XMLSerializer).serializeToString(i.getRangeAt(0).cloneContents());["A","DIV"].indexOf(a.nodeName)<0;)a=a.parentNode;if(a&&"A"===a.nodeName){var l=o(a);s=l.text(),t=l.attr("href"),r.o.minimalLinks||(e=l.attr("title"),n=l.attr("target"));var c=r.doc.createRange();c.selectNode(a),i.removeAllRanges(),i.addRange(c)}r.saveRange();var u={url:{label:"URL",required:!0,value:t},text:{label:r.lang.text,value:s}};r.o.minimalLinks||Object.assign(u,{title:{label:r.lang.title,value:e},target:{label:r.lang.target,value:n}}),r.openModalInsert(r.lang.createLink,u,function(t){var e=r.prependUrlPrefix(t.url);if(!e.length)return!1;var n=o(['<a href="',e,'">',t.text||t.url,"</a>"].join(""));return r.o.minimalLinks||(t.title.length>0&&n.attr("title",t.title),t.target.length>0&&n.attr("target",t.target)),r.range.deleteContents(),r.range.insertNode(n[0]),r.syncCode(),r.$c.trigger("tbwchange"),!0})},prependUrlPrefix:function(t){if(!this.urlPrefix)return t;if(/^([a-z][-+.a-z0-9]*:|\/|#)/i.test(t))return t;return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?"mailto:"+t:this.urlPrefix+t},unlink:function(){var t=this,e=t.doc.getSelection(),n=e.focusNode;if(e.isCollapsed){for(;["A","DIV"].indexOf(n.nodeName)<0;)n=n.parentNode;if(n&&"A"===n.nodeName){var o=t.doc.createRange();o.selectNode(n),e.removeAllRanges(),e.addRange(o)}}t.execCmd("unlink",void 0,void 0,!0)},insertImage:function(){var t=this;t.saveRange();var e={url:{label:"URL",required:!0},alt:{label:t.lang.description,value:t.getRangeText()}};t.o.imageWidthModalEdit&&(e.width={}),t.openModalInsert(t.lang.insertImage,e,function(e){t.execCmd("insertImage",e.url,!1,!0);var n=o('img[src="'+e.url+'"]:not([alt])',t.$box);return n.attr("alt",e.alt),t.o.imageWidthModalEdit&&n.attr({width:e.width}),t.syncCode(),t.$c.trigger("tbwchange"),!0})},fullscreen:function(){var t,n=this,r=n.o.prefix,i=r+"fullscreen";n.$box.toggleClass(i),t=n.$box.hasClass(i),o("body").toggleClass(r+"body-fullscreen",t),o(e).trigger("scroll"),n.$c.trigger("tbw"+(t?"open":"close")+"fullscreen")},execCmd:function(t,e,n,o){var r=this;o=!!o||"","dropdown"!==t&&r.$ed.focus();try{r.doc.execCommand("styleWithCSS",!1,n||!1)}catch(t){}try{r[t+o](e)}catch(n){try{t(e)}catch(n){"insertHorizontalRule"===t?e=void 0:"formatBlock"===t&&r.isIE&&(e="<"+e+">"),r.doc.execCommand(t,!1,e),r.syncCode(),r.semanticCode(!1,!0)}"dropdown"!==t&&(r.updateButtonPaneStatus(),r.$c.trigger("tbwchange"))}},openModal:function(t,n){var r=this,i=r.o.prefix;if(o("."+i+"modal-box",r.$box).length>0)return!1;r.o.autogrowOnEnter&&(r.autogrowOnEnterDontClose=!0),r.saveRange(),r.showOverlay(),r.$btnPane.addClass(i+"disable");var a=o("<div/>",{class:i+"modal "+i+"fixed-top"}).css({top:r.$box.offset().top+r.$btnPane.height(),zIndex:99999}).appendTo(o(r.doc.body));r.$overlay.one("click",function(){return a.trigger("tbwcancel"),!1});var s=o("<form/>",{action:"",html:n}).on("submit",function(){return a.trigger("tbwconfirm"),!1}).on("reset",function(){return a.trigger("tbwcancel"),!1}).on("submit reset",function(){r.o.autogrowOnEnter&&(r.autogrowOnEnterDontClose=!1)}),l=o("<div/>",{class:i+"modal-box",html:s}).css({top:"-"+r.$btnPane.outerHeight()+"px",opacity:0}).appendTo(a).animate({top:0,opacity:1},100);return o("<span/>",{text:t,class:i+"modal-title"}).prependTo(l),a.height(l.outerHeight()+10),o("input:first",l).focus(),r.buildModalBtn("submit",l),r.buildModalBtn("reset",l),o(e).trigger("scroll"),a},buildModalBtn:function(t,e){var n=this.o.prefix;return o("<button/>",{class:n+"modal-button "+n+"modal-"+t,type:t,text:this.lang[t]||t}).appendTo(o("form",e))},closeModal:function(){var t=this,e=t.o.prefix;t.$btnPane.removeClass(e+"disable"),t.$overlay.off();var r=o("."+e+"modal-box",o(n.body));r.animate({top:"-"+r.height()},100,function(){r.parent().remove(),t.hideOverlay()}),t.restoreRange()},openModalInsert:function(t,e,n){var r=this,i=r.o.prefix,a=r.lang,s="";return o.each(e,function(t,e){var n=e.label||t,o=e.name||t,r=e.attributes||{},l=Object.keys(r).map(function(t){return t+'="'+r[t]+'"'}).join(" ");s+='<label><input type="'+(e.type||"text")+'" name="'+o+'"'+("checkbox"===e.type&&e.value?' checked="checked"':' value="'+(e.value||"").replace(/"/g,"""))+'"'+l+'><span class="'+i+'input-infos"><span>'+(a[n]?a[n]:n)+"</span></span></label>"}),r.openModal(t,s).on("tbwconfirm",function(){var t=o("form",o(this)),i=!0,a={};o.each(e,function(e,n){var s=n.name||e,l=o('input[name="'+s+'"]',t);switch(l.attr("type").toLowerCase()){case"checkbox":a[s]=l.is(":checked");break;case"radio":a[s]=l.filter(":checked").val();break;default:a[s]=o.trim(l.val())}n.required&&""===a[s]?(i=!1,r.addErrorOnModalField(l,r.lang.required)):n.pattern&&!n.pattern.test(a[s])&&(i=!1,r.addErrorOnModalField(l,n.patternError))}),i&&(r.restoreRange(),n(a,e)&&(r.syncCode(),r.$c.trigger("tbwchange"),r.closeModal(),o(this).off("tbwconfirm")))}).one("tbwcancel",function(){o(this).off("tbwconfirm"),r.closeModal()})},addErrorOnModalField:function(t,e){var n=this.o.prefix,r=t.parent();t.on("change keyup",function(){r.removeClass(n+"input-error")}),r.addClass(n+"input-error").find("input+span").append(o("<span/>",{class:n+"msg-error",text:e}))},getDefaultImgDblClickHandler:function(){var t=this;return function(){var e=o(this),n=e.attr("src");0===n.indexOf("data:image")&&(n="(Base64)");var r={url:{label:"URL",value:n,required:!0},alt:{label:t.lang.description,value:e.attr("alt")}};return t.o.imageWidthModalEdit&&(r.width={value:e.attr("width")?e.attr("width"):""}),t.openModalInsert(t.lang.insertImage,r,function(n){return"(Base64)"!==n.url&&e.attr({src:n.url}),e.attr({alt:n.alt}),t.o.imageWidthModalEdit&&(parseInt(n.width)>0?e.attr({width:n.width}):e.removeAttr("width")),!0}),!1}},saveRange:function(){var t=this,e=t.doc.getSelection();if(t.range=null,e&&e.rangeCount){var n,o=t.range=e.getRangeAt(0),r=t.doc.createRange();r.selectNodeContents(t.$ed[0]),r.setEnd(o.startContainer,o.startOffset),n=(r+"").length,t.metaRange={start:n,end:n+(o+"").length}}},restoreRange:function(){var t,e=this,n=e.metaRange,o=e.range,r=e.doc.getSelection();if(o){if(n&&n.start!==n.end){var i,a=0,s=[e.$ed[0]],l=!1,c=!1;for(t=e.doc.createRange();!c&&(i=s.pop());)if(3===i.nodeType){var u=a+i.length;!l&&n.start>=a&&n.start<=u&&(t.setStart(i,n.start-a),l=!0),l&&n.end>=a&&n.end<=u&&(t.setEnd(i,n.end-a),c=!0),a=u}else for(var d=i.childNodes,f=d.length;f>0;)f-=1,s.push(d[f])}r.removeAllRanges(),r.addRange(t||o)}},getRangeText:function(){return this.range+""},updateButtonPaneStatus:function(){var t=this,e=t.o.prefix,n=t.getTagsRecursive(t.doc.getSelection().focusNode),r=e+"active-button "+e+"active";o("."+e+"active-button",t.$btnPane).removeClass(r),o.each(n,function(n,i){var a=t.tagToButton[i.toLowerCase()],s=o("."+e+a+"-button",t.$btnPane);if(s.length>0)s.addClass(r);else try{var l=(s=o("."+e+"dropdown ."+e+a+"-dropdown-button",t.$box)).parent().data("dropdown");o("."+e+l+"-button",t.$box).addClass(r)}catch(t){}})},getTagsRecursive:function(t,e){var n=this;if(e=e||(t&&t.tagName?[t.tagName]:[]),!t||!t.parentNode)return e;var r=(t=t.parentNode).tagName;return"DIV"===r?e:("P"===r&&""!==t.style.textAlign&&e.push(t.style.textAlign),o.each(n.tagHandlers,function(o,r){e=e.concat(r(t,n))}),e.push(r),n.getTagsRecursive(t,e).filter(function(t){return null!=t}))},initPlugins:function(){var t=this;t.loadedPlugins=[],o.each(o.trumbowyg.plugins,function(e,n){n.shouldInit&&!n.shouldInit(t)||(n.init(t),n.tagHandler&&t.tagHandlers.push(n.tagHandler),t.loadedPlugins.push(n))})},destroyPlugins:function(){o.each(this.loadedPlugins,function(t,e){e.destroy&&e.destroy()})}}}(navigator,window,document,jQuery)},yLpj:function(t,e){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(t){"object"==typeof window&&(n=window)}t.exports=n}}); |
// Prevent Carousel from pausing on mouseover
$('.carousel').carousel({
pause: "false"
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The String.prototype.concat.length property has the attribute DontEnum
es5id: 15.5.4.6_A8
description: >
Checking if enumerating the String.prototype.concat.length
property fails
---*/
//////////////////////////////////////////////////////////////////////////////
//CHECK#0
if (!(String.prototype.concat.hasOwnProperty('length'))) {
throw new Test262Error('#0: String.prototype.concat.hasOwnProperty(\'length\') return true. Actual: ' + String.prototype.concat.hasOwnProperty('length'));
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// CHECK#1
if (String.prototype.concat.propertyIsEnumerable('length')) {
throw new Test262Error('#1: String.prototype.concat.propertyIsEnumerable(\'length\') return false. Actual: ' + String.prototype.concat.propertyIsEnumerable('length'));
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// CHECK#2
var count = 0;
for (var p in String.prototype.concat) {
if (p === "length") count++;
}
if (count !== 0) {
throw new Test262Error('#2: count = 0; for (p in String.prototype.concat){ if (p==="length") count++;}; count === 0. Actual: ' + count);
}
//
//////////////////////////////////////////////////////////////////////////////
|
##########################################################################
#
# Copyright (c) 2013-2014, John Haddon. 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.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# 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 OWNER 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.
#
##########################################################################
import IECore
import Gaffer
import GafferUI
import GafferOSL
##########################################################################
# Metadata. We register dynamic Gaffer.Metadata entries which are
# implemented as queries to the OSL metadata held within the shader.
##########################################################################
def __nodeDescription( node ) :
__defaultDescription = """Loads OSL shaders for use in supported renderers. Use the ShaderAssignment node to assign shaders to objects in the scene."""
description = node.shaderMetadata( "help" )
return description or __defaultDescription
def __plugDescription( plug ) :
return plug.node().parameterMetadata( plug, "help" ) or ""
def __plugLabel( plug ) :
return plug.node().parameterMetadata( plug, "label" )
def __plugDivider( plug ) :
return plug.node().parameterMetadata( plug, "divider" ) or False
def __plugPresetNames( plug ) :
options = plug.node().parameterMetadata( plug, "options" )
if not options :
return None
return IECore.StringVectorData( [ o.partition( ":" )[0] for o in options.split( "|" ) ] )
def __plugPresetValues( plug ) :
options = plug.node().parameterMetadata( plug, "options" )
if not options :
return None
values = [ o.rpartition( ":" )[2] for o in options.split( "|" ) ]
if isinstance( plug, Gaffer.StringPlug ) :
return IECore.StringVectorData( values )
elif isinstance( plug, Gaffer.IntPlug ) :
return IECore.IntVectorData( [ int( v ) for v in values ] )
elif isinstance( plug, Gaffer.FloatPlug ) :
return IECore.FloatVectorData( [ float( v ) for v in values ] )
return None
__widgetTypes = {
"number" : "GafferUI.NumericPlugValueWidget",
"string" : "GafferUI.StringPlugValueWidget",
"boolean" : "GafferUI.BoolPlugValueWidget",
"checkBox" : "GafferUI.BoolPlugValueWidget",
"popup" : "GafferUI.PresetsPlugValueWidget",
"mapper" : "GafferUI.PresetsPlugValueWidget",
"filename" : "GafferUI.PathPlugValueWidget",
"null" : "None",
}
def __plugWidgetType( plug ) :
return __widgetTypes.get(
plug.node().parameterMetadata( plug, "widget" )
)
Gaffer.Metadata.registerNodeDescription( GafferOSL.OSLShader, __nodeDescription )
Gaffer.Metadata.registerPlugDescription( GafferOSL.OSLShader, "parameters.*", __plugDescription )
Gaffer.Metadata.registerPlugValue( GafferOSL.OSLShader, "parameters.*", "label", __plugLabel )
Gaffer.Metadata.registerPlugValue( GafferOSL.OSLShader, "parameters.*", "divider", __plugDivider )
Gaffer.Metadata.registerPlugValue( GafferOSL.OSLShader, "parameters.*", "presetNames", __plugPresetNames )
Gaffer.Metadata.registerPlugValue( GafferOSL.OSLShader, "parameters.*", "presetValues", __plugPresetValues )
Gaffer.Metadata.registerPlugValue( GafferOSL.OSLShader, "parameters.*", "layout:widgetType", __plugWidgetType )
##########################################################################
# Nodules
##########################################################################
def __outPlugNoduleCreator( plug ) :
if isinstance( plug, Gaffer.CompoundPlug ) :
return GafferUI.CompoundNodule( plug, GafferUI.LinearContainer.Orientation.Y, spacing = 0.2 )
else :
return GafferUI.StandardNodule( plug )
GafferUI.Nodule.registerNodule( GafferOSL.OSLShader, "out", __outPlugNoduleCreator )
|
export const apiMerchant = 'https://website-service-dot-autoketing-production-api-v1.appspot.com';
export const apiSubmitTicket = 'https://website-service-dot-autoketing-production-api-v1.appspot.com/create-ticket';
|
# -*- coding: utf-8 -*-
from odoo import models, fields, api
class RegistrationEditor(models.TransientModel):
_name = "registration.editor"
_description = 'Edit Attendee Details on Sales Confirmation'
sale_order_id = fields.Many2one('sale.order', 'Sales Order', required=True, ondelete='cascade')
event_registration_ids = fields.One2many('registration.editor.line', 'editor_id', string='Registrations to Edit')
@api.model
def default_get(self, fields):
res = super(RegistrationEditor, self).default_get(fields)
if not res.get('sale_order_id'):
sale_order_id = res.get('sale_order_id', self._context.get('active_id'))
res['sale_order_id'] = sale_order_id
sale_order = self.env['sale.order'].browse(res.get('sale_order_id'))
registrations = self.env['event.registration'].search([
('sale_order_id', '=', sale_order.id),
('event_ticket_id', 'in', sale_order.mapped('order_line.event_ticket_id').ids),
('state', '!=', 'cancel')])
attendee_list = []
for so_line in [l for l in sale_order.order_line if l.event_ticket_id]:
existing_registrations = [r for r in registrations if r.event_ticket_id == so_line.event_ticket_id]
for reg in existing_registrations:
attendee_list.append([0, 0, {
'event_id': reg.event_id.id,
'event_ticket_id': reg.event_ticket_id.id,
'registration_id': reg.id,
'name': reg.name,
'email': reg.email,
'phone': reg.phone,
'mobile': reg.mobile,
'sale_order_line_id': so_line.id,
}])
for count in range(int(so_line.product_uom_qty) - len(existing_registrations)):
attendee_list.append([0, 0, {
'event_id': so_line.event_id.id,
'event_ticket_id': so_line.event_ticket_id.id,
'sale_order_line_id': so_line.id,
'name': so_line.order_partner_id.name,
'email': so_line.order_partner_id.email,
'phone': so_line.order_partner_id.phone,
'mobile': so_line.order_partner_id.mobile,
}])
res['event_registration_ids'] = attendee_list
res = self._convert_to_write(res)
return res
def action_make_registration(self):
self.ensure_one()
registrations_to_create = []
for registration_line in self.event_registration_ids:
values = registration_line.get_registration_data()
if registration_line.registration_id:
registration_line.registration_id.write(values)
else:
registrations_to_create.append(values)
self.env['event.registration'].create(registrations_to_create)
self.sale_order_id.order_line._update_registrations(confirm=self.sale_order_id.amount_total == 0)
return {'type': 'ir.actions.act_window_close'}
class RegistrationEditorLine(models.TransientModel):
"""Event Registration"""
_name = "registration.editor.line"
_description = 'Edit Attendee Line on Sales Confirmation'
_order = "id desc"
editor_id = fields.Many2one('registration.editor')
sale_order_line_id = fields.Many2one('sale.order.line', string='Sales Order Line')
event_id = fields.Many2one('event.event', string='Event', required=True)
registration_id = fields.Many2one('event.registration', 'Original Registration')
event_ticket_id = fields.Many2one('event.event.ticket', string='Event Ticket')
email = fields.Char(string='Email')
phone = fields.Char(string='Phone')
mobile = fields.Char(string='Mobile')
name = fields.Char(string='Name', index=True)
def get_registration_data(self):
self.ensure_one()
return {
'event_id': self.event_id.id,
'event_ticket_id': self.event_ticket_id.id,
'partner_id': self.editor_id.sale_order_id.partner_id.id,
'name': self.name or self.editor_id.sale_order_id.partner_id.name,
'phone': self.phone or self.editor_id.sale_order_id.partner_id.phone,
'mobile': self.mobile or self.editor_id.sale_order_id.partner_id.mobile,
'email': self.email or self.editor_id.sale_order_id.partner_id.email,
'sale_order_id': self.editor_id.sale_order_id.id,
'sale_order_line_id': self.sale_order_line_id.id,
}
|
import numpy as np
import numba as nb
# Reimplementing DynaMax Jaccard in Numba to enable parallelilization and single
# execution speed ups of factor 6
@nb.njit
def np_max(arr, axis):
"""
Workaround for np.max along axis in Numba.
Credits to: https://github.com/numba/numba/issues/1269#issuecomment-472574352
:param arr np.ndarray: stacked word embeddings
:param axis int: axis for whichto get maximum
"""
assert arr.ndim == 2
assert axis in [0, 1]
if axis == 0:
result = np.empty(arr.shape[1])
for i in range(len(result)):
result[i] = np.max(arr[:, i])
else:
result = np.empty(arr.shape[0])
for i in range(len(result)):
result[i] = np.max(arr[i, :])
return result
@nb.njit
def fuzzify(s, u):
"""
Sentence fuzzifier.
Computes membership vector for the sentence S with respect to the
universe U
:param s: list of word embeddings for the sentence
:param u: the universe matrix U with shape (K, d)
:return: membership vectors for the sentence
"""
f_s = s @ u.T
m_s = np_max(f_s, axis=0)
m_s = np.maximum(m_s, 0, m_s)
return m_s
@nb.njit(fastmath=True)
def dynamax_jaccard(x, y):
"""
DynaMax-Jaccard similarity measure between two sentences
Credits to:
-- Title: Don't Settle for Average, Go for the Max: Fuzzy Sets and Max-Pooled Word Vectors
-- Authors: Vitalii Zhelezniak, Aleksandar Savkov, April Shen, Francesco Moramarco, Jack Flann, Nils Y. Hammerla
-- Published: ICLR 2019
-- Paper: https://arxiv.org/pdf/1904.13264.pdf
-- Github: https://github.com/babylonhealth/fuzzymax
:param x: list of word embeddings for the first sentence
:param y: list of word embeddings for the second sentence
:return: similarity score between the two sentences
"""
# feature generation
u = np.vstack((x, y))
m_x = fuzzify(x, u)
m_y = fuzzify(y, u)
# fuzzy jaccard
m_inter = np.sum(np.minimum(m_x, m_y))
m_union = np.sum(np.maximum(m_x, m_y))
return m_inter / m_union
|
# coding=utf-8
from ._base import manager
|
//
// jQuery Slug Generation Plugin by Perry Trinier ([email protected])
// Licensed under the GPL: http://www.gnu.org/copyleft/gpl.html
jQuery.fn.slug = function (options) {
var settings = {
slug: 'slug', // Class used for slug destination input and span. The span is created on $(document).ready()
hide: true, // Boolean - By default the slug input field is hidden, set to false to show the input field and hide the span.
override: false
};
if (options) {
jQuery.extend(settings, options);
}
$this = jQuery(this);
jQuery(document).ready(function () {
if (settings.hide) {
jQuery('input.' + settings.slug).after("<span class=" + settings.slug + "></span>");
jQuery('input.' + settings.slug).hide();
}
});
makeSlug = function () {
var slugcontent = $this.val();
var slugcontent_hyphens = slugcontent.replace(/\s/g, '-');
var slug_no_accents = normalize(slugcontent_hyphens);
var finishedslug = slug_no_accents.replace(/[^a-zA-Z0-9\-]/g, '');
jQuery('input.' + settings.slug).val(finishedslug.toLowerCase());
jQuery('span.' + settings.slug).text(finishedslug.toLowerCase());
}
normalize = function(string) {
var defaultDiacriticsRemovalMap = [
{'base':'A', 'letters':/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g},
{'base':'AA','letters':/[\uA732]/g},
{'base':'AE','letters':/[\u00C6\u01FC\u01E2]/g},
{'base':'AO','letters':/[\uA734]/g},
{'base':'AU','letters':/[\uA736]/g},
{'base':'AV','letters':/[\uA738\uA73A]/g},
{'base':'AY','letters':/[\uA73C]/g},
{'base':'B', 'letters':/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g},
{'base':'C', 'letters':/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g},
{'base':'D', 'letters':/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g},
{'base':'DZ','letters':/[\u01F1\u01C4]/g},
{'base':'Dz','letters':/[\u01F2\u01C5]/g},
{'base':'E', 'letters':/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g},
{'base':'F', 'letters':/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g},
{'base':'G', 'letters':/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g},
{'base':'H', 'letters':/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g},
{'base':'I', 'letters':/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g},
{'base':'J', 'letters':/[\u004A\u24BF\uFF2A\u0134\u0248]/g},
{'base':'K', 'letters':/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g},
{'base':'L', 'letters':/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g},
{'base':'LJ','letters':/[\u01C7]/g},
{'base':'Lj','letters':/[\u01C8]/g},
{'base':'M', 'letters':/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g},
{'base':'N', 'letters':/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g},
{'base':'NJ','letters':/[\u01CA]/g},
{'base':'Nj','letters':/[\u01CB]/g},
{'base':'O', 'letters':/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g},
{'base':'OI','letters':/[\u01A2]/g},
{'base':'OO','letters':/[\uA74E]/g},
{'base':'OU','letters':/[\u0222]/g},
{'base':'P', 'letters':/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g},
{'base':'Q', 'letters':/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g},
{'base':'R', 'letters':/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g},
{'base':'S', 'letters':/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g},
{'base':'T', 'letters':/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g},
{'base':'TZ','letters':/[\uA728]/g},
{'base':'U', 'letters':/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g},
{'base':'V', 'letters':/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g},
{'base':'VY','letters':/[\uA760]/g},
{'base':'W', 'letters':/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g},
{'base':'X', 'letters':/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g},
{'base':'Y', 'letters':/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g},
{'base':'Z', 'letters':/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g},
{'base':'a', 'letters':/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g},
{'base':'aa','letters':/[\uA733]/g},
{'base':'ae','letters':/[\u00E6\u01FD\u01E3]/g},
{'base':'ao','letters':/[\uA735]/g},
{'base':'au','letters':/[\uA737]/g},
{'base':'av','letters':/[\uA739\uA73B]/g},
{'base':'ay','letters':/[\uA73D]/g},
{'base':'b', 'letters':/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g},
{'base':'c', 'letters':/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g},
{'base':'d', 'letters':/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g},
{'base':'dz','letters':/[\u01F3\u01C6]/g},
{'base':'e', 'letters':/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g},
{'base':'f', 'letters':/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g},
{'base':'g', 'letters':/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g},
{'base':'h', 'letters':/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g},
{'base':'hv','letters':/[\u0195]/g},
{'base':'i', 'letters':/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g},
{'base':'j', 'letters':/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g},
{'base':'k', 'letters':/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g},
{'base':'l', 'letters':/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g},
{'base':'lj','letters':/[\u01C9]/g},
{'base':'m', 'letters':/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g},
{'base':'n', 'letters':/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g},
{'base':'nj','letters':/[\u01CC]/g},
{'base':'o', 'letters':/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g},
{'base':'oi','letters':/[\u01A3]/g},
{'base':'ou','letters':/[\u0223]/g},
{'base':'oo','letters':/[\uA74F]/g},
{'base':'p','letters':/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g},
{'base':'q','letters':/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g},
{'base':'r','letters':/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g},
{'base':'s','letters':/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g},
{'base':'t','letters':/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g},
{'base':'tz','letters':/[\uA729]/g},
{'base':'u','letters':/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g},
{'base':'v','letters':/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g},
{'base':'vy','letters':/[\uA761]/g},
{'base':'w','letters':/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g},
{'base':'x','letters':/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g},
{'base':'y','letters':/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g},
{'base':'z','letters':/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g}
];
for(var i=0; i<defaultDiacriticsRemovalMap.length; i++) {
string = string.replace(defaultDiacriticsRemovalMap[i].letters, defaultDiacriticsRemovalMap[i].base);
}
return string;
}
jQuery(this).keyup(makeSlug);
return $this;
};
|
{
"tagName": "div",
"id": "checklist-form",
"className": "checklist-form-t2",
"template": _.template(`
<fieldset>
<div class="form-group">
<label for="inputTransportadora" class="col-sm-3 control-label">Frota</label>
<div class="col-sm-3">
<select name="grupo_id" class="form-control" id="inputTransportadora">
<option value="0">Selecionar...</option>
<% view.get('gruposKit').each (function (frota) { %>
<option value="<%= frota.get('id') %>"><%= frota.get('nome').toString().toUpperCase() %></option>
<% }); %>
</select>
</div>
<label for="inputOutroGrupo" class="col-sm-3 control-label">Região Leiteira</label>
<div class="col-sm-3">
<select name="outro_grupo_id" class="form-control" id="inputOutroGrupo">
<option value="0">Selecionar...</option>
<% view.get('regioesKit').each (function (frota) { %>
<option value="<%= frota.get('id') %>"><%= frota.get('nome').toString().toUpperCase() %></option>
<% }); %>
</select>
</div>
</div>
</fieldset>
<fieldset><div class="form-group">
<label for="inputVinculo" class="col-sm-3 control-label">Vínculo</label>
<div class="col-sm-3"><select name="dados[vinculo]" class="form-control" id="inputVinculo">
<% _(["Selecionar...", "Frota", "Agregado", "CIF"]).each (function (vinculo, i) { %><option <% print (i==view.attributes.vinculo?"selected":"") %> value="<%= i %>"><%= vinculo %></option>
<% }); %>
</select>
</div>
<label class="col-sm-3 control-label">Data
</label>
<div class="col-sm-3">
<div class="input-group date"><input name="data" class="form-control" type="text" placeholder="YYYY-MM-DD" value="<%=view.attributes.data%>" readonly><span class="input-group-addon"><i class="fa fa-fw fa-calendar"></i></span></div>
</div>
</div></fieldset>
<fieldset><div class="form-group">
<label for="nome_motorista" class="col-sm-3 control-label">Motorista</label>
<div class="col-sm-3"><input id="nome_motorista" name="dados[nome_motorista]" class="form-control" type="text" value="<%=view.attributes.nome_motorista%>"></div>
<label for="cpf_motorista" class="col-sm-3 control-label">CPF</label>
<div class="col-sm-3"><input id="dados[cpf_motorista]" name="dados[cpf_motorista]" class="form-control" type="text" value="<%=view.attributes.cpf_motorista%>"></div>
</div></fieldset>
<fieldset class="if-cnpj"><div class="form-group">
<label class="col-sm-3 control-label">Razão Social
</label>
<div class="col-sm-3"><input name="dados[razao_motorista]" class="form-control" type="text" value="<%= view.attributes.razao_motorista %>">
</div>
<label class="col-sm-3 control-label">CNPJ
</label>
<div class="col-sm-3"><input name="dados[cnpj_motorista]" class="form-control" type="text" value="<%= view.attributes.cnpj_motorista %>">
</div>
</div></fieldset>
<fieldset>
<div class="form-group">
<label for="selectConfiguracao" class="col-sm-3 control-label">Configuração</label>
<div class="col-sm-3">
<select class="form-control" name="dados[configuracao]" id="selectConfiguracao">
<% _(["Selecionar...", "Caminhão", "Caminhão e Reboque", "Bitrem", "Vanderléia", "Rodotrem", "Reboque", "Semirreboque"]).each (function (vinculo, i) { %>
<option <%= (i === parseInt(view.attributes.configuracao) ? "selected" : "") %> value="<%= i %>"><%= vinculo %></option>
<% }); %>
</select>
</div>
</div>
</fieldset>
<% var autocategorias = new Backbone.Collection([{"id":5,"autocategoria":"CAMINHÃO SIMPLES"},{"id":11,"autocategoria":"CAMINHÃO TRUCK"},{"id":12,"autocategoria":"CAMINHÃO DIRECIONAL"},{"id":6,"autocategoria":"CAMINHÃO TRATOR"},{"id":8,"autocategoria":"SEMIRREBOQUE"},{"id":9,"autocategoria":"SEMIRREBOQUE LS"},{"id":10,"autocategoria":"REBOQUE"}]); %>
<% var _this = this; _.each (view.get('placas'), function (placa, i) { %>
<fieldset><div class="form-group">
<label for="placas[<%= i %>]" class="col-sm-3 control-label">Placa</label>
<div class="col-sm-3"><input class="form-control" type="text" id="placas[<%= i %>]" name="placas[<%= i %>]" value="<%= placa.placa %>"><p class="help-block">Placa Veículo</p></div>
<div class="col-sm-3"><input class="form-control" type="text" name="numeros[<%= i %>]" value="<%= placa.pivot.numero %>"><p class="help-block">Número Frota</p></div>
<div class="col-sm-3">
<select class="form-control autocategorias" name="categorias[<%= i %>]">
<option value="0">Selecionar...</option>
<% autocategorias.each(function (vinculo) { %>
<option <%= (placa.pivot.autocategoria_id && vinculo.get('id') === parseInt(placa.pivot.autocategoria_id) ? "selected" : "") %> value="<%= vinculo.get('id') %>"><%= vinculo.get('autocategoria') %></option>
<% }); %>
</select>
<p class="help-block">Categoria Veículo</p>
</div>
</div></fieldset>
<% }); %>
<fieldset>
<div class="form-group"><div class="col-sm-3 col-sm-offset-9"><a href="#" class="btn btn-default btn-sm" id="incluirPlaca"><i class="fa fa-fw fa-plus"></i> Incluir placa</a></div></div>
</fieldset>
<div class="form-group">
<label for="origem_uf" class="col-sm-3 control-label">Origem</label>
<div class="col-sm-3">
<select name="dados[origem_uf]" class="form-control ufs" id="origem_uf">
<option value="0">Selecionar...</option>
<% view.get('subdistritosCol').each(function (subdistrito, i) { %>
<option <%= (subdistrito.get('uf') === parseInt(view.attributes.origem_uf) ? "selected" : "") %> value="<%= subdistrito.get('uf') %>"><%= subdistrito.get('nome_uf') %></option>
<% }); %>
</select>
</div>
<label for="origem_id" class="col-sm-3 control-label">Localidade</label>
<div class="col-sm-3">
<select name="dados[origem_id]" class="form-control" id="origem_id">
<option value="0">Selecionar...</option>
<% if (view.get('subdistritosCol.' + view.attributes.origem_uf)) { %>
<% view.get('subdistritosCol.'+view.attributes.origem_uf).each(function (subdistrito, i) { %>
<option <%= (subdistrito.get('codigo_subdistrito') === view.attributes.origem_id ? "selected" : "") %> value="<%= subdistrito.get('codigo_subdistrito') %>"><%= subdistrito.get('nome_distrito') %><%= (subdistrito.get('nome_subdistrito') ? ' — ' + subdistrito.get('nome_subdistrito') : '') %></option>
<% }); } %>
</select>
</div>
</div>
<div class="form-group">
<label for="destino_uf" class="col-sm-3 control-label">Destino</label>
<div class="col-sm-3">
<select name="dados[destino_uf]" class="form-control ufs" id="destino_uf">
<option value="0">Selecionar...</option>
<% view.get('subdistritosCol').each(function (subdistrito, i) { %>
<option <%= (subdistrito.get('uf') === parseInt(view.attributes.destino_uf) ? "selected" : "") %> value="<%= subdistrito.get('uf') %>"><%= subdistrito.get('nome_uf') %></option>
<% }); %>
</select>
</div>
<label for="destino_id" class="col-sm-3 control-label">Localidade</label>
<div class="col-sm-3">
<select name="dados[destino_id]" class="form-control" id="destino_id">
<option value="0">Selecionar...</option>
<% if (view.get('subdistritosCol.' + view.attributes.destino_uf)){ %>
<% view.get('subdistritosCol.' + view.attributes.destino_uf).each(function (subdistrito, i) { %>
<option <%= (subdistrito.get('codigo_subdistrito') === view.attributes.destino_id ? "selected" : "") %> value="<%= subdistrito.get('codigo_subdistrito') %>"><%= subdistrito.get('nome_distrito') %><%= (subdistrito.get('nome_subdistrito') ? ' — ' + subdistrito.get('nome_subdistrito') : '') %></option>
<% }); } %>
</select>
</div>
</div>
<div class="form-group">
<label for="posicao" class="col-sm-3 control-label">Posição atual</label>
<div class="col-sm-3">
<select name="dados[posicao]" class="form-control" id="posicao">
<% _(["Selecionar...", "Origem", "Destino"]).each (function (vinculo, i) { %>
<option <%= (i === parseInt (view.attributes.posicao) ? "selected" : "") %> value="<%= i %>"><%= vinculo %></option>
<% }); %>
</select>
</div>
</div>`,
{"variable": "view"}),
"initialize": function ()
{
try {
this.release();
}
catch (error) {
console.error(error);
}
},
"render": function ()
{
this.$el.html(this.template(this.model)).attr("class", this.className);
return this;
},
} |
import os, sys
while 1:
line = sys.stdin.readline().strip()
if not line:
break
os.close(int(line))
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const bcrypt = require("bcrypt");
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true },
tagId: String,
});
userSchema.pre("save", function save(next) {
const user = this;
if (!user.isModified("password")) {
return next();
}
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, (err, hash) => {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
});
userSchema.methods.comparePassword = function (candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
cb(err, isMatch);
});
};
exports.User = mongoose.model("User", userSchema);
|
/**
* @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper
* @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos
* @license BSD-3-Clause (see LICENSE in the root directory of this source tree)
*/
import {DateTimeException} from '../../../src/errors';
import {Temporal} from '../../../src/temporal/Temporal';
export class EMPTY extends Temporal{
isSupported() {
return true;
}
getLong() {
throw new DateTimeException('Mock');
}
}
|
#! /usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Osman Baskaya"
""" This module finds the semantic classes with respect to
oracle accuracy. Details: The Noisy Channel Paper,
Algorithm 2.
"""
from nltk.corpus import wordnet as wn
import sys
from nlp_utils import fopen, traverse
from collections import defaultdict as dd
from copy import deepcopy
from multiprocessing import Pool
class Semantic_Class(object):
def __init__(self, test_synsets=set(), synset=None):
self.senses = set()
self.lemma_sense = dd(set)
self.synsets = dd(set)
self.synset_set = set()
self.test_synsets = test_synsets
if synset is not None:
self.add_synset(synset)
def has_sense(self, sense):
return sense in self.senses
def has_synset(self, synset):
return synset in self.synset_set
def add_synset(self, synset):
"""Add the synset and its all descendants"""
relation = lambda s: s.hyponyms()
descendants = synset.tree(relation)
for descendant in descendants:
for s in traverse(descendant):
if len(self.test_synsets) == 0 or s in self.test_synsets:
self.synset_set.add(s)
for lemma in s.lemmas:
self.senses.add(lemma.key)
lemma_name = lemma.name.lower()
self.lemma_sense[lemma_name].add(lemma.key)
self.synsets[lemma_name].add(lemma.synset)
def remove_synset(self, synset):
"""Removes the synset and its all descendants"""
#TODO: remove all lemmas and its descendant lemmas from senses set
if self.has_synset(synset):
relation = lambda s: s.hyponyms()
descendants = synset.tree(relation)
for descendant in descendants:
for s in traverse(descendant):
if len(self.test_synsets) == 0 or s in self.test_synsets:
#print "\tremoving: {}".format(s)
if self.has_synset(s):
self.synset_set.remove(s)
for lemma in s.lemmas:
if lemma.name in self.synsets:
#print lemma, lemma.name, lemma.key, lemma.synset
self.senses.remove(lemma.key)
lemma_name = lemma.name.lower()
self.lemma_sense[lemma_name].remove(lemma.key)
self.synsets[lemma_name].remove(lemma.synset)
else:
msg = "Warning: Semantic Class does not have {} synset".format(synset)
print >> sys.stderr, msg
def move_synset_to_another_sm(self, other, synset):
self.remove_synset(synset)
other.add_synset(synset)
#def __str__(self):
#return "\n".join([str(s) for s in self.senses])
def get_synsets_from_key(keys):
lemmas = map(wn.lemma_from_key, keys)
return set([lemma.synset for lemma in lemmas])
def read_all_words(key_file):
with open(key_file) as f:
wi = []
for line in f:
line = line.split()
inst_id = line[1]
word = line[2].split('%')[0]
wi.append((inst_id, word, line[2]))
return wi
def filter_by_pos(wi, pos, aw_file):
t = []
for line in fopen(aw_file):
line = line.split()
t.append((line[0], line[4].lower()[0])) #inst_id, pos-tag
d = dict(t)
return [(inst_id, word, key) for inst_id, word, key in wi if d[inst_id] == pos]
# (word, instance_id, key triple) list
def get_first_sense(lemma_name, sc):
lemma_name = lemma_name.lower()
d = dict([(int(key.split('%')[-1].replace(':', '')), key) \
for key in sc.lemma_sense[lemma_name]])
return d[min(d)]
def calc_oracle_accuracy(sc_list, gold):
tf = [] #true false
for sense in gold:
if sense != 'U':
c = None
for sc in sc_list:
if sc.has_sense(sense):
c = sc
break
assert c is not None, "Error: No semantic class has sense {}".format(sense)
lemma = sense.split('%')[0]
first_sense = get_first_sense(lemma, c)
if first_sense == sense: s = 1
else: s = 0
tf.append(s)
return sum(tf) / float(len(tf))
def _calc(pairs):
#print >> sys.stderr, "\t\tcalculating started"
sc, sc_list, synset, gold = pairs
classes = []
copy_sc = deepcopy(sc)
#print len(copy_sc.senses),
new_sm = Semantic_Class()
copy_sc.move_synset_to_another_sm(new_sm, synset)
#print len(copy_sc.senses)
classes.extend([sclass for sclass in sc_list if sclass is not sc])
classes.append(copy_sc)
classes.append(new_sm)
accuracy = calc_oracle_accuracy(classes, gold)
#print >> sys.stderr, "\t\tcalculating finished"
return (synset, (accuracy, classes))
def find_synset_with_best_accuracy(sc_list, test_synsets, gold):
"""According to oracle accuracy, find the best synset to create a new
semantic class """
pool = Pool(processes=20)
accuracies = dict()
pairs = []
for sc in sc_list:
for synset_sets in sc.synsets.itervalues():
for synset in synset_sets:
if synset in test_synsets:
pairs.append([sc, sc_list, synset, gold])
print >> sys.stderr, "\tProcessing starts. # of semantic class {}".format(len(sc_list))
print >> sys.stderr, "\t{}".format(len(pairs))
result = pool.map(_calc, pairs[:5])
accuracies = dict(result)
key = max(accuracies.iterkeys(), key=lambda x: accuracies[x][0])
return accuracies[key][1], key, accuracies[key][0]
def create_semantic_class(words, pos, test_synsets):
sm = Semantic_Class(test_synsets)
for word in words:
synsets = wn.synsets(word, pos)
for synset in synsets:
sm.add_synset(synset)
return sm
def run():
if len(sys.argv) != 5:
msg = "Usage: {} key_file number_of_semantic_class"
print >> sys.stderr, msg.format(sys.argv[0])
exit(1)
key_file = sys.argv[1]
aw_file = sys.argv[2]
pos = sys.argv[3]
n = int(sys.argv[4]) # number of semantic class we need to create
wik = filter_by_pos(read_all_words(key_file), pos, aw_file)
test_synsets = get_synsets_from_key([t[2] for t in wik if t[2].find('%') != -1])
sc = create_semantic_class([t[1] for t in wik], pos, set())
#sc = create_semantic_class([t[1] for t in wik], pos, test_synsets)
gold = [t[2] for t in wik]
sc_list = [sc,]
scores = []
for i in xrange(n):
print >> sys.stderr, "Epoch %d" % (i+1)
sc_list, sset, score = find_synset_with_best_accuracy (sc_list, test_synsets, gold)
print >> sys.stderr, "\t{}, {}".format(sset, score)
scores.append((len(sc_list), score))
for score in scores:
print score
def test():
sm = Semantic_Class()
air_synsets = wn.synsets('air', 'n')
for air in air_synsets:
sm.add_synset(air)
#sm2 = Semantic_Class()
#sm.move_synset_to_another_sm(sm2, air)
#print find_synset_with_best_accuracy([sm])
print get_first_sense('air', sm)
print sm.lemma_sense['air']
print len(sm.synsets)
#sc_list.append(sm)
#synset, score = find_synset_with_best_accuracy(sc_list, gold)
def main():
run()
if __name__ == '__main__':
main()
|
export { default as userscript } from './userscript';
|
"""
color.py
The color module defines the Color class and some popular Color
objects.
"""
#-----------------------------------------------------------------------
class Color:
"""
A Color object models an RGB color.
"""
#-------------------------------------------------------------------
def __init__(self, r=0, g=0, b=0):
"""
Construct self such that it has the given red (r),
green (g), and blue (b) components.
"""
self._r = r # Red component
self._g = g # Green component
self._b = b # Blue component
#-------------------------------------------------------------------
def getRed(self):
"""
Return the red component of self.
"""
return self._r
#-------------------------------------------------------------------
def getGreen(self):
"""
Return the green component of self.
"""
return self._g
#-------------------------------------------------------------------
def getBlue(self):
"""
Return the blue component of self.
"""
return self._b
#-------------------------------------------------------------------
def __str__(self):
"""
Return the string equivalent of self, that is, a
string of the form '(r, g, b)'.
"""
#return '#%02x%02x%02x' % (self._r, self._g, self._b)
return '(' + str(self._r) + ', ' + str(self._g) + ', ' + \
str(self._b) + ')'
#-----------------------------------------------------------------------
# Some predefined Color objects:
WHITE = Color(255, 255, 255)
BLACK = Color( 0, 0, 0)
RED = Color(255, 0, 0)
GREEN = Color( 0, 255, 0)
BLUE = Color( 0, 0, 255)
CYAN = Color( 0, 255, 255)
MAGENTA = Color(255, 0, 255)
YELLOW = Color(255, 255, 0)
DARK_RED = Color(128, 0, 0)
DARK_GREEN = Color( 0, 128, 0)
DARK_BLUE = Color( 0, 0, 128)
GRAY = Color(128, 128, 128)
DARK_GRAY = Color( 64, 64, 64)
LIGHT_GRAY = Color(192, 192, 192)
ORANGE = Color(255, 200, 0)
VIOLET = Color(238, 130, 238)
PINK = Color(255, 175, 175)
# Shade of blue used in Introduction to Programming in Java.
# It is Pantone 300U. The RGB values are approximately (9, 90, 166).
BOOK_BLUE = Color( 9, 90, 166)
BOOK_LIGHT_BLUE = Color(103, 198, 243)
# Shade of red used in Algorithms 4th edition
BOOK_RED = Color(150, 35, 31)
#-----------------------------------------------------------------------
def _main():
"""
For testing:
"""
import stdio
c1 = Color(128, 128, 128)
stdio.writeln(c1)
stdio.writeln(c1.getRed())
stdio.writeln(c1.getGreen())
stdio.writeln(c1.getBlue())
if __name__ == '__main__':
_main() |
crowdhub.controller('usersCtrl', function($scope, TasksList) {
});
|
import gdal
import numpy as np
import os,glob,shutil,sys
import netCDF4
import matplotlib.pyplot as plt
import subprocess
import multiprocessing
# On BRIDGE servers, gdal is a bit broken, set 'GDAL_DATA='/opt/bridge/CentOS6-64/python/anaconda-5.0.1-2.7/pkgs/libgdal-2.1.0-0/share/gdal'
################################################################################
# Input paths
# Input directory containing DEM tiles (5degree increments)
dem_dir = '/export/anthropocene/array-01/pu17449/MeritDEM/' # files have format e.g. n25e090_dem.tif
out_dir1 = '/export/anthropocene/array-01/pu17449/parameter_transfer_datasets/MeritDEMSlope'
out_dir2 = '/export/anthropocene/array-01/pu17449/parameter_transfer_datasets/MeritDEMSlope_p1deg'
processdir = '/export/anthropocene/array-01/pu17449/parameter_transfer_datasets/tmp'
if not os.path.exists(out_dir2):
os.mkdir(out_dir2)
numthreads = 6
def processtile(ftile,out_dir1,out_dir2,processdir):
fname = os.path.basename(ftile)
print(fname)
slopefile = os.path.join(out_dir1,fname[:-7]+'slope.tif')
if not os.path.exists(slopefile):
# Convert to EPSG:3857 projection (units in of metres not degrees)
tmpfile = os.path.join(processdir,fname[:-4]+'_epsg3857.tif')
cmd = ['gdalwarp','-t_srs','EPSG:3857','-r','near','-of','GTiff',ftile,tmpfile]
#print(cmd)
ret1 = subprocess.call(cmd)
# Calculate slope for tile
cmd = ['gdaldem','slope','-of','GTiff','-b','1','-s','1.0','-co','COMPRESS=DEFLATE',tmpfile,slopefile]
#print(cmd)
ret2 = subprocess.call(cmd)
# Clean up tmpfile
os.remove(tmpfile)
else:
ret1=ret2=0
# Regrid to 0.5deg
# For 0.5deg regridding
slopefile2 = os.path.join(out_dir2,fname[:-7]+'slope_p1deg.tif')
if not os.path.exists(slopefile2):
cmd = ['gdalwarp', '-t_srs', 'EPSG:4326', '-tr', '0.1', '0.1', '-r', 'average' ,'-of' ,'GTiff','-co','COMPRESS=DEFLATE', slopefile, slopefile2]
#print(cmd)
ret3 = subprocess.call(cmd)
else:
ret3=0
if ret1!=0 or ret2!=0 or ret3!=0:
print('Error processing',ftile)
return -5
else:
return 0
pool = multiprocessing.Pool(processes=numthreads)
for ftile in glob.glob(os.path.join(dem_dir,'*_dem.tif')):
pool.apply_async(processtile,(ftile,out_dir1,out_dir2,processdir))
# close the pool and make sure the processing has finished
pool.close()
pool.join()
|
from setuptools import setup
setup(
name='raft_std',
version='0.1.0',
description='Standard library for Raft',
author='Maviek',
author_email='[email protected]',
packages=['raft_std', 'raft_std.thread', 'raft_std.fs', 'raft_std.io'],
package_dir={'': 'lib'},
)
|
//load('d:\\NodeGridFS\\ms\\dbscript\\init.js')
var mongo = new Mongo('localhost');
var myDB = mongo.getDB('blog');
var managerColl = myDB.getCollection('managers');
managerColl.insert({'name':'admin','password':'123'});
//level级别
//levelnumber 级别数值
//levelname 级别名称
var levelColl = myDB.getCollection('levels');
//levelColl.insert({'levelnumber':'','levelname':''});
levelColl.insert({'levelnumber': 0 ,'levelname':'不堪一击'});
levelColl.insert({'levelnumber': 5 ,'levelname':'毫不足虑'});
levelColl.insert({'levelnumber': 10 ,'levelname':'不足挂齿'});
levelColl.insert({'levelnumber': 15 ,'levelname':'初学乍练'});
levelColl.insert({'levelnumber': 20 ,'levelname':'勉勉强强'});
levelColl.insert({'levelnumber': 25 ,'levelname':'初窥门径'});
levelColl.insert({'levelnumber': 30 ,'levelname':'初出茅庐'});
levelColl.insert({'levelnumber': 35 ,'levelname':'略知一二'});
levelColl.insert({'levelnumber': 40 ,'levelname':'普普通通'});
levelColl.insert({'levelnumber': 45 ,'levelname':'平平常常'});
levelColl.insert({'levelnumber': 50 ,'levelname':'平淡无奇'});
levelColl.insert({'levelnumber': 55 ,'levelname':'粗懂皮毛'});
levelColl.insert({'levelnumber': 60 ,'levelname':'半生不熟'});
levelColl.insert({'levelnumber': 65 ,'levelname':'登堂入室'});
levelColl.insert({'levelnumber': 70 ,'levelname':'略有小成'});
levelColl.insert({'levelnumber': 75 ,'levelname':'已有小成'});
levelColl.insert({'levelnumber': 80 ,'levelname':'鹤立鸡群'});
levelColl.insert({'levelnumber': 85 ,'levelname':'驾轻就熟'});
levelColl.insert({'levelnumber': 90 ,'levelname':'青出於蓝'});
levelColl.insert({'levelnumber': 95 ,'levelname':'融会贯通'});
levelColl.insert({'levelnumber': 100 ,'levelname':'心领神会'});
levelColl.insert({'levelnumber': 105 ,'levelname':'炉火纯青'});
levelColl.insert({'levelnumber': 110 ,'levelname':'了然於胸'});
levelColl.insert({'levelnumber': 115 ,'levelname':'略有大成'});
levelColl.insert({'levelnumber': 120 ,'levelname':'已有大成'});
levelColl.insert({'levelnumber': 125 ,'levelname':'豁然贯通'});
levelColl.insert({'levelnumber': 130 ,'levelname':'非比寻常'});
levelColl.insert({'levelnumber': 135 ,'levelname':'出类拔萃'});
levelColl.insert({'levelnumber': 140 ,'levelname':'罕有敌手'});
levelColl.insert({'levelnumber': 145 ,'levelname':'技冠群雄'});
levelColl.insert({'levelnumber': 150 ,'levelname':'神乎其技'});
levelColl.insert({'levelnumber': 155 ,'levelname':'出神入化'});
levelColl.insert({'levelnumber': 160 ,'levelname':'傲视群雄'});
levelColl.insert({'levelnumber': 165 ,'levelname':'登峰造极'});
levelColl.insert({'levelnumber': 170 ,'levelname':'无与伦比'});
levelColl.insert({'levelnumber': 175 ,'levelname':'所向披靡'});
levelColl.insert({'levelnumber': 180 ,'levelname':'一代宗师'});
levelColl.insert({'levelnumber': 185 ,'levelname':'精深奥妙'});
levelColl.insert({'levelnumber': 190 ,'levelname':'神功盖世'});
levelColl.insert({'levelnumber': 195 ,'levelname':'举世无双'});
levelColl.insert({'levelnumber': 200 ,'levelname':'惊世骇俗'});
levelColl.insert({'levelnumber': 205 ,'levelname':'撼天动地'});
levelColl.insert({'levelnumber': 210 ,'levelname':'震古铄今'});
levelColl.insert({'levelnumber': 215 ,'levelname':'超凡入圣'});
levelColl.insert({'levelnumber': 220 ,'levelname':'威镇寰宇'});
levelColl.insert({'levelnumber': 225 ,'levelname':'空前绝后'});
levelColl.insert({'levelnumber': 230 ,'levelname':'天人合一'});
levelColl.insert({'levelnumber': 235 ,'levelname':'深藏不露'});
levelColl.insert({'levelnumber': 240 ,'levelname':'深不可测'});
levelColl.insert({'levelnumber': 245 ,'levelname':'返璞归真'});
levelColl.insert({'levelnumber': 255 ,'levelname':'极轻很轻'});
|
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('logout');
});
module.exports = router; |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: sxp_local_bindings_info
short_description: Information module for Sxp Local Bindings
description:
- Get all Sxp Local Bindings.
- Get Sxp Local Bindings by id.
version_added: '1.0.0'
author: Rafael Campos (@racampos)
options:
id:
description:
- Id path parameter.
type: str
page:
description:
- Page query parameter. Page number.
type: int
size:
description:
- Size query parameter. Number of objects returned per page.
type: int
sortasc:
description:
- Sortasc query parameter. Sort asc.
type: str
sortdsc:
description:
- Sortdsc query parameter. Sort desc.
type: str
filter:
description:
- >
Filter query parameter. <br/> **Simple filtering** should be available through the filter query string
parameter. The structure of a filter is a triplet of field operator and value separated with dots. More than
one filter can be sent. The logical operator common to ALL filter criteria will be by default AND, and can
be changed by using the "filterType=or" query string parameter. Each resource Data model description should
specify if an attribute is a filtered field. <br/> Operator | Description <br/>
------------|----------------- <br/> EQ | Equals <br/> NEQ | Not Equals <br/> GT | Greater Than <br/> LT |
Less Then <br/> STARTSW | Starts With <br/> NSTARTSW | Not Starts With <br/> ENDSW | Ends With <br/> NENDSW
| Not Ends With <br/> CONTAINS | Contains <br/> NCONTAINS | Not Contains <br/>.
type: list
filterType:
description:
- >
FilterType query parameter. The logical operator common to ALL filter criteria will be by default AND, and
can be changed by using the parameter.
type: str
requirements:
- ciscoisesdk
seealso:
# Reference by Internet resource
- name: Sxp Local Bindings reference
description: Complete reference of the Sxp Local Bindings object model.
link: https://ciscoisesdk.readthedocs.io/en/latest/api/api.html#v3-0-0-summary
"""
EXAMPLES = r"""
- name: Get all Sxp Local Bindings
cisco.ise.sxp_local_bindings_info:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
page: 1
size: 20
sortasc: string
sortdsc: string
filter: []
filterType: AND
register: result
- name: Get Sxp Local Bindings by id
cisco.ise.sxp_local_bindings_info:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
id: string
register: result
"""
RETURN = r"""
ise_response:
description: A dictionary or list with the response returned by the Cisco ISE Python SDK
returned: always
type: dict
sample: >
{
"id": "string",
"description": "string",
"bindingName": "string",
"ipAddressOrHost": "string",
"sxpVpn": "string",
"sgt": "string",
"vns": "string",
"link": {
"rel": "string",
"href": "string",
"type": "string"
}
}
"""
|
/*
YUI 3.17.2 (build 9c3c78e)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add("lang/datatype-date-format_pt-BR",function(e){e.Intl.add("datatype-date-format","pt-BR",{a:["dom","seg","ter","qua","qui","sex","s\u00e1b"],A:["domingo","segunda-feira","ter\u00e7a-feira","quarta-feira","quinta-feira","sexta-feira","s\u00e1bado"],b:["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"],B:["janeiro","fevereiro","mar\u00e7o","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"],c:"%a, %d de %b de %Y %Hh%Mmin%Ss %Z",p:["AM","PM"],P:["am","pm"],x:"%d/%m/%y",X:"%Hh%Mmin%Ss"})},"3.17.2");
|
# -*- coding: utf-8 -*-
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
"""
Extension template for transformers, SIMPLE version.
Contains only bare minimum of implementation requirements for a functional transformer.
Also assumes *no composition*, i.e., no transformer or other estimator components.
For advanced cases (inverse transform, composition, etc),
see full extension template in forecasting.py
Purpose of this implementation template:
quick implementation of new estimators following the template
NOT a concrete class to import! This is NOT a base class or concrete class!
This is to be used as a "fill-in" coding template.
How to use this implementation template to implement a new estimator:
- make a copy of the template in a suitable location, give it a descriptive name.
- work through all the "todo" comments below
- fill in code for mandatory methods, and optionally for optional methods
- you can add more private methods, but do not override BaseEstimator's private methods
an easy way to be safe is to prefix your methods with "_custom"
- change docstrings for functions and the file
- ensure interface compatibility by sktime.utils.estimator_checks.check_estimator
- once complete: use as a local library, or contribute to sktime via PR
- more details: https://www.sktime.org/en/stable/developer_guide/add_estimators.html
Mandatory implements:
fitting - _fit(self, X, y=None)
transformation - _transform(self, X, y=None)
Testing - implement if sktime transformer (not needed locally):
get default parameters for test instance(s) - get_test_params()
"""
# todo: write an informative docstring for the file or module, remove the above
# todo: add an appropriate copyright notice for your estimator
# estimators contributed to sktime should have the copyright notice at the top
# estimators of your own do not need to have permissive or BSD-3 copyright
# todo: uncomment the following line, enter authors' GitHub IDs
# __author__ = [authorGitHubID, anotherAuthorGitHubID]
# todo: add any necessary sktime external imports here
from sktime.transformations.base import BaseTransformer
# todo: add any necessary sktime internal imports here
class MyTransformer(BaseTransformer):
"""Custom transformer. todo: write docstring.
todo: describe your custom transformer here
fill in sections appropriately
docstring must be numpydoc compliant
Parameters
----------
parama : int
descriptive explanation of parama
paramb : string, optional (default='default')
descriptive explanation of paramb
paramc : boolean, optional (default= whether paramb is not the default)
descriptive explanation of paramc
and so on
"""
# todo: fill out estimator tags here
# tags are inherited from parent class if they are not set
#
# todo: define the transformer scitype by setting the tags
# scitype:transform-input - the expected input scitype of X
# scitype:transform-output - the output scitype that transform produces
# scitype:transform-labels - whether y is used and if yes which scitype
# scitype:instancewise - whether transform uses all samples or acts by instance
#
# todo: define internal types for X, y in _fit/_transform by setting the tags
# X_inner_mtype - the internal mtype used for X in _fit and _transform
# y_inner_mtype - if y is used, the internal mtype used for y; usually "None"
# setting this guarantees that X, y passed to _fit, _transform are of above types
# for possible mtypes see datatypes.MTYPE_REGISTER, or the datatypes tutorial
#
# when scitype:transform-input is set to Panel:
# X_inner_mtype must be changed to one or a list of sktime Panel mtypes
# when scitype:transform-labels is set to Series or Panel:
# y_inner_mtype must be changed to one or a list of compatible sktime mtypes
# the other tags are "safe defaults" which can usually be left as-is
_tags = {
"scitype:transform-input": "Series",
# what is the scitype of X: Series, or Panel
"scitype:transform-output": "Series",
# what scitype is returned: Primitives, Series, Panel
"scitype:transform-labels": "None",
# what is the scitype of y: None (not needed), Primitives, Series, Panel
"scitype:instancewise": True, # is this an instance-wise transform?
"capability:inverse_transform": False, # can the transformer inverse transform?
"univariate-only": False, # can the transformer handle multivariate X?
"X_inner_mtype": "pd.DataFrame", # which mtypes do _fit/_predict support for X?
# this can be a Panel mtype even if transform-input is Series, vectorized
"y_inner_mtype": "None", # which mtypes do _fit/_predict support for y?
"requires_y": False, # does y need to be passed in fit?
"enforce_index_type": None, # index type that needs to be enforced in X/y
"fit_is_empty": True, # is fit empty and can be skipped? Yes = True
"X-y-must-have-same-index": False, # can estimator handle different X/y index?
"transform-returns-same-time-index": False,
# does transform return have the same time index as input X
"skip-inverse-transform": False, # is inverse-transform skipped when called?
"capability:unequal_length": True,
# can the transformer handle unequal length time series (if passed Panel)?
"capability:unequal_length:removes": False,
# is transform result always guaranteed to be equal length (and series)?
# not relevant for transformers that return Primitives in transform-output
"handles-missing-data": False, # can estimator handle missing data?
"capability:missing_values:removes": False,
# is transform result always guaranteed to contain no missing values?
}
# todo: add any hyper-parameters and components to constructor
def __init__(self, parama, paramb="default", paramc=None):
# todo: write any hyper-parameters to self
self.parama = parama
self.paramb = paramb
self.paramc = paramc
# important: no checking or other logic should happen here
# todo: change "MyTransformer" to the name of the class
super(MyTransformer, self).__init__()
# todo: implement this, mandatory (except in special case below)
def _fit(self, X, y=None):
"""Fit transformer to X and y.
private _fit containing the core logic, called from fit
Parameters
----------
X : Series or Panel of mtype X_inner_mtype
if X_inner_mtype is list, _fit must support all types in it
Data to fit transform to
y : Series or Panel of mtype y_inner_mtype, default=None
Additional data, e.g., labels for transformation
Returns
-------
self: reference to self
"""
# implement here
# X, y passed to this function are always of X_inner_mtype, y_inner_mtype
# IMPORTANT: avoid side effects to X, y
#
# any model parameters should be written to attributes ending in "_"
# attributes set by the constructor must not be overwritten
#
# special case: if no fitting happens before transformation
# then: delete _fit (don't implement)
# set "fit_is_empty" tag to True
#
# Note: when interfacing a model that has fit, with parameters
# that are not data (X, y) or data-like
# but model parameters, *don't* add as arguments to fit, but treat as follows:
# 1. pass to constructor, 2. write to self in constructor,
# 3. read from self in _fit, 4. pass to interfaced_model.fit in _fit
# todo: implement this, mandatory
def _transform(self, X, y=None):
"""Transform X and return a transformed version.
private _transform containing core logic, called from transform
Parameters
----------
X : Series or Panel of mtype X_inner_mtype
if X_inner_mtype is list, _transform must support all types in it
Data to be transformed
y : Series or Panel of mtype y_inner_mtype, default=None
Additional data, e.g., labels for transformation
Returns
-------
transformed version of X
"""
# implement here
# X, y passed to this function are always of X_inner_mtype, y_inner_mtype
# IMPORTANT: avoid side effects to X, y
#
# if transform-output is "Primitives":
# return should be pd.DataFrame, with as many rows as instances in input
# if input is a single series, return should be single-row pd.DataFrame
# if transform-output is "Series":
# return should be of same mtype as input, X_inner_mtype
# if multiple X_inner_mtype are supported, ensure same input/output
# if transform-output is "Panel":
# return a multi-indexed pd.DataFrame of Panel mtype pd_multiindex
#
# todo: add the return mtype/scitype to the docstring, e.g.,
# Returns
# -------
# X_transformed : Series of mtype pd.DataFrame
# transformed version of X
# todo: return default parameters, so that a test instance can be created
# required for automated unit and integration testing of estimator
@classmethod
def get_test_params(cls, parameter_set="default"):
"""Return testing parameter settings for the estimator.
Parameters
----------
parameter_set : str, default="default"
Name of the set of test parameters to return, for use in tests. If no
special parameters are defined for a value, will return `"default"` set.
There are currently no reserved values for transformers.
Returns
-------
params : dict or list of dict, default = {}
Parameters to create testing instances of the class
Each dict are parameters to construct an "interesting" test instance, i.e.,
`MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
`create_test_instance` uses the first (or only) dictionary in `params`
"""
# todo: set the testing parameters for the estimators
# Testing parameters can be dictionary or list of dictionaries.
# Testing parameter choice should cover internal cases well.
# for "simple" extension, ignore the parameter_set argument.
#
# example 1: specify params as dictionary
# any number of params can be specified
# params = {"est": value0, "parama": value1, "paramb": value2}
#
# example 2: specify params as list of dictionary
# note: Only first dictionary will be used by create_test_instance
# params = [{"est": value1, "parama": value2},
# {"est": value3, "parama": value4}]
#
# return params
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[15],{204:function(t,s,a){},226:function(t,s,a){"use strict";var n=a(204);a.n(n).a},245:function(t,s,a){"use strict";a.r(s);a(226);var n=a(0),e=Object(n.a)({},function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("div",{staticClass:"content"},[t._m(0),t._v(" "),a("p",[t._v("选人组件")]),t._v(" "),a("h-person-selector"),t._v(" "),t._m(1),t._v(" "),t._m(2),t._m(3),t._v(" "),t._m(4),a("test"),t._v(" "),t._m(5),t._v(" "),a("test",{attrs:{backgroundColor:"cadetblue"}}),t._v(" "),t._m(6)],1)},[function(){var t=this.$createElement,s=this._self._c||t;return s("h1",{attrs:{id:"人员选择器(personselector)"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#人员选择器(personselector)","aria-hidden":"true"}},[this._v("#")]),this._v(" 人员选择器(PersonSelector)")])},function(){var t=this.$createElement,s=this._self._c||t;return s("h3",{attrs:{id:"引入"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#引入","aria-hidden":"true"}},[this._v("#")]),this._v(" 引入")])},function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" HPersonSelector "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"hrkj-vux-components"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("export")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("default")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n components"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n HPersonSelector\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])])},function(){var t=this.$createElement,s=this._self._c||t;return s("h3",{attrs:{id:"使用"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#使用","aria-hidden":"true"}},[this._v("#")]),this._v(" 使用")])},function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("div",{staticClass:"language-vue extra-class"},[a("pre",{pre:!0,attrs:{class:"language-vue"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token style-attr language-css"}},[a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('="')]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token property"}},[t._v("margin-top")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" 20px")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("h-person-selector")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":limited")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("false"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":limitUserDataSource")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("limitUserData"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("@selectedPersonChanged")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("selectedUser"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("h-person-selector")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("template")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("script")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token script language-javascript"}},[t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" HPersonSelector "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"hrkj-vux-components"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("export")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("default")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n components"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n HPersonSelector\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("data")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n limitUserData"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n avatar_url"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"http://10.64.140.238/photos/user_photo_4"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n name"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"周文舒"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n dept_name"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"经理"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n selected"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("false")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n avatar_url"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"http://10.64.140.238/photos/user_photo_4"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n name"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"刘艳茹"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n dept_name"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"经理"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n selected"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("false")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n avatar_url"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"http://10.64.140.238/photos/user_photo_4"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n name"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"张涛"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n dept_name"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"经理"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n selected"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("false")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n avatar_url"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"http://10.64.140.238/photos/user_photo_4"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n name"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"韩梅梅"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n dept_name"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"经理"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n selected"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("false")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n avatar_url"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"http://10.64.140.238/photos/user_photo_4"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n name"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"李磊"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n dept_name"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"经理"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n selected"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("false")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n avatar_url"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"http://10.64.140.238/photos/user_photo_4"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n name"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"John"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n dept_name"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"经理"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n selected"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("false")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n methods"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("selectedUser")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("itemArray"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n console"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("log")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token constant"}},[t._v("JSON")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("stringify")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("itemArray"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("</")]),t._v("script")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n")])])])},function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("table",[a("thead",[a("tr",[a("th",{staticStyle:{"text-align":"center"}},[t._v("属性")]),t._v(" "),a("th",{staticStyle:{"text-align":"center"}},[t._v("类型")]),t._v(" "),a("th",{staticStyle:{"text-align":"center"}},[t._v("默认值")]),t._v(" "),a("th",{staticStyle:{"text-align":"left"}},[t._v("说明")]),t._v(" "),a("th",{staticStyle:{"text-align":"left"}},[t._v("版本")])])]),t._v(" "),a("tbody",[a("tr",[a("td",{staticStyle:{"text-align":"center"}},[t._v("limitUserDataSource")]),t._v(" "),a("td",{staticStyle:{"text-align":"center"}},[t._v("Array")]),t._v(" "),a("td",{staticStyle:{"text-align":"center"}},[t._v("----")]),t._v(" "),a("td",{staticStyle:{"text-align":"left"}},[t._v("限制选人数据源,开放式选人不用设置")]),t._v(" "),a("td",{staticStyle:{"text-align":"left"}},[t._v("0.0.11")])]),t._v(" "),a("tr",[a("td",{staticStyle:{"text-align":"center"}},[t._v("limited")]),t._v(" "),a("td",{staticStyle:{"text-align":"center"}},[t._v("Boolean")]),t._v(" "),a("td",{staticStyle:{"text-align":"center"}},[t._v("true")]),t._v(" "),a("td",{staticStyle:{"text-align":"left"}},[t._v("开放式还是限制式选人,默认为限制式选人。注:开发式选人必选在融讯通中运行才生效")]),t._v(" "),a("td",{staticStyle:{"text-align":"left"}},[t._v("0.0.11")])]),t._v(" "),a("tr",[a("td",{staticStyle:{"text-align":"center"}},[t._v("multiSelect")]),t._v(" "),a("td",{staticStyle:{"text-align":"center"}},[t._v("Boolean")]),t._v(" "),a("td",{staticStyle:{"text-align":"center"}},[t._v("false")]),t._v(" "),a("td",{staticStyle:{"text-align":"left"}},[t._v("单选还是多选,默认为单选")]),t._v(" "),a("td",{staticStyle:{"text-align":"left"}},[t._v("0.0.11")])])])])},function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("table",[a("thead",[a("tr",[a("th",{staticStyle:{"text-align":"center"}},[t._v("事件")]),t._v(" "),a("th",{staticStyle:{"text-align":"center"}},[t._v("参数")]),t._v(" "),a("th",{staticStyle:{"text-align":"center"}},[t._v("默认值")]),t._v(" "),a("th",{staticStyle:{"text-align":"left"}},[t._v("说明")]),t._v(" "),a("th",{staticStyle:{"text-align":"left"}},[t._v("版本")])])]),t._v(" "),a("tbody",[a("tr",[a("td",{staticStyle:{"text-align":"center"}},[t._v("selectedPersonChanged")]),t._v(" "),a("td",{staticStyle:{"text-align":"center"}},[t._v("item")]),t._v(" "),a("td",{staticStyle:{"text-align":"center"}},[t._v("----")]),t._v(" "),a("td",{staticStyle:{"text-align":"left"}},[t._v("已选择人员的监听回调")]),t._v(" "),a("td",{staticStyle:{"text-align":"left"}},[t._v("0.0.11")])])])])}],!1,null,"ac3660c0",null);e.options.__file="hv-person-selector.md";s.default=e.exports}}]); |
# -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import
# Import Salt Libs
from salt.states import mac_package as macpackage
# Import Salt Testing Libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import (
MagicMock,
patch
)
ensure_in_syspath('../../')
macpackage.__salt__ = {}
macpackage.__grains__ = {}
class MacPackageTestCase(TestCase):
@patch('salt.states.mac_package._mod_run_check')
def test_installed_pkg(self, _mod_run_check_mock):
'''
Test installing a PKG file
'''
expected = {
'changes': {'installed': ['some.other.id']},
'comment': '/path/to/file.pkg installed',
'name': '/path/to/file.pkg',
'result': True
}
installed_mock = MagicMock(return_value=['com.apple.id'])
get_pkg_id_mock = MagicMock(return_value=['some.other.id'])
install_mock = MagicMock(return_value={'retcode': 0})
_mod_run_check_mock.return_value = True
with patch.dict(macpackage.__salt__, {'macpackage.installed_pkgs': installed_mock,
'macpackage.get_pkg_id': get_pkg_id_mock,
'macpackage.install': install_mock}):
out = macpackage.installed('/path/to/file.pkg')
installed_mock.assert_called_once_with()
get_pkg_id_mock.assert_called_once_with('/path/to/file.pkg')
install_mock.assert_called_once_with('/path/to/file.pkg', 'LocalSystem', False, False)
self.assertEqual(out, expected)
@patch('salt.states.mac_package._mod_run_check')
def test_installed_pkg_exists(self, _mod_run_check_mock):
'''
Test installing a PKG file where it's already installed
'''
expected = {
'changes': {},
'comment': '',
'name': '/path/to/file.pkg',
'result': True
}
installed_mock = MagicMock(return_value=['com.apple.id', 'some.other.id'])
get_pkg_id_mock = MagicMock(return_value=['some.other.id'])
install_mock = MagicMock(return_value={'retcode': 0})
_mod_run_check_mock.return_value = True
with patch.dict(macpackage.__salt__, {'macpackage.installed_pkgs': installed_mock,
'macpackage.get_pkg_id': get_pkg_id_mock,
'macpackage.install': install_mock}):
out = macpackage.installed('/path/to/file.pkg')
installed_mock.assert_called_once_with()
get_pkg_id_mock.assert_called_once_with('/path/to/file.pkg')
assert not install_mock.called
self.assertEqual(out, expected)
@patch('salt.states.mac_package._mod_run_check')
def test_installed_pkg_version_succeeds(self, _mod_run_check_mock):
'''
Test installing a PKG file where the version number matches the current installed version
'''
expected = {
'changes': {},
'comment': 'Version already matches .*5\\.1\\.[0-9]',
'name': '/path/to/file.pkg',
'result': True
}
installed_mock = MagicMock(return_value=['com.apple.id', 'some.other.id'])
get_pkg_id_mock = MagicMock(return_value=['some.other.id'])
install_mock = MagicMock(return_value={'retcode': 0})
cmd_mock = MagicMock(return_value='Version of this: 5.1.9')
_mod_run_check_mock.return_value = True
with patch.dict(macpackage.__salt__, {'macpackage.installed_pkgs': installed_mock,
'macpackage.get_pkg_id': get_pkg_id_mock,
'macpackage.install': install_mock,
'cmd.run': cmd_mock}):
out = macpackage.installed('/path/to/file.pkg', version_check=r'/usr/bin/runme --version=.*5\.1\.[0-9]')
cmd_mock.assert_called_once_with('/usr/bin/runme --version', output_loglevel="quiet", ignore_retcode=True)
assert not installed_mock.called
assert not get_pkg_id_mock.called
assert not install_mock.called
self.assertEqual(out, expected)
@patch('salt.states.mac_package._mod_run_check')
def test_installed_pkg_version_fails(self, _mod_run_check_mock):
'''
Test installing a PKG file where the version number if different from the expected one
'''
expected = {
'changes': {'installed': ['some.other.id']},
'comment': 'Version Version of this: 1.8.9 doesn\'t match .*5\\.1\\.[0-9]. /path/to/file.pkg installed',
'name': '/path/to/file.pkg',
'result': True
}
installed_mock = MagicMock(return_value=['com.apple.id'])
get_pkg_id_mock = MagicMock(return_value=['some.other.id'])
install_mock = MagicMock(return_value={'retcode': 0})
cmd_mock = MagicMock(return_value='Version of this: 1.8.9')
_mod_run_check_mock.return_value = True
with patch.dict(macpackage.__salt__, {'macpackage.installed_pkgs': installed_mock,
'macpackage.get_pkg_id': get_pkg_id_mock,
'macpackage.install': install_mock,
'cmd.run': cmd_mock}):
out = macpackage.installed('/path/to/file.pkg', version_check=r'/usr/bin/runme --version=.*5\.1\.[0-9]')
cmd_mock.assert_called_once_with('/usr/bin/runme --version', output_loglevel="quiet", ignore_retcode=True)
installed_mock.assert_called_once_with()
get_pkg_id_mock.assert_called_once_with('/path/to/file.pkg')
install_mock.assert_called_once_with('/path/to/file.pkg', 'LocalSystem', False, False)
self.assertEqual(out, expected)
@patch('salt.states.mac_package._mod_run_check')
def test_installed_dmg(self, _mod_run_check_mock):
'''
Test installing a DMG file
'''
expected = {
'changes': {'installed': ['some.other.id']},
'comment': '/path/to/file.dmg installed',
'name': '/path/to/file.dmg',
'result': True
}
mount_mock = MagicMock(return_value=['success', '/tmp/dmg-X'])
unmount_mock = MagicMock()
installed_mock = MagicMock(return_value=['com.apple.id'])
get_pkg_id_mock = MagicMock(return_value=['some.other.id'])
install_mock = MagicMock(return_value={'retcode': 0})
_mod_run_check_mock.return_value = True
with patch.dict(macpackage.__salt__, {'macpackage.mount': mount_mock,
'macpackage.unmount': unmount_mock,
'macpackage.installed_pkgs': installed_mock,
'macpackage.get_pkg_id': get_pkg_id_mock,
'macpackage.install': install_mock}):
out = macpackage.installed('/path/to/file.dmg', dmg=True)
mount_mock.assert_called_once_with('/path/to/file.dmg')
unmount_mock.assert_called_once_with('/tmp/dmg-X')
installed_mock.assert_called_once_with()
get_pkg_id_mock.assert_called_once_with('/tmp/dmg-X/*.pkg')
install_mock.assert_called_once_with('/tmp/dmg-X/*.pkg', 'LocalSystem', False, False)
self.assertEqual(out, expected)
@patch('salt.states.mac_package._mod_run_check')
def test_installed_dmg_exists(self, _mod_run_check_mock):
'''
Test installing a DMG file when the package already exists
'''
expected = {
'changes': {},
'comment': '',
'name': '/path/to/file.dmg',
'result': True
}
mount_mock = MagicMock(return_value=['success', '/tmp/dmg-X'])
unmount_mock = MagicMock()
installed_mock = MagicMock(return_value=['com.apple.id', 'some.other.id'])
get_pkg_id_mock = MagicMock(return_value=['some.other.id'])
install_mock = MagicMock(return_value={'retcode': 0})
_mod_run_check_mock.return_value = True
with patch.dict(macpackage.__salt__, {'macpackage.mount': mount_mock,
'macpackage.unmount': unmount_mock,
'macpackage.installed_pkgs': installed_mock,
'macpackage.get_pkg_id': get_pkg_id_mock,
'macpackage.install': install_mock}):
out = macpackage.installed('/path/to/file.dmg', dmg=True)
mount_mock.assert_called_once_with('/path/to/file.dmg')
unmount_mock.assert_called_once_with('/tmp/dmg-X')
installed_mock.assert_called_once_with()
get_pkg_id_mock.assert_called_once_with('/tmp/dmg-X/*.pkg')
assert not install_mock.called
self.assertEqual(out, expected)
@patch('os.path.exists')
@patch('salt.states.mac_package._mod_run_check')
def test_installed_app(self, _mod_run_check_mock, exists_mock):
'''
Test installing an APP file
'''
expected = {
'changes': {'installed': ['file.app']},
'comment': 'file.app installed',
'name': '/path/to/file.app',
'result': True
}
install_mock = MagicMock()
_mod_run_check_mock.return_value = True
exists_mock.return_value = False
with patch.dict(macpackage.__salt__, {'macpackage.install_app': install_mock}):
out = macpackage.installed('/path/to/file.app', app=True)
install_mock.assert_called_once_with('/path/to/file.app', '/Applications/')
self.assertEqual(out, expected)
@patch('os.path.exists')
@patch('salt.states.mac_package._mod_run_check')
def test_installed_app_exists(self, _mod_run_check_mock, exists_mock):
'''
Test installing an APP file that already exists
'''
expected = {
'changes': {},
'comment': '',
'name': '/path/to/file.app',
'result': True
}
install_mock = MagicMock()
_mod_run_check_mock.return_value = True
exists_mock.return_value = True
with patch.dict(macpackage.__salt__, {'macpackage.install_app': install_mock}):
out = macpackage.installed('/path/to/file.app', app=True)
assert not install_mock.called
self.assertEqual(out, expected)
@patch('os.path.exists')
@patch('salt.states.mac_package._mod_run_check')
def test_installed_app_dmg(self, _mod_run_check_mock, exists_mock):
'''
Test installing an APP file contained in a DMG file
'''
expected = {
'changes': {'installed': ['file.app']},
'comment': 'file.app installed',
'name': '/path/to/file.dmg',
'result': True
}
install_mock = MagicMock()
mount_mock = MagicMock(return_value=['success', '/tmp/dmg-X'])
unmount_mock = MagicMock()
cmd_mock = MagicMock(return_value='file.app')
_mod_run_check_mock.return_value = True
exists_mock.return_value = False
with patch.dict(macpackage.__salt__, {'macpackage.install_app': install_mock,
'macpackage.mount': mount_mock,
'macpackage.unmount': unmount_mock,
'cmd.run': cmd_mock}):
out = macpackage.installed('/path/to/file.dmg', app=True, dmg=True)
mount_mock.assert_called_once_with('/path/to/file.dmg')
unmount_mock.assert_called_once_with('/tmp/dmg-X')
cmd_mock.assert_called_once_with('ls -d *.app', python_shell=True, cwd='/tmp/dmg-X')
install_mock.assert_called_once_with('/tmp/dmg-X/file.app', '/Applications/')
self.assertEqual(out, expected)
@patch('os.path.exists')
@patch('salt.states.mac_package._mod_run_check')
def test_installed_app_dmg_exists(self, _mod_run_check_mock, exists_mock):
'''
Test installing an APP file contained in a DMG file where the file exists
'''
expected = {
'changes': {},
'comment': '',
'name': '/path/to/file.dmg',
'result': True
}
install_mock = MagicMock()
mount_mock = MagicMock(return_value=['success', '/tmp/dmg-X'])
unmount_mock = MagicMock()
cmd_mock = MagicMock(return_value='file.app')
_mod_run_check_mock.return_value = True
exists_mock.return_value = True
with patch.dict(macpackage.__salt__, {'macpackage.install_app': install_mock,
'macpackage.mount': mount_mock,
'macpackage.unmount': unmount_mock,
'cmd.run': cmd_mock}):
out = macpackage.installed('/path/to/file.dmg', app=True, dmg=True)
mount_mock.assert_called_once_with('/path/to/file.dmg')
unmount_mock.assert_called_once_with('/tmp/dmg-X')
cmd_mock.assert_called_once_with('ls -d *.app', python_shell=True, cwd='/tmp/dmg-X')
assert not install_mock.called
self.assertEqual(out, expected)
def test_installed_pkg_only_if_pass(self):
'''
Test installing a PKG file where the only if call passes
'''
expected = {
'changes': {'installed': ['some.other.id']},
'comment': '/path/to/file.pkg installed',
'name': '/path/to/file.pkg',
'result': True
}
installed_mock = MagicMock(return_value=['com.apple.id'])
get_pkg_id_mock = MagicMock(return_value=['some.other.id'])
install_mock = MagicMock(return_value={'retcode': 0})
cmd_mock = MagicMock(return_value=0)
with patch.dict(macpackage.__salt__, {'macpackage.installed_pkgs': installed_mock,
'macpackage.get_pkg_id': get_pkg_id_mock,
'macpackage.install': install_mock,
'cmd.retcode': cmd_mock}):
out = macpackage.installed('/path/to/file.pkg')
installed_mock.assert_called_once_with()
get_pkg_id_mock.assert_called_once_with('/path/to/file.pkg')
install_mock.assert_called_once_with('/path/to/file.pkg', 'LocalSystem', False, False)
self.assertEqual(out, expected)
def test_installed_pkg_onlyif_fail(self,):
'''
Test installing a PKG file where the onlyif call fails
'''
expected = {
'changes': {},
'comment': 'onlyif execution failed',
'skip_watch': True,
'result': True,
'name': '/path/to/file.pkg',
}
mock = MagicMock(return_value=1)
with patch.dict(macpackage.__salt__, {'cmd.retcode': mock}):
out = macpackage.installed('/path/to/file.pkg', onlyif='some command')
self.assertEqual(out, expected)
def test_installed_pkg_unless_fail(self,):
'''
Test installing a PKG file where the unless run fails
'''
expected = {
'changes': {},
'comment': 'unless execution succeeded',
'skip_watch': True,
'result': True,
'name': '/path/to/file.pkg',
}
mock = MagicMock(return_value=0)
with patch.dict(macpackage.__salt__, {'cmd.retcode': mock}):
out = macpackage.installed('/path/to/file.pkg', unless='some command')
self.assertEqual(out, expected)
if __name__ == '__main__':
from integration import run_tests
run_tests(MacPackageTestCase, needs_daemon=False)
|
def average(array):
# your code goes here
arr = list(set(array))
s = sum(arr)
l = len(arr)
return (s/l)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result) |
import itertools
import re
import sys
import traceback
from instruction import Instruction
from register import Register, UnusedRegister
class MIPSProgram:
def __init__(self, lines=None, text_base=0, data_base=0x4000):
self.text_base = text_base if isinstance(text_base, int) else eval(text_base)
self.data_base = data_base if isinstance(data_base, int) else eval(data_base)
self.instructions = []
self.data = []
self.labels = {}
self.defines = {}
if lines is not None:
self.AddLines(lines)
def AddLines(self, lines):
for l in lines:
self.HandleLine(l)
def HandleLine(self, line):
loc = sum([x.Size() for x in self.instructions])
for replace,value in self.defines.iteritems():
line = re.sub(replace, value, line)
if re.match("^\s*$", line) is not None:
return
try:
m = re.match(
r'''^\s*\.DEFINE\s*(?P<label>[_a-zA-Z0-9]+)\s*(?P<value>.*)$''',
line)
if m is not None:
self.defines[m.group('label')] = m.group('value')
return
m = re.match(
r'''^\s*\.STRING\s*(?P<label>[_a-zA-Z0-9]+)\s*(?P<str>".*")''',
line)
if m is not None:
self.RegisterDataLabel(m.group('label'), eval(m.group('str')))
return
m = re.match("^\s*(?P<label>[_a-zA-Z0-9]+):\.*$", line)
if m is not None:
self.RegisterLabel(m.group('label'), loc)
return
m = re.match("^\s*#.*$", line)
if m is not None:
return
inst = Instruction.parseline(self, loc, line)
self.instructions.append(inst)
except Exception as e:
print
print traceback.format_exc(e)
print "*** Invalid line: '%s'"%(line)
print
sys.exit(1)
def RegisterLabel(self, label, addr):
self.labels[label] = addr
def RegisterDataLabel(self, label, string):
string = string + "\0"
position = sum([len(x) for x in self.data])
self.labels[label] = self.data_base + position
self.data.append(string)
# Returns the label position
def Label(self, label):
if hasattr(label, '__call__'):
value = label()
return value
if label not in self.labels.keys():
raise Exception("Unknown label: '%s'"%(label))
return self.labels[label]
def Bytes(self, endian="big"):
return list(itertools.chain( *[x.Bytes(endian=endian) for x
in self.instructions] ))
|
$(function(){var e=$("*");e.each(function(){var e=$(this);var t=e.attr("class");var n=e.prop("tagName").toLowerCase();if(!e.attr("class")){e.attr("class",n)}else{e.attr("class",t+" "+n)}})})
|
'''
Copyright (C) 2010-2021 Alibaba Group Holding Limited.
process images andload imagenet and cifar
'''
# pylint: disable=W0613,not-callable,invalid-name,too-many-locals,too-many-arguments
import os
import sys
import math
import torch
import torch.utils.data
import torch.utils.data.distributed
from torchvision import transforms
from torchvision import datasets
import numpy as np
import PIL
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
try:
import hotfix.transforms
import autoaugment
except ImportError:
print('fail to import zen_nas modules')
_IMAGENET_PCA = {
'eigval': torch.Tensor([0.2175, 0.0188, 0.0045]),
'eigvec': torch.Tensor([
[-0.5675, 0.7192, 0.4009],
[-0.5808, -0.0045, -0.8140],
[-0.5836, -0.6948, 0.4203],
])
}
LIGHTING_PARAM = 0.1
params_dict = {
'imagenet': {
'train_dir': os.path.expanduser('~/data/imagenet/images/train/'),
'val_dir': os.path.expanduser('~/data/imagenet/images/val/'),
'num_train_samples': 1281167,
'num_val_samples': 50000,
'num_classes': 1000,
},
'myimagenet100': {
'train_dir': os.path.expanduser('~/data/myimagenet100/train/'),
'val_dir': os.path.expanduser('~/data/myimagenet100/val/'),
'num_train_samples': 129395,
'num_val_samples': 5000,
'num_classes': 100,
},
'cifar10': {
'train_dir': os.path.expanduser('/home/ouc/Documents/Ding/datasets/cifar-10-python'),
'val_dir': os.path.expanduser('/home/ouc/Documents/Ding/datasets/cifar-10-python'),
'num_train_samples': 50000,
'num_val_samples': 10000,
'num_classes': 10,
},
'cifar100': {
'train_dir': os.path.expanduser('/home/ouc/Documents/Ding/datasets/cifar-100-python'),
'val_dir': os.path.expanduser('/home/ouc/Documents/Ding/datasets/cifar-100-python'),
'num_train_samples': 50000,
'num_val_samples': 10000,
'num_classes': 100,
},
}
def fast_collate(batch, memory_format):
"""conver array to tensor"""
imgs = [img[0] for img in batch]
targets = torch.tensor([target[1] for target in batch], dtype=torch.int64)
# print('image size: ',imgs[0].size())
height = imgs[0].size()[1]
weight = imgs[0].size()[2]
tensor = torch.zeros((len(imgs), 3, height, weight), dtype=torch.uint8).contiguous(memory_format=memory_format)
for i, img in enumerate(imgs):
nump_array = np.asarray(img, dtype=np.uint8)
if nump_array.ndim < 3:
nump_array = np.expand_dims(nump_array, axis=-1)
# nump_array = np.rollaxis(nump_array, 2)
tensor[i] += torch.from_numpy(nump_array)
return tensor, targets
# pylint: disable=too-few-public-methods
class Lighting():
"""Lighting noise(AlexNet - style PCA - based noise)"""
def __init__(self, alphastd, eigval, eigvec):
self.alphastd = alphastd
self.eigval = eigval
self.eigvec = eigvec
def __call__(self, img):
if self.alphastd == 0:
return img
alpha = img.new().resize_(3).normal_(0, self.alphastd)
rgb = self.eigvec.type_as(img).clone() \
.mul(alpha.view(1, 3).expand(3, 3)) \
.mul(self.eigval.view(1, 3).expand(3, 3)) \
.sum(1).squeeze()
return img.add(rgb.view(3, 1, 1).expand_as(img))
def load_imagenet_like(dataset_name, set_name, train_augment, random_erase, auto_augment,
data_dir, input_image_size, input_image_crop, rank, world_size,
shuffle, batch_size, num_workers, drop_last, dataset_image_folder_class,
dataloader_testing, channel_last=False):
"""load imagenet dataset
:param dataset_name (str): dataset name
:param set_name (str): train or val
:param batch_size (int): batch size
:param train_augment (bool): data augmentation
:param random_erase (bool): random erase
:param auto_augment (bool): Auto Augmentation
:param input_image_size (int): input image size
:param input_image_crop (float): input image crop ratio
:param rank (int): rank
:param world_size (int): number of GPUs
:param shuffle (bool): shuffle
:param num_workers (int): the number of workers
:param drop_last (bool): drop last
:param dataset_image_folder_class: datasets.ImageFolder
:param dataloader_testing (bool): dataloader testing
:param channel_last (bool): channel_last or contiguous_format
:return data_loader, sampler
"""
resize_image_size = int(math.ceil(input_image_size / input_image_crop))
transforms_normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
if train_augment is False:
assert random_erase is False and auto_augment is False
transform_list = [transforms.Resize(resize_image_size, interpolation=PIL.Image.BICUBIC),
transforms.CenterCrop(input_image_size),
transforms.ToTensor(), transforms_normalize]
else:
if auto_augment:
transform_list = [transforms.RandomResizedCrop(input_image_size, interpolation=PIL.Image.BICUBIC),
transforms.RandomHorizontalFlip(),
autoaugment.ImageNetPolicy(),
transforms.ToTensor(),
Lighting(LIGHTING_PARAM, _IMAGENET_PCA['eigval'], _IMAGENET_PCA['eigvec']),
transforms_normalize]
else:
transform_list = [transforms.RandomResizedCrop(input_image_size, interpolation=PIL.Image.BICUBIC),
transforms.RandomHorizontalFlip(),
transforms.ColorJitter(0.4, 0.4, 0.4),
transforms.ToTensor(),
Lighting(LIGHTING_PARAM, _IMAGENET_PCA['eigval'], _IMAGENET_PCA['eigvec']),
transforms_normalize]
if random_erase:
transform_list.append(hotfix.transforms.RandomErasing())
transformer = transforms.Compose(transform_list)
the_dataset = dataset_image_folder_class(data_dir, transformer)
if dataloader_testing:
tmp_indices = np.arange(0, len(the_dataset))
indices_or_sections = 100 if set_name == 'train' else 10
tmp_indices = np.array_split(tmp_indices, indices_or_sections)[0]
the_dataset = torch.utils.data.Subset(the_dataset, indices=tmp_indices)
if shuffle:
sampler = torch.utils.data.distributed.DistributedSampler(the_dataset)
else:
sampler = None
if world_size > 1:
tmp_indices = np.arange(0, len(the_dataset))
tmp_indices = np.array_split(tmp_indices, world_size)[rank]
the_dataset = torch.utils.data.Subset(the_dataset, indices=tmp_indices)
data_loader = torch.utils.data.DataLoader(the_dataset, batch_size=batch_size, shuffle=False,
num_workers=num_workers, pin_memory=True, sampler=sampler,
drop_last=drop_last)
return {'data_loader': data_loader,
'sampler': sampler,
}
# pylint: disable=too-many-branches
def load_cifar_like(dataset_name, set_name, train_augment, random_erase, auto_augment,
data_dir, input_image_size, input_image_crop, rank, world_size,
shuffle, batch_size, num_workers, drop_last, dataset_image_folder_class,
dataloader_testing=False):
"""load cifar dataset
:param dataset_name (str): dataset name
:param set_name (str): train or val
:param batch_size (int): batch size
:param train_augment (bool): data augmentation
:param random_erase (bool): random erase
:param auto_augment (bool): Auto Augmentation
:param input_image_size (int): input image size
:param input_image_crop (float): input image crop ratio
:param rank (int): rank
:param world_size (int): number of GPUs
:param shuffle (bool): shuffle
:param num_workers (int): the number of workers
:param drop_last (bool): drop last
:param dataset_image_folder_class: datasets.ImageFolder
:param dataloader_testing (bool): dataloader testing
:return data_loader, sampler
"""
transforms_normalize = transforms.Normalize(mean=[0.4914, 0.4822, 0.4465], std=[0.2023, 0.1994, 0.2010])
if train_augment is False:
assert random_erase is False and auto_augment is False
if input_image_size > 32:
transform_list = [transforms.Resize(input_image_size, interpolation=PIL.Image.BICUBIC)]
else:
transform_list = []
transform_list += [transforms.ToTensor(), transforms_normalize]
else:
if input_image_size > 32:
resize_image_size = round(input_image_size / 0.75)
transform_list = [transforms.Resize(resize_image_size, interpolation=PIL.Image.BICUBIC)]
transform_list += [transforms.RandomResizedCrop(input_image_size, scale=(0.8, 1.0),
interpolation=PIL.Image.BICUBIC)]
else:
transform_list = [transforms.RandomCrop(input_image_size, padding=4)]
if auto_augment:
autoaugment_policy = autoaugment.CIFAR10Policy()
transform_list += [transforms.RandomHorizontalFlip(), autoaugment_policy,
transforms.ToTensor(),
transforms_normalize]
else:
transform_list += [transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms_normalize]
if random_erase:
transform_list.append(hotfix.transforms.RandomErasing())
transformer = transforms.Compose(transform_list)
if dataset_name == 'cifar10':
the_dataset = datasets.CIFAR10(root=data_dir, train=set_name == 'train', download=False, transform=transformer)
elif dataset_name == 'cifar100':
the_dataset = datasets.CIFAR100(root=data_dir, train=set_name == 'train', download=True, transform=transformer)
else:
raise ValueError('Unknown dataset_name=' + dataset_name)
if dataloader_testing:
tmp_indices = np.arange(0, len(the_dataset))
indices_or_sections = 100 if set_name == 'train' else 10
tmp_indices = np.array_split(tmp_indices, indices_or_sections)[0]
the_dataset = torch.utils.data.Subset(the_dataset, indices=tmp_indices)
if shuffle:
sampler = torch.utils.data.distributed.DistributedSampler(the_dataset,
num_replicas=world_size,
rank=rank)
else:
sampler = None
if world_size > 1:
tmp_indices = np.arange(0, len(the_dataset))
tmp_indices = np.array_split(tmp_indices, world_size)[rank]
the_dataset = torch.utils.data.Subset(the_dataset, indices=tmp_indices)
data_loader = torch.utils.data.DataLoader(the_dataset, batch_size=batch_size, shuffle=False,
num_workers=num_workers, pin_memory=True, sampler=sampler,
drop_last=drop_last)
return {'data_loader': data_loader,
'sampler': sampler,
}
# pylint: disable=inconsistent-return-statements
def _get_data_(dataset_name=None, set_name=None, batch_size=None,
train_augment=False, random_erase=False, auto_augment=False,
input_image_size=224, input_image_crop=0.875, rank=0, world_size=1,
shuffle=False, num_workers=6, drop_last=False, dataset_image_folder_class=None,
dataloader_testing=False, argv=None, channel_last=False):
"""get imagenet/cifar dataset
:param dataset_name (str): dataset name
:param set_name (str): train or val
:param batch_size (int): batch size
:param train_augment (bool): data augmentation
:param random_erase (bool): random erase
:param auto_augment (bool): Auto Augmentation
:param input_image_size (int): input image size
:param input_image_crop (float): input image crop ratio
:param rank (int): rank
:param world_size (int): number of GPUs
:param shuffle (bool): shuffle
:param num_workers (int): the number of workers
:param drop_last (bool): drop last
:param dataset_image_folder_class: datasets.ImageFolder
:param dataloader_testing (bool): dataloader testing
:param argv: sys.argv
:param channel_last (bool): channel_last or contiguous_format
:return data_loader, sampler
"""
if dataset_name in ['imagenet', 'myimagenet100']:
dataset_params = params_dict[dataset_name]
data_dir = dataset_params['train_dir'] if set_name == 'train' else dataset_params['val_dir']
if dataset_image_folder_class is None:
dataset_image_folder_class = datasets.ImageFolder
return load_imagenet_like(dataset_name=dataset_name, set_name=set_name, train_augment=train_augment,
random_erase=random_erase, auto_augment=auto_augment,
data_dir=data_dir,
input_image_size=input_image_size, input_image_crop=input_image_crop, rank=rank,
world_size=world_size, shuffle=shuffle, batch_size=batch_size,
num_workers=num_workers, drop_last=drop_last,
dataset_image_folder_class=dataset_image_folder_class,
dataloader_testing=dataloader_testing,
channel_last=channel_last)
if dataset_name in ['cifar10', 'cifar100']:
dataset_params = params_dict[dataset_name]
data_dir = dataset_params['train_dir'] if set_name == 'train' else dataset_params['val_dir']
if dataset_image_folder_class is None:
dataset_image_folder_class = datasets.ImageFolder
return load_cifar_like(dataset_name=dataset_name, set_name=set_name, train_augment=train_augment,
random_erase=random_erase, auto_augment=auto_augment,
data_dir=data_dir,
input_image_size=input_image_size, input_image_crop=input_image_crop, rank=rank,
world_size=world_size, shuffle=shuffle, batch_size=batch_size,
num_workers=num_workers, drop_last=drop_last,
dataset_image_folder_class=dataset_image_folder_class,
dataloader_testing=dataloader_testing)
def get_data(opt, argv):
"""get train/val loader and sampler"""
dataset_name = opt.dataset
batch_size = opt.batch_size_per_gpu
random_erase = opt.random_erase
auto_augment = opt.auto_augment
input_image_size = opt.input_image_size
input_image_crop = opt.input_image_crop
rank = opt.rank
world_size = opt.world_size
num_workers = opt.workers_per_gpu
channel_last = opt.channels_last
# check if independent training
if opt.independent_training:
rank = 0
world_size = 1
# load train set
set_name = 'train'
if opt.no_data_augment:
train_augment = False
else:
train_augment = True
shuffle = True
drop_last = True
batch_size *= opt.batches_per_allreduce
train_dataset_info = _get_data_(dataset_name, set_name, batch_size, train_augment, random_erase, auto_augment,
input_image_size, input_image_crop, rank, world_size, shuffle,
num_workers, drop_last, dataloader_testing=opt.dataloader_testing,
argv=argv, channel_last=channel_last)
# load val set
set_name = 'val'
train_augment = False
random_erase = False
auto_augment = False
shuffle = False
drop_last = False
val_dataset_info = _get_data_(dataset_name, set_name, batch_size, train_augment, random_erase, auto_augment,
input_image_size, input_image_crop, rank, world_size, shuffle,
num_workers, drop_last, dataloader_testing=opt.dataloader_testing,
argv=argv, channel_last=channel_last)
return {
'train_loader': train_dataset_info['data_loader'],
'val_loader': val_dataset_info['data_loader'],
'train_sampler': train_dataset_info['sampler'],
'val_sampler': val_dataset_info['sampler'],
}
|
!function(e){const i=e.af=e.af||{};i.dictionary=Object.assign(i.dictionary||{},{"%0 of %1":"","Align center":"Belyn in die middel","Align left":"Belyn links","Align right":"Belyn regs","Block quote":"Blok-aanhaling",Bold:"Vetgedruk",Cancel:"Kanselleer","Cannot upload file:":"Lêer nie opgelaai nie:","Could not insert image at the current position.":"Beeld kan nie in die posisie toegevoeg word nie.","Could not obtain resized image URL.":"","Insert image or file":"Voeg beeld of lêer in","Inserting image failed":"",Italic:"Skuinsgedruk",Justify:"Belyn beide kante","Remove color":"","Restore default":"",Save:"Berg","Selecting resized image failed":"","Show more items":"",Strikethrough:"Deurgetrek","Text alignment":"Teksbelyning","Text alignment toolbar":"",Underline:"Onderstreep"}),i.getPluralForm=function(e){return 1!=e}}(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={})); |
define(["../../../polymer/polymer-legacy.js", "../../../polymer/lib/legacy/polymer-fn.js", "../../../polymer/lib/utils/html-tag.js", "../app-scroll-effects-behavior.js"], function (_polymerLegacy, _polymerFn, _htmlTag, _appScrollEffectsBehavior) {
"use strict";
var _templateObject_93b2a5c0941711ec8d52c707f928eca0;
(0, _polymerFn.Polymer)({
_template: (0, _htmlTag.html)(_templateObject_93b2a5c0941711ec8d52c707f928eca0 || (_templateObject_93b2a5c0941711ec8d52c707f928eca0 = babelHelpers.taggedTemplateLiteral(["\n <style>\n :host {\n position: relative;\n display: block;\n }\n\n #background,\n #backgroundFrontLayer,\n #backgroundRearLayer {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n }\n\n #backgroundFrontLayer {\n bottom: -200px;\n }\n\n #mainTitle, #condensedTitle {\n display: block;\n overflow: hidden;\n margin: 0;\n padding: 0;\n position: absolute;\n }\n\n #mainTitle {\n height: 18px;\n top: 0;\n left: 0;\n }\n\n #condensedTitle {\n height: 37px;\n top: 100px;\n left: 100px;\n }\n\n </style>\n\n <div id=\"background\"></div>\n <div id=\"backgroundFrontLayer\"></div>\n <div id=\"backgroundRearLayer\"></div>\n <h4 id=\"mainTitle\">Title</h4>\n <h1 id=\"condensedTitle\">Condensed title</h1>\n"]))),
is: 'x-container',
behaviors: [_appScrollEffectsBehavior.AppScrollEffectsBehavior],
properties: {
shadow: {
type: Boolean,
reflectToAttribute: true
}
},
observers: ['_xScrollEffectChanged(effects)'],
_getDOMRef: function _getDOMRef(id) {
return this.$[id] || null;
},
_updateScrollState: function _updateScrollState(scrollTop) {
this._runEffects(scrollTop / this.offsetHeight, scrollTop);
},
_xScrollEffectChanged: function _xScrollEffectChanged() {
this._updateScrollState(this._scrollTop);
}
});
}); |
'use strict'
var __decorate =
(this && this.__decorate) ||
function(decorators, target, key, desc) {
var c = arguments.length,
r =
c < 3
? target
: desc === null
? (desc = Object.getOwnPropertyDescriptor(target, key))
: desc,
d
if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function')
r = Reflect.decorate(decorators, target, key, desc)
else
for (var i = decorators.length - 1; i >= 0; i--)
if ((d = decorators[i]))
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r
return c > 3 && r && Object.defineProperty(target, key, r), r
}
var __metadata =
(this && this.__metadata) ||
function(k, v) {
if (typeof Reflect === 'object' && typeof Reflect.metadata === 'function')
return Reflect.metadata(k, v)
}
var __param =
(this && this.__param) ||
function(paramIndex, decorator) {
return function(target, key) {
decorator(target, key, paramIndex)
}
}
Object.defineProperty(exports, '__esModule', { value: true })
const openapi = require('@nestjs/swagger')
const common_1 = require('@nestjs/common')
const swagger_1 = require('@nestjs/swagger')
const like_dto_1 = require('./dto/like.dto')
const like_service_1 = require('./like.service')
let LikeController = class LikeController {
constructor(likesService) {
this.likesService = likesService
}
async create(data) {
try {
return this.likesService.add(data)
} catch (error) {
throw new Error(error)
}
}
async unlike(data) {
try {
return this.likesService.edit(data.uid, data)
} catch (error) {
throw new Error(error)
}
}
async relike(data) {
try {
return this.likesService.edit(data.uid, data)
} catch (error) {
throw new Error(error)
}
}
async findAndCount(req) {
try {
const { post_uid } = req.query
return this.likesService.findLikeCount(post_uid)
} catch (error) {
throw new Error(error)
}
}
async findAll() {
try {
return this.likesService.findAll()
} catch (error) {
throw new Error(error)
}
}
}
__decorate(
[
common_1.Post('like'),
swagger_1.ApiCreatedResponse({
status: 201,
description: 'The post has been successfully liked.',
type: like_dto_1.LikeDTO,
}),
swagger_1.ApiResponse({ status: 403, description: 'Forbidden.' }),
openapi.ApiResponse({ status: 201, type: Object }),
__param(0, common_1.Body()),
__metadata('design:type', Function),
__metadata('design:paramtypes', [like_dto_1.LikeDTO]),
__metadata('design:returntype', Promise),
],
LikeController.prototype,
'create',
null,
)
__decorate(
[
common_1.Put('unlike'),
swagger_1.ApiCreatedResponse({
status: 201,
description: 'The post has been successfully unliked.',
type: like_dto_1.LikeDTO,
}),
swagger_1.ApiResponse({ status: 403, description: 'Forbidden.' }),
openapi.ApiResponse({ status: 200, type: Object }),
__param(0, common_1.Body()),
__metadata('design:type', Function),
__metadata('design:paramtypes', [like_dto_1.LikeDTO]),
__metadata('design:returntype', Promise),
],
LikeController.prototype,
'unlike',
null,
)
__decorate(
[
common_1.Put('relike'),
swagger_1.ApiCreatedResponse({
status: 201,
description: 'The post has been successfully reliked.',
type: like_dto_1.LikeDTO,
}),
swagger_1.ApiResponse({ status: 403, description: 'Forbidden.' }),
openapi.ApiResponse({ status: 200, type: Object }),
__param(0, common_1.Body()),
__metadata('design:type', Function),
__metadata('design:paramtypes', [like_dto_1.LikeDTO]),
__metadata('design:returntype', Promise),
],
LikeController.prototype,
'relike',
null,
)
__decorate(
[
common_1.Get('likes'),
swagger_1.ApiCreatedResponse({
status: 201,
description: 'All likes have been successfully retreived.',
type: [like_dto_1.LikeDTO],
}),
swagger_1.ApiResponse({ status: 403, description: 'Forbidden.' }),
openapi.ApiResponse({ status: 200, type: Object }),
__param(0, common_1.Req()),
__metadata('design:type', Function),
__metadata('design:paramtypes', [Object]),
__metadata('design:returntype', Promise),
],
LikeController.prototype,
'findAndCount',
null,
)
__decorate(
[
common_1.Get('post_likes'),
swagger_1.ApiCreatedResponse({
status: 201,
description: 'All likes have been successfully retreived.',
type: [like_dto_1.LikeDTO],
}),
swagger_1.ApiResponse({ status: 403, description: 'Forbidden.' }),
openapi.ApiResponse({ status: 200, type: Object }),
__metadata('design:type', Function),
__metadata('design:paramtypes', []),
__metadata('design:returntype', Promise),
],
LikeController.prototype,
'findAll',
null,
)
LikeController = __decorate(
[
swagger_1.ApiTags('posts'),
common_1.Controller('likes'),
__metadata('design:paramtypes', [like_service_1.LikeService]),
],
LikeController,
)
exports.LikeController = LikeController
//# sourceMappingURL=like.controller.js.map
|
"use strict";
/*
This is a stripped down version of the Reference object in FHIR
(https://www.hl7.org/fhir/references.html)
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=Reference.js.map |
var Issue = require('../issue');
module.exports = {
name: 'focusable-tabindex-style',
on: ['tag'],
filter: ['a', 'area', 'button', 'input', 'img', 'select', 'textarea'],
desc: [
'If set, all focusable elements',
'(`a`, `area`, `button`, `input`, `img`, `select`, `textarea`)',
'must have a positive `tabindex` attribute, if any.',
'',
'Reasoning: [IITAA, 10.3 and 10.4](http://www.dhs.state.il.us/IITAA/IITAAWebImplementationGuidelines.html)'
].join('\n'),
detectedStyle: null
};
module.exports.end = function () {
this.detectedStyle = null;
};
module.exports.lint = function (element, opts) {
if (this.isDisabled(element)) {
return [];
}
var tabIndexStyle = this.getTabIndexStyle(element);
if (this.detectedStyle !== null &&
this.detectedStyle !== tabIndexStyle) {
var msg = tabIndexStyle ? 'remove the tabindex'
: 'add a positive tabindex';
return new Issue('E026', element.openLineCol, {op: msg});
}
this.detectedStyle = tabIndexStyle;
return [];
};
module.exports.isDisabled = function (element) {
return element.attribs && element.attribs.hasOwnProperty('disabled');
};
module.exports.getTabIndexStyle = function (element) {
var a = element.attribs;
if (a && a.hasOwnProperty('tabindex') && typeof a !== 'undefined') {
return a.tabindex.value > 0;
}
return false;
};
|
#bet, chips, player, check, bet_or_raise, call, fold, button, ante |
import pandas as pd
import numpy as np
import os
from collections import defaultdict
import re
from typing import Dict, Union, Generator, DefaultDict
from sklearn import model_selection
from src.data.logparser import parse_file_drain3, save_drain3_to_file
SEED = 160121
def load_labels(file_path: str) -> pd.DataFrame:
df = pd.read_csv(file_path, converters={'Label': lambda x: True if x == 'Anomaly' else False})
return df
def load_data(file_path: str) -> DefaultDict:
traces = defaultdict(list)
regex = re.compile(r'(blk_-?\d+)') # pattern eg. blk_-1608999687919862906
with open(file_path, 'r') as f:
for line in f:
block_id = find_block_id_in_log(regex, line)
traces[block_id].append(line)
return traces
def find_block_id_in_log(regex: re.Pattern, line: str) -> str:
res = regex.search(line)
return res.group()
def save_logs_to_file(data: Dict, file_path: str):
with open(file_path, 'w') as f:
for logs in data.values():
f.writelines(logs)
def save_labels_to_file(data: pd.DataFrame, file_path: str):
data.replace({True: 'Anomaly', False: 'Normal'}).to_csv(file_path, index=False)
def get_data_by_indices(data: Union[DefaultDict, Dict], labels: pd.DataFrame) -> Dict:
ret = {block_id: data[block_id] for block_id in labels['BlockId']}
return ret
def stratified_train_test_split(data: Union[DefaultDict, Dict], labels: pd.DataFrame, test_size: float,
seed: int) -> tuple:
# assumes that one block is one label, otherwise it would generate more data
train_labels, test_labels = model_selection.train_test_split(labels, stratify=labels['Label'], test_size=test_size,
random_state=seed)
train_data = get_data_by_indices(data, train_labels)
test_data = get_data_by_indices(data, test_labels)
return train_data, test_data, train_labels, test_labels
def process_raw_hdfs(data_dir: str, output_dir: str = None, save_to_file: bool = True, test_size: float = 0.1) -> tuple:
"""
The logs are sliced into traces according to block ids. Then each trace associated with a specific block id is
assigned a ground-truth label.
:return:
"""
labels = load_labels(os.path.join(data_dir, 'anomaly_label.csv'))
data = load_data(os.path.join(data_dir, 'HDFS.log'))
data_drain3 = parse_file_drain3(data)
train_data, test_data, train_labels, test_labels = stratified_train_test_split(data, labels, seed=SEED,
test_size=test_size)
train_data_drain3 = get_data_by_indices(data_drain3, train_labels)
test_data_drain3 = get_data_by_indices(data_drain3, test_labels)
if save_to_file and output_dir:
save_logs_to_file(train_data, os.path.join(output_dir, 'train-data-HDFS1.log'))
save_logs_to_file(test_data, os.path.join(output_dir, 'test-data-HDFS1.log'))
save_drain3_to_file(train_data_drain3, os.path.join(output_dir, 'train-data-Drain3-HDFS1.binlog'))
save_drain3_to_file(test_data_drain3, os.path.join(output_dir, 'test-data-Drain3-HDFS1.binlog'))
save_labels_to_file(train_labels, os.path.join(output_dir, 'train-labels-HDFS1.csv'))
save_labels_to_file(test_labels, os.path.join(output_dir, 'test-labels-HDFS1.csv'))
return (train_data, test_data, train_labels, test_labels), (train_data_drain3,)
def get_train_val_hdfs(data: Dict, labels: pd.DataFrame, n_folds: int, test_size: float = 0.1) -> Generator:
if n_folds == 1: # it isn't CV but train_test_split
yield stratified_train_test_split(data, labels, seed=SEED, test_size=test_size)
else:
skf = model_selection.StratifiedKFold(n_folds, shuffle=True, random_state=SEED)
for train_index, test_index in skf.split(np.zeros(len(labels)), labels['Label']): # data is not important here
train_labels = labels.iloc[train_index]
test_labels = labels.iloc[test_index]
train_data = get_data_by_indices(data, train_labels)
test_data = get_data_by_indices(data, test_labels)
yield train_data, test_data, train_labels, test_labels
def prepare_and_save_splits(data_dir: str, output_dir: str, n_folds: int):
(train_data_logs, _, train_labels_logs, _), (train_data_drain3,) = process_raw_hdfs(data_dir, output_dir)
splits = get_train_val_hdfs(train_data_logs, train_labels_logs, n_folds)
for idx, (train_data, test_data, train_labels, test_labels) in enumerate(splits, start=1):
save_logs_to_file(train_data, os.path.join(output_dir, f'train-data-HDFS1-cv{idx}-{n_folds}.log'))
save_logs_to_file(test_data, os.path.join(output_dir, f'val-data-HDFS1-cv{idx}-{n_folds}.log'))
save_labels_to_file(train_labels, os.path.join(output_dir, f'train-labels-HDFS1-cv{idx}-{n_folds}.csv'))
save_labels_to_file(test_labels, os.path.join(output_dir, f'val-labels-HDFS1-cv{idx}-{n_folds}.csv'))
# save data for baseline methods parsed by Drain3
splits = get_train_val_hdfs(train_data_drain3, train_labels_logs, n_folds)
for idx, (train_data, test_data, train_labels, test_labels) in enumerate(splits, start=1):
save_drain3_to_file(train_data, os.path.join(output_dir, f'train-data-Drain3-HDFS1-cv{idx}-{n_folds}.binlog'))
save_drain3_to_file(test_data, os.path.join(output_dir, f'val-data-Drain3-HDFS1-cv{idx}-{n_folds}.binlog'))
|
const sqlite3 = require('sqlite3')
const { open } = require('sqlite') // traz o método open do sqlite3
module.exports = () =>
open({
filename: './database.sqlite',
driver: sqlite3.Database
})
|
import React, { useState, useEffect } from "react";
import { Drawer as MantineDrawer } from "@mantine/core";
import PropTypes from "prop-types";
import { omit } from "ramda";
import { renderDashComponent } from "dash-extensions-js";
/**
* Display overlay area at any side of the screen. For more information, see: https://mantine.dev/core/drawer/
*/
const Drawer = (props) => {
const { opened, children, setProps, class_name, title } = props;
const [open, setOpen] = useState(opened);
useEffect(() => {
setOpen(opened);
}, [opened]);
const onClose = () => {
setOpen(false);
setProps({ opened: false });
};
return (
<MantineDrawer
{...omit(
["opened", "setProps", "children", "class_name", "title"],
props
)}
opened={open}
onClose={onClose}
className={class_name}
title={renderDashComponent(title)}
>
{children}
</MantineDrawer>
);
};
Drawer.displayName = "Drawer";
Drawer.defaultProps = {
opened: false,
};
Drawer.propTypes = {
/**
* Drawer children components
*/
children: PropTypes.node,
/**
* Often used with CSS to style elements with common properties
*/
class_name: PropTypes.string,
/**
* Disable onClick trigger for outside events
*/
closeOnClickOutside: PropTypes.bool,
/**
* Disable onClick trigger for escape key press
*/
closeOnEscape: PropTypes.bool,
/**
* Hides close button, modal still can be closed with escape key and by clicking outside
*/
hideCloseButton: PropTypes.bool,
/**
* The ID of this component, used to identify dash components in callbacks
*/
id: PropTypes.string,
/**
* Disables scroll lock
*/
lockScroll: PropTypes.bool,
/**
* If true drawer is mounted to the dom
*/
opened: PropTypes.bool,
/**
* Sets overlay color, defaults to theme.black in light theme and to theme.colors.dark[9] in dark theme
*/
overlayColor: PropTypes.string,
/**
* Sets overlay opacity, defaults to 0.75 in light theme and to 0.85 in dark theme
*/
overlayOpacity: PropTypes.number,
/**
* Drawer body padding from theme or number for padding in px
*/
padding: PropTypes.oneOfType([
PropTypes.oneOf(["xs", "sm", "md", "lg", "xl"]),
PropTypes.number,
]),
/**
* Drawer body position
*/
position: PropTypes.oneOf(["left", "right", "top", "bottom"]),
/**
* Tells dash if any prop has changed its value
*/
setProps: PropTypes.func,
/**
* Drawer body shadow from theme or any css shadow value
*/
shadow: PropTypes.oneOfType([
PropTypes.oneOf(["xs", "sm", "md", "lg", "xl"]),
PropTypes.number,
]),
/**
* Drawer body width (right | left position) or height (top | bottom position), cannot exceed 100vh for height and 100% for width
*/
size: PropTypes.oneOfType([
PropTypes.oneOf(["xs", "sm", "md", "lg", "xl"]),
PropTypes.string,
PropTypes.number,
]),
/**
* Drawer title, displayed in header before close button
*/
title: PropTypes.any,
/**
* Drawer appear and disappear transition, see Transition component for full documentation
*/
transition: PropTypes.oneOf([
"fade",
"skew-up",
"skew-down",
"rotate-right",
"rotate-left",
"slide-down",
"slide-up",
"slide-right",
"slide-left",
"scale-y",
"scale-x",
"scale",
"pop",
"pop-top-left",
"pop-top-right",
"pop-bottom-left",
"pop-bottom-right",
]),
/**
* Transition duration in ms
*/
transitionDuration: PropTypes.number,
/**
* Drawer transitionTimingFunction css property
*/
transitionTimingFunction: PropTypes.string,
/**
* Disables focus trap
*/
trapFocus: PropTypes.bool,
/**
* Hides close button if set to false, drawer still can be closed with escape key and by clicking outside
*/
withCloseButton: PropTypes.bool,
/**
* Removes overlay entirely
*/
withOverlay: PropTypes.bool,
/**
* Popper zIndex
*/
zIndex: PropTypes.number,
};
export default Drawer;
|
// Copyright 2018-2021 Polyaxon, Inc.
//
// 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.
/**
* Polyaxon SDKs and REST API specification.
* Polyaxon SDKs and REST API specification.
*
* The version of the OpenAPI document: 1.11.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD.
define(['expect.js', process.cwd()+'/src/index'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
factory(require('expect.js'), require(process.cwd()+'/src/index'));
} else {
// Browser globals (root is window)
factory(root.expect, root.PolyaxonSdk);
}
}(this, function(expect, PolyaxonSdk) {
'use strict';
var instance;
beforeEach(function() {
instance = new PolyaxonSdk.V1TruncationStoppingPolicy();
});
var getProperty = function(object, getter, property) {
// Use getter method if present; otherwise, get the property directly.
if (typeof object[getter] === 'function')
return object[getter]();
else
return object[property];
}
var setProperty = function(object, setter, property, value) {
// Use setter method if present; otherwise, set the property directly.
if (typeof object[setter] === 'function')
object[setter](value);
else
object[property] = value;
}
describe('V1TruncationStoppingPolicy', function() {
it('should create an instance of V1TruncationStoppingPolicy', function() {
// uncomment below and update the code to test V1TruncationStoppingPolicy
//var instane = new PolyaxonSdk.V1TruncationStoppingPolicy();
//expect(instance).to.be.a(PolyaxonSdk.V1TruncationStoppingPolicy);
});
it('should have the property kind (base name: "kind")', function() {
// uncomment below and update the code to test the property kind
//var instane = new PolyaxonSdk.V1TruncationStoppingPolicy();
//expect(instance).to.be();
});
it('should have the property percent (base name: "percent")', function() {
// uncomment below and update the code to test the property percent
//var instane = new PolyaxonSdk.V1TruncationStoppingPolicy();
//expect(instance).to.be();
});
it('should have the property evaluationInterval (base name: "evaluationInterval")', function() {
// uncomment below and update the code to test the property evaluationInterval
//var instane = new PolyaxonSdk.V1TruncationStoppingPolicy();
//expect(instance).to.be();
});
it('should have the property minInterval (base name: "minInterval")', function() {
// uncomment below and update the code to test the property minInterval
//var instane = new PolyaxonSdk.V1TruncationStoppingPolicy();
//expect(instance).to.be();
});
it('should have the property minSamples (base name: "minSamples")', function() {
// uncomment below and update the code to test the property minSamples
//var instane = new PolyaxonSdk.V1TruncationStoppingPolicy();
//expect(instance).to.be();
});
it('should have the property includeSucceeded (base name: "includeSucceeded")', function() {
// uncomment below and update the code to test the property includeSucceeded
//var instane = new PolyaxonSdk.V1TruncationStoppingPolicy();
//expect(instance).to.be();
});
});
}));
|
############################################################
# FlatCAM: 2D Post-processing for Manufacturing #
# http://flatcam.org #
# Author: Juan Pablo Caram (c) #
# Date: 2/5/2014 #
# MIT Licence #
############################################################
#################################################
# FlatCAM - Version settings #
#################################################
import logging
version = {
"number": 8.5,
"date": (2016, 7, 1), # Year, Month, Day
"name": "MK-Dev",
"release": False,
}
def setup(app):
app.version = version["number"]
app.version_date = version["date"]
if version["release"]:
app.log.setLevel(logging.WARNING)
else:
app.log.setLevel(logging.DEBUG)
if version["name"] is None and version["release"] == False:
app.version_name = "Development Version"
else:
app.version_name = version["name"]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.