text
stringlengths
3
1.05M
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("a11yhelp","uk",{title:"Спеціальні Інструкції",contents:"Довідка. Натисніть ESC і вона зникне.",legend:[{name:"Основне",items:[{name:"Панель Редактора",legend:"Натисніть ${toolbarFocus} для переходу до панелі інструментів. Для переміщення між групами панелі інструментів використовуйте TAB і SHIFT+TAB. Для переміщення між кнопками панелі іструментів використовуйте кнопки СТРІЛКА ВПРАВО або ВЛІВО. Натисніть ПРОПУСК або ENTER для запуску кнопки панелі інструментів."},{name:"Діалог Редактора", legend:'Усередині діалогу, натисніть TAB щоб перейти до наступного елементу діалогу, натисніть SHIFT+TAB щоб перейти до попереднього елемента діалогу, натисніть ENTER щоб відправити діалог, натисніть ESC щоб скасувати діалог. Коли діалогове вікно має декілька вкладок, отримати доступ до панелі вкладок як частині діалогу можна натисканням або поєднання ALT+F10 або TAB, при цьому активні елементи діалогу будуть перебиратися з урахуванням порядку табуляції. При активній панелі вкладок, перехід до наступної або попередньої вкладці здійснюється натисканням стрілки "ВПРАВО" або стрілки "ВЛЕВО" відповідно.'}, {name:"Контекстне Меню Редактора",legend:"Press ${contextMenu} or APPLICATION KEY to open context-menu. Потім перейдіть до наступного пункту меню за допомогою TAB або СТРІЛКИ ВНИЗ. Натисніть ПРОПУСК або ENTER для вибору параметру меню. Відкрийте підменю поточного параметру, натиснувши ПРОПУСК або ENTER або СТРІЛКУ ВПРАВО. Перейдіть до батьківського елемента меню, натиснувши ESC або СТРІЛКУ ВЛІВО. Закрийте контекстне меню, натиснувши ESC."},{name:"Скринька Списків Редактора",legend:"Усередині списку, перехід до наступного пункту списку виконується клавішею TAB або СТРІЛКА ВНИЗ. Перехід до попереднього елемента списку клавішею SHIFT+TAB або СТРІЛКА ВГОРУ. Натисніть ПРОПУСК або ENTER, щоб вибрати параметр списку. Натисніть клавішу ESC, щоб закрити список."}, {name:"Шлях до елемента редактора",legend:"Натисніть ${elementsPathFocus} для навігації між елементами панелі. Перейдіть до наступного елемента кнопкою TAB або СТРІЛКА ВПРАВО. Перейдіть до попереднього елемента кнопкою SHIFT+TAB або СТРІЛКА ВЛІВО. Натисніть ПРОПУСК або ENTER для вибору елемента в редакторі."}]},{name:"Команди",items:[{name:"Відмінити команду",legend:"Натисніть ${undo}"},{name:"Повторити",legend:"Натисніть ${redo}"},{name:"Жирний",legend:"Натисніть ${bold}"},{name:"Курсив",legend:"Натисніть ${italic}"}, {name:"Підкреслений",legend:"Натисніть ${underline}"},{name:"Посилання",legend:"Натисніть ${link}"},{name:"Згорнути панель інструментів",legend:"Натисніть ${toolbarCollapse}"},{name:"Доступ до попереднього місця фокусування",legend:"Натисніть ${accessNextSpace} для доступу до найближчої недосяжної області фокусування перед кареткою, наприклад: два сусідні елементи HR. Повторіть комбінацію клавіш для досягнення віддалених областей фокусування."},{name:"Доступ до наступного місця фокусування",legend:"Натисніть ${accessNextSpace} для доступу до найближчої недосяжної області фокусування після каретки, наприклад: два сусідні елементи HR. Повторіть комбінацію клавіш для досягнення віддалених областей фокусування."}, {name:"Допомога з доступності",legend:"Натисніть ${a11yHelp}"},{name:" Paste as plain text",legend:"Press ${pastetext}",legendEdge:"Press ${pastetext}, followed by ${paste}"}]}],tab:"Tab",pause:"Pause",capslock:"Caps Lock",escape:"Esc",pageUp:"Page Up",pageDown:"Page Down",leftArrow:"Ліва стрілка",upArrow:"Стрілка вгору",rightArrow:"Права стрілка",downArrow:"Стрілка вниз",insert:"Вставити",leftWindowKey:"Ліва клавіша Windows",rightWindowKey:"Права клавіша Windows",selectKey:"Виберіть клавішу",numpad0:"Numpad 0", numpad1:"Numpad 1",numpad2:"Numpad 2",numpad3:"Numpad 3",numpad4:"Numpad 4",numpad5:"Numpad 5",numpad6:"Numpad 6",numpad7:"Numpad 7",numpad8:"Numpad 8",numpad9:"Numpad 9",multiply:"Множення",add:"Додати",subtract:"Віднімання",decimalPoint:"Десяткова кома",divide:"Ділення",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Num Lock",scrollLock:"Scroll Lock",semiColon:"Крапка з комою",equalSign:"Знак рівності",comma:"Кома",dash:"Тире",period:"Період", forwardSlash:"Коса риска",graveAccent:"Гравіс",openBracket:"Відкрити дужку",backSlash:"Зворотна коса риска",closeBracket:"Закрити дужку",singleQuote:"Одинарні лапки"});
const { Schema, Types } = require('mongoose'); const reactionSchema = new Schema( { reactionId: { type: Schema.Types.ObjectId, default: () => new Types.ObjectId(), }, reactionBody: { type: String, required: true, maxlength: 280, }, username: { type: String, required: true, }, createdAt: { type: Date, default: Date.now, }, }, { toJSON: { getters: true, }, id: false, } ); reactionSchema.virtual('created') .get(function () { return this.createdAt.default; }); module.exports = reactionSchema;
// FNV_PRIMES and FNV_OFFSETS from // http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param const FNV_PRIMES = { 32: 16_777_619n, 64: 1_099_511_628_211n, 128: 309_485_009_821_345_068_724_781_371n, 256: 374_144_419_156_711_147_060_143_317_175_368_453_031_918_731_002_211n, 512: 35_835_915_874_844_867_368_919_076_489_095_108_449_946_327_955_754_392_558_399_825_615_420_669_938_882_575_126_094_039_892_345_713_852_759n, 1024: 5_016_456_510_113_118_655_434_598_811_035_278_955_030_765_345_404_790_744_303_017_523_831_112_055_108_147_451_509_157_692_220_295_382_716_162_651_878_526_895_249_385_292_291_816_524_375_083_746_691_371_804_094_271_873_160_484_737_966_720_260_389_217_684_476_157_468_082_573n, }; const FNV_OFFSETS = { 32: 2_166_136_261n, 64: 14_695_981_039_346_656_037n, 128: 144_066_263_297_769_815_596_495_629_667_062_367_629n, 256: 100_029_257_958_052_580_907_070_968_620_625_704_837_092_796_014_241_193_945_225_284_501_741_471_925_557n, 512: 9_659_303_129_496_669_498_009_435_400_716_310_466_090_418_745_672_637_896_108_374_329_434_462_657_994_582_932_197_716_438_449_813_051_892_206_539_805_784_495_328_239_340_083_876_191_928_701_583_869_517_785n, 1024: 14_197_795_064_947_621_068_722_070_641_403_218_320_880_622_795_441_933_960_878_474_914_617_582_723_252_296_732_303_717_722_150_864_096_521_202_355_549_365_628_174_669_108_571_814_760_471_015_076_148_029_755_969_804_077_320_157_692_458_563_003_215_304_957_150_157_403_644_460_363_550_505_412_711_285_966_361_610_267_868_082_893_823_963_790_439_336_411_086_884_584_107_735_010_676_915n, }; export default function fnv1a(string, {size = 32} = {}) { if (!FNV_PRIMES[size]) { throw new Error('The `size` option must be one of 32, 64, 128, 256, 512, or 1024'); } let hash = FNV_OFFSETS[size]; const fnvPrime = FNV_PRIMES[size]; // Handle Unicode code points > 0x7f let isUnicoded = false; for (let index = 0; index < string.length; index++) { let characterCode = string.charCodeAt(index); // Non-ASCII characters trigger the Unicode escape logic if (characterCode > 0x7F && !isUnicoded) { string = unescape(encodeURIComponent(string)); characterCode = string.charCodeAt(index); isUnicoded = true; } hash ^= BigInt(characterCode); hash = BigInt.asUintN(size, hash * fnvPrime); } return hash; }
import tensorflow as tf from tfsnippet.utils import (add_name_arg_doc, is_tensor_object, get_static_shape, is_shape_equal) __all__ = [ 'assert_scalar_equal', 'assert_rank', 'assert_rank_at_least', 'assert_shape_equal', ] def _assertion_error_message(expected, actual, message=None): ret = 'Assertion failed for {}: {}'.format(expected, actual) if message: ret += '; {}'.format(message) return ret def _make_assertion_error(expected, actual, message=None): return AssertionError(_assertion_error_message(expected, actual, message)) @add_name_arg_doc def assert_scalar_equal(a, b, message=None, name=None): """ Assert 0-d scalar `a` == `b`. Args: a: A 0-d tensor. b: A 0-d tensor. message: Message to display when assertion failed. Returns: tf.Operation or None: The TensorFlow assertion operation, or None if can be statically asserted. """ if not is_tensor_object(a) and not is_tensor_object(b): if a != b: raise _make_assertion_error( 'a == b', '{!r} != {!r}'.format(a, b), message) else: return tf.assert_equal(a, b, message=message, name=name) @add_name_arg_doc def assert_rank(x, ndims, message=None, name=None): """ Assert the rank of `x` is `ndims`. Args: x: A tensor. ndims (int or tf.Tensor): An integer, or a 0-d integer tensor. message: Message to display when assertion failed. Returns: tf.Operation or None: The TensorFlow assertion operation, or None if can be statically asserted. """ if not is_tensor_object(ndims) and get_static_shape(x) is not None: ndims = int(ndims) x_ndims = len(get_static_shape(x)) if x_ndims != ndims: raise _make_assertion_error( 'rank(x) == ndims', '{!r} != {!r}'.format(x_ndims, ndims), message ) else: return tf.assert_rank(x, ndims, message=message, name=name) @add_name_arg_doc def assert_rank_at_least(x, ndims, message=None, name=None): """ Assert the rank of `x` is at least `ndims`. Args: x: A tensor. ndims (int or tf.Tensor): An integer, or a 0-d integer tensor. message: Message to display when assertion failed. Returns: tf.Operation or None: The TensorFlow assertion operation, or None if can be statically asserted. """ x = tf.convert_to_tensor(x) if not is_tensor_object(ndims) and get_static_shape(x) is not None: ndims = int(ndims) x_ndims = len(get_static_shape(x)) if x_ndims < ndims: raise _make_assertion_error( 'rank(x) >= ndims', '{!r} < {!r}'.format(x_ndims, ndims), message ) else: return tf.assert_rank_at_least(x, ndims, message=message, name=name) @add_name_arg_doc def assert_shape_equal(x, y, message=None, name=None): """ Assert the shape of `x` equals to `y`. Args: x: A tensor. y: Another tensor, to compare with `x`. message: Message to display when assertion failed. Returns: tf.Operation or None: The TensorFlow assertion operation, or None if can be statically asserted. """ x = tf.convert_to_tensor(x) y = tf.convert_to_tensor(y) with tf.name_scope(name or 'assert_shape_equal', values=[x, y]): err_msg = _assertion_error_message( 'x.shape == y.shape', '{!r} vs {!r}'.format(x, y), message) compare_ret = is_shape_equal(x, y) if compare_ret is False: raise AssertionError(err_msg) elif compare_ret is True: return None else: return tf.assert_equal(compare_ret, True, message=message)
"use strict";exports.__esModule=!0,module.exports={SettingsAPI:SettingsAPI,settingsapi:settingsapi}; //# sourceMappingURL=Settings.js.map
/** * AJAX File Upload * http://github.com/davgothic/AjaxFileUpload * * Copyright (c) 2010-2013 David Hancock (http://davidhancock.co) * * Thanks to Steven Barnett for his generous contributions * * Licensed under the MIT license ( http://www.opensource.org/licenses/MIT ) */ ;(function($) { $.fn.AjaxFileUpload = function(options) { var defaults = { action: "upload.php", onChange: function(filename) {}, onSubmit: function(filename) {}, onComplete: function(filename, response) {} }, settings = $.extend({}, defaults, options), randomId = (function() { var id = 0; return function () { return "_AjaxFileUpload" + id++; }; })(); return this.each(function() { var $this = $(this); if ($this.is("input") && $this.attr("type") === "file") { $this.bind("change", onChange); } }); function onChange(e) { var $element = $(e.target), id = $element.attr('id'), $clone = $element.removeAttr('id').clone().attr('id', id).AjaxFileUpload(options), filename = $element.val().replace(/.*(\/|\\)/, ""), iframe = createIframe(), form = createForm(iframe); // We append a clone since the original input will be destroyed $clone.insertBefore($element); settings.onChange.call($clone[0], filename); iframe.bind("load", {element: $clone, form: form, filename: filename}, onComplete); form.append($element).bind("submit", {element: $clone, iframe: iframe, filename: filename}, onSubmit).submit(); } function onSubmit(e) { var data = settings.onSubmit.call(e.data.element, e.data.filename); // If false cancel the submission if (data === false) { // Remove the temporary form and iframe $(e.target).remove(); e.data.iframe.remove(); return false; } else { // Else, append additional inputs for (var variable in data) { $("<input />") .attr("type", "hidden") .attr("name", variable) .val(data[variable]) .appendTo(e.target); } } } function onComplete (e) { var $iframe = $(e.target), doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document, response = doc.body.innerText; if (response) { response = $.parseJSON(response); } else { response = {}; } settings.onComplete.call(e.data.element, e.data.filename, response); // Remove the temporary form and iframe e.data.form.remove(); $iframe.remove(); } function createIframe() { var id = randomId(); // The iframe must be appended as a string otherwise IE7 will pop up the response in a new window // http://stackoverflow.com/a/6222471/268669 $("body") .append('<iframe src="javascript:false;" name="' + id + '" id="' + id + '" style="display: none;"></iframe>'); return $('#' + id); } function createForm(iframe) { return $("<form />") .attr({ method: "post", action: settings.action, enctype: "multipart/form-data", target: iframe[0].name }) .hide() .appendTo("body"); } }; })(jQuery);
class Solution: def dayOfYear(self, date: str) -> int: year, month, day = [int(i) for i in date.split("-")] days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if year % 4 == 0 and year % 100 != 0: days_in_month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] return sum(days_in_month[:month - 1]) + day
// import 'fullcalendar'; $(document).ready(() => { var date = new Date(); var today = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(); var calendar = new FullCalendar.Calendar($("#calendar"), { header: { left: 'prev,next today', center: 'title', right: 'listDay,listWeek,month' }, themeSystem: 'bootstrap4', bootstrapFontAwesome: true, // customize the button names, // otherwise they'd all just say "list" views: { listDay: { buttonText: 'list day' }, listWeek: { buttonText: 'list week' } }, defaultView: 'listWeek', defaultDate: today, navLinks: true, // can click day/week names to navigate views editable: true, eventLimit: true, // allow "more" link when too many events events: [ { title: 'All Day Event', start: '2018-03-01' }, { title: 'Long Event', start: '2018-03-07', end: '2018-03-10' }, { id: 999, title: 'Repeating Event', start: '2018-03-09T16:00:00' }, { id: 999, title: 'Repeating Event', start: '2018-03-16T16:00:00' }, { title: 'Conference', start: '2018-03-11', end: '2018-03-13' }, { title: 'Meeting', start: '2018-03-12T10:30:00', end: '2018-03-12T12:30:00' }, { title: 'Lunch', start: '2018-03-12T12:00:00' }, { title: 'Meeting', start: '2018-03-12T14:30:00' }, { title: 'Happy Hour', start: '2018-03-12T17:30:00' }, { title: 'Dinner', start: '2018-03-12T20:00:00' }, { title: 'Birthday Party', start: '2018-03-13T07:00:00' }, { title: 'Click for Google', url: 'http://google.com/', start: '2018-03-28' } ] }); $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,basicWeek,basicDay' }, themeSystem: 'bootstrap4', bootstrapFontAwesome: true, defaultDate: today, navLinks: true, // can click day/week names to navigate views editable: true, eventLimit: true, // allow "more" link when too many events events: [ { title: 'All Day Event', start: '2018-03-01' }, { // TODO THIS IS WHAT I NEED FOR DISPLAYING ABSENCES title: 'Long Event', start: '2018-03-07', end: '2018-03-10' }, { id: 999, title: 'Repeating Event', start: '2018-03-09T16:00:00' }, { id: 999, title: 'Repeating Event', start: '2018-03-16T16:00:00' }, { title: 'Conference', start: '2018-03-11', end: '2018-03-13' }, { title: 'Meeting', start: '2018-03-12T10:30:00', end: '2018-03-12T12:30:00' }, { title: 'Lunch', start: '2018-03-12T12:00:00' }, { title: 'Meeting', start: '2018-03-12T14:30:00' }, { title: 'Happy Hour', start: '2018-03-12T17:30:00' }, { title: 'Dinner', start: '2018-03-12T20:00:00' }, { title: 'Birthday Party', start: '2018-03-13T07:00:00' }, { title: 'Click for Google', url: 'http://google.com/', start: '2018-03-28' } ] }); $('#calendar-bg-events').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay,listMonth' }, themeSystem: 'bootstrap4', bootstrapFontAwesome: true, defaultDate: '2018-03-12', navLinks: true, // can click day/week names to navigate views businessHours: true, // display business hours editable: true, events: [ { title: 'Business Lunch', start: '2018-03-03T13:00:00', constraint: 'businessHours' }, { title: 'Meeting', start: '2018-03-13T11:00:00', constraint: 'availableForMeeting', // defined below color: '#257e4a' }, { title: 'Conference', start: '2018-03-18', end: '2018-03-20' }, { title: 'Party', start: '2018-03-29T20:00:00' }, // areas where "Meeting" must be dropped { id: 'availableForMeeting', start: '2018-03-11T10:00:00', end: '2018-03-11T16:00:00', rendering: 'background' }, { id: 'availableForMeeting', start: '2018-03-13T10:00:00', end: '2018-03-13T16:00:00', rendering: 'background' }, // red areas where no events can be dropped { start: '2018-03-24', end: '2018-03-28', overlap: false, rendering: 'background', color: 'var(--danger)' }, { start: '2018-03-06', end: '2018-03-08', overlap: false, rendering: 'background', color: 'var(--success)' } ] }); });
/* Create a function that: * **Takes** an array of animals * Each animal has propeties `name`, `species` and `legsCount` * **groups** the animals by `species` * the groups are sorted by `species` descending * **sorts** them ascending by `legsCount` * if two animals have the same number of legs sort them by name * **prints** them to the console in the format: ``` ----------- (number of dashes is equal to the length of the GROUP_1_NAME + 1) GROUP_1_NAME: ----------- (number of dashes is equal to the length of the GROUP_1_NAME + 1) NAME has LEGS_COUNT legs //for the first animal in group 1 NAME has LEGS_COUNT legs //for the second animal in group 1 ----------- (number of dashes is equal to the length of the GROUP_2_NAME + 1) GROUP_2_NAME: ----------- (number of dashes is equal to the length of the GROUP_2_NAME + 1) NAME has LEGS_COUNT legs //for the first animal in the group 2 NAME has LEGS_COUNT legs //for the second animal in the group 2 NAME has LEGS_COUNT legs //for the third animal in the group 2 NAME has LEGS_COUNT legs //for the fourth animal in the group 2 ``` * **Use underscore.js for all operations** */ function solve() { return function (animals) { var animalsGroupedBySpecies = _.chain(animals).sortBy('species').reverse().groupBy('species').value(); _.each(animalsGroupedBySpecies, function (value, key) { value = _.chain(value).sortBy('legsCount').sortBy(value, 'name').value(); console.log(Array(key.length + 2).join('-')); console.log(key + ':'); console.log(Array(key.length + 2).join('-')); for (var i = 0; i < value.length; i++) { console.log(value[i].name + ' has ' + value[i].legsCount + ' legs') } }); }; } module.exports = solve;
import React, { Fragment } from 'react'; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogTitle from '@material-ui/core/DialogTitle'; import { withStyles } from '@material-ui/core/styles'; import dialog from 'utils/dialog'; import classNames from 'classnames'; import DialogContentText from '@material-ui/core/DialogContentText'; const styles = { paper: { maxWidth: 2400, }, width100: { width: 100, }, width200: { width: 200, }, width300: { width: 300, }, width400: { width: 400, }, width500: { width: 500, }, width600: { width: 600, }, width700: { width: 700, }, width800: { width: 800, }, width900: { width: 900, }, width1000: { width: 1000, }, top100: { position: 'absolute', top: 100, }, top200: { position: 'absolute', top: 200, }, top300: { position: 'absolute', top: 300, }, top400: { position: 'absolute', top: 400, }, top500: { position: 'absolute', top: 500, }, warning: { verticalAlign: 'bottom', marginRight: '10px', color: '#faad14', }, content: { margin: '0 20px', display: 'grid', }, }; class CustomDialog extends React.Component { handleClose = () => { const { id, onClose } = this.props; if (onClose) { onClose(); } dialog.close(id); }; handleOk = () => { this.props.onOk(); }; renderChildren() { const { classes, title, content } = this.props; const isString = typeof content === 'string' || typeof content === 'undefined'; return ( <Fragment> <DialogTitle> {title || '提示'} </DialogTitle> <div className={classes.content}> {isString ? <DialogContentText id="alert-dialog-description"> {content} </DialogContentText> : content } </div> </Fragment>); } render() { const { classes, width, top } = this.props; return ( <Dialog classes={{ paper: classNames(classes.paper, classes[`width${width}`], classes[`top${top}`]) }} open scroll="paper" onClose={this.handleClose} > {this.renderChildren()} <DialogActions> <Button onClick={this.handleClose} color="primary"> 取消 </Button> <Button onClick={this.handleOk} color="primary"> 确定 </Button> </DialogActions> </Dialog> ); } } CustomDialog.defaultProps = { width: 400, }; export default withStyles(styles)(CustomDialog);
// exports.area = function(width, height) { // return width * height; // }; exports.numeric = function(num) { var scale = [ "", "ty", "hundred", "thousand", "ten thousand", "hundredthousand", "million" ]; var degit = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" ] // var unit = 0; // var num = num.toString().length; var readNum = ""; var number = ""; var unit = ""; var numberString = num.toString(); for (var i = 0; i <= numberString.length - 1; i++) { if (numberString[i] !== '0') { var index = numberString[i] - 1; readNum = degit[index] + scale[numberString.length - (i + 1)]; number += readNum; number = number.replace("onetyone", "eleven"); number = number.replace("onetytwo", "twelve"); number = number.replace("onetythree", "thirteen"); number = number.replace("onetyfour", "fourteen"); number = number.replace("onetyfive", "fifteen"); number = number.replace("onetysix", "sixteen"); number = number.replace("onetyseven", "seventeen"); number = number.replace("onetyeight", "eighteen"); number = number.replace("onetynine", "nineteen"); number = number.replace("twoty", "twenty"); number = number.replace("threety", "thirty"); number = number.replace("fivety", "fifty"); number = number.replace("eightty", "eighty"); number = number.replace("ninety", "ninety"); number = number.replace("twoten thousand", "twentythousand"); number = number.replace("threeten thousand", "thirtythousand"); number = number.replace("fiveten thousand", "fiftythousand"); number = number.replace("eightten thousand", "eightythousand"); number = number.replace("nineten thousand", "ninetythousand"); } // readNum = degit[numberString[i] - 1]; // unit = scale[numberString.length - 1]; // number += unit; } // number = number.replace("onetyonety", "eleven"); // number = number.replace("onety", "ten"); // number = number.replace("onetytwo", "twelve"); // number = number.replace("threety", "Thirteen"); return number; };
import { NotImplementedError } from '../extensions/index.js'; /** * Create name of dream team based on the names of its members * * @param {Array} members names of the members * @return {String | Boolean} name of the team or false * in case of incorrect members * * @example * * createDreamTeam(['Matt', 'Ann', 'Dmitry', 'Max']) => 'ADMM' * createDreamTeam(['Olivia', 1111, 'Lily', 'Oscar', true, null]) => 'LOO' * */ export default function createDreamTeam(members) { if(members instanceof Array){ return members.map(element => { if (typeof element === "string") return element.toUpperCase().trim().split('').slice(0, 1); }).sort().join(''); } else { return false; } };
const { $trace, $debug, $warn } = require('../logger')('queue') const nanoid = require('nanoid/generate') const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' function uid () { return nanoid(ALPHABET, 16) } // A queue implementation needs to be able to: // // - perform basic job queue things: // + register interest for jobs of a certain type / name // + submit jobs of any type / name // + mark jobs as being worked on (so they're not processed elsewhere) // + mark jobs as being completed // + (most job queues can do this, but message queues will need shimming) // // - and some slightly more advanced things: // + send back data to the "client" of a job on completion // + send back failure/success indications to the client // + (many job queues can do this, those that can't can be shimmed with messaging) // // - and some more advanced things // + set job progress while it's being worked on (in a way that the client can read) // + send back data to the client at any point while processing // + (only some job queues can do this natively, but messaging can shim it) // // - and ideally it should: // + be able to work on many jobs at a time given a single connection // + be able to command many jobs at a time given a single connection // + be able to query what job types / individual queues exist at this point // + and how many workers there are subscribed to each of those // + (very few job queues can do that, and it's not easy to shim) // // Gearman can do all that. But it doesn't scale well beyond a single daemon. // It might be easier to figure out *consistent* scaling of Gearman rather than // shimming a full-featured job queue on top of another queue that scales well. class Queue { constructor (client) { this.client = client this.nodeid = uid() this.registry = new Map $trace('nodeid', this.nodeid) this.register(`armstrong::job`, this.job.bind(this)) this.register(`armstrong::watch`, this.job.bind(this)) this.register(`armstrong::node::${this.nodeid}::job`, this.job.bind(this)) this.register(`armstrong::node::${this.nodeid}::query`, this.query.bind(this)) this.register(`armstrong::node::${this.nodeid}::placement`, this.placement.bind(this)) process.on('SIGINT', () => { $warn('goodness me, a sigint') this.shutdown() }) } register (name, impl) { $debug('registering', name) this.registry.set(name, impl) } async nodes () { throw new Error('should be implemented by subclass!') } async shutdown () { throw new Error('should be implemented by subclass!') } job (...args) { $debug('got job request') $trace(args) } watch (...args) { $debug('got watch request') $trace(args) } query (...args) { $debug('got query request') $trace(args) } placement (...args) { $debug('got placement request') $trace(args) } } module.exports = Queue module.exports.NODE_FN_REGEX = /^armstrong::node::(\w+)::/
import Check from "../Core/Check.js"; import defaultValue from "../Core/defaultValue.js"; import defined from "../Core/defined.js"; import MetadataEntity from "./MetadataEntity.js"; import MetadataTableProperty from "./MetadataTableProperty.js"; import MetadataType from "./MetadataType.js"; /** * A table containing binary metadata for a collection of entities. This is * used for representing binary properties of a batch table, as well as binary * metadata in 3D Tiles next extensions. * <p> * For 3D Tiles Next details, see the {@link https://github.com/CesiumGS/3d-tiles/tree/3d-tiles-next/extensions/3DTILES_metadata|3DTILES_metadata Extension} for 3D Tiles, as well as the {@link https://github.com/CesiumGS/glTF/tree/3d-tiles-next/extensions/2.0/Vendor/EXT_feature_metadata|EXT_feature_metadata Extension} for glTF. * </p> * * @param {Object} options Object with the following properties: * @param {Number} options.count The number of entities in the table. * @param {Object} [options.properties] A dictionary containing properties. * @param {MetadataClass} [options.class] The class that properties conform to. * @param {Object.<String, Uint8Array>} [options.bufferViews] An object mapping bufferView IDs to Uint8Array objects. * * @alias MetadataTable * @constructor * * @private * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy. */ function MetadataTable(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); var count = options.count; //>>includeStart('debug', pragmas.debug); Check.typeOf.number.greaterThan("options.count", count, 0); //>>includeEnd('debug'); var properties = {}; if (defined(options.properties)) { for (var propertyId in options.properties) { if (options.properties.hasOwnProperty(propertyId)) { properties[propertyId] = new MetadataTableProperty({ count: count, property: options.properties[propertyId], classProperty: options.class.properties[propertyId], bufferViews: options.bufferViews, }); } } } this._count = count; this._class = options.class; this._properties = properties; } Object.defineProperties(MetadataTable.prototype, { /** * The number of entities in the table. * * @memberof MetadataTable.prototype * @type {Number} * @readonly * @private */ count: { get: function () { return this._count; }, }, /** * The class that properties conform to. * * @memberof MetadataTable.prototype * @type {MetadataClass} * @readonly * @private */ class: { get: function () { return this._class; }, }, }); /** * Returns whether the table has this property. * * @param {String} propertyId The case-sensitive ID of the property. * @returns {Boolean} Whether the table has this property. * @private */ MetadataTable.prototype.hasProperty = function (propertyId) { return MetadataEntity.hasProperty(propertyId, this._properties, this._class); }; /** * Returns whether the table has a property with the given semantic. * * @param {String} semantic The case-sensitive semantic of the property. * @returns {Boolean} Whether the table has a property with the given semantic. * @private */ MetadataTable.prototype.hasPropertyBySemantic = function (semantic) { return MetadataEntity.hasPropertyBySemantic( semantic, this._properties, this._class ); }; /** * Returns an array of property IDs. * * @param {String[]} [results] An array into which to store the results. * @returns {String[]} The property IDs. * @private */ MetadataTable.prototype.getPropertyIds = function (results) { return MetadataEntity.getPropertyIds(this._properties, this._class, results); }; /** * Returns a copy of the value of the property with the given ID. * <p> * If the property is an enum the name of the enum is returned. * </p> * <p> * If the property is normalized the normalized value is returned. The value is * in the range [-1.0, 1.0] for signed integer types and [0.0, 1.0] for unsigned * integer types. * </p> * <p> * If the property is not normalized and type or componentType is INT64 or * UINT64 a BigInt will be returned. On platforms that don't support BigInt a * number will be returned instead. Note that numbers only support up to 52 bits * of integer precision. Values greater than 2^53 - 1 or less than -(2^53 - 1) * may lose precision when read. * </p> * * @param {Number} index The index of the entity. * @param {String} propertyId The case-sensitive ID of the property. * @returns {*} The value of the property or <code>undefined</code> if the entity does not have this property. * * @exception {DeveloperError} index is required and between zero and count - 1 * @private */ MetadataTable.prototype.getProperty = function (index, propertyId) { //>>includeStart('debug', pragmas.debug); Check.typeOf.string("propertyId", propertyId); //>>includeEnd('debug'); var property = this._properties[propertyId]; var value; if (defined(property)) { value = property.get(index); } else { value = getDefault(this._class, propertyId); } return value; }; /** * Sets the value of the property with the given ID. * <p> * If the property is an enum the name of the enum must be provided, not the * integer value. * </p> * <p> * If the property is normalized a normalized value must be provided to this * function. The value must be in the range [-1.0, 1.0] for signed integer * types and [0.0, 1.0] for unsigned integer types. * </p> * <p> * If the property is not normalized and type or componentType is INT64 or * UINT64 a BigInt may be provided. On platforms that don't support BigInt a * number may be provided instead. Note that numbers only support up to 52 bits * of integer precision. Values greater than 2^53 - 1 or less than -(2^53 - 1) * may lose precision when set." * </p> * * @param {Number} index The index of the entity. * @param {String} propertyId The case-sensitive ID of the property. * @param {*} value The value of the property that will be copied. * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise. * * @exception {DeveloperError} index is required and between zero and count - 1 * @exception {DeveloperError} value does not match type * @exception {DeveloperError} value is out of range for type * @exception {DeveloperError} Array length does not match componentCount * @private */ MetadataTable.prototype.setProperty = function (index, propertyId, value) { //>>includeStart('debug', pragmas.debug); Check.typeOf.string("propertyId", propertyId); //>>includeEnd('debug'); var property = this._properties[propertyId]; if (defined(property)) { property.set(index, value); return true; } return false; }; /** * Returns a copy of the value of the property with the given semantic. * * @param {Number} index The index of the entity. * @param {String} semantic The case-sensitive semantic of the property. * @returns {*} The value of the property or <code>undefined</code> if the entity does not have this semantic. * * @exception {DeveloperError} index is required and between zero and count - 1 * @private */ MetadataTable.prototype.getPropertyBySemantic = function (index, semantic) { //>>includeStart('debug', pragmas.debug); Check.typeOf.string("semantic", semantic); //>>includeEnd('debug'); if (defined(this._class)) { var property = this._class.propertiesBySemantic[semantic]; if (defined(property)) { return this.getProperty(index, property.id); } } return undefined; }; /** * Sets the value of the property with the given semantic. * * @param {Number} index The index of the entity. * @param {String} semantic The case-sensitive semantic of the property. * @param {*} value The value of the property that will be copied. * @returns {Boolean} <code>true</code> if the property was set, <code>false</code> otherwise. * * @exception {DeveloperError} index is required and between zero and count - 1 * @exception {DeveloperError} value does not match type * @exception {DeveloperError} value is out of range for type * @exception {DeveloperError} Array length does not match componentCount * @private */ MetadataTable.prototype.setPropertyBySemantic = function ( index, semantic, value ) { //>>includeStart('debug', pragmas.debug); Check.typeOf.string("semantic", semantic); //>>includeEnd('debug'); if (defined(this._class)) { var property = this._class.propertiesBySemantic[semantic]; if (defined(property)) { return this.setProperty(index, property.id, value); } } return false; }; /** * Returns a typed array containing the property values for a given propertyId. * * @param {String} propertyId The case-sensitive ID of the property. * @returns {*} The typed array containing the property values or <code>undefined</code> if the property values are not stored in a typed array. * * @private */ MetadataTable.prototype.getPropertyTypedArray = function (propertyId) { //>>includeStart('debug', pragmas.debug); Check.typeOf.string("propertyId", propertyId); //>>includeEnd('debug'); var property = this._properties[propertyId]; if (defined(property)) { return property.getTypedArray(); } return undefined; }; /** * Returns a typed array containing the property values for the property with the given semantic. * * @param {String} semantic The case-sensitive semantic of the property. * @returns {*} The typed array containing the property values or <code>undefined</code> if the property values are not stored in a typed array. * * @private */ MetadataTable.prototype.getPropertyTypedArrayBySemantic = function (semantic) { //>>includeStart('debug', pragmas.debug); Check.typeOf.string("semantic", semantic); //>>includeEnd('debug'); if (defined(this._class)) { var property = this._class.propertiesBySemantic[semantic]; if (defined(property)) { return this.getPropertyTypedArray(property.id); } } return undefined; }; function getDefault(classDefinition, propertyId) { if (defined(classDefinition)) { var classProperty = classDefinition.properties[propertyId]; if (defined(classProperty) && defined(classProperty.default)) { var value = classProperty.default; if (classProperty.type === MetadataType.ARRAY) { value = value.slice(); // clone } value = classProperty.normalize(value); return classProperty.unpackVectorAndMatrixTypes(value); } } } export default MetadataTable;
class Parking { constructor(number) { this.capacity = number; this.vehicles = []; }; addCar(carModel, carNumber) { this._isEnoughCapacity(); this.vehicles.push({carModel: carModel, carNumber: carNumber, payed: false}); return `The ${carModel}, with a registration number ${carNumber}, parked.` }; removeCar(carNumber) { if (!this._findVehicle(carNumber)) { throw new Error("The car, you're looking for, is not found."); } if (!this._findVehicle(carNumber).payed) { throw new Error(`${carNumber} needs to pay before leaving the parking lot.`); } this.vehicles = this.vehicles.filter(v => v.carNumber !== carNumber); return `${carNumber} left the parking lot.` }; pay(carNumber) { if (!this._findVehicle(carNumber)) { throw new Error(`${carNumber} is not in the parking lot.`); } if (this._findVehicle(carNumber).payed) { throw new Error(`${carNumber}'s driver has already payed his ticket.`); } this._findVehicle(carNumber).payed = true; return `${carNumber}'s driver successfully payed for his stay.` }; getStatistics(carNumber = 0){ return carNumber === 0 ? this. _getAllInfoParking() : this._printVehicle(carNumber); }; _printVehicle(carNumber){ let vehicle = this._findVehicle(carNumber); return `${vehicle.carModel} == ${vehicle.carNumber} - ${vehicle.payed ? 'Has payed' : 'Not payed'}` }; _getAllInfoParking(){ let print = this.vehicles.sort((a,b)=> a.carModel.localeCompare(b.carModel)) .map(v => `${v.carModel} == ${v.carNumber} - ${v.payed ? 'Has payed' : 'Not payed'}`); print.unshift(`The Parking Lot has ${Math.abs(this.vehicles.length - this.capacity)} empty spots left.`); return print.join('\n'); }; _isEnoughCapacity() { if (this.vehicles.length === this.capacity) { throw new Error("Not enough parking space."); } }; _findVehicle(regNumber) { return this.vehicles.find(vehicle => vehicle.carNumber === regNumber); }; } const parking = new Parking(12); console.log(parking.addCar("Volvo t600", "TX3691CA")); console.log(parking.getStatistics()); console.log(parking.pay("TX3691CA")); console.log(parking.removeCar("TX3691CA"));
const { test } = require('tap') const requireInject = require('require-inject') let getIdentityImpl = () => 'someperson' let npmFetchBody = null const npmFetch = async (uri, opts) => { npmFetchBody = opts.body } npmFetch.json = async (uri, opts) => { return { versions: { '1.0.0': {}, '1.0.1': {}, '1.0.1-pre': {}, }, } } const Deprecate = requireInject('../../lib/deprecate.js', { '../../lib/utils/get-identity.js': async () => getIdentityImpl(), '../../lib/utils/otplease.js': async (opts, fn) => fn(opts), libnpmaccess: { lsPackages: async () => ({ foo: 'write', bar: 'write', baz: 'write', buzz: 'read' }), }, 'npm-registry-fetch': npmFetch, }) const deprecate = new Deprecate({ flatOptions: { registry: 'https://registry.npmjs.org' }, }) test('completion', async t => { const defaultIdentityImpl = getIdentityImpl t.teardown(() => { getIdentityImpl = defaultIdentityImpl }) const testComp = async (argv, expect) => { const res = await deprecate.completion({ conf: { argv: { remain: argv } } }) t.strictSame(res, expect, `completion: ${argv}`) } await Promise.all([ testComp([], ['foo', 'bar', 'baz']), testComp(['b'], ['bar', 'baz']), testComp(['fo'], ['foo']), testComp(['g'], []), testComp(['foo', 'something'], []), ]) getIdentityImpl = () => { throw new Error('deprecate test failure') } t.rejects(testComp([], []), { message: 'deprecate test failure' }) }) test('no args', t => { deprecate.exec([], (err) => { t.match(err, /Usage: npm deprecate/, 'logs usage') t.end() }) }) test('only one arg', t => { deprecate.exec(['foo'], (err) => { t.match(err, /Usage: npm deprecate/, 'logs usage') t.end() }) }) test('invalid semver range', t => { deprecate.exec(['foo@notaversion', 'this will fail'], (err) => { t.match(err, /invalid version range/, 'logs semver error') t.end() }) }) test('deprecates given range', t => { t.teardown(() => { npmFetchBody = null }) deprecate.exec(['foo@1.0.0', 'this version is deprecated'], (err) => { if (err) throw err t.match(npmFetchBody, { versions: { '1.0.0': { deprecated: 'this version is deprecated', }, '1.0.1': { // the undefined here is necessary to ensure that we absolutely // did not assign this property deprecated: undefined, }, }, }) t.end() }) }) test('deprecates all versions when no range is specified', t => { t.teardown(() => { npmFetchBody = null }) deprecate.exec(['foo', 'this version is deprecated'], (err) => { if (err) throw err t.match(npmFetchBody, { versions: { '1.0.0': { deprecated: 'this version is deprecated', }, '1.0.1': { deprecated: 'this version is deprecated', }, '1.0.1-pre': { deprecated: 'this version is deprecated', }, }, }) t.end() }) })
// server.js // where your node app starts // init project var express = require('express'); var app = express(); // enable CORS (https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) // so that your API is remotely testable by FCC var cors = require('cors'); app.use(cors({optionSuccessStatus: 200})); // some legacy browsers choke on 204 // http://expressjs.com/en/starter/static-files.html app.use(express.static('public')); // http://expressjs.com/en/starter/basic-routing.html app.get("/", function (req, res) { res.sendFile(__dirname + '/views/index.html'); }); // your first API endpoint... app.get("/api/hello", function (req, res) { res.json({greeting: 'hello API'}); }); // listen for requests :) var listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); app.get("/api/whoami", (req, res)=>{ res.json({ ipaddress:req.ip, language: req.headers["accept-language"], software: req.headers["user-agent"] }); })
#!/usr/bin/env python # encoding: utf-8 # Copyright (C) 2009 Ballistic Pigeon, LLC import sys import os from launcher import Launcher class DreamCheekyLauncher(Launcher): """Driver for DreamCheeky USB dart launcher""" def __init__(self, device): super(DreamCheekyLauncher, self).__init__() self._device = device self._started = False self.azimuthRange = (-2.76383645932, 2.76383645932) # Range of rotation in radians self.elevationRange = (-0.120671968473228, 0.432407775570538) def start(self): """Opens the launcher and takes control of it""" self._handle = handle = self._device.open() try: handle.reset() handle.claimInterface(0) except: handle.detachKernelDriver(0) handle.reset() handle.claimInterface(0) self._started = True def sendCommand(self, command): """Sends a command to the robot""" if not self._started: self.start() self._handle.controlMsg(0x21, 0x09, [command], 0x0200) def moveLeft(self): """Starts turret moving counterclockwise""" self.sendCommand(4) def moveRight(self): """Starts turret moving clockwise""" self.sendCommand(8) def moveUp(self): """Starts turret moving towards higher elevation""" self.sendCommand(2) def moveDown(self): """Starts turret moving towards lower elevation""" self.sendCommand(1) def stop(self): """Stops turrent movement""" self.sendCommand(0x20) def primeRocket(self): """Primes rocket for firing""" pass def fireRocket(self): """Fires rocket""" self.sendCommand(0x10) def checkExtents(self): """Checks to see if the rocket is at any of its extents""" self.sendCommand(0x40) byte, = self._handle.bulkRead(1, 1) bottom = (byte & 0x1) <> 0 top = (byte & 0x2) <> 0 left = (byte & 0x4) <> 0 right = (byte & 0x8) <> 0 extents = (bottom, top, left, right) self.updatePositionWithExtents(extents) return extents
/** * Created by Rahul on 9/22/2016. */ var playerOneCode = 1; var playerTwoCode = 2; var redBlocks = 0; var greenBlocks = 0; var isMillRed = false; var isMillGreen = false; var isActiveRed = false; var isActiveGreen = false; //discussion var isGreenThreeLeft = false; var isRedThreeLeft = false; // var blockWidth = 16; var strokeWidth = 2; var lastX = 0; var lastY = 0; var lastCenterX = 0; var lastCenterY = 0; var numberOfTurns = 0; var rows = 7; var columns = 7; var clickSound; var positionMatrix = new Array(7); var referenceMatrix = new Array(7); var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); function initializeGame() { clickSound = new sound("sound.wav"); initializeArray(); alert("Player 1 turns first followed by Player 2"); } function sound(src) { this.sound = document.createElement("audio"); this.sound.src = src; this.sound.setAttribute("preload", "auto"); this.sound.setAttribute("controls", "none"); this.sound.style.display = "none"; document.body.appendChild(this.sound); this.play = function () { this.sound.play(); } } function initializeArray() { for (var i = 0; i < 7; i++) { referenceMatrix[i] = new Array(7); positionMatrix[i] = new Array(7); } for (var j = 0; j < 7; j++) { for (var k = 0; k < 7; k++) { //Make all diagonal elements + boundary + center to zero if ((j == 3) || (k == 3) || (j == k) || (j + k == 6)) { referenceMatrix[j][k] = 0; positionMatrix[j][k] = 0; } else { referenceMatrix[j][k] = -1; positionMatrix[j][k] = -1; } } } //Finally making center also -1 referenceMatrix[3][3] = -1; positionMatrix[3][3] = -1; } function makeMove(X, Y) { var yCenter; var xCenter; switch (X) { case 0: { switch (Y) { case 0: { yCenter = 25; xCenter = 25; break; } case 3: { yCenter = 275; xCenter = 25; break; } case 6: { yCenter = 525; xCenter = 25; break; } } break; } case 1: { switch (Y) { case 1: { yCenter = 115; xCenter = 115; break; } case 3: { yCenter = 275; xCenter = 115; break; } case 5: { yCenter = 435; xCenter = 115; break; } } break; } case 2: { switch (Y) { case 2: { yCenter = 195; xCenter = 195; break; } case 3: { yCenter = 275; xCenter = 195; break; } case 4: { yCenter = 355; xCenter = 195; break; } } break; } case 3: { switch (Y) { case 0: { yCenter = 25; xCenter = 275; break; } case 1: { yCenter = 115; xCenter = 275; break; } case 2: { yCenter = 195; xCenter = 275; break; } case 4: { yCenter = 355; xCenter = 275; break; } case 5: { yCenter = 435; xCenter = 275; break; } case 6: { yCenter = 525; xCenter = 275; break; } } break; } case 4: { switch (Y) { case 2: { yCenter = 195; xCenter = 355; break; } case 3: { yCenter = 275; xCenter = 355; break; } case 4: { yCenter = 355; xCenter = 355; break; } } break; } case 5: { switch (Y) { case 1: { yCenter = 115; xCenter = 435; break; } case 3: { yCenter = 275; xCenter = 435; break; } case 5: { yCenter = 435; xCenter = 435; break; } } break; } case 6: { switch (Y) { case 0: { yCenter = 25; xCenter = 525; break; } case 3: { yCenter = 275; xCenter = 525; break; } case 6: { yCenter = 525; xCenter = 525; break; } } break; } } if (isMillGreen || isMillRed) { //In this case don't change player turn and remove other player block in next click var playerCode = (isMillGreen) ? 1 : 2; if (positionMatrix[X][Y] != playerCode && (positionMatrix[X][Y] != 0)) { //Check that it shouldn't be the part of other mill if (!checkMill(X, Y, ((isMillRed) ? 1 : 2)) || allArePartOfMill(((isMillRed) ? 1 : 2))) { //Remove that block and update array value to zero clickSound.play(); if (playerCode == 1) { redBlocks--; document.getElementById("message").innerHTML = "Red block removed"; } else { document.getElementById("message").innerHTML = "Green block removed"; greenBlocks--; } context.clearRect(xCenter - blockWidth - strokeWidth, yCenter - blockWidth - strokeWidth, 2 * (blockWidth + strokeWidth), 2 * ( blockWidth + strokeWidth)); positionMatrix[X][Y] = 0; turnOffMill(); update(); } else { document.getElementById("message").innerHTML = "Can't remove a block which is already a part of mill"; } } } else if (numberOfTurns >= 18 && (isActiveRed || isActiveGreen)) { if ((((X == lastX) && (Y == lastY)) || (positionMatrix[X][Y] == 1 || positionMatrix[X][Y] == 2))) { turnOffActive(lastCenterX, lastCenterY); } if ((positionMatrix[X][Y] == 0)) { //Checking for adjacent element. if (((X == lastX) || (Y == lastY))) { if (X == 0 || X == 6 || Y == 0 || Y == 6) { if (((Math.abs(X - lastX) + Math.abs(Y - lastY)) == 3 ) || ((Math.abs(X - lastX) + Math.abs(Y - lastY)) == 1 )) { //Remove previous block and make a new block at the the given position positionMatrix[lastX][lastY] = 0; clearBlock(lastCenterX, lastCenterY); drawBlock(xCenter, yCenter, X, Y); } } else if (X == 1 || X == 5 || Y == 1 || Y == 5) { if (((Math.abs(X - lastX) + Math.abs(Y - lastY)) == 2 ) || ((Math.abs(X - lastX) + Math.abs(Y - lastY)) == 1 )) { //Remove previous block and make a new block at the the given position positionMatrix[lastX][lastY] = 0; clearBlock(lastCenterX, lastCenterY); drawBlock(xCenter, yCenter, X, Y); } } else if (X == 2 || X == 4 || Y == 2 || Y == 4) { if (((Math.abs(X - lastX) + Math.abs(Y - lastY)) == 1 )) { //Remove previous block and make a new block at the the given position positionMatrix[lastX][lastY] = 0; clearBlock(lastCenterX, lastCenterY); drawBlock(xCenter, yCenter, X, Y); } } } else { if (isGreenThreeLeft && (positionMatrix[lastX][lastY] == playerOneCode)) { positionMatrix[lastX][lastY] = 0; clearBlock(lastCenterX, lastCenterY); drawBlock(xCenter, yCenter, X, Y); } else if (isRedThreeLeft && (positionMatrix[lastX][lastY] == playerTwoCode)) { positionMatrix[lastX][lastY] = 0; clearBlock(lastCenterX, lastCenterY); drawBlock(xCenter, yCenter, X, Y); } else { turnOffActive(lastCenterX, lastCenterY); } } } } else if (positionMatrix[X][Y] == 0 && numberOfTurns < 18) { clickSound.play(); if (numberOfTurns % 2 != 0) { //Player two made a move, hence made a block red. redBlocks++; positionMatrix[X][Y] = 2; context.beginPath(); context.arc(xCenter, yCenter, blockWidth, 0, 2 * Math.PI, false); context.fillStyle = '#F44336'; context.fill(); context.lineWidth = strokeWidth; context.strokeStyle = '#003300'; context.stroke(); document.getElementById("turn").innerHTML = "P1"; if (checkMill(X, Y, 2)) { isMillRed = true; document.getElementById("turn").innerHTML = "P2"; document.getElementById("message").innerHTML = "A Mill is formed. Click on green block to remove it."; } else { document.getElementById("message").innerHTML = "Click on empty spot to place your piece"; } } else { //Player one just made a move, hence made a block green greenBlocks++; positionMatrix[X][Y] = 1; context.beginPath(); context.arc(xCenter, yCenter, blockWidth, 0, 2 * Math.PI, false); context.fillStyle = '#2E7D32'; context.fill(); context.lineWidth = strokeWidth; context.strokeStyle = '#003300'; context.stroke(); document.getElementById("turn").innerHTML = "P2"; if (checkMill(X, Y, 1)) { isMillGreen = true; document.getElementById("turn").innerHTML = "P1"; document.getElementById("message").innerHTML = "A Mill is formed. Click on red block to remove it."; } else { document.getElementById("message").innerHTML = "Click on empty spot to place your piece"; } } if (numberOfTurns == 17) { document.getElementById("message").innerHTML = "Now, Move one step by clicking on Block"; } numberOfTurns++; } else if (numberOfTurns >= 18 && positionMatrix[X][Y] != 0) { //Do nothing when clicked on empty element and check the all possible moves that // a player have after clicking on a particular position of his own color. if (numberOfTurns % 2 != 0 && positionMatrix[X][Y] == 2) { //Player two made a move, hence made a block fade red. clickSound.play(); isActiveRed = true; if (checkThreeLeft(playerTwoCode)) { isRedThreeLeft = true; document.getElementById("message").innerHTML = "Red can now move anywhere (3 are left only)"; } else { document.getElementById("message").innerHTML = "Move one step by clicking on Block"; } updateLastParam(xCenter, yCenter, X, Y); context.beginPath(); context.arc(xCenter, yCenter, blockWidth, 0, 2 * Math.PI, false); context.fillStyle = '#FFCDD2'; context.fill(); context.lineWidth = strokeWidth; context.strokeStyle = '#003300'; context.stroke(); } else if (numberOfTurns % 2 == 0 && positionMatrix[X][Y] == 1) { //Player one just made a move, hence made a block green clickSound.play(); isActiveGreen = true; if (checkThreeLeft(playerOneCode)) { isGreenThreeLeft = true; document.getElementById("message").innerHTML = "Green can now move anywhere (3 are left only)"; } else { document.getElementById("message").innerHTML = "Move one step by clicking on Block"; } updateLastParam(xCenter, yCenter, X, Y); context.beginPath(); context.arc(xCenter, yCenter, blockWidth, 0, 2 * Math.PI, false); context.fillStyle = '#AED581'; context.fill(); context.lineWidth = strokeWidth; context.strokeStyle = '#003300'; context.stroke(); } } // // for (var r = 0; r < 7; r++) { // console.log(positionMatrix[0][r] + "\t" + positionMatrix[1][r] + "\t" + positionMatrix[2][r] + "\t" + // positionMatrix[3][r] + "\t" + positionMatrix[4][r] + "\t" + positionMatrix[5][r] + "\t" + positionMatrix[6][r]); // } checkGameOver(); } canvas.addEventListener("click", mouseClick); function mouseClick(event) { //Get the X and Y co-ordinate at the point of touch in canvas var X = event.clientX - (canvas.getBoundingClientRect()).left; var Y = event.clientY - (canvas.getBoundingClientRect()).top; //Check if touch event occurs in canvas or not if ((X >= 0 && X <= 550) && (Y >= 0 && Y <= 550)) { if ((X >= 0 && X <= 75) && (Y >= 0 && Y <= 75)) { makeMove(0, 0); } else if ((X >= 235 && X <= 315) && (Y >= 0 && Y <= 75)) { makeMove(3, 0); } else if ((X >= 475 && X <= 550) && (Y >= 0 && Y <= 75)) { makeMove(6, 0); } else if ((X >= 75 && X <= 155) && (Y >= 75 && Y <= 155)) { makeMove(1, 1); } else if ((X >= 235 && X <= 315) && (Y >= 75 && Y <= 155)) { makeMove(3, 1); } else if ((X >= 395 && X <= 475) && (Y >= 75 && Y <= 155)) { makeMove(5, 1); } else if ((X >= 155 && X <= 235) && (Y >= 155 && Y <= 235)) { makeMove(2, 2); } else if ((X >= 235 && X <= 315) && (Y >= 155 && Y <= 235)) { makeMove(3, 2); } else if ((X >= 315 && X <= 395) && (Y >= 155 && Y <= 235)) { makeMove(4, 2); } else if ((X >= 0 && X <= 75) && (Y >= 235 && Y <= 315)) { makeMove(0, 3); } else if ((X >= 75 && X <= 155) && (Y >= 235 && Y <= 315)) { makeMove(1, 3); } else if ((X >= 155 && X <= 235) && (Y >= 235 && Y <= 315)) { makeMove(2, 3); } else if ((X >= 315 && X <= 395) && (Y >= 235 && Y <= 315)) { makeMove(4, 3); } else if ((X >= 395 && X <= 475) && (Y >= 235 && Y <= 315)) { makeMove(5, 3); } else if ((X >= 475 && X <= 550) && (Y >= 235 && Y <= 315)) { makeMove(6, 3); } else if ((X >= 155 && X <= 235) && (Y >= 315 && Y <= 395)) { makeMove(2, 4); } else if ((X >= 235 && X <= 315) && (Y >= 315 && Y <= 395)) { makeMove(3, 4); } else if ((X >= 315 && X <= 395) && (Y >= 315 && Y <= 395)) { makeMove(4, 4); } else if ((X >= 75 && X <= 155) && (Y >= 395 && Y <= 475)) { makeMove(1, 5); } else if ((X >= 235 && X <= 315) && (Y >= 395 && Y <= 475)) { makeMove(3, 5); } else if ((X >= 395 && X <= 475) && (Y >= 395 && Y <= 475)) { makeMove(5, 5); } else if ((X >= 0 && X <= 75) && (Y >= 475 && Y <= 550)) { makeMove(0, 6); } else if ((X >= 235 && X <= 315) && (Y >= 475 && Y <= 550)) { makeMove(3, 6); } else if ((X >= 475 && X <= 550) && (Y >= 475 && Y <= 550)) { makeMove(6, 6); } } } function updateLastParam(xCenter, yCenter, X, Y) { lastCenterX = xCenter; lastCenterY = yCenter; lastX = X; lastY = Y; } function turnOffActive(x, y) { clickSound.play(); context.beginPath(); context.arc(x, y, blockWidth, 0, 2 * Math.PI, false); if (isActiveRed) { context.fillStyle = '#F44336'; } else { context.fillStyle = '#2E7D32'; } context.fill(); context.lineWidth = 2; context.strokeStyle = '#003300'; context.stroke(); isActiveRed = false; isActiveGreen = false; } function turnOffMill() { isMillGreen = false; isMillRed = false; } function clearBlock(xI, yI) { clickSound.play(); //Clear canvas at previous position context.clearRect(xI - blockWidth - strokeWidth, yI - blockWidth - strokeWidth, 2 * (blockWidth + strokeWidth), 2 * ( blockWidth + strokeWidth)); positionMatrix[lastX][lastY] = 0; } function drawBlock(x, y, X, Y) { context.beginPath(); context.arc(x, y, blockWidth, 0, 2 * Math.PI, false); if (isActiveRed) { positionMatrix[X][Y] = 2; context.fillStyle = '#F44336'; if (checkMill(X, Y, 2)) { isMillRed = true; document.getElementById("message").innerHTML = "Click on green block to remove it."; } } else { positionMatrix[X][Y] = 1; context.fillStyle = '#2E7D32'; if (checkMill(X, Y, 1)) { isMillGreen = true; document.getElementById("message").innerHTML = "Click on red block to remove it."; } } context.fill(); context.lineWidth = 2; context.strokeStyle = '#003300'; context.stroke(); isActiveGreen = false; isActiveRed = false; numberOfTurns++; update(); } function checkMill(x, y, playerCode) { //Using the fact that two mills cannot occur simultaneously var flag = 0; var temp = 0; //Transverse through the given row and column and check for mill for (var i = 0; i < 5; i++) { flag = 0; for (var j = temp; j < temp + 3; j++) { if (positionMatrix[j][y] == playerCode) { continue; } else { flag = 1; break; } } if (flag == 0) { //console.log("This is from : " + 1); return true; } else { temp++; } } flag = 0; temp = 0; //Now moving along the given column for (var k = 0; k < 5; k++) { flag = 0; for (var l = temp; l < temp + 3; l++) { if (positionMatrix[x][l] == playerCode) { continue; } else { flag = 1; break; } } if (flag == 0) { // console.log("This is from : " + 2); return true; } else { temp++; } } var check = true; var oppositeCode = (playerCode == 1) ? 2 : 1; for (var a = 0; a < 7; a++) { if ((positionMatrix[a][y] == oppositeCode) || (positionMatrix[a][y] == 0)) { check = false; break; } } if (check == true) { //console.log("This is from : " + 3); return true; } check = true; for (var b = 0; b < 7; b++) { //Check for any empty element of any element of anther type if ((positionMatrix[x][b] == oppositeCode) || (positionMatrix[x][b] == 0)) { check = false; break; } } if (check == true) { //console.log("This is from : " + 4); return true; } return false; } function checkThreeLeft(playerCode) { return (numberOfTurns >= 18 && (((playerCode == 1) ? greenBlocks : redBlocks) == 3 )) } function checkGameOver() { //If less than 3 players left of any team. if (numberOfTurns >= 18) { if (redBlocks < 3 || greenBlocks < 3) { alert("Only 2 " + ((greenBlocks < 3) ? "Green" : "Red") + " blocks left !\n" + "Hence, Player " + ((greenBlocks < 3) ? 2 : 1) + " wins !"); location.reload(true); } else { //Check if no adjacent element available for any of the player. if (!canMove(playerOneCode, greenBlocks)) { alert("No possible moves left for Player " + playerOneCode + "\n" + "Hence, Player " + playerTwoCode + " wins !"); location.reload(true); } else if (!canMove(playerTwoCode, redBlocks)) { alert("No possible moves left for Player " + playerTwoCode + "\n" + "Hence, Player " + playerOneCode + " wins !"); location.reload(true); } } } } function allArePartOfMill(playerCode) { //return false if atleast one of them is not a part of the mill for (var i = 0; i < rows; i++) { for (var j = 0; j < columns; j++) { if (positionMatrix[i][j] == playerCode){ if (!checkMill(i, j, playerCode)) { return false; } } } } return true; } function canMove(playerCode, blocksLeft) { //If only 3 are left then it can always move anywhere if (blocksLeft == 3) { return true; } //return true even if one of them have at least one valid move left for (var i = 0; i < rows; i++) { for (var j = 0; j < columns; j++) { if (positionMatrix[j][i] == playerCode) { //now move in all four directions until index becomes < 0 || >6 // or after -1's zero comes at the given position. //Left if (!(j == 4 && i == 3)) { for (var k = j - 1; k >= 0; k--) { if (positionMatrix[k][i] != -1) { if (positionMatrix[k][i] == 0) { return true; } else { //Adjacent piece is occupied by some block break; } } } } //Top if (!(j == 3 && i == 4)) { for (var l = i - 1; l >= 0; l--) { if (positionMatrix[j][l] != -1) { if (positionMatrix[j][l] == 0) { return true; } else { //Adjacent piece is occupied by some block break; } } } } //Right if (!(j == 2 && i == 3)) { for (var m = j + 1; m < 7; m++) { if (positionMatrix[m][i] != -1) { if (positionMatrix[m][i] == 0) { return true; } else { //Adjacent piece is occupied by some block break; } } } } //Bottom if (!(j == 3 && i == 2)) { for (var n = i + 1; n < 7; n++) { if (positionMatrix[j][n] != -1) { if (positionMatrix[j][n] == 0) { return true; } else { //Adjacent piece is occupied by some block break; } } } } } } } return false; } function update() { //Update player turn if (numberOfTurns % 2 != 0) { document.getElementById("turn").innerHTML = "P2"; } else { document.getElementById("turn").innerHTML = "P1"; } }
"use strict"; const id = document.querySelector("#id"), psword = document.querySelector("#psword"), loginBtn = document.querySelector("button"); loginBtn.addEventListener("click", login); function login() { const req = { id: id.value, psword: psword.value, }; console.log(req); console.log(JSON.stringify(req)); // fetch("/login", { // body: JSON.stringify(req) // }) }
import * as tslib_1 from "tslib"; import * as ɵngcc0 from '@angular/core'; var AgmCircle_1; import { Directive, EventEmitter, Input, Output } from '@angular/core'; import { CircleManager } from '../services/managers/circle-manager'; let AgmCircle = AgmCircle_1 = class AgmCircle { constructor(_manager) { this._manager = _manager; /** * Indicates whether this Circle handles mouse events. Defaults to true. */ this.clickable = true; /** * If set to true, the user can drag this circle over the map. Defaults to false. */ // tslint:disable-next-line:no-input-rename this.draggable = false; /** * If set to true, the user can edit this circle by dragging the control points shown at * the center and around the circumference of the circle. Defaults to false. */ this.editable = false; /** * The radius in meters on the Earth's surface. */ this.radius = 0; /** * The stroke position. Defaults to CENTER. * This property is not supported on Internet Explorer 8 and earlier. */ this.strokePosition = 'CENTER'; /** * The stroke width in pixels. */ this.strokeWeight = 0; /** * Whether this circle is visible on the map. Defaults to true. */ this.visible = true; /** * This event is fired when the circle's center is changed. */ this.centerChange = new EventEmitter(); /** * This event emitter gets emitted when the user clicks on the circle. */ this.circleClick = new EventEmitter(); /** * This event emitter gets emitted when the user clicks on the circle. */ this.circleDblClick = new EventEmitter(); /** * This event is repeatedly fired while the user drags the circle. */ this.drag = new EventEmitter(); /** * This event is fired when the user stops dragging the circle. */ this.dragEnd = new EventEmitter(); /** * This event is fired when the user starts dragging the circle. */ this.dragStart = new EventEmitter(); /** * This event is fired when the DOM mousedown event is fired on the circle. */ this.mouseDown = new EventEmitter(); /** * This event is fired when the DOM mousemove event is fired on the circle. */ this.mouseMove = new EventEmitter(); /** * This event is fired on circle mouseout. */ this.mouseOut = new EventEmitter(); /** * This event is fired on circle mouseover. */ this.mouseOver = new EventEmitter(); /** * This event is fired when the DOM mouseup event is fired on the circle. */ this.mouseUp = new EventEmitter(); /** * This event is fired when the circle's radius is changed. */ this.radiusChange = new EventEmitter(); /** * This event is fired when the circle is right-clicked on. */ this.rightClick = new EventEmitter(); this._circleAddedToManager = false; this._eventSubscriptions = []; } /** @internal */ ngOnInit() { this._manager.addCircle(this); this._circleAddedToManager = true; this._registerEventListeners(); } /** @internal */ ngOnChanges(changes) { if (!this._circleAddedToManager) { return; } if (changes['latitude'] || changes['longitude']) { this._manager.setCenter(this); } if (changes['editable']) { this._manager.setEditable(this); } if (changes['draggable']) { this._manager.setDraggable(this); } if (changes['visible']) { this._manager.setVisible(this); } if (changes['radius']) { this._manager.setRadius(this); } this._updateCircleOptionsChanges(changes); } _updateCircleOptionsChanges(changes) { let options = {}; let optionKeys = Object.keys(changes).filter(k => AgmCircle_1._mapOptions.indexOf(k) !== -1); optionKeys.forEach((k) => { options[k] = changes[k].currentValue; }); if (optionKeys.length > 0) { this._manager.setOptions(this, options); } } _registerEventListeners() { let events = new Map(); events.set('center_changed', this.centerChange); events.set('click', this.circleClick); events.set('dblclick', this.circleDblClick); events.set('drag', this.drag); events.set('dragend', this.dragEnd); events.set('dragstart', this.dragStart); events.set('mousedown', this.mouseDown); events.set('mousemove', this.mouseMove); events.set('mouseout', this.mouseOut); events.set('mouseover', this.mouseOver); events.set('mouseup', this.mouseUp); events.set('radius_changed', this.radiusChange); events.set('rightclick', this.rightClick); events.forEach((eventEmitter, eventName) => { this._eventSubscriptions.push(this._manager.createEventObservable(eventName, this).subscribe((value) => { switch (eventName) { case 'radius_changed': this._manager.getRadius(this).then((radius) => eventEmitter.emit(radius)); break; case 'center_changed': this._manager.getCenter(this).then((center) => eventEmitter.emit({ lat: center.lat(), lng: center.lng() })); break; default: eventEmitter.emit({ coords: { lat: value.latLng.lat(), lng: value.latLng.lng() } }); } })); }); } /** @internal */ ngOnDestroy() { this._eventSubscriptions.forEach(function (s) { s.unsubscribe(); }); this._eventSubscriptions = null; this._manager.removeCircle(this); } /** * Gets the LatLngBounds of this Circle. */ getBounds() { return this._manager.getBounds(this); } getCenter() { return this._manager.getCenter(this); } }; AgmCircle.ɵfac = function AgmCircle_Factory(t) { return new (t || AgmCircle)(ɵngcc0.ɵɵdirectiveInject(CircleManager)); }; AgmCircle.ɵdir = ɵngcc0.ɵɵdefineDirective({ type: AgmCircle, selectors: [["agm-circle"]], inputs: { clickable: "clickable", draggable: ["circleDraggable", "draggable"], editable: "editable", radius: "radius", strokePosition: "strokePosition", strokeWeight: "strokeWeight", visible: "visible", latitude: "latitude", longitude: "longitude", fillColor: "fillColor", fillOpacity: "fillOpacity", strokeColor: "strokeColor", strokeOpacity: "strokeOpacity", zIndex: "zIndex" }, outputs: { centerChange: "centerChange", circleClick: "circleClick", circleDblClick: "circleDblClick", drag: "drag", dragEnd: "dragEnd", dragStart: "dragStart", mouseDown: "mouseDown", mouseMove: "mouseMove", mouseOut: "mouseOut", mouseOver: "mouseOver", mouseUp: "mouseUp", radiusChange: "radiusChange", rightClick: "rightClick" }, features: [ɵngcc0.ɵɵNgOnChangesFeature()] }); AgmCircle._mapOptions = [ 'fillColor', 'fillOpacity', 'strokeColor', 'strokeOpacity', 'strokePosition', 'strokeWeight', 'visible', 'zIndex', 'clickable', ]; AgmCircle.ctorParameters = () => [ { type: CircleManager } ]; tslib_1.__decorate([ Input(), tslib_1.__metadata("design:type", Number) ], AgmCircle.prototype, "latitude", void 0); tslib_1.__decorate([ Input(), tslib_1.__metadata("design:type", Number) ], AgmCircle.prototype, "longitude", void 0); tslib_1.__decorate([ Input(), tslib_1.__metadata("design:type", Object) ], AgmCircle.prototype, "clickable", void 0); tslib_1.__decorate([ Input('circleDraggable'), tslib_1.__metadata("design:type", Object) ], AgmCircle.prototype, "draggable", void 0); tslib_1.__decorate([ Input(), tslib_1.__metadata("design:type", Object) ], AgmCircle.prototype, "editable", void 0); tslib_1.__decorate([ Input(), tslib_1.__metadata("design:type", String) ], AgmCircle.prototype, "fillColor", void 0); tslib_1.__decorate([ Input(), tslib_1.__metadata("design:type", Number) ], AgmCircle.prototype, "fillOpacity", void 0); tslib_1.__decorate([ Input(), tslib_1.__metadata("design:type", Object) ], AgmCircle.prototype, "radius", void 0); tslib_1.__decorate([ Input(), tslib_1.__metadata("design:type", String) ], AgmCircle.prototype, "strokeColor", void 0); tslib_1.__decorate([ Input(), tslib_1.__metadata("design:type", Number) ], AgmCircle.prototype, "strokeOpacity", void 0); tslib_1.__decorate([ Input(), tslib_1.__metadata("design:type", String) ], AgmCircle.prototype, "strokePosition", void 0); tslib_1.__decorate([ Input(), tslib_1.__metadata("design:type", Object) ], AgmCircle.prototype, "strokeWeight", void 0); tslib_1.__decorate([ Input(), tslib_1.__metadata("design:type", Object) ], AgmCircle.prototype, "visible", void 0); tslib_1.__decorate([ Input(), tslib_1.__metadata("design:type", Number) ], AgmCircle.prototype, "zIndex", void 0); tslib_1.__decorate([ Output(), tslib_1.__metadata("design:type", EventEmitter) ], AgmCircle.prototype, "centerChange", void 0); tslib_1.__decorate([ Output(), tslib_1.__metadata("design:type", EventEmitter) ], AgmCircle.prototype, "circleClick", void 0); tslib_1.__decorate([ Output(), tslib_1.__metadata("design:type", EventEmitter) ], AgmCircle.prototype, "circleDblClick", void 0); tslib_1.__decorate([ Output(), tslib_1.__metadata("design:type", EventEmitter) ], AgmCircle.prototype, "drag", void 0); tslib_1.__decorate([ Output(), tslib_1.__metadata("design:type", EventEmitter) ], AgmCircle.prototype, "dragEnd", void 0); tslib_1.__decorate([ Output(), tslib_1.__metadata("design:type", EventEmitter) ], AgmCircle.prototype, "dragStart", void 0); tslib_1.__decorate([ Output(), tslib_1.__metadata("design:type", EventEmitter) ], AgmCircle.prototype, "mouseDown", void 0); tslib_1.__decorate([ Output(), tslib_1.__metadata("design:type", EventEmitter) ], AgmCircle.prototype, "mouseMove", void 0); tslib_1.__decorate([ Output(), tslib_1.__metadata("design:type", EventEmitter) ], AgmCircle.prototype, "mouseOut", void 0); tslib_1.__decorate([ Output(), tslib_1.__metadata("design:type", EventEmitter) ], AgmCircle.prototype, "mouseOver", void 0); tslib_1.__decorate([ Output(), tslib_1.__metadata("design:type", EventEmitter) ], AgmCircle.prototype, "mouseUp", void 0); tslib_1.__decorate([ Output(), tslib_1.__metadata("design:type", EventEmitter) ], AgmCircle.prototype, "radiusChange", void 0); tslib_1.__decorate([ Output(), tslib_1.__metadata("design:type", EventEmitter) ], AgmCircle.prototype, "rightClick", void 0); AgmCircle = AgmCircle_1 = tslib_1.__decorate([ tslib_1.__metadata("design:paramtypes", [CircleManager]) ], AgmCircle); /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(AgmCircle, [{ type: Directive, args: [{ selector: 'agm-circle' }] }], function () { return [{ type: CircleManager }]; }, { clickable: [{ type: Input }], draggable: [{ type: Input, args: ['circleDraggable'] }], editable: [{ type: Input }], radius: [{ type: Input }], strokePosition: [{ type: Input }], strokeWeight: [{ type: Input }], visible: [{ type: Input }], centerChange: [{ type: Output }], circleClick: [{ type: Output }], circleDblClick: [{ type: Output }], drag: [{ type: Output }], dragEnd: [{ type: Output }], dragStart: [{ type: Output }], mouseDown: [{ type: Output }], mouseMove: [{ type: Output }], mouseOut: [{ type: Output }], mouseOver: [{ type: Output }], mouseUp: [{ type: Output }], radiusChange: [{ type: Output }], rightClick: [{ type: Output }], latitude: [{ type: Input }], longitude: [{ type: Input }], fillColor: [{ type: Input }], fillOpacity: [{ type: Input }], strokeColor: [{ type: Input }], strokeOpacity: [{ type: Input }], zIndex: [{ type: Input }] }); })(); export { AgmCircle }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkM6L1VzZXJzL3VzZXIvRGVza3RvcC9QUk9KRUNUUy9TVFVBTkEvSWRleVBheS90b3ZvLWFuZ3VsYXItOS1hcHAtbGFuZGluZy1wYWdlL25vZGVfbW9kdWxlcy9AYWdtL2NvcmUvZXNtMjAxNS9kaXJlY3RpdmVzL2NpcmNsZS5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7QUFDQTs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O2kxQkF5S0U7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OzhDQW9INEMsQUFJM0M7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O29CQUNXIiwiZmlsZSI6ImNpcmNsZS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCAqIGFzIHRzbGliXzEgZnJvbSBcInRzbGliXCI7XG52YXIgQWdtQ2lyY2xlXzE7XG5pbXBvcnQgeyBEaXJlY3RpdmUsIEV2ZW50RW1pdHRlciwgSW5wdXQsIE91dHB1dCB9IGZyb20gJ0Bhbmd1bGFyL2NvcmUnO1xuaW1wb3J0IHsgQ2lyY2xlTWFuYWdlciB9IGZyb20gJy4uL3NlcnZpY2VzL21hbmFnZXJzL2NpcmNsZS1tYW5hZ2VyJztcbmxldCBBZ21DaXJjbGUgPSBBZ21DaXJjbGVfMSA9IGNsYXNzIEFnbUNpcmNsZSB7XG4gICAgY29uc3RydWN0b3IoX21hbmFnZXIpIHtcbiAgICAgICAgdGhpcy5fbWFuYWdlciA9IF9tYW5hZ2VyO1xuICAgICAgICAvKipcbiAgICAgICAgICogSW5kaWNhdGVzIHdoZXRoZXIgdGhpcyBDaXJjbGUgaGFuZGxlcyBtb3VzZSBldmVudHMuIERlZmF1bHRzIHRvIHRydWUuXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLmNsaWNrYWJsZSA9IHRydWU7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBJZiBzZXQgdG8gdHJ1ZSwgdGhlIHVzZXIgY2FuIGRyYWcgdGhpcyBjaXJjbGUgb3ZlciB0aGUgbWFwLiBEZWZhdWx0cyB0byBmYWxzZS5cbiAgICAgICAgICovXG4gICAgICAgIC8vIHRzbGludDpkaXNhYmxlLW5leHQtbGluZTpuby1pbnB1dC1yZW5hbWVcbiAgICAgICAgdGhpcy5kcmFnZ2FibGUgPSBmYWxzZTtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIElmIHNldCB0byB0cnVlLCB0aGUgdXNlciBjYW4gZWRpdCB0aGlzIGNpcmNsZSBieSBkcmFnZ2luZyB0aGUgY29udHJvbCBwb2ludHMgc2hvd24gYXRcbiAgICAgICAgICogdGhlIGNlbnRlciBhbmQgYXJvdW5kIHRoZSBjaXJjdW1mZXJlbmNlIG9mIHRoZSBjaXJjbGUuIERlZmF1bHRzIHRvIGZhbHNlLlxuICAgICAgICAgKi9cbiAgICAgICAgdGhpcy5lZGl0YWJsZSA9IGZhbHNlO1xuICAgICAgICAvKipcbiAgICAgICAgICogVGhlIHJhZGl1cyBpbiBtZXRlcnMgb24gdGhlIEVhcnRoJ3Mgc3VyZmFjZS5cbiAgICAgICAgICovXG4gICAgICAgIHRoaXMucmFkaXVzID0gMDtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFRoZSBzdHJva2UgcG9zaXRpb24uIERlZmF1bHRzIHRvIENFTlRFUi5cbiAgICAgICAgICogVGhpcyBwcm9wZXJ0eSBpcyBub3Qgc3VwcG9ydGVkIG9uIEludGVybmV0IEV4cGxvcmVyIDggYW5kIGVhcmxpZXIuXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLnN0cm9rZVBvc2l0aW9uID0gJ0NFTlRFUic7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBUaGUgc3Ryb2tlIHdpZHRoIGluIHBpeGVscy5cbiAgICAgICAgICovXG4gICAgICAgIHRoaXMuc3Ryb2tlV2VpZ2h0ID0gMDtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFdoZXRoZXIgdGhpcyBjaXJjbGUgaXMgdmlzaWJsZSBvbiB0aGUgbWFwLiBEZWZhdWx0cyB0byB0cnVlLlxuICAgICAgICAgKi9cbiAgICAgICAgdGhpcy52aXNpYmxlID0gdHJ1ZTtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFRoaXMgZXZlbnQgaXMgZmlyZWQgd2hlbiB0aGUgY2lyY2xlJ3MgY2VudGVyIGlzIGNoYW5nZWQuXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLmNlbnRlckNoYW5nZSA9IG5ldyBFdmVudEVtaXR0ZXIoKTtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFRoaXMgZXZlbnQgZW1pdHRlciBnZXRzIGVtaXR0ZWQgd2hlbiB0aGUgdXNlciBjbGlja3Mgb24gdGhlIGNpcmNsZS5cbiAgICAgICAgICovXG4gICAgICAgIHRoaXMuY2lyY2xlQ2xpY2sgPSBuZXcgRXZlbnRFbWl0dGVyKCk7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBUaGlzIGV2ZW50IGVtaXR0ZXIgZ2V0cyBlbWl0dGVkIHdoZW4gdGhlIHVzZXIgY2xpY2tzIG9uIHRoZSBjaXJjbGUuXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLmNpcmNsZURibENsaWNrID0gbmV3IEV2ZW50RW1pdHRlcigpO1xuICAgICAgICAvKipcbiAgICAgICAgICogVGhpcyBldmVudCBpcyByZXBlYXRlZGx5IGZpcmVkIHdoaWxlIHRoZSB1c2VyIGRyYWdzIHRoZSBjaXJjbGUuXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLmRyYWcgPSBuZXcgRXZlbnRFbWl0dGVyKCk7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBUaGlzIGV2ZW50IGlzIGZpcmVkIHdoZW4gdGhlIHVzZXIgc3RvcHMgZHJhZ2dpbmcgdGhlIGNpcmNsZS5cbiAgICAgICAgICovXG4gICAgICAgIHRoaXMuZHJhZ0VuZCA9IG5ldyBFdmVudEVtaXR0ZXIoKTtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFRoaXMgZXZlbnQgaXMgZmlyZWQgd2hlbiB0aGUgdXNlciBzdGFydHMgZHJhZ2dpbmcgdGhlIGNpcmNsZS5cbiAgICAgICAgICovXG4gICAgICAgIHRoaXMuZHJhZ1N0YXJ0ID0gbmV3IEV2ZW50RW1pdHRlcigpO1xuICAgICAgICAvKipcbiAgICAgICAgICogVGhpcyBldmVudCBpcyBmaXJlZCB3aGVuIHRoZSBET00gbW91c2Vkb3duIGV2ZW50IGlzIGZpcmVkIG9uIHRoZSBjaXJjbGUuXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLm1vdXNlRG93biA9IG5ldyBFdmVudEVtaXR0ZXIoKTtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFRoaXMgZXZlbnQgaXMgZmlyZWQgd2hlbiB0aGUgRE9NIG1vdXNlbW92ZSBldmVudCBpcyBmaXJlZCBvbiB0aGUgY2lyY2xlLlxuICAgICAgICAgKi9cbiAgICAgICAgdGhpcy5tb3VzZU1vdmUgPSBuZXcgRXZlbnRFbWl0dGVyKCk7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBUaGlzIGV2ZW50IGlzIGZpcmVkIG9uIGNpcmNsZSBtb3VzZW91dC5cbiAgICAgICAgICovXG4gICAgICAgIHRoaXMubW91c2VPdXQgPSBuZXcgRXZlbnRFbWl0dGVyKCk7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBUaGlzIGV2ZW50IGlzIGZpcmVkIG9uIGNpcmNsZSBtb3VzZW92ZXIuXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLm1vdXNlT3ZlciA9IG5ldyBFdmVudEVtaXR0ZXIoKTtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFRoaXMgZXZlbnQgaXMgZmlyZWQgd2hlbiB0aGUgRE9NIG1vdXNldXAgZXZlbnQgaXMgZmlyZWQgb24gdGhlIGNpcmNsZS5cbiAgICAgICAgICovXG4gICAgICAgIHRoaXMubW91c2VVcCA9IG5ldyBFdmVudEVtaXR0ZXIoKTtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFRoaXMgZXZlbnQgaXMgZmlyZWQgd2hlbiB0aGUgY2lyY2xlJ3MgcmFkaXVzIGlzIGNoYW5nZWQuXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLnJhZGl1c0NoYW5nZSA9IG5ldyBFdmVudEVtaXR0ZXIoKTtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFRoaXMgZXZlbnQgaXMgZmlyZWQgd2hlbiB0aGUgY2lyY2xlIGlzIHJpZ2h0LWNsaWNrZWQgb24uXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLnJpZ2h0Q2xpY2sgPSBuZXcgRXZlbnRFbWl0dGVyKCk7XG4gICAgICAgIHRoaXMuX2NpcmNsZUFkZGVkVG9NYW5hZ2VyID0gZmFsc2U7XG4gICAgICAgIHRoaXMuX2V2ZW50U3Vic2NyaXB0aW9ucyA9IFtdO1xuICAgIH1cbiAgICAvKiogQGludGVybmFsICovXG4gICAgbmdPbkluaXQoKSB7XG4gICAgICAgIHRoaXMuX21hbmFnZXIuYWRkQ2lyY2xlKHRoaXMpO1xuICAgICAgICB0aGlzLl9jaXJjbGVBZGRlZFRvTWFuYWdlciA9IHRydWU7XG4gICAgICAgIHRoaXMuX3JlZ2lzdGVyRXZlbnRMaXN0ZW5lcnMoKTtcbiAgICB9XG4gICAgLyoqIEBpbnRlcm5hbCAqL1xuICAgIG5nT25DaGFuZ2VzKGNoYW5nZXMpIHtcbiAgICAgICAgaWYgKCF0aGlzLl9jaXJjbGVBZGRlZFRvTWFuYWdlcikge1xuICAgICAgICAgICAgcmV0dXJuO1xuICAgICAgICB9XG4gICAgICAgIGlmIChjaGFuZ2VzWydsYXRpdHVkZSddIHx8IGNoYW5nZXNbJ2xvbmdpdHVkZSddKSB7XG4gICAgICAgICAgICB0aGlzLl9tYW5hZ2VyLnNldENlbnRlcih0aGlzKTtcbiAgICAgICAgfVxuICAgICAgICBpZiAoY2hhbmdlc1snZWRpdGFibGUnXSkge1xuICAgICAgICAgICAgdGhpcy5fbWFuYWdlci5zZXRFZGl0YWJsZSh0aGlzKTtcbiAgICAgICAgfVxuICAgICAgICBpZiAoY2hhbmdlc1snZHJhZ2dhYmxlJ10pIHtcbiAgICAgICAgICAgIHRoaXMuX21hbmFnZXIuc2V0RHJhZ2dhYmxlKHRoaXMpO1xuICAgICAgICB9XG4gICAgICAgIGlmIChjaGFuZ2VzWyd2aXNpYmxlJ10pIHtcbiAgICAgICAgICAgIHRoaXMuX21hbmFnZXIuc2V0VmlzaWJsZSh0aGlzKTtcbiAgICAgICAgfVxuICAgICAgICBpZiAoY2hhbmdlc1sncmFkaXVzJ10pIHtcbiAgICAgICAgICAgIHRoaXMuX21hbmFnZXIuc2V0UmFkaXVzKHRoaXMpO1xuICAgICAgICB9XG4gICAgICAgIHRoaXMuX3VwZGF0ZUNpcmNsZU9wdGlvbnNDaGFuZ2VzKGNoYW5nZXMpO1xuICAgIH1cbiAgICBfdXBkYXRlQ2lyY2xlT3B0aW9uc0NoYW5nZXMoY2hhbmdlcykge1xuICAgICAgICBsZXQgb3B0aW9ucyA9IHt9O1xuICAgICAgICBsZXQgb3B0aW9uS2V5cyA9IE9iamVjdC5rZXlzKGNoYW5nZXMpLmZpbHRlcihrID0+IEFnbUNpcmNsZV8xLl9tYXBPcHRpb25zLmluZGV4T2YoaykgIT09IC0xKTtcbiAgICAgICAgb3B0aW9uS2V5cy5mb3JFYWNoKChrKSA9PiB7IG9wdGlvbnNba10gPSBjaGFuZ2VzW2tdLmN1cnJlbnRWYWx1ZTsgfSk7XG4gICAgICAgIGlmIChvcHRpb25LZXlzLmxlbmd0aCA+IDApIHtcbiAgICAgICAgICAgIHRoaXMuX21hbmFnZXIuc2V0T3B0aW9ucyh0aGlzLCBvcHRpb25zKTtcbiAgICAgICAgfVxuICAgIH1cbiAgICBfcmVnaXN0ZXJFdmVudExpc3RlbmVycygpIHtcbiAgICAgICAgbGV0IGV2ZW50cyA9IG5ldyBNYXAoKTtcbiAgICAgICAgZXZlbnRzLnNldCgnY2VudGVyX2NoYW5nZWQnLCB0aGlzLmNlbnRlckNoYW5nZSk7XG4gICAgICAgIGV2ZW50cy5zZXQoJ2NsaWNrJywgdGhpcy5jaXJjbGVDbGljayk7XG4gICAgICAgIGV2ZW50cy5zZXQoJ2RibGNsaWNrJywgdGhpcy5jaXJjbGVEYmxDbGljayk7XG4gICAgICAgIGV2ZW50cy5zZXQoJ2RyYWcnLCB0aGlzLmRyYWcpO1xuICAgICAgICBldmVudHMuc2V0KCdkcmFnZW5kJywgdGhpcy5kcmFnRW5kKTtcbiAgICAgICAgZXZlbnRzLnNldCgnZHJhZ3N0YXJ0JywgdGhpcy5kcmFnU3RhcnQpO1xuICAgICAgICBldmVudHMuc2V0KCdtb3VzZWRvd24nLCB0aGlzLm1vdXNlRG93bik7XG4gICAgICAgIGV2ZW50cy5zZXQoJ21vdXNlbW92ZScsIHRoaXMubW91c2VNb3ZlKTtcbiAgICAgICAgZXZlbnRzLnNldCgnbW91c2VvdXQnLCB0aGlzLm1vdXNlT3V0KTtcbiAgICAgICAgZXZlbnRzLnNldCgnbW91c2VvdmVyJywgdGhpcy5tb3VzZU92ZXIpO1xuICAgICAgICBldmVudHMuc2V0KCdtb3VzZXVwJywgdGhpcy5tb3VzZVVwKTtcbiAgICAgICAgZXZlbnRzLnNldCgncmFkaXVzX2NoYW5nZWQnLCB0aGlzLnJhZGl1c0NoYW5nZSk7XG4gICAgICAgIGV2ZW50cy5zZXQoJ3JpZ2h0Y2xpY2snLCB0aGlzLnJpZ2h0Q2xpY2spO1xuICAgICAgICBldmVudHMuZm9yRWFjaCgoZXZlbnRFbWl0dGVyLCBldmVudE5hbWUpID0+IHtcbiAgICAgICAgICAgIHRoaXMuX2V2ZW50U3Vic2NyaXB0aW9ucy5wdXNoKHRoaXMuX21hbmFnZXIuY3JlYXRlRXZlbnRPYnNlcnZhYmxlKGV2ZW50TmFtZSwgdGhpcykuc3Vic2NyaWJlKCh2YWx1ZSkgPT4ge1xuICAgICAgICAgICAgICAgIHN3aXRjaCAoZXZlbnROYW1lKSB7XG4gICAgICAgICAgICAgICAgICAgIGNhc2UgJ3JhZGl1c19jaGFuZ2VkJzpcbiAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMuX21hbmFnZXIuZ2V0UmFkaXVzKHRoaXMpLnRoZW4oKHJhZGl1cykgPT4gZXZlbnRFbWl0dGVyLmVtaXQocmFkaXVzKSk7XG4gICAgICAgICAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgICAgICAgICAgY2FzZSAnY2VudGVyX2NoYW5nZWQnOlxuICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5fbWFuYWdlci5nZXRDZW50ZXIodGhpcykudGhlbigoY2VudGVyKSA9PiBldmVudEVtaXR0ZXIuZW1pdCh7IGxhdDogY2VudGVyLmxhdCgpLCBsbmc6IGNlbnRlci5sbmcoKSB9KSk7XG4gICAgICAgICAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgICAgICAgICAgZGVmYXVsdDpcbiAgICAgICAgICAgICAgICAgICAgICAgIGV2ZW50RW1pdHRlci5lbWl0KHsgY29vcmRzOiB7IGxhdDogdmFsdWUubGF0TG5nLmxhdCgpLCBsbmc6IHZhbHVlLmxhdExuZy5sbmcoKSB9IH0pO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH0pKTtcbiAgICAgICAgfSk7XG4gICAgfVxuICAgIC8qKiBAaW50ZXJuYWwgKi9cbiAgICBuZ09uRGVzdHJveSgpIHtcbiAgICAgICAgdGhpcy5fZXZlbnRTdWJzY3JpcHRpb25zLmZvckVhY2goZnVuY3Rpb24gKHMpIHsgcy51bnN1YnNjcmliZSgpOyB9KTtcbiAgICAgICAgdGhpcy5fZXZlbnRTdWJzY3JpcHRpb25zID0gbnVsbDtcbiAgICAgICAgdGhpcy5fbWFuYWdlci5yZW1vdmVDaXJjbGUodGhpcyk7XG4gICAgfVxuICAgIC8qKlxuICAgICAqIEdldHMgdGhlIExhdExuZ0JvdW5kcyBvZiB0aGlzIENpcmNsZS5cbiAgICAgKi9cbiAgICBnZXRCb3VuZHMoKSB7IHJldHVybiB0aGlzLl9tYW5hZ2VyLmdldEJvdW5kcyh0aGlzKTsgfVxuICAgIGdldENlbnRlcigpIHsgcmV0dXJuIHRoaXMuX21hbmFnZXIuZ2V0Q2VudGVyKHRoaXMpOyB9XG59O1xuQWdtQ2lyY2xlLl9tYXBPcHRpb25zID0gW1xuICAgICdmaWxsQ29sb3InLCAnZmlsbE9wYWNpdHknLCAnc3Ryb2tlQ29sb3InLCAnc3Ryb2tlT3BhY2l0eScsICdzdHJva2VQb3NpdGlvbicsICdzdHJva2VXZWlnaHQnLFxuICAgICd2aXNpYmxlJywgJ3pJbmRleCcsICdjbGlja2FibGUnLFxuXTtcbkFnbUNpcmNsZS5jdG9yUGFyYW1ldGVycyA9ICgpID0+IFtcbiAgICB7IHR5cGU6IENpcmNsZU1hbmFnZXIgfVxuXTtcbnRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgSW5wdXQoKSxcbiAgICB0c2xpYl8xLl9fbWV0YWRhdGEoXCJkZXNpZ246dHlwZVwiLCBOdW1iZXIpXG5dLCBBZ21DaXJjbGUucHJvdG90eXBlLCBcImxhdGl0dWRlXCIsIHZvaWQgMCk7XG50c2xpYl8xLl9fZGVjb3JhdGUoW1xuICAgIElucHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgTnVtYmVyKVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJsb25naXR1ZGVcIiwgdm9pZCAwKTtcbnRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgSW5wdXQoKSxcbiAgICB0c2xpYl8xLl9fbWV0YWRhdGEoXCJkZXNpZ246dHlwZVwiLCBPYmplY3QpXG5dLCBBZ21DaXJjbGUucHJvdG90eXBlLCBcImNsaWNrYWJsZVwiLCB2b2lkIDApO1xudHNsaWJfMS5fX2RlY29yYXRlKFtcbiAgICBJbnB1dCgnY2lyY2xlRHJhZ2dhYmxlJyksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgT2JqZWN0KVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJkcmFnZ2FibGVcIiwgdm9pZCAwKTtcbnRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgSW5wdXQoKSxcbiAgICB0c2xpYl8xLl9fbWV0YWRhdGEoXCJkZXNpZ246dHlwZVwiLCBPYmplY3QpXG5dLCBBZ21DaXJjbGUucHJvdG90eXBlLCBcImVkaXRhYmxlXCIsIHZvaWQgMCk7XG50c2xpYl8xLl9fZGVjb3JhdGUoW1xuICAgIElucHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgU3RyaW5nKVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJmaWxsQ29sb3JcIiwgdm9pZCAwKTtcbnRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgSW5wdXQoKSxcbiAgICB0c2xpYl8xLl9fbWV0YWRhdGEoXCJkZXNpZ246dHlwZVwiLCBOdW1iZXIpXG5dLCBBZ21DaXJjbGUucHJvdG90eXBlLCBcImZpbGxPcGFjaXR5XCIsIHZvaWQgMCk7XG50c2xpYl8xLl9fZGVjb3JhdGUoW1xuICAgIElucHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgT2JqZWN0KVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJyYWRpdXNcIiwgdm9pZCAwKTtcbnRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgSW5wdXQoKSxcbiAgICB0c2xpYl8xLl9fbWV0YWRhdGEoXCJkZXNpZ246dHlwZVwiLCBTdHJpbmcpXG5dLCBBZ21DaXJjbGUucHJvdG90eXBlLCBcInN0cm9rZUNvbG9yXCIsIHZvaWQgMCk7XG50c2xpYl8xLl9fZGVjb3JhdGUoW1xuICAgIElucHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgTnVtYmVyKVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJzdHJva2VPcGFjaXR5XCIsIHZvaWQgMCk7XG50c2xpYl8xLl9fZGVjb3JhdGUoW1xuICAgIElucHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgU3RyaW5nKVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJzdHJva2VQb3NpdGlvblwiLCB2b2lkIDApO1xudHNsaWJfMS5fX2RlY29yYXRlKFtcbiAgICBJbnB1dCgpLFxuICAgIHRzbGliXzEuX19tZXRhZGF0YShcImRlc2lnbjp0eXBlXCIsIE9iamVjdClcbl0sIEFnbUNpcmNsZS5wcm90b3R5cGUsIFwic3Ryb2tlV2VpZ2h0XCIsIHZvaWQgMCk7XG50c2xpYl8xLl9fZGVjb3JhdGUoW1xuICAgIElucHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgT2JqZWN0KVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJ2aXNpYmxlXCIsIHZvaWQgMCk7XG50c2xpYl8xLl9fZGVjb3JhdGUoW1xuICAgIElucHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgTnVtYmVyKVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJ6SW5kZXhcIiwgdm9pZCAwKTtcbnRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgT3V0cHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgRXZlbnRFbWl0dGVyKVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJjZW50ZXJDaGFuZ2VcIiwgdm9pZCAwKTtcbnRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgT3V0cHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgRXZlbnRFbWl0dGVyKVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJjaXJjbGVDbGlja1wiLCB2b2lkIDApO1xudHNsaWJfMS5fX2RlY29yYXRlKFtcbiAgICBPdXRwdXQoKSxcbiAgICB0c2xpYl8xLl9fbWV0YWRhdGEoXCJkZXNpZ246dHlwZVwiLCBFdmVudEVtaXR0ZXIpXG5dLCBBZ21DaXJjbGUucHJvdG90eXBlLCBcImNpcmNsZURibENsaWNrXCIsIHZvaWQgMCk7XG50c2xpYl8xLl9fZGVjb3JhdGUoW1xuICAgIE91dHB1dCgpLFxuICAgIHRzbGliXzEuX19tZXRhZGF0YShcImRlc2lnbjp0eXBlXCIsIEV2ZW50RW1pdHRlcilcbl0sIEFnbUNpcmNsZS5wcm90b3R5cGUsIFwiZHJhZ1wiLCB2b2lkIDApO1xudHNsaWJfMS5fX2RlY29yYXRlKFtcbiAgICBPdXRwdXQoKSxcbiAgICB0c2xpYl8xLl9fbWV0YWRhdGEoXCJkZXNpZ246dHlwZVwiLCBFdmVudEVtaXR0ZXIpXG5dLCBBZ21DaXJjbGUucHJvdG90eXBlLCBcImRyYWdFbmRcIiwgdm9pZCAwKTtcbnRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgT3V0cHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgRXZlbnRFbWl0dGVyKVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJkcmFnU3RhcnRcIiwgdm9pZCAwKTtcbnRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgT3V0cHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgRXZlbnRFbWl0dGVyKVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJtb3VzZURvd25cIiwgdm9pZCAwKTtcbnRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgT3V0cHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgRXZlbnRFbWl0dGVyKVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJtb3VzZU1vdmVcIiwgdm9pZCAwKTtcbnRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgT3V0cHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgRXZlbnRFbWl0dGVyKVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJtb3VzZU91dFwiLCB2b2lkIDApO1xudHNsaWJfMS5fX2RlY29yYXRlKFtcbiAgICBPdXRwdXQoKSxcbiAgICB0c2xpYl8xLl9fbWV0YWRhdGEoXCJkZXNpZ246dHlwZVwiLCBFdmVudEVtaXR0ZXIpXG5dLCBBZ21DaXJjbGUucHJvdG90eXBlLCBcIm1vdXNlT3ZlclwiLCB2b2lkIDApO1xudHNsaWJfMS5fX2RlY29yYXRlKFtcbiAgICBPdXRwdXQoKSxcbiAgICB0c2xpYl8xLl9fbWV0YWRhdGEoXCJkZXNpZ246dHlwZVwiLCBFdmVudEVtaXR0ZXIpXG5dLCBBZ21DaXJjbGUucHJvdG90eXBlLCBcIm1vdXNlVXBcIiwgdm9pZCAwKTtcbnRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgT3V0cHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgRXZlbnRFbWl0dGVyKVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJyYWRpdXNDaGFuZ2VcIiwgdm9pZCAwKTtcbnRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgT3V0cHV0KCksXG4gICAgdHNsaWJfMS5fX21ldGFkYXRhKFwiZGVzaWduOnR5cGVcIiwgRXZlbnRFbWl0dGVyKVxuXSwgQWdtQ2lyY2xlLnByb3RvdHlwZSwgXCJyaWdodENsaWNrXCIsIHZvaWQgMCk7XG5BZ21DaXJjbGUgPSBBZ21DaXJjbGVfMSA9IHRzbGliXzEuX19kZWNvcmF0ZShbXG4gICAgRGlyZWN0aXZlKHtcbiAgICAgICAgc2VsZWN0b3I6ICdhZ20tY2lyY2xlJyxcbiAgICB9KSxcbiAgICB0c2xpYl8xLl9fbWV0YWRhdGEoXCJkZXNpZ246cGFyYW10eXBlc1wiLCBbQ2lyY2xlTWFuYWdlcl0pXG5dLCBBZ21DaXJjbGUpO1xuZXhwb3J0IHsgQWdtQ2lyY2xlIH07XG4iXX0=
# commented out pending test rework ''' from copy import copy from unittest import TestCase from os.path import join, abspath, exists import os from bank2ynab.bank_process import B2YBank, build_bank from bank2ynab.b2y_utilities import fix_conf_params from bank2ynab.plugins.null import NullBank from test.utils import get_test_confparser, get_project_dir class TestB2YBank(TestCase): TESTCONFPATH = join("test-data", "test.conf") def setUp(self): self.cp = get_test_confparser() self.defaults = dict(self.cp.defaults()) self.b = None self.test_data = join(get_project_dir(), "test-data") def tearDown(self): pass """ '''
function carregar() { var msg = document.getElementById('msg') var img = document.getElementById('imagem') var date = new Date() var hour = date.getHours() //A message announciong the time and the conditional change the background-color and the image's src msg.innerHTML = `Agora são <strong> ${hour} horas. </strong>` if (hour >= 0 && hour < 12) { img.src = 'imagens/manha.jpg' document.body.style.backgroundColor = 'rgba(236, 223, 104, 0.3)' } else if (hour >= 12 && hour < 18) { img.src = 'imagens/tarde.jpg' document.body.style.backgroundColor = 'rgba(171, 228, 125, 0.4)' } else { img.src = 'imagens/noite.jpg' document.body.style.backgroundColor = 'rgba(154, 74, 161, 0.6)' } }
import { __assign } from "tslib"; import { getCurrentHub } from '@sentry/core'; import { fill, logger, parseSemver } from '@sentry/utils'; import { cleanSpanDescription, extractUrl, isSentryRequest, normalizeRequestArgs, } from './utils/http'; var NODE_VERSION = parseSemver(process.versions.node); /** http module integration */ var Http = /** @class */ (function () { /** * @inheritDoc */ function Http(options) { if (options === void 0) { options = {}; } /** * @inheritDoc */ this.name = Http.id; this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; this._tracing = typeof options.tracing === 'undefined' ? false : options.tracing; } /** * @inheritDoc */ Http.prototype.setupOnce = function () { // No need to instrument if we don't want to track anything if (!this._breadcrumbs && !this._tracing) { return; } var wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, this._tracing); // eslint-disable-next-line @typescript-eslint/no-var-requires var httpModule = require('http'); fill(httpModule, 'get', wrappedHandlerMaker); fill(httpModule, 'request', wrappedHandlerMaker); // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. // If we do, we'd get double breadcrumbs and double spans for `https` calls. // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. if (NODE_VERSION.major && NODE_VERSION.major > 8) { // eslint-disable-next-line @typescript-eslint/no-var-requires var httpsModule = require('https'); fill(httpsModule, 'get', wrappedHandlerMaker); fill(httpsModule, 'request', wrappedHandlerMaker); } }; /** * @inheritDoc */ Http.id = 'Http'; return Http; }()); export { Http }; /** * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` * and `https` modules. (NB: Not a typo - this is a creator^2!) * * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs * @param tracingEnabled Whether or not to record outgoing requests as tracing spans * * @returns A function which accepts the exiting handler and returns a wrapped handler */ function _createWrappedRequestMethodFactory(breadcrumbsEnabled, tracingEnabled) { return function wrappedRequestMethodFactory(originalRequestMethod) { return function wrappedMethod() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } // eslint-disable-next-line @typescript-eslint/no-this-alias var httpModule = this; var requestArgs = normalizeRequestArgs(this, args); var requestOptions = requestArgs[0]; var requestUrl = extractUrl(requestOptions); // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method if (isSentryRequest(requestUrl)) { return originalRequestMethod.apply(httpModule, requestArgs); } var span; var parentSpan; var scope = getCurrentHub().getScope(); if (scope && tracingEnabled) { parentSpan = scope.getSpan(); if (parentSpan) { span = parentSpan.startChild({ description: (requestOptions.method || 'GET') + " " + requestUrl, op: 'http.client', }); var sentryTraceHeader = span.toTraceparent(); logger.log("[Tracing] Adding sentry-trace header " + sentryTraceHeader + " to outgoing request to " + requestUrl + ": "); requestOptions.headers = __assign(__assign({}, requestOptions.headers), { 'sentry-trace': sentryTraceHeader }); } } // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access return originalRequestMethod .apply(httpModule, requestArgs) .once('response', function (res) { // eslint-disable-next-line @typescript-eslint/no-this-alias var req = this; if (breadcrumbsEnabled) { addRequestBreadcrumb('response', requestUrl, req, res); } if (tracingEnabled && span) { if (res.statusCode) { span.setHttpStatus(res.statusCode); } span.description = cleanSpanDescription(span.description, requestOptions, req); span.finish(); } }) .once('error', function () { // eslint-disable-next-line @typescript-eslint/no-this-alias var req = this; if (breadcrumbsEnabled) { addRequestBreadcrumb('error', requestUrl, req); } if (tracingEnabled && span) { span.setHttpStatus(500); span.description = cleanSpanDescription(span.description, requestOptions, req); span.finish(); } }); }; }; } /** * Captures Breadcrumb based on provided request/response pair */ function addRequestBreadcrumb(event, url, req, res) { if (!getCurrentHub().getIntegration(Http)) { return; } getCurrentHub().addBreadcrumb({ category: 'http', data: { method: req.method, status_code: res && res.statusCode, url: url, }, type: 'http', }, { event: event, request: req, response: res, }); } //# sourceMappingURL=http.js.map
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const React = require("react"); const wrapIcon_1 = require("../utils/wrapIcon"); const rawSvg = (iconProps) => { const { className, primaryFill } = iconProps; return React.createElement("svg", { width: 16, height: 16, viewBox: "0 0 16 16", xmlns: "http://www.w3.org/2000/svg", className: className }, React.createElement("path", { d: "M7.7 4.26a.75.75 0 111.1-1.02l4 4.25c.27.29.27.73 0 1.02l-4 4.25a.75.75 0 11-1.1-1.02L11.23 8 7.7 4.26zm-4 0a.75.75 0 111.1-1.02l4 4.25c.27.29.27.73 0 1.02l-4 4.25a.75.75 0 11-1.1-1.02L7.23 8 3.7 4.26z", fill: primaryFill })); }; const ChevronDoubleRight16Filled = wrapIcon_1.default(rawSvg({}), 'ChevronDoubleRight16Filled'); exports.default = ChevronDoubleRight16Filled;
import Page from 'components/Page'; import ReactDOM from "react-dom" import React from 'react'; import { Card, CardBody, CardHeader, Col, FormGroup, Input, Label, Row, Table, Button, Modal, ModalBody, ModalFooter, ModalHeader, CustomInput, } from 'reactstrap'; import { MdSearch, } from 'react-icons/md'; import XLSX from "xlsx" import * as FileSaver from "file-saver" import axios from 'axios'; class FormPage extends React.Component { componentDidMount() { axios.get(`http://localhost:4000/api/komoditi`) .then(res => this.setState({komoditi: res.data})) } state = { modal_edit: false, modal_export: false, komoditi: [], filteredData: [], selectedData: {}, value: "", fileName: "", fileFormat: "xlsx", name: "", suhu: "", musim: "", ketinggian: "", tanah: "", }; toggle = (modalType, selected) => () => { console.log(modalType); if (!modalType) { return this.setState({ modal_edit: !this.state.modal_edit, }); } this.setState({ [`modal_${modalType}`]: !this.state[`modal_${modalType}`], name: "", suhu: "", musim: "", ketinggian: "", tanah: "", }); if(selected){ this.setState({selectedData: selected}) } }; handleFilter = e => { let data = this.state.komoditi let filteredData = [] let value = e.target.value this.setState({ value }) if (value.length) { filteredData = data.filter(col => { let startsWithCondition = col.name.toLowerCase().startsWith(value.toLowerCase()) || col.id .toString() .toLowerCase() .startsWith(value.toLowerCase()) let includesCondition = col.name.toLowerCase().includes(value.toLowerCase()) || col.id .toString() .toLowerCase() .includes(value.toLowerCase()) if (startsWithCondition) return startsWithCondition else if (!startsWithCondition && includesCondition) return includesCondition else return null }) this.setState({ value, filteredData }) } } toggleExport = () => { this.setState({ modal_export: !this.state.modal_export }) } handleExport = () => { this.toggle() let table = ReactDOM.findDOMNode(this.tableRef) let bookType = this.state.fileFormat.length ? this.state.fileFormat : "xlsx" let wb = XLSX.utils.table_to_book(table, { sheet: "Sheet JS" }) let wbout = XLSX.write(wb, { bookType, bookSST: true, type: "binary" }) const s2ab = s => { var buf = new ArrayBuffer(s.length) var view = new Uint8Array(buf) for (var i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff return buf } let file = this.state.fileFormat.length && this.state.fileFormat.length ? `${this.state.fileName}.${this.state.fileFormat}` : this.state.fileName.length ? `${this.state.fileName}.xlsx` : this.state.fileFormat.length ? `excel-sheet.${this.state.fileFormat}` : "excel-sheet.xlsx" return FileSaver.saveAs( new Blob([s2ab(wbout)], { type: "application/octet-stream" }), file ) } handleSave = (toggle) => { axios.put("http://localhost:4000/api/update-komoditi/" + this.state.selectedData.id, { name: this.state.selectedData.name, }) .then(response => { toggle() axios.get(`http://localhost:4000/api/komoditi`) .then(res => this.setState({komoditi: res.data})) }) .catch(response => { console.log(response) }) } handleDelete = (toggle) => { axios.delete("http://localhost:4000/api/delete-komoditi/" + this.state.selectedData.id) .then(response => { toggle() axios.get(`http://localhost:4000/api/komoditi`) .then(res => this.setState({komoditi: res.data})) }) .catch(response => { console.log(response) }) } handleAdd = (toggle) => { if(this.state.name === ''){ alert("Data tidak boleh kosong!") } else { axios.post("http://localhost:4000/api/add-komoditi", { name: this.state.name, musim: this.state.musim, ketinggian: this.state.ketinggian, tanah: this.state.tanah, suhu: this.state.suhu, }) .then(response => { toggle() console.log(response) axios.get(`http://localhost:4000/api/komoditi`) .then(res => this.setState({komoditi: res.data})) }) .catch(response => { console.log(response) }) } } handleChange = (e) => { this.setState({isAdmin: e.target.value}) } render() { let array = this.state.value ? this.state.filteredData : this.state.komoditi let renderTableData = array.map((user ,i) => { return ( <tr key={user.id}> <th scope="row">{i + 1}</th> <td>{user.name}</td> {/* <td>{user.password}</td> <td>{user.email}</td> <td>{user.name}</td> */} <td> <Button type='button' onClick={this.toggle('edit', user)}>Ubah</Button> <Button className="ml-1" color="danger" type='button' onClick={this.toggle('delete', user)}>Hapus</Button> </td> </tr> ) }) return ( <Page title="List Komoditi" breadcrumbs={[{ name: 'Users', active: true }]}> <Row> <Col> <Card> <CardHeader className="d-flex flex-wrap justify-content-between mb-1"> <Label>User List</Label> <div inline className="cr-search-form"> <MdSearch size="20" className="cr-search-form__icon-search text-secondary" style={{top: 8}} /> <Input type="search" className="cr-search-form__input" value={this.state.value} onChange={e => this.handleFilter(e)} placeholder="Search..." /> </div> <Button onClick={this.toggleExport}>Export as CSV</Button> </CardHeader> <CardBody> <Table innerRef={el => (this.tableRef = el)} responsive> <thead> <tr> <th>#</th> <th>Nama Komoditi</th> {/* <th>Password</th> <th>Email</th> <th>Name</th> */} <th>Aksi</th> </tr> </thead> <tbody> {renderTableData} </tbody> <tfoot> <Button color="primary" type='button' onClick={this.toggle('add')}>Tambah Komoditi</Button> </tfoot> </Table> <Modal isOpen={this.state.modal_edit} toggle={this.toggle('edit')} className={this.props.className}> <ModalHeader toggle={this.toggle('edit')}>Ubah data</ModalHeader> <ModalBody> <FormGroup> <Label for="exampleEmail">Komoditi</Label> <Input type="text" name="name" defaultValue={this.state.selectedData.name} placeholder="name" onChange={e => this.setState({ selectedData: {...this.state.selectedData, name: e.target.value }})} /> </FormGroup> </ModalBody> <ModalFooter> <Button onClick={() => this.handleSave(this.toggle('edit'))}> Simpan </Button> <Button color="primary" onClick={this.toggle('edit')}> Close </Button> </ModalFooter> </Modal> <Modal isOpen={this.state.modal_delete} toggle={this.toggle('delete')} className={this.props.className}> <ModalHeader toggle={this.toggle('delete')}>Hapus data</ModalHeader> <ModalBody> Apakah anda yakin untuk menghapus data ini ? </ModalBody> <ModalFooter> <Button color="primary" onClick={() => this.handleDelete(this.toggle('delete'))}> Yes </Button> <Button color="secondary" onClick={this.toggle('delete')}> Close </Button> </ModalFooter> </Modal> <Modal isOpen={this.state.modal_add} toggle={this.toggle('add')} className={this.props.className}> <ModalHeader toggle={this.toggle('add')}>Tambah data</ModalHeader> <ModalBody> <FormGroup> <Label for="exampleEmail">Nama Komoditi</Label> <Input type="text" name="name" defaultValue={this.state.name} placeholder="nama komoditi" onChange={e => this.setState({ name: e.target.value })} /> </FormGroup> <FormGroup> <Label for="exampleEmail">Bobot Musim</Label> <Input type="text" name="name" defaultValue={this.state.musim} placeholder="bobot musim" onChange={e => this.setState({ musim: e.target.value })} /> </FormGroup> <FormGroup> <Label for="exampleEmail">Bobot Ketinggian</Label> <Input type="text" name="name" defaultValue={this.state.ketinggian} placeholder="bobot ketinggian" onChange={e => this.setState({ ketinggian: e.target.value })} /> </FormGroup> <FormGroup> <Label for="exampleEmail">Bobot Tanah</Label> <Input type="text" name="name" defaultValue={this.state.tanah} placeholder="bobot tanah" onChange={e => this.setState({ tanah: e.target.value })} /> </FormGroup> <FormGroup> <Label for="exampleEmail">Bobot Suhu</Label> <Input type="text" name="name" defaultValue={this.state.suhu} placeholder="bobot suhu" onChange={e => this.setState({ suhu: e.target.value })} /> </FormGroup> </ModalBody> <ModalFooter> <Button onClick={() => this.handleAdd(this.toggle('add'))}> Simpan </Button> <Button color="primary" onClick={this.toggle('add')}> Close </Button> </ModalFooter> </Modal> <Modal isOpen={this.state.modal_export} toggle={this.toggleExport} className="modal-dialog-centered"> <ModalHeader toggle={this.toggleModal}>Export To Excel</ModalHeader> <ModalBody> <FormGroup> <Input type="text" value={this.state.fileName} onChange={e => this.setState({ fileName: e.target.value })} placeholder="Enter File Name" /> </FormGroup> <FormGroup> <CustomInput type="select" id="selectFileFormat" name="customSelect" value={this.state.fileFormat} onChange={e => this.setState({ fileFormat: e.target.value })}> <option>xlsx</option> <option>csv</option> {/* <option>txt</option> */} </CustomInput> </FormGroup> </ModalBody> <ModalFooter> <Button color="primary" onClick={this.handleExport}> Export </Button> <Button color="flat-danger" onClick={this.toggleExport}> Cancel </Button> </ModalFooter> </Modal> </CardBody> </Card> </Col> </Row> </Page> ); }; }; export default FormPage;
/** * Created by PanJiaChen on 16/11/18. */ /** * @param {string} path * @returns {Boolean} */ export function isExternal(path) { return /^(https?:|mailto:|tel:)/.test(path) } /** * @param {string} str * @returns {Boolean} */ export function validUsername(str) { // const valid_map = ['admin', 'editor', 'teacher', 'student'] // return valid_map.indexOf(str.trim()) >= 0 return 1 } /** * @param {string} url * @returns {Boolean} */ export function validURL(url) { const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/ return reg.test(url) } /** * @param {string} str * @returns {Boolean} */ export function validLowerCase(str) { const reg = /^[a-z]+$/ return reg.test(str) } /** * @param {string} str * @returns {Boolean} */ export function validUpperCase(str) { const reg = /^[A-Z]+$/ return reg.test(str) } /** * @param {string} str * @returns {Boolean} */ export function validAlphabets(str) { const reg = /^[A-Za-z]+$/ return reg.test(str) } /** * @param {string} email * @returns {Boolean} */ export function validEmail(email) { const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ return reg.test(email) } /** * @param {string} str * @returns {Boolean} */ export function isString(str) { if (typeof str === 'string' || str instanceof String) { return true } return false } /** * @param {Array} arg * @returns {Boolean} */ export function isArray(arg) { if (typeof Array.isArray === 'undefined') { return Object.prototype.toString.call(arg) === '[object Array]' } return Array.isArray(arg) }
# Copyright (c) 2020 Seven Bridges. See LICENSE __version__ = "2021.1.5"
IntlPolyfill.__addLocaleData({locale:"mgh",date:{ca:["gregory","buddhist","chinese","coptic","dangi","ethioaa","ethiopic","generic","hebrew","indian","islamic","islamicc","japanese","persian","roc"],hourNo0:true,hour12:false,formats:{short:"{1} {0}",medium:"{1} {0}",full:"{1} {0}",long:"{1} {0}",availableFormats:{"d":"d","E":"ccc",Ed:"E d",Ehm:"E h:mm a",EHm:"E HH:mm",Ehms:"E h:mm:ss a",EHms:"E HH:mm:ss",Gy:"G y",GyMMM:"G y MMM",GyMMMd:"G y MMM d",GyMMMEd:"G y MMM d, E","h":"h a","H":"HH",hm:"h:mm a",Hm:"HH:mm",hms:"h:mm:ss a",Hms:"HH:mm:ss",hmsv:"h:mm:ss a v",Hmsv:"HH:mm:ss v",hmv:"h:mm a v",Hmv:"HH:mm v","M":"L",Md:"d/M",MEd:"E, M/d",MMM:"LLL",MMMd:"MMM d",MMMEd:"E, MMM d",MMMMd:"MMMM d",ms:"m:ss","y":"y",yM:"M/y",yMd:"d/M/y",yMEd:"E, M/d/y",yMMM:"MMM y",yMMMd:"MMM d, y",yMMMEd:"E, MMM d, y",yMMMM:"y MMMM",yQQQ:"QQQ y",yQQQQ:"QQQQ y"},dateFormats:{yMMMMEEEEd:"EEEE, d MMMM y",yMMMMd:"d MMMM y",yMMMd:"d MMM y",yMd:"dd/MM/y"},timeFormats:{hmmsszzzz:"HH:mm:ss zzzz",hmsz:"HH:mm:ss z",hms:"HH:mm:ss",hm:"HH:mm"}},calendars:{buddhist:{months:{narrow:["K","U","R","C","T","M","S","N","T","K","M","Y"],short:["Kwa","Una","Rar","Che","Tha","Moc","Sab","Nan","Tis","Kum","Moj","Yel"],long:["Mweri wo kwanza","Mweri wo unayeli","Mweri wo uneraru","Mweri wo unecheshe","Mweri wo unethanu","Mweri wo thanu na mocha","Mweri wo saba","Mweri wo nane","Mweri wo tisa","Mweri wo kumi","Mweri wo kumi na moja","Mweri wo kumi na yel’li"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},eras:{narrow:["BE"],short:["BE"],long:["BE"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},chinese:{months:{narrow:["1","2","3","4","5","6","7","8","9","10","11","12"],short:["M01","M02","M03","M04","M05","M06","M07","M08","M09","M10","M11","M12"],long:["M01","M02","M03","M04","M05","M06","M07","M08","M09","M10","M11","M12"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},coptic:{months:{narrow:["1","2","3","4","5","6","7","8","9","10","11","12","13"],short:["Tout","Baba","Hator","Kiahk","Toba","Amshir","Baramhat","Baramouda","Bashans","Paona","Epep","Mesra","Nasie"],long:["Tout","Baba","Hator","Kiahk","Toba","Amshir","Baramhat","Baramouda","Bashans","Paona","Epep","Mesra","Nasie"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},eras:{narrow:["ERA0","ERA1"],short:["ERA0","ERA1"],long:["ERA0","ERA1"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},dangi:{months:{narrow:["1","2","3","4","5","6","7","8","9","10","11","12"],short:["M01","M02","M03","M04","M05","M06","M07","M08","M09","M10","M11","M12"],long:["M01","M02","M03","M04","M05","M06","M07","M08","M09","M10","M11","M12"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},ethiopic:{months:{narrow:["1","2","3","4","5","6","7","8","9","10","11","12","13"],short:["Meskerem","Tekemt","Hedar","Tahsas","Ter","Yekatit","Megabit","Miazia","Genbot","Sene","Hamle","Nehasse","Pagumen"],long:["Meskerem","Tekemt","Hedar","Tahsas","Ter","Yekatit","Megabit","Miazia","Genbot","Sene","Hamle","Nehasse","Pagumen"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},eras:{narrow:["ERA0","ERA1"],short:["ERA0","ERA1"],long:["ERA0","ERA1"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},ethioaa:{months:{narrow:["1","2","3","4","5","6","7","8","9","10","11","12","13"],short:["Meskerem","Tekemt","Hedar","Tahsas","Ter","Yekatit","Megabit","Miazia","Genbot","Sene","Hamle","Nehasse","Pagumen"],long:["Meskerem","Tekemt","Hedar","Tahsas","Ter","Yekatit","Megabit","Miazia","Genbot","Sene","Hamle","Nehasse","Pagumen"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},eras:{narrow:["ERA0"],short:["ERA0"],long:["ERA0"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},generic:{months:{narrow:["1","2","3","4","5","6","7","8","9","10","11","12"],short:["M01","M02","M03","M04","M05","M06","M07","M08","M09","M10","M11","M12"],long:["M01","M02","M03","M04","M05","M06","M07","M08","M09","M10","M11","M12"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},eras:{narrow:["ERA0","ERA1"],short:["ERA0","ERA1"],long:["ERA0","ERA1"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},gregory:{months:{narrow:["K","U","R","C","T","M","S","N","T","K","M","Y"],short:["Kwa","Una","Rar","Che","Tha","Moc","Sab","Nan","Tis","Kum","Moj","Yel"],long:["Mweri wo kwanza","Mweri wo unayeli","Mweri wo uneraru","Mweri wo unecheshe","Mweri wo unethanu","Mweri wo thanu na mocha","Mweri wo saba","Mweri wo nane","Mweri wo tisa","Mweri wo kumi","Mweri wo kumi na moja","Mweri wo kumi na yel’li"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},eras:{narrow:["HY","YY","BCE","CE"],short:["HY","YY","BCE","CE"],long:["Hinapiya yesu","Yopia yesu","BCE","CE"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},hebrew:{months:{narrow:["1","2","3","4","5","6","7","8","9","10","11","12","13","7"],short:["Tishri","Heshvan","Kislev","Tevet","Shevat","Adar I","Adar","Nisan","Iyar","Sivan","Tamuz","Av","Elul","Adar II"],long:["Tishri","Heshvan","Kislev","Tevet","Shevat","Adar I","Adar","Nisan","Iyar","Sivan","Tamuz","Av","Elul","Adar II"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},eras:{narrow:["AM"],short:["AM"],long:["AM"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},indian:{months:{narrow:["1","2","3","4","5","6","7","8","9","10","11","12"],short:["Chaitra","Vaisakha","Jyaistha","Asadha","Sravana","Bhadra","Asvina","Kartika","Agrahayana","Pausa","Magha","Phalguna"],long:["Chaitra","Vaisakha","Jyaistha","Asadha","Sravana","Bhadra","Asvina","Kartika","Agrahayana","Pausa","Magha","Phalguna"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},eras:{narrow:["Saka"],short:["Saka"],long:["Saka"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},islamic:{months:{narrow:["1","2","3","4","5","6","7","8","9","10","11","12"],short:["Muh.","Saf.","Rab. I","Rab. II","Jum. I","Jum. II","Raj.","Sha.","Ram.","Shaw.","Dhuʻl-Q.","Dhuʻl-H."],long:["Muharram","Safar","Rabiʻ I","Rabiʻ II","Jumada I","Jumada II","Rajab","Shaʻban","Ramadan","Shawwal","Dhuʻl-Qiʻdah","Dhuʻl-Hijjah"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},eras:{narrow:["AH"],short:["AH"],long:["AH"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},islamicc:{months:{narrow:["1","2","3","4","5","6","7","8","9","10","11","12"],short:["Muh.","Saf.","Rab. I","Rab. II","Jum. I","Jum. II","Raj.","Sha.","Ram.","Shaw.","Dhuʻl-Q.","Dhuʻl-H."],long:["Muharram","Safar","Rabiʻ I","Rabiʻ II","Jumada I","Jumada II","Rajab","Shaʻban","Ramadan","Shawwal","Dhuʻl-Qiʻdah","Dhuʻl-Hijjah"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},eras:{narrow:["AH"],short:["AH"],long:["AH"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},japanese:{months:{narrow:["K","U","R","C","T","M","S","N","T","K","M","Y"],short:["Kwa","Una","Rar","Che","Tha","Moc","Sab","Nan","Tis","Kum","Moj","Yel"],long:["Mweri wo kwanza","Mweri wo unayeli","Mweri wo uneraru","Mweri wo unecheshe","Mweri wo unethanu","Mweri wo thanu na mocha","Mweri wo saba","Mweri wo nane","Mweri wo tisa","Mweri wo kumi","Mweri wo kumi na moja","Mweri wo kumi na yel’li"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},eras:{narrow:["Taika (645–650)","Hakuchi (650–671)","Hakuhō (672–686)","Shuchō (686–701)","Taihō (701–704)","Keiun (704–708)","Wadō (708–715)","Reiki (715–717)","Yōrō (717–724)","Jinki (724–729)","Tenpyō (729–749)","Tenpyō-kampō (749-749)","Tenpyō-shōhō (749-757)","Tenpyō-hōji (757-765)","Tenpyō-jingo (765-767)","Jingo-keiun (767-770)","Hōki (770–780)","Ten-ō (781-782)","Enryaku (782–806)","Daidō (806–810)","Kōnin (810–824)","Tenchō (824–834)","Jōwa (834–848)","Kajō (848–851)","Ninju (851–854)","Saikō (854–857)","Ten-an (857-859)","Jōgan (859–877)","Gangyō (877–885)","Ninna (885–889)","Kanpyō (889–898)","Shōtai (898–901)","Engi (901–923)","Enchō (923–931)","Jōhei (931–938)","Tengyō (938–947)","Tenryaku (947–957)","Tentoku (957–961)","Ōwa (961–964)","Kōhō (964–968)","Anna (968–970)","Tenroku (970–973)","Ten’en (973–976)","Jōgen (976–978)","Tengen (978–983)","Eikan (983–985)","Kanna (985–987)","Eien (987–989)","Eiso (989–990)","Shōryaku (990–995)","Chōtoku (995–999)","Chōhō (999–1004)","Kankō (1004–1012)","Chōwa (1012–1017)","Kannin (1017–1021)","Jian (1021–1024)","Manju (1024–1028)","Chōgen (1028–1037)","Chōryaku (1037–1040)","Chōkyū (1040–1044)","Kantoku (1044–1046)","Eishō (1046–1053)","Tengi (1053–1058)","Kōhei (1058–1065)","Jiryaku (1065–1069)","Enkyū (1069–1074)","Shōho (1074–1077)","Shōryaku (1077–1081)","Eihō (1081–1084)","Ōtoku (1084–1087)","Kanji (1087–1094)","Kahō (1094–1096)","Eichō (1096–1097)","Jōtoku (1097–1099)","Kōwa (1099–1104)","Chōji (1104–1106)","Kashō (1106–1108)","Tennin (1108–1110)","Ten-ei (1110-1113)","Eikyū (1113–1118)","Gen’ei (1118–1120)","Hōan (1120–1124)","Tenji (1124–1126)","Daiji (1126–1131)","Tenshō (1131–1132)","Chōshō (1132–1135)","Hōen (1135–1141)","Eiji (1141–1142)","Kōji (1142–1144)","Ten’yō (1144–1145)","Kyūan (1145–1151)","Ninpei (1151–1154)","Kyūju (1154–1156)","Hōgen (1156–1159)","Heiji (1159–1160)","Eiryaku (1160–1161)","Ōho (1161–1163)","Chōkan (1163–1165)","Eiman (1165–1166)","Nin’an (1166–1169)","Kaō (1169–1171)","Shōan (1171–1175)","Angen (1175–1177)","Jishō (1177–1181)","Yōwa (1181–1182)","Juei (1182–1184)","Genryaku (1184–1185)","Bunji (1185–1190)","Kenkyū (1190–1199)","Shōji (1199–1201)","Kennin (1201–1204)","Genkyū (1204–1206)","Ken’ei (1206–1207)","Jōgen (1207–1211)","Kenryaku (1211–1213)","Kenpō (1213–1219)","Jōkyū (1219–1222)","Jōō (1222–1224)","Gennin (1224–1225)","Karoku (1225–1227)","Antei (1227–1229)","Kanki (1229–1232)","Jōei (1232–1233)","Tenpuku (1233–1234)","Bunryaku (1234–1235)","Katei (1235–1238)","Ryakunin (1238–1239)","En’ō (1239–1240)","Ninji (1240–1243)","Kangen (1243–1247)","Hōji (1247–1249)","Kenchō (1249–1256)","Kōgen (1256–1257)","Shōka (1257–1259)","Shōgen (1259–1260)","Bun’ō (1260–1261)","Kōchō (1261–1264)","Bun’ei (1264–1275)","Kenji (1275–1278)","Kōan (1278–1288)","Shōō (1288–1293)","Einin (1293–1299)","Shōan (1299–1302)","Kengen (1302–1303)","Kagen (1303–1306)","Tokuji (1306–1308)","Enkyō (1308–1311)","Ōchō (1311–1312)","Shōwa (1312–1317)","Bunpō (1317–1319)","Genō (1319–1321)","Genkō (1321–1324)","Shōchū (1324–1326)","Karyaku (1326–1329)","Gentoku (1329–1331)","Genkō (1331–1334)","Kenmu (1334–1336)","Engen (1336–1340)","Kōkoku (1340–1346)","Shōhei (1346–1370)","Kentoku (1370–1372)","Bunchū (1372–1375)","Tenju (1375–1379)","Kōryaku (1379–1381)","Kōwa (1381–1384)","Genchū (1384–1392)","Meitoku (1384–1387)","Kakei (1387–1389)","Kōō (1389–1390)","Meitoku (1390–1394)","Ōei (1394–1428)","Shōchō (1428–1429)","Eikyō (1429–1441)","Kakitsu (1441–1444)","Bun’an (1444–1449)","Hōtoku (1449–1452)","Kyōtoku (1452–1455)","Kōshō (1455–1457)","Chōroku (1457–1460)","Kanshō (1460–1466)","Bunshō (1466–1467)","Ōnin (1467–1469)","Bunmei (1469–1487)","Chōkyō (1487–1489)","Entoku (1489–1492)","Meiō (1492–1501)","Bunki (1501–1504)","Eishō (1504–1521)","Taiei (1521–1528)","Kyōroku (1528–1532)","Tenbun (1532–1555)","Kōji (1555–1558)","Eiroku (1558–1570)","Genki (1570–1573)","Tenshō (1573–1592)","Bunroku (1592–1596)","Keichō (1596–1615)","Genna (1615–1624)","Kan’ei (1624–1644)","Shōho (1644–1648)","Keian (1648–1652)","Jōō (1652–1655)","Meireki (1655–1658)","Manji (1658–1661)","Kanbun (1661–1673)","Enpō (1673–1681)","Tenna (1681–1684)","Jōkyō (1684–1688)","Genroku (1688–1704)","Hōei (1704–1711)","Shōtoku (1711–1716)","Kyōhō (1716–1736)","Genbun (1736–1741)","Kanpō (1741–1744)","Enkyō (1744–1748)","Kan’en (1748–1751)","Hōreki (1751–1764)","Meiwa (1764–1772)","An’ei (1772–1781)","Tenmei (1781–1789)","Kansei (1789–1801)","Kyōwa (1801–1804)","Bunka (1804–1818)","Bunsei (1818–1830)","Tenpō (1830–1844)","Kōka (1844–1848)","Kaei (1848–1854)","Ansei (1854–1860)","Man’en (1860–1861)","Bunkyū (1861–1864)","Genji (1864–1865)","Keiō (1865–1868)","M","T","S","H"],short:["Taika (645–650)","Hakuchi (650–671)","Hakuhō (672–686)","Shuchō (686–701)","Taihō (701–704)","Keiun (704–708)","Wadō (708–715)","Reiki (715–717)","Yōrō (717–724)","Jinki (724–729)","Tenpyō (729–749)","Tenpyō-kampō (749-749)","Tenpyō-shōhō (749-757)","Tenpyō-hōji (757-765)","Tenpyō-jingo (765-767)","Jingo-keiun (767-770)","Hōki (770–780)","Ten-ō (781-782)","Enryaku (782–806)","Daidō (806–810)","Kōnin (810–824)","Tenchō (824–834)","Jōwa (834–848)","Kajō (848–851)","Ninju (851–854)","Saikō (854–857)","Ten-an (857-859)","Jōgan (859–877)","Gangyō (877–885)","Ninna (885–889)","Kanpyō (889–898)","Shōtai (898–901)","Engi (901–923)","Enchō (923–931)","Jōhei (931–938)","Tengyō (938–947)","Tenryaku (947–957)","Tentoku (957–961)","Ōwa (961–964)","Kōhō (964–968)","Anna (968–970)","Tenroku (970–973)","Ten’en (973–976)","Jōgen (976–978)","Tengen (978–983)","Eikan (983–985)","Kanna (985–987)","Eien (987–989)","Eiso (989–990)","Shōryaku (990–995)","Chōtoku (995–999)","Chōhō (999–1004)","Kankō (1004–1012)","Chōwa (1012–1017)","Kannin (1017–1021)","Jian (1021–1024)","Manju (1024–1028)","Chōgen (1028–1037)","Chōryaku (1037–1040)","Chōkyū (1040–1044)","Kantoku (1044–1046)","Eishō (1046–1053)","Tengi (1053–1058)","Kōhei (1058–1065)","Jiryaku (1065–1069)","Enkyū (1069–1074)","Shōho (1074–1077)","Shōryaku (1077–1081)","Eihō (1081–1084)","Ōtoku (1084–1087)","Kanji (1087–1094)","Kahō (1094–1096)","Eichō (1096–1097)","Jōtoku (1097–1099)","Kōwa (1099–1104)","Chōji (1104–1106)","Kashō (1106–1108)","Tennin (1108–1110)","Ten-ei (1110-1113)","Eikyū (1113–1118)","Gen’ei (1118–1120)","Hōan (1120–1124)","Tenji (1124–1126)","Daiji (1126–1131)","Tenshō (1131–1132)","Chōshō (1132–1135)","Hōen (1135–1141)","Eiji (1141–1142)","Kōji (1142–1144)","Ten’yō (1144–1145)","Kyūan (1145–1151)","Ninpei (1151–1154)","Kyūju (1154–1156)","Hōgen (1156–1159)","Heiji (1159–1160)","Eiryaku (1160–1161)","Ōho (1161–1163)","Chōkan (1163–1165)","Eiman (1165–1166)","Nin’an (1166–1169)","Kaō (1169–1171)","Shōan (1171–1175)","Angen (1175–1177)","Jishō (1177–1181)","Yōwa (1181–1182)","Juei (1182–1184)","Genryaku (1184–1185)","Bunji (1185–1190)","Kenkyū (1190–1199)","Shōji (1199–1201)","Kennin (1201–1204)","Genkyū (1204–1206)","Ken’ei (1206–1207)","Jōgen (1207–1211)","Kenryaku (1211–1213)","Kenpō (1213–1219)","Jōkyū (1219–1222)","Jōō (1222–1224)","Gennin (1224–1225)","Karoku (1225–1227)","Antei (1227–1229)","Kanki (1229–1232)","Jōei (1232–1233)","Tenpuku (1233–1234)","Bunryaku (1234–1235)","Katei (1235–1238)","Ryakunin (1238–1239)","En’ō (1239–1240)","Ninji (1240–1243)","Kangen (1243–1247)","Hōji (1247–1249)","Kenchō (1249–1256)","Kōgen (1256–1257)","Shōka (1257–1259)","Shōgen (1259–1260)","Bun’ō (1260–1261)","Kōchō (1261–1264)","Bun’ei (1264–1275)","Kenji (1275–1278)","Kōan (1278–1288)","Shōō (1288–1293)","Einin (1293–1299)","Shōan (1299–1302)","Kengen (1302–1303)","Kagen (1303–1306)","Tokuji (1306–1308)","Enkyō (1308–1311)","Ōchō (1311–1312)","Shōwa (1312–1317)","Bunpō (1317–1319)","Genō (1319–1321)","Genkō (1321–1324)","Shōchū (1324–1326)","Karyaku (1326–1329)","Gentoku (1329–1331)","Genkō (1331–1334)","Kenmu (1334–1336)","Engen (1336–1340)","Kōkoku (1340–1346)","Shōhei (1346–1370)","Kentoku (1370–1372)","Bunchū (1372–1375)","Tenju (1375–1379)","Kōryaku (1379–1381)","Kōwa (1381–1384)","Genchū (1384–1392)","Meitoku (1384–1387)","Kakei (1387–1389)","Kōō (1389–1390)","Meitoku (1390–1394)","Ōei (1394–1428)","Shōchō (1428–1429)","Eikyō (1429–1441)","Kakitsu (1441–1444)","Bun’an (1444–1449)","Hōtoku (1449–1452)","Kyōtoku (1452–1455)","Kōshō (1455–1457)","Chōroku (1457–1460)","Kanshō (1460–1466)","Bunshō (1466–1467)","Ōnin (1467–1469)","Bunmei (1469–1487)","Chōkyō (1487–1489)","Entoku (1489–1492)","Meiō (1492–1501)","Bunki (1501–1504)","Eishō (1504–1521)","Taiei (1521–1528)","Kyōroku (1528–1532)","Tenbun (1532–1555)","Kōji (1555–1558)","Eiroku (1558–1570)","Genki (1570–1573)","Tenshō (1573–1592)","Bunroku (1592–1596)","Keichō (1596–1615)","Genna (1615–1624)","Kan’ei (1624–1644)","Shōho (1644–1648)","Keian (1648–1652)","Jōō (1652–1655)","Meireki (1655–1658)","Manji (1658–1661)","Kanbun (1661–1673)","Enpō (1673–1681)","Tenna (1681–1684)","Jōkyō (1684–1688)","Genroku (1688–1704)","Hōei (1704–1711)","Shōtoku (1711–1716)","Kyōhō (1716–1736)","Genbun (1736–1741)","Kanpō (1741–1744)","Enkyō (1744–1748)","Kan’en (1748–1751)","Hōreki (1751–1764)","Meiwa (1764–1772)","An’ei (1772–1781)","Tenmei (1781–1789)","Kansei (1789–1801)","Kyōwa (1801–1804)","Bunka (1804–1818)","Bunsei (1818–1830)","Tenpō (1830–1844)","Kōka (1844–1848)","Kaei (1848–1854)","Ansei (1854–1860)","Man’en (1860–1861)","Bunkyū (1861–1864)","Genji (1864–1865)","Keiō (1865–1868)","Meiji","Taishō","Shōwa","Heisei"],long:["Taika (645–650)","Hakuchi (650–671)","Hakuhō (672–686)","Shuchō (686–701)","Taihō (701–704)","Keiun (704–708)","Wadō (708–715)","Reiki (715–717)","Yōrō (717–724)","Jinki (724–729)","Tenpyō (729–749)","Tenpyō-kampō (749-749)","Tenpyō-shōhō (749-757)","Tenpyō-hōji (757-765)","Tenpyō-jingo (765-767)","Jingo-keiun (767-770)","Hōki (770–780)","Ten-ō (781-782)","Enryaku (782–806)","Daidō (806–810)","Kōnin (810–824)","Tenchō (824–834)","Jōwa (834–848)","Kajō (848–851)","Ninju (851–854)","Saikō (854–857)","Ten-an (857-859)","Jōgan (859–877)","Gangyō (877–885)","Ninna (885–889)","Kanpyō (889–898)","Shōtai (898–901)","Engi (901–923)","Enchō (923–931)","Jōhei (931–938)","Tengyō (938–947)","Tenryaku (947–957)","Tentoku (957–961)","Ōwa (961–964)","Kōhō (964–968)","Anna (968–970)","Tenroku (970–973)","Ten’en (973–976)","Jōgen (976–978)","Tengen (978–983)","Eikan (983–985)","Kanna (985–987)","Eien (987–989)","Eiso (989–990)","Shōryaku (990–995)","Chōtoku (995–999)","Chōhō (999–1004)","Kankō (1004–1012)","Chōwa (1012–1017)","Kannin (1017–1021)","Jian (1021–1024)","Manju (1024–1028)","Chōgen (1028–1037)","Chōryaku (1037–1040)","Chōkyū (1040–1044)","Kantoku (1044–1046)","Eishō (1046–1053)","Tengi (1053–1058)","Kōhei (1058–1065)","Jiryaku (1065–1069)","Enkyū (1069–1074)","Shōho (1074–1077)","Shōryaku (1077–1081)","Eihō (1081–1084)","Ōtoku (1084–1087)","Kanji (1087–1094)","Kahō (1094–1096)","Eichō (1096–1097)","Jōtoku (1097–1099)","Kōwa (1099–1104)","Chōji (1104–1106)","Kashō (1106–1108)","Tennin (1108–1110)","Ten-ei (1110-1113)","Eikyū (1113–1118)","Gen’ei (1118–1120)","Hōan (1120–1124)","Tenji (1124–1126)","Daiji (1126–1131)","Tenshō (1131–1132)","Chōshō (1132–1135)","Hōen (1135–1141)","Eiji (1141–1142)","Kōji (1142–1144)","Ten’yō (1144–1145)","Kyūan (1145–1151)","Ninpei (1151–1154)","Kyūju (1154–1156)","Hōgen (1156–1159)","Heiji (1159–1160)","Eiryaku (1160–1161)","Ōho (1161–1163)","Chōkan (1163–1165)","Eiman (1165–1166)","Nin’an (1166–1169)","Kaō (1169–1171)","Shōan (1171–1175)","Angen (1175–1177)","Jishō (1177–1181)","Yōwa (1181–1182)","Juei (1182–1184)","Genryaku (1184–1185)","Bunji (1185–1190)","Kenkyū (1190–1199)","Shōji (1199–1201)","Kennin (1201–1204)","Genkyū (1204–1206)","Ken’ei (1206–1207)","Jōgen (1207–1211)","Kenryaku (1211–1213)","Kenpō (1213–1219)","Jōkyū (1219–1222)","Jōō (1222–1224)","Gennin (1224–1225)","Karoku (1225–1227)","Antei (1227–1229)","Kanki (1229–1232)","Jōei (1232–1233)","Tenpuku (1233–1234)","Bunryaku (1234–1235)","Katei (1235–1238)","Ryakunin (1238–1239)","En’ō (1239–1240)","Ninji (1240–1243)","Kangen (1243–1247)","Hōji (1247–1249)","Kenchō (1249–1256)","Kōgen (1256–1257)","Shōka (1257–1259)","Shōgen (1259–1260)","Bun’ō (1260–1261)","Kōchō (1261–1264)","Bun’ei (1264–1275)","Kenji (1275–1278)","Kōan (1278–1288)","Shōō (1288–1293)","Einin (1293–1299)","Shōan (1299–1302)","Kengen (1302–1303)","Kagen (1303–1306)","Tokuji (1306–1308)","Enkyō (1308–1311)","Ōchō (1311–1312)","Shōwa (1312–1317)","Bunpō (1317–1319)","Genō (1319–1321)","Genkō (1321–1324)","Shōchū (1324–1326)","Karyaku (1326–1329)","Gentoku (1329–1331)","Genkō (1331–1334)","Kenmu (1334–1336)","Engen (1336–1340)","Kōkoku (1340–1346)","Shōhei (1346–1370)","Kentoku (1370–1372)","Bunchū (1372–1375)","Tenju (1375–1379)","Kōryaku (1379–1381)","Kōwa (1381–1384)","Genchū (1384–1392)","Meitoku (1384–1387)","Kakei (1387–1389)","Kōō (1389–1390)","Meitoku (1390–1394)","Ōei (1394–1428)","Shōchō (1428–1429)","Eikyō (1429–1441)","Kakitsu (1441–1444)","Bun’an (1444–1449)","Hōtoku (1449–1452)","Kyōtoku (1452–1455)","Kōshō (1455–1457)","Chōroku (1457–1460)","Kanshō (1460–1466)","Bunshō (1466–1467)","Ōnin (1467–1469)","Bunmei (1469–1487)","Chōkyō (1487–1489)","Entoku (1489–1492)","Meiō (1492–1501)","Bunki (1501–1504)","Eishō (1504–1521)","Taiei (1521–1528)","Kyōroku (1528–1532)","Tenbun (1532–1555)","Kōji (1555–1558)","Eiroku (1558–1570)","Genki (1570–1573)","Tenshō (1573–1592)","Bunroku (1592–1596)","Keichō (1596–1615)","Genna (1615–1624)","Kan’ei (1624–1644)","Shōho (1644–1648)","Keian (1648–1652)","Jōō (1652–1655)","Meireki (1655–1658)","Manji (1658–1661)","Kanbun (1661–1673)","Enpō (1673–1681)","Tenna (1681–1684)","Jōkyō (1684–1688)","Genroku (1688–1704)","Hōei (1704–1711)","Shōtoku (1711–1716)","Kyōhō (1716–1736)","Genbun (1736–1741)","Kanpō (1741–1744)","Enkyō (1744–1748)","Kan’en (1748–1751)","Hōreki (1751–1764)","Meiwa (1764–1772)","An’ei (1772–1781)","Tenmei (1781–1789)","Kansei (1789–1801)","Kyōwa (1801–1804)","Bunka (1804–1818)","Bunsei (1818–1830)","Tenpō (1830–1844)","Kōka (1844–1848)","Kaei (1848–1854)","Ansei (1854–1860)","Man’en (1860–1861)","Bunkyū (1861–1864)","Genji (1864–1865)","Keiō (1865–1868)","Meiji","Taishō","Shōwa","Heisei"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},persian:{months:{narrow:["1","2","3","4","5","6","7","8","9","10","11","12"],short:["Farvardin","Ordibehesht","Khordad","Tir","Mordad","Shahrivar","Mehr","Aban","Azar","Dey","Bahman","Esfand"],long:["Farvardin","Ordibehesht","Khordad","Tir","Mordad","Shahrivar","Mehr","Aban","Azar","Dey","Bahman","Esfand"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},eras:{narrow:["AP"],short:["AP"],long:["AP"]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}},roc:{months:{narrow:["K","U","R","C","T","M","S","N","T","K","M","Y"],short:["Kwa","Una","Rar","Che","Tha","Moc","Sab","Nan","Tis","Kum","Moj","Yel"],long:["Mweri wo kwanza","Mweri wo unayeli","Mweri wo uneraru","Mweri wo unecheshe","Mweri wo unethanu","Mweri wo thanu na mocha","Mweri wo saba","Mweri wo nane","Mweri wo tisa","Mweri wo kumi","Mweri wo kumi na moja","Mweri wo kumi na yel’li"]},days:{narrow:["S","J","J","J","A","I","J"],short:["Sab","Jtt","Jnn","Jtn","Ara","Iju","Jmo"],long:["Sabato","Jumatatu","Jumanne","Jumatano","Arahamisi","Ijumaa","Jumamosi"]},eras:{narrow:["Before R.O.C.","R.O.C."],short:["Before R.O.C.","R.O.C."],long:["Before R.O.C.","R.O.C."]},dayPeriods:{am:"wichishu",pm:"mchochil’l"}}}},number:{nu:["latn"],patterns:{decimal:{positivePattern:"{number}",negativePattern:"{minusSign}{number}"},currency:{positivePattern:"{currency} {number}",negativePattern:"{minusSign}{currency} {number}"},percent:{positivePattern:"{number}{percentSign}",negativePattern:"{minusSign}{number}{percentSign}"}},symbols:{latn:{decimal:",",group:".",nan:"NaN",plusSign:"+",minusSign:"-",percentSign:"%",infinity:"∞"}},currencies:{AUD:"A$",BRL:"R$",CAD:"CA$",CNY:"CN¥",EUR:"€",GBP:"£",HKD:"HK$",ILS:"₪",INR:"₹",JPY:"JP¥",KRW:"₩",MXN:"MX$",MZN:"MTn",NZD:"NZ$",TWD:"NT$",USD:"US$",VND:"₫",XAF:"FCFA",XCD:"EC$",XOF:"CFA",XPF:"CFPF"}}});
/* The MIT License Copyright (c) 2017,2018,2019,2020,2021 Klaus Landsdorf (https://osi.bianco-royal.com/) All rights reserved. node-red-contrib-bacnet */ 'use strict' module.exports = function (RED) { const bacnetCore = require('./core/bacnet-core') function BACnetRead (config) { RED.nodes.createNode(this, config) this.name = config.name this.objectType = parseInt(config.objectType) this.propertyId = parseInt(config.propertyId) this.multipleRead = config.multipleRead this.instance = RED.nodes.getNode(config.instance) this.objectInstance = parseInt(this.instance.instanceAddress) || 0 this.device = RED.nodes.getNode(config.device) this.deviceIPAddress = this.device.deviceAddress || '127.0.0.1' this.connector = RED.nodes.getNode(config.server) const node = this node.status({ fill: 'green', shape: 'dot', text: 'active' }) node.on('input', function (msg) { if (!node.connector) { node.error(new Error('Client Not Ready To Read'), msg) return } const options = msg.payload.options || {} if (node.multipleRead) { bacnetCore.internalDebugLog('Multiple Read') const defaultRequestArray = [{ objectId: { type: node.objectType, instance: parseInt(node.objectInstance) }, properties: [{ id: parseInt(node.propertyId) }] }] try { bacnetCore.internalDebugLog('readProperty node.deviceIPAddress: ' + node.deviceIPAddress) bacnetCore.internalDebugLog('readProperty msg.payload.deviceIPAddress: ' + msg.payload.deviceIPAddress) bacnetCore.internalDebugLog('readPropertyMultiple default requestArray: ' + JSON.stringify(defaultRequestArray)) bacnetCore.internalDebugLog('readPropertyMultiple msg.payload.requestArray: ' + JSON.stringify(msg.payload.requestArray)) bacnetCore.internalDebugLog('readPropertyMultiple node.propertyId: ' + node.propertyId) bacnetCore.internalDebugLog('readPropertyMultiple msg.payload.propertyId: ' + msg.payload.propertyId) } catch (e) { bacnetCore.internalDebugLog('readPropertyMultiple error: ' + e) } node.connector.client.readPropertyMultiple( msg.payload.deviceIPAddress || node.deviceIPAddress, msg.payload.requestArray || defaultRequestArray, options, function (err, result) { if (err) { const translatedError = bacnetCore.translateErrorMessage(err) bacnetCore.internalDebugLog(translatedError) node.error(translatedError, msg) } else { msg.input = msg.payload msg.payload = result node.send(msg) } }) } else { bacnetCore.internalDebugLog('Read') const objectId = { type: parseInt(node.objectType), instance: parseInt(node.objectInstance) } try { bacnetCore.internalDebugLog('readProperty node.deviceIPAddress: ' + node.deviceIPAddress) bacnetCore.internalDebugLog('readProperty msg.payload.deviceIPAddress: ' + msg.payload.deviceIPAddress) bacnetCore.internalDebugLog('readProperty default objectId: ' + JSON.stringify(objectId)) bacnetCore.internalDebugLog('readProperty msg.payload.objectId: ' + JSON.stringify(msg.payload.objectId)) bacnetCore.internalDebugLog('readProperty node.propertyId: ' + node.propertyId) bacnetCore.internalDebugLog('readProperty msg.payload.propertyId: ' + msg.payload.propertyId) } catch (e) { bacnetCore.internalDebugLog('readProperty error: ' + e) } node.connector.client.readProperty( msg.payload.deviceIPAddress || node.deviceIPAddress, msg.payload.objectId || objectId, parseInt(msg.payload.propertyId) || parseInt(node.propertyId), options, function (err, result) { if (err) { const translatedError = bacnetCore.translateErrorMessage(err) bacnetCore.internalDebugLog(translatedError) node.error(translatedError, msg) } else { msg.input = msg.payload msg.payload = result node.send(msg) } }) } }) } RED.nodes.registerType('BACnet-Read', BACnetRead) }
# Generated by Django 2.1.3 on 2018-12-28 09:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('data', '0097_merge_20190101_2250'), ] operations = [ migrations.AddField( model_name='attachmentfile', name='text_content', field=models.TextField(blank=True), ), ]
"""SBApp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ #url(r'^admin/', admin.site.urls), url(r'^', include('app1.urls')), ]
/*! * jQuery Validation Plugin v1.13.1 * * http://jqueryvalidation.org/ * * Copyright (c) 2014 Jörn Zaefferer * Released under the MIT license */ (function( factory ) { if ( typeof define === "function" && define.amd ) { define( ["jquery"], factory ); } else { factory( jQuery ); } }(function( $ ) { $.extend($.fn, { // http://jqueryvalidation.org/validate/ validate: function( options ) { // if nothing is selected, return nothing; can't chain anyway if ( !this.length ) { if ( options && options.debug && window.console ) { console.warn( "Nothing selected, can't validate, returning nothing." ); } return; } // check if a validator for this form was already created var validator = $.data( this[ 0 ], "validator" ); if ( validator ) { return validator; } // Add novalidate tag if HTML5. this.attr( "novalidate", "novalidate" ); validator = new $.validator( options, this[ 0 ] ); $.data( this[ 0 ], "validator", validator ); if ( validator.settings.onsubmit ) { this.validateDelegate( ":submit", "click", function( event ) { if ( validator.settings.submitHandler ) { validator.submitButton = event.target; } // allow suppressing validation by adding a cancel class to the submit button if ( $( event.target ).hasClass( "cancel" ) ) { validator.cancelSubmit = true; } // allow suppressing validation by adding the html5 formnovalidate attribute to the submit button if ( $( event.target ).attr( "formnovalidate" ) !== undefined ) { validator.cancelSubmit = true; } }); // validate the form on submit this.submit( function( event ) { if ( validator.settings.debug ) { // prevent form submit to be able to see console output event.preventDefault(); } function handle() { var hidden, result; if ( validator.settings.submitHandler ) { if ( validator.submitButton ) { // insert a hidden input as a replacement for the missing submit button hidden = $( "<input type='hidden'/>" ) .attr( "name", validator.submitButton.name ) .val( $( validator.submitButton ).val() ) .appendTo( validator.currentForm ); } result = validator.settings.submitHandler.call( validator, validator.currentForm, event ); if ( validator.submitButton ) { // and clean up afterwards; thanks to no-block-scope, hidden can be referenced hidden.remove(); } if ( result !== undefined ) { return result; } return false; } return true; } // prevent submit for invalid forms or custom submit handlers if ( validator.cancelSubmit ) { validator.cancelSubmit = false; return handle(); } if ( validator.form() ) { if ( validator.pendingRequest ) { validator.formSubmitted = true; return false; } return handle(); } else { validator.focusInvalid(); return false; } }); } return validator; }, // http://jqueryvalidation.org/valid/ valid: function() { var valid, validator; if ( $( this[ 0 ] ).is( "form" ) ) { valid = this.validate().form(); } else { valid = true; validator = $( this[ 0 ].form ).validate(); this.each( function() { valid = validator.element( this ) && valid; }); } return valid; }, // attributes: space separated list of attributes to retrieve and remove removeAttrs: function( attributes ) { var result = {}, $element = this; $.each( attributes.split( /\s/ ), function( index, value ) { result[ value ] = $element.attr( value ); $element.removeAttr( value ); }); return result; }, // http://jqueryvalidation.org/rules/ rules: function( command, argument ) { var element = this[ 0 ], settings, staticRules, existingRules, data, param, filtered; if ( command ) { settings = $.data( element.form, "validator" ).settings; staticRules = settings.rules; existingRules = $.validator.staticRules( element ); switch ( command ) { case "add": $.extend( existingRules, $.validator.normalizeRule( argument ) ); // remove messages from rules, but allow them to be set separately delete existingRules.messages; staticRules[ element.name ] = existingRules; if ( argument.messages ) { settings.messages[ element.name ] = $.extend( settings.messages[ element.name ], argument.messages ); } break; case "remove": if ( !argument ) { delete staticRules[ element.name ]; return existingRules; } filtered = {}; $.each( argument.split( /\s/ ), function( index, method ) { filtered[ method ] = existingRules[ method ]; delete existingRules[ method ]; if ( method === "required" ) { $( element ).removeAttr( "aria-required" ); } }); return filtered; } } data = $.validator.normalizeRules( $.extend( {}, $.validator.classRules( element ), $.validator.attributeRules( element ), $.validator.dataRules( element ), $.validator.staticRules( element ) ), element ); // make sure required is at front if ( data.required ) { param = data.required; delete data.required; data = $.extend( { required: param }, data ); $( element ).attr( "aria-required", "true" ); } // make sure remote is at back if ( data.remote ) { param = data.remote; delete data.remote; data = $.extend( data, { remote: param }); } return data; } }); // Custom selectors $.extend( $.expr[ ":" ], { // http://jqueryvalidation.org/blank-selector/ blank: function( a ) { return !$.trim( "" + $( a ).val() ); }, // http://jqueryvalidation.org/filled-selector/ filled: function( a ) { return !!$.trim( "" + $( a ).val() ); }, // http://jqueryvalidation.org/unchecked-selector/ unchecked: function( a ) { return !$( a ).prop( "checked" ); } }); // constructor for validator $.validator = function( options, form ) { this.settings = $.extend( true, {}, $.validator.defaults, options ); this.currentForm = form; this.init(); }; // http://jqueryvalidation.org/jQuery.validator.format/ $.validator.format = function( source, params ) { if ( arguments.length === 1 ) { return function() { var args = $.makeArray( arguments ); args.unshift( source ); return $.validator.format.apply( this, args ); }; } if ( arguments.length > 2 && params.constructor !== Array ) { params = $.makeArray( arguments ).slice( 1 ); } if ( params.constructor !== Array ) { params = [ params ]; } $.each( params, function( i, n ) { source = source.replace( new RegExp( "\\{" + i + "\\}", "g" ), function() { return n; }); }); return source; }; $.extend( $.validator, { defaults: { messages: {}, groups: {}, rules: {}, errorClass: "error", validClass: "valid", errorElement: "label", focusCleanup: false, focusInvalid: true, errorContainer: $( [] ), errorLabelContainer: $( [] ), onsubmit: true, ignore: ":hidden", ignoreTitle: false, onfocusin: function( element ) { this.lastActive = element; // Hide error label and remove error class on focus if enabled if ( this.settings.focusCleanup ) { if ( this.settings.unhighlight ) { this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass ); } this.hideThese( this.errorsFor( element ) ); } }, onfocusout: function( element ) { if ( !this.checkable( element ) && ( element.name in this.submitted || !this.optional( element ) ) ) { this.element( element ); } }, onkeyup: function( element, event ) { if ( event.which === 9 && this.elementValue( element ) === "" ) { return; } else if ( element.name in this.submitted || element === this.lastElement ) { this.element( element ); } }, onclick: function( element ) { // click on selects, radiobuttons and checkboxes if ( element.name in this.submitted ) { this.element( element ); // or option elements, check parent select in that case } else if ( element.parentNode.name in this.submitted ) { this.element( element.parentNode ); } }, highlight: function( element, errorClass, validClass ) { if ( element.type === "radio" ) { this.findByName( element.name ).addClass( errorClass ).removeClass( validClass ); } else { $( element ).addClass( errorClass ).removeClass( validClass ); } }, unhighlight: function( element, errorClass, validClass ) { if ( element.type === "radio" ) { this.findByName( element.name ).removeClass( errorClass ).addClass( validClass ); } else { $( element ).removeClass( errorClass ).addClass( validClass ); } } }, // http://jqueryvalidation.org/jQuery.validator.setDefaults/ setDefaults: function( settings ) { $.extend( $.validator.defaults, settings ); }, messages: { required: "Ce champ est obligatoire.", remote: "Please fix this field.", email: "Se il vous plaît entrer une adresse email valide.", tel: "Se il vous plaît entrer un numéro tel valide.", url: "Please enter a valid URL.", date: "Please enter a valid date.", dateISO: "Please enter a valid date ( ISO ).", number: "Please enter a valid number.", digits: "Please enter only digits.", creditcard: "Please enter a valid credit card number.", equalTo: "Please enter the same value again.", maxlength: $.validator.format( "Please enter no more than {0} characters." ), minlength: $.validator.format( "Please enter at least {0} characters." ), rangelength: $.validator.format( "Please enter a value between {0} and {1} characters long." ), range: $.validator.format( "Please enter a value between {0} and {1}." ), max: $.validator.format( "Please enter a value less than or equal to {0}." ), min: $.validator.format( "Please enter a value greater than or equal to {0}." ) }, autoCreateRanges: false, prototype: { init: function() { this.labelContainer = $( this.settings.errorLabelContainer ); this.errorContext = this.labelContainer.length && this.labelContainer || $( this.currentForm ); this.containers = $( this.settings.errorContainer ).add( this.settings.errorLabelContainer ); this.submitted = {}; this.valueCache = {}; this.pendingRequest = 0; this.pending = {}; this.invalid = {}; this.reset(); var groups = ( this.groups = {} ), rules; $.each( this.settings.groups, function( key, value ) { if ( typeof value === "string" ) { value = value.split( /\s/ ); } $.each( value, function( index, name ) { groups[ name ] = key; }); }); rules = this.settings.rules; $.each( rules, function( key, value ) { rules[ key ] = $.validator.normalizeRule( value ); }); function delegate( event ) { var validator = $.data( this[ 0 ].form, "validator" ), eventType = "on" + event.type.replace( /^validate/, "" ), settings = validator.settings; if ( settings[ eventType ] && !this.is( settings.ignore ) ) { settings[ eventType ].call( validator, this[ 0 ], event ); } } $( this.currentForm ) .validateDelegate( ":text, [type='password'], [type='file'], select, textarea, " + "[type='number'], [type='search'] ,[type='tel'], [type='url'], " + "[type='email'], [type='datetime'], [type='date'], [type='month'], " + "[type='week'], [type='time'], [type='datetime-local'], " + "[type='range'], [type='color'], [type='radio'], [type='checkbox']", "focusin focusout keyup", delegate) // Support: Chrome, oldIE // "select" is provided as event.target when clicking a option .validateDelegate("select, option, [type='radio'], [type='checkbox']", "click", delegate); if ( this.settings.invalidHandler ) { $( this.currentForm ).bind( "invalid-form.validate", this.settings.invalidHandler ); } // Add aria-required to any Static/Data/Class required fields before first validation // Screen readers require this attribute to be present before the initial submission http://www.w3.org/TR/WCAG-TECHS/ARIA2.html $( this.currentForm ).find( "[required], [data-rule-required], .required" ).attr( "aria-required", "true" ); }, // http://jqueryvalidation.org/Validator.form/ form: function() { this.checkForm(); $.extend( this.submitted, this.errorMap ); this.invalid = $.extend({}, this.errorMap ); if ( !this.valid() ) { $( this.currentForm ).triggerHandler( "invalid-form", [ this ]); } this.showErrors(); return this.valid(); }, checkForm: function() { this.prepareForm(); for ( var i = 0, elements = ( this.currentElements = this.elements() ); elements[ i ]; i++ ) { this.check( elements[ i ] ); } return this.valid(); }, // http://jqueryvalidation.org/Validator.element/ element: function( element ) { var cleanElement = this.clean( element ), checkElement = this.validationTargetFor( cleanElement ), result = true; this.lastElement = checkElement; if ( checkElement === undefined ) { delete this.invalid[ cleanElement.name ]; } else { this.prepareElement( checkElement ); this.currentElements = $( checkElement ); result = this.check( checkElement ) !== false; if ( result ) { delete this.invalid[ checkElement.name ]; } else { this.invalid[ checkElement.name ] = true; } } // Add aria-invalid status for screen readers $( element ).attr( "aria-invalid", !result ); if ( !this.numberOfInvalids() ) { // Hide error containers on last error this.toHide = this.toHide.add( this.containers ); } this.showErrors(); return result; }, // http://jqueryvalidation.org/Validator.showErrors/ showErrors: function( errors ) { if ( errors ) { // add items to error list and map $.extend( this.errorMap, errors ); this.errorList = []; for ( var name in errors ) { this.errorList.push({ message: errors[ name ], element: this.findByName( name )[ 0 ] }); } // remove items from success list this.successList = $.grep( this.successList, function( element ) { return !( element.name in errors ); }); } if ( this.settings.showErrors ) { this.settings.showErrors.call( this, this.errorMap, this.errorList ); } else { this.defaultShowErrors(); } }, // http://jqueryvalidation.org/Validator.resetForm/ resetForm: function() { if ( $.fn.resetForm ) { $( this.currentForm ).resetForm(); } this.submitted = {}; this.lastElement = null; this.prepareForm(); this.hideErrors(); this.elements() .removeClass( this.settings.errorClass ) .removeData( "previousValue" ) .removeAttr( "aria-invalid" ); }, numberOfInvalids: function() { return this.objectLength( this.invalid ); }, objectLength: function( obj ) { /* jshint unused: false */ var count = 0, i; for ( i in obj ) { count++; } return count; }, hideErrors: function() { this.hideThese( this.toHide ); }, hideThese: function( errors ) { errors.not( this.containers ).text( "" ); this.addWrapper( errors ).hide(); }, valid: function() { return this.size() === 0; }, size: function() { return this.errorList.length; }, focusInvalid: function() { if ( this.settings.focusInvalid ) { try { $( this.findLastActive() || this.errorList.length && this.errorList[ 0 ].element || []) .filter( ":visible" ) .focus() // manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find .trigger( "focusin" ); } catch ( e ) { // ignore IE throwing errors when focusing hidden elements } } }, findLastActive: function() { var lastActive = this.lastActive; return lastActive && $.grep( this.errorList, function( n ) { return n.element.name === lastActive.name; }).length === 1 && lastActive; }, elements: function() { var validator = this, rulesCache = {}; // select all valid inputs inside the form (no submit or reset buttons) return $( this.currentForm ) .find( "input, select, textarea" ) .not( ":submit, :reset, :image, [disabled], [readonly]" ) .not( this.settings.ignore ) .filter( function() { if ( !this.name && validator.settings.debug && window.console ) { console.error( "%o has no name assigned", this ); } // select only the first element for each name, and only those with rules specified if ( this.name in rulesCache || !validator.objectLength( $( this ).rules() ) ) { return false; } rulesCache[ this.name ] = true; return true; }); }, clean: function( selector ) { return $( selector )[ 0 ]; }, errors: function() { var errorClass = this.settings.errorClass.split( " " ).join( "." ); return $( this.settings.errorElement + "." + errorClass, this.errorContext ); }, reset: function() { this.successList = []; this.errorList = []; this.errorMap = {}; this.toShow = $( [] ); this.toHide = $( [] ); this.currentElements = $( [] ); }, prepareForm: function() { this.reset(); this.toHide = this.errors().add( this.containers ); }, prepareElement: function( element ) { this.reset(); this.toHide = this.errorsFor( element ); }, elementValue: function( element ) { var val, $element = $( element ), type = element.type; if ( type === "radio" || type === "checkbox" ) { return $( "input[name='" + element.name + "']:checked" ).val(); } else if ( type === "number" && typeof element.validity !== "undefined" ) { return element.validity.badInput ? false : $element.val(); } val = $element.val(); if ( typeof val === "string" ) { return val.replace(/\r/g, "" ); } return val; }, check: function( element ) { element = this.validationTargetFor( this.clean( element ) ); var rules = $( element ).rules(), rulesCount = $.map( rules, function( n, i ) { return i; }).length, dependencyMismatch = false, val = this.elementValue( element ), result, method, rule; for ( method in rules ) { rule = { method: method, parameters: rules[ method ] }; try { result = $.validator.methods[ method ].call( this, val, element, rule.parameters ); // if a method indicates that the field is optional and therefore valid, // don't mark it as valid when there are no other rules if ( result === "dependency-mismatch" && rulesCount === 1 ) { dependencyMismatch = true; continue; } dependencyMismatch = false; if ( result === "pending" ) { this.toHide = this.toHide.not( this.errorsFor( element ) ); return; } if ( !result ) { this.formatAndAdd( element, rule ); return false; } } catch ( e ) { if ( this.settings.debug && window.console ) { console.log( "Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.", e ); } throw e; } } if ( dependencyMismatch ) { return; } if ( this.objectLength( rules ) ) { this.successList.push( element ); } return true; }, // return the custom message for the given element and validation method // specified in the element's HTML5 data attribute // return the generic message if present and no method specific message is present customDataMessage: function( element, method ) { return $( element ).data( "msg" + method.charAt( 0 ).toUpperCase() + method.substring( 1 ).toLowerCase() ) || $( element ).data( "msg" ); }, // return the custom message for the given element name and validation method customMessage: function( name, method ) { var m = this.settings.messages[ name ]; return m && ( m.constructor === String ? m : m[ method ]); }, // return the first defined argument, allowing empty strings findDefined: function() { for ( var i = 0; i < arguments.length; i++) { if ( arguments[ i ] !== undefined ) { return arguments[ i ]; } } return undefined; }, defaultMessage: function( element, method ) { return this.findDefined( this.customMessage( element.name, method ), this.customDataMessage( element, method ), // title is never undefined, so handle empty string as undefined !this.settings.ignoreTitle && element.title || undefined, $.validator.messages[ method ], "<strong>Warning: No message defined for " + element.name + "</strong>" ); }, formatAndAdd: function( element, rule ) { var message = this.defaultMessage( element, rule.method ), theregex = /\$?\{(\d+)\}/g; if ( typeof message === "function" ) { message = message.call( this, rule.parameters, element ); } else if ( theregex.test( message ) ) { message = $.validator.format( message.replace( theregex, "{$1}" ), rule.parameters ); } this.errorList.push({ message: message, element: element, method: rule.method }); this.errorMap[ element.name ] = message; this.submitted[ element.name ] = message; }, addWrapper: function( toToggle ) { if ( this.settings.wrapper ) { toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) ); } return toToggle; }, defaultShowErrors: function() { var i, elements, error; for ( i = 0; this.errorList[ i ]; i++ ) { error = this.errorList[ i ]; if ( this.settings.highlight ) { this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass ); } this.showLabel( error.element, error.message ); } if ( this.errorList.length ) { this.toShow = this.toShow.add( this.containers ); } if ( this.settings.success ) { for ( i = 0; this.successList[ i ]; i++ ) { this.showLabel( this.successList[ i ] ); } } if ( this.settings.unhighlight ) { for ( i = 0, elements = this.validElements(); elements[ i ]; i++ ) { this.settings.unhighlight.call( this, elements[ i ], this.settings.errorClass, this.settings.validClass ); } } this.toHide = this.toHide.not( this.toShow ); this.hideErrors(); this.addWrapper( this.toShow ).show(); }, validElements: function() { return this.currentElements.not( this.invalidElements() ); }, invalidElements: function() { return $( this.errorList ).map(function() { return this.element; }); }, showLabel: function( element, message ) { var place, group, errorID, error = this.errorsFor( element ), elementID = this.idOrName( element ), describedBy = $( element ).attr( "aria-describedby" ); if ( error.length ) { // refresh error/success class error.removeClass( this.settings.validClass ).addClass( this.settings.errorClass ); // replace message on existing label error.html( message ); } else { // create error element error = $( "<" + this.settings.errorElement + ">" ) .attr( "id", elementID + "-error" ) .addClass( this.settings.errorClass ) .html( message || "" ); // Maintain reference to the element to be placed into the DOM place = error; if ( this.settings.wrapper ) { // make sure the element is visible, even in IE // actually showing the wrapped element is handled elsewhere place = error.hide().show().wrap( "<" + this.settings.wrapper + "/>" ).parent(); } if ( this.labelContainer.length ) { this.labelContainer.append( place ); } else if ( this.settings.errorPlacement ) { this.settings.errorPlacement( place, $( element ) ); } else { place.insertAfter( element ); } // Link error back to the element if ( error.is( "label" ) ) { // If the error is a label, then associate using 'for' error.attr( "for", elementID ); } else if ( error.parents( "label[for='" + elementID + "']" ).length === 0 ) { // If the element is not a child of an associated label, then it's necessary // to explicitly apply aria-describedby errorID = error.attr( "id" ).replace( /(:|\.|\[|\])/g, "\\$1"); // Respect existing non-error aria-describedby if ( !describedBy ) { describedBy = errorID; } else if ( !describedBy.match( new RegExp( "\\b" + errorID + "\\b" ) ) ) { // Add to end of list if not already present describedBy += " " + errorID; } $( element ).attr( "aria-describedby", describedBy ); // If this element is grouped, then assign to all elements in the same group group = this.groups[ element.name ]; if ( group ) { $.each( this.groups, function( name, testgroup ) { if ( testgroup === group ) { $( "[name='" + name + "']", this.currentForm ) .attr( "aria-describedby", error.attr( "id" ) ); } }); } } } if ( !message && this.settings.success ) { error.text( "" ); if ( typeof this.settings.success === "string" ) { error.addClass( this.settings.success ); } else { this.settings.success( error, element ); } } this.toShow = this.toShow.add( error ); }, errorsFor: function( element ) { var name = this.idOrName( element ), describer = $( element ).attr( "aria-describedby" ), selector = "label[for='" + name + "'], label[for='" + name + "'] *"; // aria-describedby should directly reference the error element if ( describer ) { selector = selector + ", #" + describer.replace( /\s+/g, ", #" ); } return this .errors() .filter( selector ); }, idOrName: function( element ) { return this.groups[ element.name ] || ( this.checkable( element ) ? element.name : element.id || element.name ); }, validationTargetFor: function( element ) { // If radio/checkbox, validate first element in group instead if ( this.checkable( element ) ) { element = this.findByName( element.name ); } // Always apply ignore filter return $( element ).not( this.settings.ignore )[ 0 ]; }, checkable: function( element ) { return ( /radio|checkbox/i ).test( element.type ); }, findByName: function( name ) { return $( this.currentForm ).find( "[name='" + name + "']" ); }, getLength: function( value, element ) { switch ( element.nodeName.toLowerCase() ) { case "select": return $( "option:selected", element ).length; case "input": if ( this.checkable( element ) ) { return this.findByName( element.name ).filter( ":checked" ).length; } } return value.length; }, depend: function( param, element ) { return this.dependTypes[typeof param] ? this.dependTypes[typeof param]( param, element ) : true; }, dependTypes: { "boolean": function( param ) { return param; }, "string": function( param, element ) { return !!$( param, element.form ).length; }, "function": function( param, element ) { return param( element ); } }, optional: function( element ) { var val = this.elementValue( element ); return !$.validator.methods.required.call( this, val, element ) && "dependency-mismatch"; }, startRequest: function( element ) { if ( !this.pending[ element.name ] ) { this.pendingRequest++; this.pending[ element.name ] = true; } }, stopRequest: function( element, valid ) { this.pendingRequest--; // sometimes synchronization fails, make sure pendingRequest is never < 0 if ( this.pendingRequest < 0 ) { this.pendingRequest = 0; } delete this.pending[ element.name ]; if ( valid && this.pendingRequest === 0 && this.formSubmitted && this.form() ) { $( this.currentForm ).submit(); this.formSubmitted = false; } else if (!valid && this.pendingRequest === 0 && this.formSubmitted ) { $( this.currentForm ).triggerHandler( "invalid-form", [ this ]); this.formSubmitted = false; } }, previousValue: function( element ) { return $.data( element, "previousValue" ) || $.data( element, "previousValue", { old: null, valid: true, message: this.defaultMessage( element, "remote" ) }); } }, classRuleSettings: { required: { required: true }, email: { email: true }, tel: { tel: true }, url: { url: true }, date: { date: true }, dateISO: { dateISO: true }, number: { number: true }, digits: { digits: true }, creditcard: { creditcard: true } }, addClassRules: function( className, rules ) { if ( className.constructor === String ) { this.classRuleSettings[ className ] = rules; } else { $.extend( this.classRuleSettings, className ); } }, classRules: function( element ) { var rules = {}, classes = $( element ).attr( "class" ); if ( classes ) { $.each( classes.split( " " ), function() { if ( this in $.validator.classRuleSettings ) { $.extend( rules, $.validator.classRuleSettings[ this ]); } }); } return rules; }, attributeRules: function( element ) { var rules = {}, $element = $( element ), type = element.getAttribute( "type" ), method, value; for ( method in $.validator.methods ) { // support for <input required> in both html5 and older browsers if ( method === "required" ) { value = element.getAttribute( method ); // Some browsers return an empty string for the required attribute // and non-HTML5 browsers might have required="" markup if ( value === "" ) { value = true; } // force non-HTML5 browsers to return bool value = !!value; } else { value = $element.attr( method ); } // convert the value to a number for number inputs, and for text for backwards compability // allows type="date" and others to be compared as strings if ( /min|max/.test( method ) && ( type === null || /number|range|text/.test( type ) ) ) { value = Number( value ); } if ( value || value === 0 ) { rules[ method ] = value; } else if ( type === method && type !== "range" ) { // exception: the jquery validate 'range' method // does not test for the html5 'range' type rules[ method ] = true; } } // maxlength may be returned as -1, 2147483647 ( IE ) and 524288 ( safari ) for text inputs if ( rules.maxlength && /-1|2147483647|524288/.test( rules.maxlength ) ) { delete rules.maxlength; } return rules; }, dataRules: function( element ) { var method, value, rules = {}, $element = $( element ); for ( method in $.validator.methods ) { value = $element.data( "rule" + method.charAt( 0 ).toUpperCase() + method.substring( 1 ).toLowerCase() ); if ( value !== undefined ) { rules[ method ] = value; } } return rules; }, staticRules: function( element ) { var rules = {}, validator = $.data( element.form, "validator" ); if ( validator.settings.rules ) { rules = $.validator.normalizeRule( validator.settings.rules[ element.name ] ) || {}; } return rules; }, normalizeRules: function( rules, element ) { // handle dependency check $.each( rules, function( prop, val ) { // ignore rule when param is explicitly false, eg. required:false if ( val === false ) { delete rules[ prop ]; return; } if ( val.param || val.depends ) { var keepRule = true; switch ( typeof val.depends ) { case "string": keepRule = !!$( val.depends, element.form ).length; break; case "function": keepRule = val.depends.call( element, element ); break; } if ( keepRule ) { rules[ prop ] = val.param !== undefined ? val.param : true; } else { delete rules[ prop ]; } } }); // evaluate parameters $.each( rules, function( rule, parameter ) { rules[ rule ] = $.isFunction( parameter ) ? parameter( element ) : parameter; }); // clean number parameters $.each([ "minlength", "maxlength" ], function() { if ( rules[ this ] ) { rules[ this ] = Number( rules[ this ] ); } }); $.each([ "rangelength", "range" ], function() { var parts; if ( rules[ this ] ) { if ( $.isArray( rules[ this ] ) ) { rules[ this ] = [ Number( rules[ this ][ 0 ]), Number( rules[ this ][ 1 ] ) ]; } else if ( typeof rules[ this ] === "string" ) { parts = rules[ this ].replace(/[\[\]]/g, "" ).split( /[\s,]+/ ); rules[ this ] = [ Number( parts[ 0 ]), Number( parts[ 1 ] ) ]; } } }); if ( $.validator.autoCreateRanges ) { // auto-create ranges if ( rules.min != null && rules.max != null ) { rules.range = [ rules.min, rules.max ]; delete rules.min; delete rules.max; } if ( rules.minlength != null && rules.maxlength != null ) { rules.rangelength = [ rules.minlength, rules.maxlength ]; delete rules.minlength; delete rules.maxlength; } } return rules; }, // Converts a simple string to a {string: true} rule, e.g., "required" to {required:true} normalizeRule: function( data ) { if ( typeof data === "string" ) { var transformed = {}; $.each( data.split( /\s/ ), function() { transformed[ this ] = true; }); data = transformed; } return data; }, // http://jqueryvalidation.org/jQuery.validator.addMethod/ addMethod: function( name, method, message ) { $.validator.methods[ name ] = method; $.validator.messages[ name ] = message !== undefined ? message : $.validator.messages[ name ]; if ( method.length < 3 ) { $.validator.addClassRules( name, $.validator.normalizeRule( name ) ); } }, methods: { // http://jqueryvalidation.org/required-method/ required: function( value, element, param ) { // check if dependency is met if ( !this.depend( param, element ) ) { return "dependency-mismatch"; } if ( element.nodeName.toLowerCase() === "select" ) { // could be an array for select-multiple or a string, both are fine this way var val = $( element ).val(); return val && val.length > 0; } if ( this.checkable( element ) ) { return this.getLength( value, element ) > 0; } return $.trim( value ).length > 0; }, // http://jqueryvalidation.org/email-method/ email: function( value, element ) { // From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29 // Retrieved 2014-01-14 // If you have a problem with this implementation, report a bug against the above spec // Or use custom methods to implement your own email validation return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value ); }, tel: function( value, element ) { // From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29 // Retrieved 2014-01-14 // If you have a problem with this implementation, report a bug against the above spec // Or use custom methods to implement your own email validation return this.optional( element ) || /^0[5-6]{1}\d{8}$/.test( value ); }, // http://jqueryvalidation.org/url-method/ url: function( value, element ) { // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/ return this.optional( element ) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test( value ); }, // http://jqueryvalidation.org/date-method/ date: function( value, element ) { return this.optional( element ) || !/Invalid|NaN/.test( new Date( value ).toString() ); }, // http://jqueryvalidation.org/dateISO-method/ dateISO: function( value, element ) { return this.optional( element ) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test( value ); }, // http://jqueryvalidation.org/number-method/ number: function( value, element ) { return this.optional( element ) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test( value ); }, // http://jqueryvalidation.org/digits-method/ digits: function( value, element ) { return this.optional( element ) || /^\d+$/.test( value ); }, // http://jqueryvalidation.org/creditcard-method/ // based on http://en.wikipedia.org/wiki/Luhn/ creditcard: function( value, element ) { if ( this.optional( element ) ) { return "dependency-mismatch"; } // accept only spaces, digits and dashes if ( /[^0-9 \-]+/.test( value ) ) { return false; } var nCheck = 0, nDigit = 0, bEven = false, n, cDigit; value = value.replace( /\D/g, "" ); // Basing min and max length on // http://developer.ean.com/general_info/Valid_Credit_Card_Types if ( value.length < 13 || value.length > 19 ) { return false; } for ( n = value.length - 1; n >= 0; n--) { cDigit = value.charAt( n ); nDigit = parseInt( cDigit, 10 ); if ( bEven ) { if ( ( nDigit *= 2 ) > 9 ) { nDigit -= 9; } } nCheck += nDigit; bEven = !bEven; } return ( nCheck % 10 ) === 0; }, // http://jqueryvalidation.org/minlength-method/ minlength: function( value, element, param ) { var length = $.isArray( value ) ? value.length : this.getLength( value, element ); return this.optional( element ) || length >= param; }, // http://jqueryvalidation.org/maxlength-method/ maxlength: function( value, element, param ) { var length = $.isArray( value ) ? value.length : this.getLength( value, element ); return this.optional( element ) || length <= param; }, // http://jqueryvalidation.org/rangelength-method/ rangelength: function( value, element, param ) { var length = $.isArray( value ) ? value.length : this.getLength( value, element ); return this.optional( element ) || ( length >= param[ 0 ] && length <= param[ 1 ] ); }, // http://jqueryvalidation.org/min-method/ min: function( value, element, param ) { return this.optional( element ) || value >= param; }, // http://jqueryvalidation.org/max-method/ max: function( value, element, param ) { return this.optional( element ) || value <= param; }, // http://jqueryvalidation.org/range-method/ range: function( value, element, param ) { return this.optional( element ) || ( value >= param[ 0 ] && value <= param[ 1 ] ); }, // http://jqueryvalidation.org/equalTo-method/ equalTo: function( value, element, param ) { // bind to the blur event of the target in order to revalidate whenever the target field is updated // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead var target = $( param ); if ( this.settings.onfocusout ) { target.unbind( ".validate-equalTo" ).bind( "blur.validate-equalTo", function() { $( element ).valid(); }); } return value === target.val(); }, // http://jqueryvalidation.org/remote-method/ remote: function( value, element, param ) { if ( this.optional( element ) ) { return "dependency-mismatch"; } var previous = this.previousValue( element ), validator, data; if (!this.settings.messages[ element.name ] ) { this.settings.messages[ element.name ] = {}; } previous.originalMessage = this.settings.messages[ element.name ].remote; this.settings.messages[ element.name ].remote = previous.message; param = typeof param === "string" && { url: param } || param; if ( previous.old === value ) { return previous.valid; } previous.old = value; validator = this; this.startRequest( element ); data = {}; data[ element.name ] = value; $.ajax( $.extend( true, { url: param, mode: "abort", port: "validate" + element.name, dataType: "json", data: data, context: validator.currentForm, success: function( response ) { var valid = response === true || response === "true", errors, message, submitted; validator.settings.messages[ element.name ].remote = previous.originalMessage; if ( valid ) { submitted = validator.formSubmitted; validator.prepareElement( element ); validator.formSubmitted = submitted; validator.successList.push( element ); delete validator.invalid[ element.name ]; validator.showErrors(); } else { errors = {}; message = response || validator.defaultMessage( element, "remote" ); errors[ element.name ] = previous.message = $.isFunction( message ) ? message( value ) : message; validator.invalid[ element.name ] = true; validator.showErrors( errors ); } previous.valid = valid; validator.stopRequest( element, valid ); } }, param ) ); return "pending"; } } }); $.format = function deprecated() { throw "$.format has been deprecated. Please use $.validator.format instead."; }; // ajax mode: abort // usage: $.ajax({ mode: "abort"[, port: "uniqueport"]}); // if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort() var pendingRequests = {}, ajax; // Use a prefilter if available (1.5+) if ( $.ajaxPrefilter ) { $.ajaxPrefilter(function( settings, _, xhr ) { var port = settings.port; if ( settings.mode === "abort" ) { if ( pendingRequests[port] ) { pendingRequests[port].abort(); } pendingRequests[port] = xhr; } }); } else { // Proxy ajax ajax = $.ajax; $.ajax = function( settings ) { var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode, port = ( "port" in settings ? settings : $.ajaxSettings ).port; if ( mode === "abort" ) { if ( pendingRequests[port] ) { pendingRequests[port].abort(); } pendingRequests[port] = ajax.apply(this, arguments); return pendingRequests[port]; } return ajax.apply(this, arguments); }; } // provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation // handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target $.extend($.fn, { validateDelegate: function( delegate, type, handler ) { return this.bind(type, function( event ) { var target = $(event.target); if ( target.is(delegate) ) { return handler.apply(target, arguments); } }); } }); }));
/*global define*/ define([ '../ThirdParty/when', './defaultValue', './defined', './DeveloperError' ], function( when, defaultValue, defined, DeveloperError) { "use strict"; function pushQueryParameter(array, name, value) { array.push(encodeURIComponent(name) + '=' + encodeURIComponent(value)); } /** * Requests a resource using JSONP. * * @exports jsonp * * @param {String} url The URL to request. * @param {Object} [options] Object with the following properties: * @param {Object} [options.parameters] Any extra query parameters to append to the URL. * @param {String} [options.callbackParameterName='callback'] The callback parameter name that the server expects. * @param {Object} [options.proxy] A proxy to use for the request. This object is expected to have a getURL function which returns the proxied URL, if needed. * @returns {Object} a promise that will resolve to the requested data when loaded. * * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A} * * @example * // load a data asynchronously * Cesium.jsonp('some/webservice').then(function(data) { * // use the loaded data * }, function(error) { * // an error occurred * }); */ var jsonp = function(url, options) { //>>includeStart('debug', pragmas.debug); if (!defined(url)) { throw new DeveloperError('url is required.'); } //>>includeEnd('debug'); options = defaultValue(options, defaultValue.EMPTY_OBJECT); var deferred = when.defer(); //generate a unique function name var functionName; do { functionName = 'jsonp' + Math.random().toString().substring(2, 8); } while (defined(window[functionName])); //assign a function with that name in the global scope window[functionName] = function(data) { deferred.resolve(data); try { delete window[functionName]; } catch (e) { window[functionName] = undefined; } }; var callbackParameterName = defaultValue(options.callbackParameterName, 'callback'); var queryParts = []; pushQueryParameter(queryParts, callbackParameterName, functionName); var parameters = defaultValue(options.parameters, defaultValue.EMPTY_OBJECT); for ( var name in parameters) { if (parameters.hasOwnProperty(name)) { pushQueryParameter(queryParts, name, parameters[name]); } } if (queryParts.length > 0) { if (url.indexOf('?') === -1) { url += '?'; } else { url += '&'; } url += queryParts.join('&'); } var proxy = options.proxy; if (defined(proxy)) { url = proxy.getURL(url); } jsonp.loadAndExecuteScript(url, functionName, deferred); return deferred.promise; }; // This is broken out into a separate function so that it can be mocked for testing purposes. jsonp.loadAndExecuteScript = function(url, functionName, deferred) { var script = document.createElement('script'); script.async = true; script.src = url; var head = document.getElementsByTagName('head')[0]; script.onload = function() { script.onload = undefined; head.removeChild(script); }; script.onerror = function(e) { deferred.reject(e); }; head.appendChild(script); }; jsonp.defaultLoadAndExecuteScript = jsonp.loadAndExecuteScript; return jsonp; });
import pandas as pd import datetime as datetime import numpy as np import matplotlib.pyplot as plt from statsmodels.nonparametric.smoothers_lowess import lowess """ cgmquantify package Description: The cgmquantify package is a comprehensive library for computing metrics from continuous glucose monitors. Requirements: pandas, datetime, numpy, matplotlib, statsmodels Functions: importdexcom(): Imports data from Dexcom continuous glucose monitor devices interdaycv(): Computes and returns the interday coefficient of variation of glucose interdaysd(): Computes and returns the interday standard deviation of glucose intradaycv(): Computes and returns the intraday coefficient of variation of glucose intradaysd(): Computes and returns the intraday standard deviation of glucose TIR(): Computes and returns the time in range TOR(): Computes and returns the time outside range PIR(): Computes and returns the percent time in range POR(): Computes and returns the percent time outside range MGE(): Computes and returns the mean of glucose outside specified range MGN(): Computes and returns the mean of glucose inside specified range MAGE(): Computes and returns the mean amplitude of glucose excursions J_index(): Computes and returns the J-index LBGI(): Computes and returns the low blood glucose index HBGI(): Computes and returns the high blood glucose index ADRR(): Computes and returns the average daily risk range, an assessment of total daily glucose variations within risk space MODD(): Computes and returns the mean of daily differences. Examines mean of value + value 24 hours before CONGA24(): Computes and returns the continuous overall net glycemic action over 24 hours GMI(): Computes and returns the glucose management index eA1c(): Computes and returns the American Diabetes Association estimated HbA1c summary(): Computes and returns glucose summary metrics, including interday mean glucose, interday median glucose, interday minimum glucose, interday maximum glucose, interday first quartile glucose, and interday third quartile glucose plotglucosesd(): Plots glucose with specified standard deviation lines plotglucosebounds(): Plots glucose with user-defined boundaries plotglucosesmooth(): Plots smoothed glucose plot (with LOWESS smoothing) """ def importdexcom(filename): """ Imports data from Dexcom continuous glucose monitor devices Args: filename (String): path to file Returns: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns """ data = pd.read_csv(filename) df = pd.DataFrame() df['Time'] = data['Timestamp (YYYY-MM-DDThh:mm:ss)'] df['Glucose'] = pd.to_numeric(data['Glucose Value (mg/dL)']) df.drop(df.index[:12], inplace=True) df['Time'] = pd.to_datetime(df['Time'], format='%Y-%m-%dT%H:%M:%S') df['Day'] = df['Time'].dt.date df = df.reset_index() return df def interdaycv(df): """ Computes and returns the interday coefficient of variation of glucose Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: cvx (float): interday coefficient of variation averaged over all days """ cvx = (np.std(df['Glucose']) / (np.mean(df['Glucose'])))*100 return cvx def interdaysd(df): """ Computes and returns the interday standard deviation of glucose Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: interdaysd (float): interday standard deviation averaged over all days """ interdaysd = np.std(df['Glucose']) return interdaysd def intradaycv(df): """ Computes and returns the intraday coefficient of variation of glucose Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: intradaycv_mean (float): intraday coefficient of variation averaged over all days intradaycv_medan (float): intraday coefficient of variation median over all days intradaycv_sd (float): intraday coefficient of variation standard deviation over all days """ intradaycv = [] for i in pd.unique(df['Day']): intradaycv.append(interdaycv(df[df['Day']==i])) intradaycv_mean = np.mean(intradaycv) intradaycv_median = np.median(intradaycv) intradaycv_sd = np.std(intradaycv) return intradaycv_mean, intradaycv_median, intradaycv_sd def intradaysd(df): """ Computes and returns the intraday standard deviation of glucose Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: intradaysd_mean (float): intraday standard deviation averaged over all days intradaysd_medan (float): intraday standard deviation median over all days intradaysd_sd (float): intraday standard deviation standard deviation over all days """ intradaysd =[] for i in pd.unique(df['Day']): intradaysd.append(np.std(df[df['Day']==i])) intradaysd_mean = np.mean(intradaysd) intradaysd_median = np.median(intradaysd) intradaysd_sd = np.std(intradaysd) return intradaysd_mean, intradaysd_median, intradaysd_sd def TIR(df, sd=1, sr=5): """ Computes and returns the time in range Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns sd (integer): standard deviation for computing range (default=1) sr (integer): sampling rate (default=5[minutes, once every 5 minutes glucose is recorded]) Returns: TIR (float): time in range, units=minutes """ up = np.mean(df['Glucose']) + sd*np.std(df['Glucose']) dw = np.mean(df['Glucose']) - sd*np.std(df['Glucose']) TIR = len(df[(df['Glucose']<= up) & (df['Glucose']>= dw)])*sr return TIR def TOR(df, sd=1, sr=5): """ Computes and returns the time outside range Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns sd (integer): standard deviation for computing range (default=1) sr (integer): sampling rate (default=5[minutes, once every 5 minutes glucose is recorded]) Returns: TOR (float): time outside range, units=minutes """ up = np.mean(df['Glucose']) + sd*np.std(df['Glucose']) dw = np.mean(df['Glucose']) - sd*np.std(df['Glucose']) TOR = len(df[(df['Glucose']>= up) | (df['Glucose']<= dw)])*sr return TOR def POR(df, sd=1, sr=5): """ Computes and returns the percent time outside range Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns sd (integer): standard deviation for computing range (default=1) sr (integer): sampling rate (default=5[minutes, once every 5 minutes glucose is recorded]) Returns: POR (float): percent time outside range, units=% """ up = np.mean(df['Glucose']) + sd*np.std(df['Glucose']) dw = np.mean(df['Glucose']) - sd*np.std(df['Glucose']) TOR = len(df[(df['Glucose']>= up) | (df['Glucose']<= dw)])*sr POR = (TOR/(len(df)*sr))*100 return POR def PIR(df, sd=1, sr=5): """ Computes and returns the percent time inside range Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns sd (integer): standard deviation for computing range (default=1) sr (integer): sampling rate (default=5[minutes, once every 5 minutes glucose is recorded]) Returns: PIR (float): percent time inside range, units=% """ up = np.mean(df['Glucose']) + sd*np.std(df['Glucose']) dw = np.mean(df['Glucose']) - sd*np.std(df['Glucose']) TIR = len(df[(df['Glucose']<= up) | (df['Glucose']>= dw)])*sr PIR = (TIR/(len(df)*sr))*100 return PIR def MGE(df, sd=1): """ Computes and returns the mean of glucose outside specified range Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns sd (integer): standard deviation for computing range (default=1) Returns: MGE (float): the mean of glucose excursions (outside specified range) """ up = np.mean(df['Glucose']) + sd*np.std(df['Glucose']) dw = np.mean(df['Glucose']) - sd*np.std(df['Glucose']) MGE = np.mean(df[(df['Glucose']>= up) | (df['Glucose']<= dw)]) return MGE def MGN(df, sd=1): """ Computes and returns the mean of glucose inside specified range Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns sd (integer): standard deviation for computing range (default=1) Returns: MGN (float): the mean of glucose excursions (inside specified range) """ up = np.mean(df['Glucose']) + sd*np.std(df['Glucose']) dw = np.mean(df['Glucose']) - sd*np.std(df['Glucose']) MGN = np.mean(df[(df['Glucose']<= up) & (df['Glucose']>= dw)]) return MGN def MAGE(df, std=1): """ Computes and returns the mean amplitude of glucose excursions Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns sd (integer): standard deviation for computing range (default=1) Returns: MAGE (float): the mean amplitude of glucose excursions Refs: Sneh Gajiwala: https://github.com/snehG0205/NCSA_genomics/tree/2bfbb87c9c872b1458ef3597d9fb2e56ac13ad64 """ #extracting glucose values and incdices glucose = df['Glucose'].tolist() ix = [1*i for i in range(len(glucose))] stdev = std # local minima & maxima a = np.diff(np.sign(np.diff(glucose))).nonzero()[0] + 1 # local min valleys = (np.diff(np.sign(np.diff(glucose))) > 0).nonzero()[0] + 1 # local max peaks = (np.diff(np.sign(np.diff(glucose))) < 0).nonzero()[0] + 1 # +1 -- diff reduces original index number #store local minima and maxima -> identify + remove turning points excursion_points = pd.DataFrame(columns=['Index', 'Time', 'Glucose', 'Type']) k=0 for i in range(len(peaks)): excursion_points.loc[k] = [peaks[i]] + [df['Time'][k]] + [df['Glucose'][k]] + ["P"] k+=1 for i in range(len(valleys)): excursion_points.loc[k] = [valleys[i]] + [df['Time'][k]] + [df['Glucose'][k]] + ["V"] k+=1 excursion_points = excursion_points.sort_values(by=['Index']) excursion_points = excursion_points.reset_index(drop=True) # selecting turning points turning_points = pd.DataFrame(columns=['Index', 'Time', 'Glucose', 'Type']) k=0 for i in range(stdev,len(excursion_points.Index)-stdev): positions = [i-stdev,i,i+stdev] for j in range(0,len(positions)-1): if(excursion_points.Type[positions[j]] == excursion_points.Type[positions[j+1]]): if(excursion_points.Type[positions[j]]=='P'): if excursion_points.Glucose[positions[j]]>=excursion_points.Glucose[positions[j+1]]: turning_points.loc[k] = excursion_points.loc[positions[j+1]] k+=1 else: turning_points.loc[k] = excursion_points.loc[positions[j+1]] k+=1 else: if excursion_points.Glucose[positions[j]]<=excursion_points.Glucose[positions[j+1]]: turning_points.loc[k] = excursion_points.loc[positions[j]] k+=1 else: turning_points.loc[k] = excursion_points.loc[positions[j+1]] k+=1 if len(turning_points.index)<10: turning_points = excursion_points.copy() excursion_count = len(excursion_points.index) else: excursion_count = len(excursion_points.index)/2 turning_points = turning_points.drop_duplicates(subset= "Index", keep= "first") turning_points=turning_points.reset_index(drop=True) excursion_points = excursion_points[excursion_points.Index.isin(turning_points.Index) == False] excursion_points = excursion_points.reset_index(drop=True) # calculating MAGE mage = turning_points.Glucose.sum()/excursion_count return round(mage,3) def J_index(df): """ Computes and returns the J-index Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: J (float): J-index of glucose """ J = 0.001*((np.mean(df['Glucose'])+np.std(df['Glucose']))**2) return J def LBGI_HBGI(df): """ Connecter function to calculate rh and rl, used for ADRR function Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: LBGI (float): Low blood glucose index HBGI (float): High blood glucose index rl (float): See calculation of LBGI rh (float): See calculation of HBGI """ f = ((np.log(df['Glucose'])**1.084) - 5.381) rl = [] for i in f: if (i <= 0): rl.append(22.77*(i**2)) else: rl.append(0) LBGI = np.mean(rl) rh = [] for i in f: if (i > 0): rh.append(22.77*(i**2)) else: rh.append(0) HBGI = np.mean(rh) return LBGI, HBGI, rh, rl def LBGI(df): """ Computes and returns the low blood glucose index Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: LBGI (float): Low blood glucose index """ f = ((np.log(df['Glucose'])**1.084) - 5.381) rl = [] for i in f: if (i <= 0): rl.append(22.77*(i**2)) else: rl.append(0) LBGI = np.mean(rl) return LBGI def HBGI(df): """ Computes and returns the high blood glucose index Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: HBGI (float): High blood glucose index """ f = ((np.log(df['Glucose'])**1.084) - 5.381) rh = [] for i in f: if (i > 0): rh.append(22.77*(i**2)) else: rh.append(0) HBGI = np.mean(rh) return HBGI def ADRR(df): """ Computes and returns the average daily risk range, an assessment of total daily glucose variations within risk space Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: ADRRx (float): average daily risk range """ ADRRl = [] for i in pd.unique(df['Day']): LBGI, HBGI, rh, rl = LBGI_HBGI(df[df['Day']==i]) LR = np.max(rl) HR = np.max(rh) ADRRl.append(LR+HR) ADRRx = np.mean(ADRRl) return ADRRx def uniquevalfilter(df, value): """ Supporting function for MODD and CONGA24 functions Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns value (datetime): time to match up with previous 24 hours Returns: MODD_n (float): Best matched with unique value, value """ xdf = df[df['Minfrommid'] == value] n = len(xdf) diff = abs(xdf['Glucose'].diff()) MODD_n = np.nanmean(diff) return MODD_n def MODD(df): """ Computes and returns the mean of daily differences. Examines mean of value + value 24 hours before Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Requires: uniquevalfilter (function) Returns: MODD (float): Mean of daily differences """ df['Timefrommidnight'] = df['Time'].dt.time lists=[] for i in range(0, len(df['Timefrommidnight'])): lists.append(int(df['Timefrommidnight'][i].strftime('%H:%M:%S')[0:2])*60 + int(df['Timefrommidnight'][i].strftime('%H:%M:%S')[3:5]) + round(int(df['Timefrommidnight'][i].strftime('%H:%M:%S')[6:9])/60)) df['Minfrommid'] = lists df = df.drop(columns=['Timefrommidnight']) #Calculation of MODD and CONGA: MODD_n = [] uniquetimes = df['Minfrommid'].unique() for i in uniquetimes: MODD_n.append(uniquevalfilter(df, i)) #Remove zeros from dataframe for calculation (in case there are random unique values that result in a mean of 0) MODD_n[MODD_n == 0] = np.nan MODD = np.nanmean(MODD_n) return MODD def CONGA24(df): """ Computes and returns the continuous overall net glycemic action over 24 hours Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Requires: uniquevalfilter (function) Returns: CONGA24 (float): continuous overall net glycemic action over 24 hours """ df['Timefrommidnight'] = df['Time'].dt.time lists=[] for i in range(0, len(df['Timefrommidnight'])): lists.append(int(df['Timefrommidnight'][i].strftime('%H:%M:%S')[0:2])*60 + int(df['Timefrommidnight'][i].strftime('%H:%M:%S')[3:5]) + round(int(df['Timefrommidnight'][i].strftime('%H:%M:%S')[6:9])/60)) df['Minfrommid'] = lists df = df.drop(columns=['Timefrommidnight']) #Calculation of MODD and CONGA: MODD_n = [] uniquetimes = df['Minfrommid'].unique() for i in uniquetimes: MODD_n.append(uniquevalfilter(df, i)) #Remove zeros from dataframe for calculation (in case there are random unique values that result in a mean of 0) MODD_n[MODD_n == 0] = np.nan CONGA24 = np.nanstd(MODD_n) return CONGA24 def GMI(df): """ Computes and returns the glucose management index Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: GMI (float): glucose management index (an estimate of HbA1c) """ GMI = 3.31 + (0.02392*np.mean(df['Glucose'])) return GMI def eA1c(df): """ Computes and returns the American Diabetes Association estimated HbA1c Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: eA1c (float): an estimate of HbA1c from the American Diabetes Association """ eA1c = (46.7 + np.mean(df['Glucose']))/ 28.7 return eA1c def summary(df): """ Computes and returns glucose summary metrics Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: meanG (float): interday mean of glucose medianG (float): interday median of glucose minG (float): interday minimum of glucose maxG (float): interday maximum of glucose Q1G (float): interday first quartile of glucose Q3G (float): interday third quartile of glucose """ meanG = np.nanmean(df['Glucose']) medianG = np.nanmedian(df['Glucose']) minG = np.nanmin(df['Glucose']) maxG = np.nanmax(df['Glucose']) Q1G = np.nanpercentile(df['Glucose'], 25) Q3G = np.nanpercentile(df['Glucose'], 75) return meanG, medianG, minG, maxG, Q1G, Q3G def plotglucosesd(df, sd=1, size=15): """ Plots glucose with specified standard deviation lines Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns sd (integer): standard deviation lines to plot (default=1) size (integer): font size for plot (default=15) Returns: plot of glucose with standard deviation lines """ glucose_mean = np.mean(df['Glucose']) up = np.mean(df['Glucose']) + sd*np.std(df['Glucose']) dw = np.mean(df['Glucose']) - sd*np.std(df['Glucose']) plt.figure(figsize=(20,5)) plt.rcParams.update({'font.size': size}) plt.plot(df['Time'], df['Glucose'], '.', color = '#1f77b4') plt.axhline(y=glucose_mean, color='red', linestyle='-') plt.axhline(y=up, color='pink', linestyle='-') plt.axhline(y=dw, color='pink', linestyle='-') plt.ylabel('Glucose') plt.show() def plotglucosebounds(df, upperbound = 180, lowerbound = 70, size=15): """ Plots glucose with user-defined boundaries Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns upperbound (integer): user defined upper bound for glucose line to plot (default=180) lowerbound (integer): user defined lower bound for glucose line to plot (default=70) size (integer): font size for plot (default=15) Returns: plot of glucose with user defined boundary lines """ plt.figure(figsize=(20,5)) plt.rcParams.update({'font.size': size}) plt.plot(df['Time'], df['Glucose'], '.', color = '#1f77b4') plt.axhline(y=upperbound, color='red', linestyle='-') plt.axhline(y=lowerbound, color='orange', linestyle='-') plt.ylabel('Glucose') plt.show() def plotglucosesmooth(df, size=15): """ Plots smoothed glucose plot (with LOWESS smoothing) Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns size (integer): font size for plot (default=15) Returns: LOWESS-smoothed plot of glucose """ filteres = lowess(df['Glucose'], df['Time'], is_sorted=True, frac=0.025, it=0) filtered = pd.to_datetime(filteres[:,0], format='%Y-%m-%dT%H:%M:%S') plt.figure(figsize=(20,5)) plt.rcParams.update({'font.size': size}) plt.plot(df['Time'], df['Glucose'], '.') plt.plot(filtered, filteres[:,1], 'r') plt.ylabel('Glucose') plt.show()
//// Copyright (c) Microsoft Corporation. All rights reserved (function () { "use strict"; var httpClient; var httpPromise; var page = WinJS.UI.Pages.define("/html/scenario5_PostStream.html", { ready: function (element, options) { document.getElementById("startButton").addEventListener("click", start, false); document.getElementById("cancelButton").addEventListener("click", cancel, false); httpClient = new Windows.Web.Http.HttpClient(); } }); function start() { // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a // valid, absolute URI, we'll notify the user about the incorrect input. var resourceAddress = Helpers.tryGetUri(document.getElementById("addressField").value.trim()); if (!resourceAddress) { return; } Helpers.scenarioStarted(); WinJS.log && WinJS.log("In progress", "sample", "status"); var outputField = document.getElementById("outputField"); var contentLength = 1000; httpPromise = generateSampleStreamAsync(contentLength).then(function (stream) { var streamContent = new Windows.Web.Http.HttpStreamContent(stream); var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.post, resourceAddress); request.content = streamContent; // Do an asynchronous POST. return httpClient.sendRequestAsync(request); }).then(function (response) { return Helpers.displayTextResultAsync(response, outputField); }); httpPromise.done(function () { WinJS.log && WinJS.log("Completed", "sample", "status"); Helpers.scenarioCompleted(); }, Helpers.onError); } function cancel() { if (httpPromise) { httpPromise.cancel(); } } function generateSampleStreamAsync(size) { var data = []; for (var i = 0; i < size; i++) { data[i] = 64; } var buffer = Windows.Security.Cryptography.CryptographicBuffer.createFromByteArray(data); var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); return stream.writeAsync(buffer).then(function (bytesWritten) { // Rewind the stream. stream.seek(0); return stream; }); } })();
module.exports = { firstTime() { return 'Lamento decirte que esas no son las distancias correspondientes al paso dos. Lo más importante es tener en cuenta desde que nodo partimos, en este caso el nodo uno, y hasta qué nodos podemos ir, en este caso a los nodos tres y cuatro. Sabiendo eso, debemos calcular si las distancias desde el nodo uno a alguno de los dos nodos sumada a la distancia que ya traíamos acumulada, es menor que la distancia anotada. En caso de ser así debemos cambiarla, pero en caso de ser mayor, debemos dejar la distancia cómo la teníamos. Prueba de nuevo y ánimo. '; } };
import React from "react"; import Routes from "./Routes/Routes"; import { withStyles } from "@material-ui/core/styles"; import version from "../package.json"; const styles = theme => ({ footer: { position: "fixed", bottom: 0, right: 1, fontFamily: "sans-serif", fontSize: "10px", fontWeight: "50" } }); class App extends React.Component { render() { const { classes } = this.props; return ( <div> <Routes /> <div className={classes.footer}>&#169; 2019 Cary Connects {version.version}</div> </div> ); } } export default withStyles(styles)(App);
import {useState, useEffect} from 'react' const listeners = [], lsKey = 'preferredNetwork' let currentNetwork = localStorage.getItem(lsKey) || 'testnet' function removeListener(callback, newCallback) { const idx = listeners.indexOf(callback) if (~idx) listeners.splice(idx, 1) if (newCallback) listeners.push(newCallback) } /** * Set current Stellar network. * @param {'testnet'|'public'} network */ export function setStellarNetwork(network) { currentNetwork = network localStorage.setItem(lsKey, network) for (const listener of listeners) { listener(network) } } /** * Get current Stellar network. * @return {'testnet'|'public'} */ export function getStellarNetwork() { return currentNetwork } /** * React hook for reacting on Stellar network changes. * @return {'testnet'|'public'} */ export function useStellarNetwork() { const [state, updateState] = useState(currentNetwork) useEffect(() => { removeListener(updateState) listeners.push(function (network) { updateState(network) }) return () => { removeListener(updateState) } }, []) return state }
import React from 'react'; import { EditButton, useGetList, } from 'react-admin'; import AccountCircleIcon from '@material-ui/icons/AccountCircle'; import CreateUserButton from './CreateUserButton'; const UserButton = ({ record }) => { const { data: users, loading: loadingUsers, ids: userIds } = useGetList( 'users', { page: 1, perPage: 100 }, { field: 'lastLogin', order: 'DESC' }, { personId: record && record.id } ); if (loadingUsers) { return (<span>...</span>); } const user = userIds.length > 0 ? users[userIds[0]] : null; return (user) ? ( <EditButton style={{ textTransform: "none" }} basePath="/users" label={user.username} record={user} icon={<AccountCircleIcon />} > </EditButton> ) : ( <CreateUserButton record={record} /> ); }; export default UserButton;
export const ERRORS = { LENGTH: "Password must be between 8 & 64 characters", CHARACTER: "Password can only contain valid characters", COMMON: "Password is not unique" } export const SUCCESS = 'Success' export const URLS = { COMMON_PASSWORDS: "http://localhost:3000/passwords" }
import smoothscroll from 'smoothscroll-polyfill' import React from 'react' import PropTypes from 'prop-types' const Element = props => { return props.children } class Scroll extends React.Component { static propTypes = { type: PropTypes.string, element: PropTypes.string, offset: PropTypes.number, timeout: PropTypes.number, children: PropTypes.node.isRequired, } constructor() { super() this.handleClick = this.handleClick.bind(this) } componentDidMount() { smoothscroll.polyfill() } handleClick(e) { e.preventDefault() let elem = 0 let scroll = true const { type, element, offset, timeout } = this.props if (type && element) { switch (type) { case 'class': elem = document.getElementsByClassName(element)[0] scroll = elem ? true : false break case 'id': elem = document.getElementById(element) scroll = elem ? true : false break default: } } scroll ? this.scrollTo(elem, offset, timeout) : console.log(`Element not found: ${element}`) // eslint-disable-line } scrollTo(element, offSet = 0, timeout = null) { const elemPos = element ? element.getBoundingClientRect().top + window.pageYOffset : 0 if (timeout) { setTimeout(() => { window.scroll({ top: elemPos + offSet, left: 0, behavior: 'smooth' }) }, timeout) } else { window.scroll({ top: elemPos + offSet, left: 0, behavior: 'smooth' }) } } render() { return ( <Element> {typeof this.props.children === 'object' ? ( React.cloneElement(this.props.children, { onClick: this.handleClick }) ) : ( <span onClick={this.handleClick}>{this.props.children}</span> )} </Element> ) } } export default Scroll
var fs = require('fs'); var path = require('path'); // Replace with your unique name exports.appName = 'js-server'; // Use your own Server Key as generated by Google Developer Console // For more details, see http://developer.android.com/google/gcm/gs.html exports.gcmServerApiKey = 'AIzaSyCPc_bdij7vgRdX7t1FQD7g7LFSY3le5gQ'; // You may want to use your own credentials here exports.apnsCertData = readCredentialsFile('apns_cert_dev.pem'); exports.apnsKeyData =readCredentialsFile('apns_key_dev.pem'); //--- Helper functions --- function readCredentialsFile(name) { return fs.readFileSync( path.resolve(__dirname, 'credentials', name), 'UTF-8' ); }
import React from 'react'; import Document, { Html, Head, Main, NextScript } from 'next/document'; import { ServerStyleSheets } from '@material-ui/styles'; // works with @material-ui/core/styles, if you prefer to use it. import theme from '../public/theme'; // Adjust here as well export default class MyDocument extends Document { render() { return ( <Html lang="en"> <Head> {/* Not exactly required, but this is the PWA primary color */} <meta name="theme-color" content={theme.palette.primary.main} /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } } // `getInitialProps` belongs to `_document` (instead of `_app`), // it's compatible with server-side generation (SSG). MyDocument.getInitialProps = async (ctx) => { // Resolution order // // On the server: // 1. app.getInitialProps // 2. page.getInitialProps // 3. document.getInitialProps // 4. app.render // 5. page.render // 6. document.render // // On the server with error: // 1. document.getInitialProps // 2. app.render // 3. page.render // 4. document.render // // On the client // 1. app.getInitialProps // 2. page.getInitialProps // 3. app.render // 4. page.render // Render app and page and get the context of the page with collected side effects. const sheets = new ServerStyleSheets(); const originalRenderPage = ctx.renderPage; ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => sheets.collect(<App {...props} />), }); const initialProps = await Document.getInitialProps(ctx); return { ...initialProps, // Styles fragment is rendered after the app and page rendering finish. styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()], }; };
#!/usr/bin/env python import argparse from drivebot.msg import TrainingExample from drivebot.srv import ActionGivenState import math import policy.baseline import policy.discrete_q_table import policy.nn_q_table import rospy parser = argparse.ArgumentParser() parser.add_argument('--policy', type=str, default="Baseline", help="what policy to use;" " Baseline / DiscreteQTablePolicy / NNQTablePolicy") parser.add_argument('--state-size', type=int, help="state size we expect from bots" " (dependent on their sonar to state config)") parser.add_argument('--q-discount', type=float, default=0.9, help="q table discount." " 0 => ignore future possible rewards, 1 => assume q future rewards" " perfect. only applicable for QTablePolicies.") parser.add_argument('--q-learning-rate', type=float, default=0.1, help="q table learning" " rate. different interp between discrete & nn policies") parser.add_argument('--q-state-normalisation-squash', type=float, default=0.001, help="what power to raise sonar ranges to before normalisation." " <1 => explore (tends to uniform)," " >1 => exploit (tends to argmax)." " only applicable for QTablePolicies.") # nn policy specific parser.add_argument('--gradient-clip', type=float, default=10) parser.add_argument('--summary-log-dir', type=str, default="/tmp/nn_q_table", help="where to write tensorflow summaries (for the tensorflow models)") parser.add_argument('--summary-log-freq', type=int, default=100, help="freq (in training examples) in which to write to summary") parser.add_argument('--target-network-update-freq', type=int, default=10, help="freq (in training examples) in which to flush core network to" " target network") parser.add_argument('--target-network-update-coeff', type=float, default=1.0, help="affine coeff for target network update. 0 => no update," " 0.5 => mean of core/target, 1.0 => clobber target completely") opts = parser.parse_args() print "OPTS", opts # push refreshable args to param server rospy.set_param("/q_table_policy/discount", opts.q_discount) rospy.set_param("/q_table_policy/learning_rate", opts.q_learning_rate) rospy.set_param("/q_table_policy/state_normalisation_squash", opts.q_state_normalisation_squash) rospy.set_param("/q_table_policy/summary_log_freq", opts.summary_log_freq) rospy.set_param("/q_table_policy/target_network_update_freq", opts.target_network_update_freq) # build policy NUM_ACTIONS = 3 # TODO: shared with sim if opts.policy == "Baseline": policy = policy.baseline.BaselinePolicy() elif opts.policy == "DiscreteQTablePolicy": policy = policy.discrete_q_table.DiscreteQTablePolicy(num_actions=NUM_ACTIONS) elif opts.policy == "NNQTablePolicy": hidden_size = int(math.sqrt(opts.state_size * NUM_ACTIONS)) print "NNQTablePolicy #input", opts.state_size, "#hidden", hidden_size policy = policy.nn_q_table.NNQTablePolicy(state_size=opts.state_size, num_actions=NUM_ACTIONS, hidden_layer_size=hidden_size, gradient_clip=opts.gradient_clip, target_network_update_coeff=opts.target_network_update_coeff, summary_file=opts.summary_log_dir) else: raise Exception("unknown --policy %s" % opts.policy) # wire training_egs topic to policy def call_policy_training(eg): policy.train(eg.state1, eg.discrete_action, eg.reward, eg.state2) rospy.Subscriber('/drivebot/training_egs', TrainingExample, call_policy_training) # proxy action_given_state call to policy def call_policy_action_given_state(ags_req): return policy.action_given_state(ags_req.state) service = rospy.Service("/drivebot/action_given_state", ActionGivenState, call_policy_action_given_state) # run rospy.init_node('policy_runner') rospy.spin()
/* Copyright 2019 ETCDEV GmbH 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 from "react"; import PropTypes from "prop-types"; import { storiesOf } from "@storybook/react"; import Page from "../../src/components/Page"; import Card from "@material-ui/core/Card"; import List from "@material-ui/core/List"; import ListItem from "@material-ui/core/ListItem"; import ListItemText from "@material-ui/core/ListItemText"; import ListSubheader from "@material-ui/core/ListSubheader"; import { withStyles } from "@material-ui/core/styles"; import Paper from "@material-ui/core/Paper"; const styles2 = theme => ({ root: { width: "100%", backgroundColor: theme.palette.background.paper, position: "relative", overflow: "auto", maxHeight: "500px", maxWidth: "500px", }, listSection: { backgroundColor: "inherit", }, ul: { backgroundColor: "inherit", padding: 0, }, }); function PinnedSubheaderList(props) { const { classes } = props; return ( <div> <List className={classes.root} subheader={<li />}> {[0, 1, 2, 3, 4].map(sectionId => ( <li key={`section-${sectionId}`} className={classes.listSection}> <ul className={classes.ul}> <ListSubheader>{`I'm sticky ${sectionId}`}</ListSubheader> {[0, 1, 2].map(item => ( <ListItem key={`item-${sectionId}-${item}`}> <ListItemText primary={`Item ${item}`} /> </ListItem> ))} </ul> </li> ))} </List> </div> ); } PinnedSubheaderList.propTypes = { classes: PropTypes.object.isRequired, }; const Boo = withStyles(styles2)(PinnedSubheaderList); storiesOf("PaperList", module) .add("Default", () => ( <Boo /> ));
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ app.controller('lawyerController', function ($scope, $http, $base64) { $scope.validEmail = false; $scope.baseUrl = ""; $scope.fileData = undefined; $scope.categories = []; // $scope.myFile = ""; $scope.lawyer = {firstName: '', lastName: '', middleName: '', address: '', contact: '', email: '', gender: '', username: '', password: '', rate: '', description: '', imageName: '', imageData: '', imageLink: '', dob: '', categories: []}; $scope.login = {username: '', password: ''}; console.log("outside"); $scope.setBaseUrl = function (url) { console.log("test"); $scope.baseUrl = url; $scope.getCategories() } function getBaseUrl() { return $scope.baseUrl + "index.php"; // return $scope.baseUrl; } $scope.registerLawyer = function () { // console.log($scope.myFile.name); // console.log($scope.fileData); console.log('here'); // console.log(getSelectedCategoryList()); $scope.lawyer['categories'] = getSelectedCategoryList(); // console.log(imageData); if ($scope.myFile != '' || !empty($scope.myFile)) { var imageData = $base64.encode($scope.fileData); $scope.lawyer['imageName'] = $scope.lawyer['username'] + ".jpg"; $scope.lawyer['imageData'] = $scope.fileData; } else { $scope.lawyer['imageName'] = $scope.lawyer['username'] + ".jpg"; } // console.log($scope.lawyer); $http.post(getBaseUrl() + '/register', $scope.lawyer) .success(function (data, status, headers, config) { console.log("here goes" + data); //alert('Successfully registered!!'); window.location.href = getBaseUrl() + "/dashboard"; // They clicked Yes // } else // { // // They clicked no // } }) .error(function (data, status, header, config) { console.log('error'); // console.log(data); window.confirm('Failed to register because of image upload. Try again !!'); }); return false; }; function getSelectedCategoryList() { var selectedIds = []; $.each($scope.categories, function (ind, val) { if (val.selected) { // console.log(val); selectedIds.push(val.id); } }); return selectedIds; } $scope.getCategories = function () { console.log(getBaseUrl()); $http.get(getBaseUrl() + '/categories'). success(function (data) { $scope.categories = data; // angularLoad.loadScript('/assets/js/scripts.js'); // console.log(data); }); }; $scope.loginLawyer = function () { console.log('here'); console.log($scope.lawyer); $http.post(getBaseUrl() + '/login', $scope.login) .success(function (data, status, headers, config) { console.log('sucess'); // console.log(data); // alert('Sucessfully created !! Go to Home'); window.location.href = getBaseUrl() + "/dashboard"; // They clicked Yes }) .error(function (data, status, header, config) { console.log('error'); alert('Incorrect username or password '); }); }; });
const assert = require("assert"); const count = require("../problems/08-count.js"); describe("count", function() { it("", function() { let result1 = count([18, 5, 32, 7, 100], function(n) { return n % 2 === 0; }); assert.equal(result1, 3); let result2 = count([17, 5, 31, 7, 100], function(n) { return n % 2 === 0; }); assert.equal(result2, 1); let result3 = count(["follow", "the", "yellow", "brick", "road"], function( str ) { return str.includes("o"); }); assert.equal(result3, 3); let result4 = count(["follow", "the", "yellow", "brick", "road"], function( str ) { return str.includes("x"); }); assert.equal(result4, 0); }); });
from tir import Webapp import unittest import time #//------------------------------------------------------------------- #/*/{Protheus.doc} MATA320 - recalculo de custo #@author JEFFERSON SILVA DE SOUSA #@since 16/10/2019 #@version 1.0 #/*/ #//------------------------------------------------------------------- class MATA320(unittest.TestCase): @classmethod def setUpClass(inst): ''' SETUP Test Case Initial Setup ''' #Endereço do webapp e o nome do Browser inst.oHelper = Webapp() #Parametros de inicializaçao inst.oHelper.Setup("SIGAEST","16/10/2019","T1","D MG 01 ","04") #Nome da rotina do Caso de Teste inst.oHelper.Program("MATA320") #CT001 Calculo de custo com base na estrutura def test_MATA320_001(self): Cod = 'ESTSE0000000000000000000000565' Custo = 0 #Variaveis de Verificaçao self.oHelper.SetButton("Parâmetros") self.oHelper.SetValue("Utilizar Qual Moeda ?", 'Nenhuma') self.oHelper.SetValue("Utilizar Taxa ?", 'Mensal') self.oHelper.SetValue('Calcular os Custos Por ?',"Estrutura") self.oHelper.SetValue('Considerar Ult. Preco Compra ?',"Sim") self.oHelper.SetValue('Dt.Final Ref.Taxa ?',"16/10/2019") self.oHelper.SetValue('Do Tipo do Produto',"") self.oHelper.SetValue('Ate o Tipo do Produto',"ZZ") self.oHelper.SetValue('Do Grupo do Produto',"EST1") self.oHelper.SetValue('Ate o Grupo do Produto',"EST1") self.oHelper.SetValue("Considerar Qtdes. Negativa ?", 'Sim') self.oHelper.SetValue("Avisar Divergencia ?", 'Atualizar') self.oHelper.SetValue("Seleciona filiais ?", 'Nao') self.oHelper.SetValue("Considera Mão de Obra?", 'Ambos') self.oHelper.SetValue("Considera Tipo Dec. OP ?", 'Sim') self.oHelper.SetButton("Ok") self.oHelper.SetButton("Ok") ####################################################### ## Verificando se atualizou o valor de custo do PA ## ####################################################### self.oHelper.SetLateralMenu("Atualizações > Cadastros > Produto > Produtos") #self.oHelper.WaitShow("Atualizacao de Produtos") time.sleep(3) self.oHelper.SearchBrowse(f"D MG 01 {Cod}", "Filial+codigo") self.oHelper.SetButton("Visualizar") time.sleep(4) Custo = float(self.oHelper.GetValue("B1_CUSTD").replace(",",".")) self.oHelper.SetButton("Fechar") self.oHelper.SetKey("ESC") self.oHelper.Program('MATA320') Custo > 0 self.oHelper.AssertTrue() def test_MATA320_002(self): #self.oHelper.WaitShow("Recálculo do Custo de Reposição") time.sleep(3) self.oHelper.SetButton("Parâmetros") self.oHelper.SetValue("Utilizar Qual Moeda ?", 'Nenhuma') self.oHelper.SetValue("Utilizar Taxa ?", 'Mensal') self.oHelper.SetValue('Calcular os Custos Por ?',"Ult Cust Compra") self.oHelper.SetValue('Considerar Ult. Preco Compra ?',"Sim") self.oHelper.SetValue('Dt.Final Ref.Taxa ?',"16/10/2019") self.oHelper.SetValue('Do Tipo do Produto',"") self.oHelper.SetValue('Ate o Tipo do Produto',"ZZ") self.oHelper.SetValue('Do Grupo do Produto',"EST1") self.oHelper.SetValue('Ate o Grupo do Produto',"EST1") self.oHelper.SetValue("Considerar Qtdes. Negativa ?", 'Nao') self.oHelper.SetValue("Avisar Divergencia ?", 'Atualizar') self.oHelper.SetValue("Seleciona filiais ?", 'Nao') self.oHelper.SetValue("Considera Mão de Obra?", 'Rot. Operações') self.oHelper.SetValue("Considera Tipo Dec. OP ?", 'Sim') self.oHelper.SetButton("Ok") self.oHelper.AssertTrue() def test_MATA320_003(self): #self.oHelper.WaitShow("Recálculo do Custo de Reposição") time.sleep(3) self.oHelper.SetButton("Parâmetros") self.oHelper.SetValue("Utilizar Qual Moeda ?", '2a moeda') self.oHelper.SetValue("Utilizar Taxa ?", 'Diaria') self.oHelper.SetValue('Calcular os Custos Por ?',"Ult Prec Compra") self.oHelper.SetValue('Considerar Ult. Preco Compra ?',"Sim") self.oHelper.SetValue('Dt.Final Ref.Taxa ?',"16/10/2019") self.oHelper.SetValue('Do Tipo do Produto',"") self.oHelper.SetValue('Ate o Tipo do Produto',"ZZ") self.oHelper.SetValue('Do Grupo do Produto',"EST1") self.oHelper.SetValue('Ate o Grupo do Produto',"EST1") self.oHelper.SetValue("Considerar Qtdes. Negativa ?", 'Nao') self.oHelper.SetValue("Avisar Divergencia ?", 'Atualizar') self.oHelper.SetValue("Seleciona filiais ?", 'Nao') self.oHelper.SetValue("Considera Mão de Obra?", 'Rot. Operações') self.oHelper.SetValue("Considera Tipo Dec. OP ?", 'Sim') self.oHelper.SetButton("Ok") self.oHelper.AssertTrue() @classmethod def tearDownClass(inst): ''' Method that finishes the test case. ''' inst.oHelper.TearDown() if __name__ == '__main__': unittest.main()
import { SET_AUTHED_USER } from '../actions/authedUser' export default function authedUser (state = null, action) { switch(action.type) { case SET_AUTHED_USER: return action.id default: return state } }
/* * @Author: yinseng * @Date: 2016-10-17 09:04:22 * @Last Modified by: yinseng * @Last Modified time: 2016-10-26 11:48:22 */ (function() { app.service('genfunc', ['$http', '$rootScope', '$window', function($http, $rootScope, $window) { var public_method = { // header path getSessionId: function() { var session = $('meta[name="api:session"]');         session = session ? session.attr('content') : ''; return session; }, getLang: function() { var _lang = $('meta[name="se:lang"]');         _lang = _lang ? _lang.attr('content') : ''; return _lang; }, getUrlLang: function(){ var _lang = $('meta[name="se:lang"]');         _lang = _lang ? _lang.attr('content') : ''; if(_lang == 'kh' || _lang == '') return ''; else return '/'+_lang; }, getURL: function() { var _domain = $('meta[name="se:url"]');         _domain = _domain ? _domain.attr('content') : ''; return atob(_domain); }, getToken: function() { var token = $('meta[name="api:bearer"]'); token = token ? token.attr('content') : ''; return token; }, getRequestId: function() { var request = $('meta[name="api:request"]'); request = request ? request.attr('content') : ''; return request; }, getUser : function(){ var user = $('meta[name="se:info"]'); user = user ? user.attr('content') : ''; // console.log("user",user); if(!user || user== "undefined") return ''; user = atob(user); // console.log(user); return JSON.parse(user); }, getRemote: function(){ var remote = $('meta[name="se:remoteUrl"]'); remote = remote ? remote.attr('content') : ''; return atob(remote); }, timeFromNow: function(date) { if(!date) return moment().local().fromNow(); // check null and is valid date formate if (typeof moment != "undefined" && (!date || !moment(date).isValid())) return; // if timesteam conver to string if (_.isNumber(date)) { date = new Date(date); } // return moment([moment(date).get('year'), moment(date).get('month'), moment(date).get('date')]).local().fromNow(); return moment(date).local().fromNow(); }, formatMoney: function() { Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; }, // local storage addLocalstorage: function(storage, scope, data) { var obj = JSON.parse(localStorage.getItem(storage)); obj.result.push(data.result); localStorage.setItem(storage, JSON.stringify(obj)); scope.push(data.result); }, updateLocalstorage: function(storage, scope, data) {}, deleteLocalstorage: function(storage, scope, _id) { scope = _.filter(scope, function(v) { return v._id != _id; }); public_method.modifyLocalstorage(storage, scope); return scope; }, modifyLocalstorage: function(storage, scope) { localStorage.setItem(storage, JSON.stringify(scope)); }, setNavPath: function(_path) { localStorage.navPath = _path; }, getNavPath: function() { $rootScope.path = localStorage.navPath; }, // date functions convertLocalDate: function(_date) { return _date ? moment.utc(_date).local().format('DD MMM YYYY') : null; }, // validation isNumber: function(n) { return !isNaN(parseFloat(n)) && isFinite(n); }, // handle error onError: function(data, status, headers, config) { if (status == 500) { console.dir(data); } if (status == 401) { console.dir(data); } }, toPercent: function(total, amount) { return Math.round(amount / total * 100) || 0; }, callLayzr: function(time) { setTimeout(function() { var layzr = new Layzr({ container: "category-item-listing", selector: '[data-layzr]', attr: 'data-layzr', retinaAttr: 'data-layzr-retina', bgAttr: 'data-layzr-bg', hiddenAttr: 'data-layzr-hidden', threshold: 50, callback: null }); }, time); }, notify: function(status, message, duration) { console.log('duration', duration); UIkit.notify(message, { status: status, pos: 'top-center', timeout: duration || 2000 }); }, closeSpinner: function(uri, data, headers, query) { $('.spinner-container').addClass('spinner-close'); }, openSpinner: function(uri, data, headers, query) { $('.spinner-container').removeClass('spinner-close'); }, hideElement: function(selector) { $(selector).addClass('disable-display'); }, showElement: function(selector) { $(selector).removeClass('disable-display'); } }; return public_method; }]); }());
const STAR_MAPPING = { 5: '\u2605\u2605\u2605\u2605\u2605', 4: '\u2605\u2605\u2605\u2605\u2606', 3: '\u2605\u2605\u2605\u2606\u2606', 2: '\u2605\u2605\u2606\u2606\u2606', 1: '\u2605\u2606\u2606\u2606\u2606', 0: '\u2606\u2606\u2606\u2606\u2606' } const REVERSE_STAR_MAPPING = { '\u2605\u2605\u2605\u2605\u2605': 5, '\u2605\u2605\u2605\u2605\u2606': 4, '\u2605\u2605\u2605\u2606\u2606': 3, '\u2605\u2605\u2606\u2606\u2606': 2, '\u2605\u2606\u2606\u2606\u2606': 1, '\u2606\u2606\u2606\u2606\u2606': 0 } const LETTER_SOUNDS = { 'ā': 'assets/letter_a_bar.mp3', 'b': 'assets/letter_b.mp3', 't': 'assets/letter_t.mp3', 'th': 'assets/letter_th.mp3', 'dj': 'assets/letter_dj.mp3', 'ḥ': 'assets/letter_h_dot.mp3', 'kh': 'assets/letter_kh.mp3', 'd': 'assets/letter_d.mp3', 'dh': 'assets/letter_dh.mp3', 'r': 'assets/letter_r.mp3', 'z': 'assets/letter_z.mp3', 's': 'assets/letter_s.mp3', 'sh': 'assets/letter_sh.mp3', 'ṣ': 'assets/letter_s_dot.mp3', 'ḍ': 'assets/letter_d_dot.mp3', 'ṭ': 'assets/letter_t_dot.mp3', 'ẓ': 'assets/letter_z_dot.mp3', 'ʿ / ‘': 'assets/letter_3.mp3', 'gh': 'assets/letter_3_dot.mp3', 'f': 'assets/letter_f.mp3', 'q': 'assets/letter_q.mp3', 'k': 'assets/letter_k.mp3', 'l': 'assets/letter_l.mp3', 'm': 'assets/letter_m.mp3', 'n': 'assets/letter_n.mp3', 'h': 'assets/letter_h.mp3', 'ou': 'assets/letter_w.mp3', 'i': 'assets/letter_y.mp3', } const WORD_SOUNDS = { 'ح ب ي ب ي': 'assets/habibi.mp3', 'خ ي ار': 'assets/khiar.mp3', 'ت ب و ل ة': 'assets/tabboule.mp3', 'ث و م': 'assets/thoum.mp3', 'د ج ا ج': 'assets/djedj.mp3', 'ذ ر ة': 'assets/dhara.mp3', 'ر ز': 'assets/roz.mp3', 'ش م س': 'assets/shams.mp3', 'ص و ص أ ص ف ر': 'assets/souss asfar.mp3', 'ض و': 'assets/daouw.mp3', 'ب ط ا ط ا': 'assets/batata.mp3', 'ظ ل': 'assets/zol.mp3', 'ع ي د ا': 'assets/aida.mp3', 'غ س ل ا ل ي د ي ن': 'assets/rassil al idain.mp3', 'ق م ر': 'assets/qamar.mp3', 'ك ل ب': 'assets/kalb.mp3', 'ن و ر': 'assets/nuur.mp3', 'ه ذ ا': 'assets/haida.mp3' } const LETTER_MAPPING = { 'ā': 'ا', 'b': 'ب', 't': 'ت', 'th': 'ث', 'dj': 'ج', 'ḥ': 'ح', 'kh': 'خ', 'd': 'د', 'dh': 'ذ', 'r': 'ر', 'z': 'ز', 's': 'س', 'sh': 'ش', 'ṣ': 'ص', 'ḍ': 'ض', 'ṭ': 'ط', 'ẓ': 'ظ', 'ʿ / ‘': 'ع', 'gh': 'غ', 'f': 'ف', 'q': 'ق', 'k': 'ك', 'l': 'ل', 'm': 'م', 'n': 'ن', 'h': 'ه', 'ou': 'و', 'i': 'ي', } const LEVEL1 = [ ['recognition', ['ā', 'ou', 'i']], ['drawing', ['ā', 'ou', 'i']] ] const LEVEL2 = [ ['recognition', ['b', 't', 'th']], ['drawing', ['b', 't', 'th']], ['recognition', ['ā', 'ou', 'i', 'b', 't', 'th']], ['drawing', ['ā', 'ou', 'i', 'b', 't', 'th']] ] const LEVEL3 = [ ['recognition', ['dj', 'ḥ', 'kh']], ['drawing', ['dj', 'ḥ', 'kh']], ['recognition', ['ā', 'ou', 'i', 'b', 't', 'th', 'dj', 'ḥ', 'kh']], ['drawing', ['ā', 'ou', 'i', 'b', 't', 'th', 'dj', 'ḥ', 'kh']] ] const LEVEL4 = [ ['recognition', ['d', 'dh', 'r', 'z']], ['drawing', ['d', 'dh', 'r', 'z']], ['recognition', ['t', 'th', 'dj', 'ḥ', 'kh', 'd', 'dh', 'r', 'z']], ['drawing', ['t', 'th', 'dj', 'ḥ', 'kh', 'd', 'dh', 'r', 'z']] ] const LEVEL5 = [ ['recognition', ['s', 'sh', 'ṣ', 'ḍ']], ['drawing', ['s', 'sh', 'ṣ', 'ḍ']], ['recognition', ['d', 'dh', 'r', 'z', 's', 'sh', 'ṣ', 'ḍ']], ['drawing', ['d', 'dh', 'r', 'z', 's', 'sh', 'ṣ', 'ḍ']], ] const LEVEL6 = [ ['recognition', ['ṭ', 'ẓ', 'ʿ / ‘', 'gh']], ['drawing', ['ṭ', 'ẓ', 'ʿ / ‘', 'gh']], ['recognition', ['z', 's', 'sh', 'ṣ', 'ḍ', 'ṭ', 'ẓ', 'ʿ / ‘', 'gh']], ['drawing', ['z', 's', 'sh', 'ṣ', 'ḍ', 'ṭ', 'ẓ', 'ʿ / ‘', 'gh']], ] const LEVEL7 = [ ['recognition', ['f', 'q', 'k']], ['drawing', ['f', 'q', 'k']], ['recognition', ['ṭ', 'ẓ', 'ʿ / ‘', 'gh', 'f', 'q', 'k']], ['drawing', ['ṭ', 'ẓ', 'ʿ / ‘', 'gh', 'f', 'q', 'k']] ] const LEVEL8 = [ ['recognition', ['l', 'm', 'n', 'h']], ['drawing', ['l', 'm', 'n', 'h']], ['recognition', ['f', 'q', 'k', 'l', 'm', 'n', 'h']], ['drawing', ['f', 'q', 'k', 'l', 'm', 'n', 'h']], ] // emphatiques et consoeurs const LEVEL9 = [ ['recognition', ['ṣ', 'ḍ', 'ṭ', 'ẓ']], ['drawing', ['ṣ', 'ḍ', 'ṭ', 'ẓ']], ['recognition', ['s', 'd', 't', 'z']], ['drawing', ['s', 'd', 't', 'z']], ['recognition', ['ṣ', 'ḍ', 'ṭ', 'ẓ', 's', 'd', 't', 'z']], ['drawing', ['ṣ', 'ḍ', 'ṭ', 'ẓ', 's', 'd', 't', 'z']], ] const LEVELS = [LEVEL1, LEVEL2, LEVEL3, LEVEL4, LEVEL5, LEVEL6, LEVEL7, LEVEL8, LEVEL9] function randInt(N) { // returns integer between O and N-1 return Math.floor(Math.random() * N); } /* Sketcher related stuff */ const DRAW_INTERACTIVE = { firstPointSize: 3, lineWidth: 3, strokeStyle: '#F0F', fillStyle: '#F0F', lineCap: 'round', lineJoin: 'round', miterLimit: 10 } function centerStroke(stroke, offsetX, offsetY) { let centers_x = [] let centers_y = [] for (let curve in stroke) { var xmean = 0; var ymean = 0; for (let point in stroke[curve]) { xmean += stroke[curve][point][0]; ymean += stroke[curve][point][1]; } xmean /= stroke[curve].length; ymean /= stroke[curve].length; centers_x.push(xmean); centers_y.push(ymean); } var newStroke = [] for (let curve in stroke) { var newCurve = [] xmean = centers_x[curve] - offsetX; ymean = centers_y[curve] - offsetY; for (let point in stroke[curve]) { newCurve.push([stroke[curve][point][0] - xmean, stroke[curve][point][1] - ymean]); } newStroke.push(newCurve); } return newStroke; } var strokesCorrectAnswer = [ [ [181, 121], [184, 123], [185, 126], [187, 128], [189, 131], [192, 134], [195, 138], [197, 140], [199, 143], [201, 145], [203, 148], [205, 149], [206, 151], [208, 152], [209, 154], [210, 155], [211, 156], [213, 158], [214, 159], [215, 161], [216, 161], [217, 162], [217, 163], [218, 163], [218, 164], [219, 164], [219, 162], [221, 159], [223, 155], [225, 151], [227, 147], [229, 143], [230, 139], [232, 136], [234, 133], [236, 129], [237, 125], [239, 122], [243, 117], [246, 113], [249, 109], [252, 104], [255, 101], [258, 97], [260, 93], [263, 88], [267, 83], [270, 78], [271, 72], [273, 69], [275, 64], [276, 62], [276, 61], [277, 60], [277, 59], [277, 59], [277, 59] ], ]; var strokesIncorrectAnswer = [ [ [176, 62], [178, 62], [183, 64], [188, 69], [196, 75], [204, 81], [218, 92], [230, 100], [240, 107], [249, 113], [256, 118], [261, 122], [267, 128], [272, 133], [275, 137], [277, 141], [280, 145], [281, 146], [282, 148], [283, 148], [283, 149], [283, 149], [283, 149], [284, 150], [286, 151], [287, 152], [288, 152], [289, 153], [290, 153], [290, 154] ], [ [172, 160], [172, 159], [172, 157], [174, 153], [177, 149], [183, 142], [188, 136], [192, 131], [197, 124], [201, 121], [205, 116], [208, 112], [212, 108], [216, 104], [219, 101], [223, 98], [227, 94], [233, 90], [235, 88], [240, 84], [243, 81], [250, 75], [256, 70], [261, 66], [264, 62], [269, 58], [274, 54], [277, 51], [280, 48], [282, 47], [283, 46], [283, 46], [284, 46] ] ] // let's define a global sketch variable var sketcher; /* disable scrolling helper functions based on https://stackoverflow.com/questions/4770025/how-to-disable-scrolling-temporarily */ // left: 37, up: 38, right: 39, down: 40, // spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 var keys = { 37: 1, 38: 1, 39: 1, 40: 1 }; function preventDefault(e) { e.preventDefault(); } function preventDefaultForScrollKeys(e) { if (keys[e.keyCode]) { preventDefault(e); return false; } } // modern Chrome requires { passive: false } when adding event var supportsPassive = false; try { window.addEventListener("test", null, Object.defineProperty({}, 'passive', { // eslint-disable-next-line getter-return get: function() { supportsPassive = true; } })); // eslint-disable-next-line no-empty } catch (e) {} var wheelOpt = supportsPassive ? { passive: false } : false; var wheelEvent = 'onwheel' in document.createElement('div') ? 'wheel' : 'mousewheel'; // call this to Disable function disableScroll() { window.addEventListener('DOMMouseScroll', preventDefault, false); // older FF window.addEventListener(wheelEvent, preventDefault, wheelOpt); // modern desktop window.addEventListener('touchmove', preventDefault, wheelOpt); // mobile window.addEventListener('keydown', preventDefaultForScrollKeys, false); } // call this to Enable function enableScroll() { window.removeEventListener('DOMMouseScroll', preventDefault, false); window.removeEventListener(wheelEvent, preventDefault, wheelOpt); window.removeEventListener('touchmove', preventDefault, wheelOpt); window.removeEventListener('keydown', preventDefaultForScrollKeys, false); } /** * Actual game logic starts here. */ function updateExerciseProgressBar(isFinished = false) { // updates progress bar var quizzData = document.getElementById('game-area').quizzData; var progressBar = document.getElementById('progress-bar'); if (isFinished) { progressBar.innerHTML = 'Question : ' + (quizzData['correct'] + quizzData['incorrect']) + '/' + quizzData['total'] + ' | Correctes : ' + quizzData['correct'] + '/' + (quizzData['correct'] + quizzData['incorrect']); } else { progressBar.innerHTML = 'Question : ' + (quizzData['correct'] + quizzData['incorrect'] + 1) + '/' + quizzData['total'] + ' | Correctes : ' + quizzData['correct'] + '/' + (quizzData['correct'] + quizzData['incorrect']); } } function generateNewRecognitionQuestion() { // sets up a new question var taskLetters = document.getElementById('game-area').taskLetters if (document.getElementById('game-area').hasAttributes('answer')) { // generate a new random letter that is not the same as the previous one var previousValue = document.getElementById('game-area').answer; var possibletaskLetters = taskLetters .filter(function(value) { return value != previousValue; }); randomAnswer = possibletaskLetters[randInt(possibletaskLetters .length)]; randomLetter = LETTER_MAPPING[randomAnswer]; } else { // generate any new random letter the first time we start the game var randomAnswer = taskLetters[randInt(taskLetters .length)]; var randomLetter = LETTER_MAPPING[randomAnswer]; } // saving the new answer for later document.getElementById('game-area').answer = randomAnswer; // drawing the new letter on the canvas drawLetterOnCanvas(randomLetter); // update progress bar updateExerciseProgressBar(); } function clearCanvas() { var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); sketcher.handler(function(elem, data) { data.sketch.beginPath() .lineStyle('gray', 3) .line(0, 200, 500, 200) .stroke() .closePath() }); } function drawLetterOnCanvas(randomLetter, clearBeforeDrawing = true) { if (clearBeforeDrawing) { clearCanvas(); } var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.font = "280px Amiri"; ctx.fillStyle = 'black'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(randomLetter, canvas.width / 2., canvas.height / 2.); } function showRightWrongAnswer(caller) { if (document.getElementById('game-area').answer == caller.innerHTML) { document.getElementById('game-area').quizzData['correct'] += 1; sketcher.config({ interactive: false, graphics: { lineWidth: 20, strokeStyle: 'green' }, }); sketcher.clear() sketcher.strokes(centerStroke(strokesCorrectAnswer, sketcher.elem.width / 2., sketcher.elem.height / 2.)) .animate.strokes() // add some button highlights caller.classList.toggle('right-answer'); setTimeout(function() { caller.classList.toggle("right-answer"); }, 1500); } else { document.getElementById('game-area').quizzData['incorrect'] += 1; sketcher.config({ interactive: false, graphics: { lineWidth: 20, strokeStyle: 'red' } }); sketcher.clear() sketcher.strokes(centerStroke(strokesIncorrectAnswer, sketcher.elem.width / 2., sketcher.elem.height / 2.)) .animate.strokes() // add some highlights to buttons correct/incorrect caller.classList.toggle("wrong-answer"); setTimeout(function() { caller.classList.toggle("wrong-answer"); }, 1500); let buttons = document.getElementsByClassName('quizz-button'); for (let button of buttons) { if (button.innerHTML == document.getElementById('game-area').answer) { button.classList.toggle('right-answer'); setTimeout(function() { button.classList.toggle("right-answer"); }, 1500); break; } } } } function validateRecognitionAnswer(e) { var quizzData = document.getElementById('game-area').quizzData; var caller = e.target || e.srcElement; if (quizzData['correct'] + quizzData['incorrect'] < quizzData['total'] - 1) { // there are still questions left showRightWrongAnswer(caller); setTimeout(generateNewRecognitionQuestion, 1500); } else { // this exercise is now finished showRightWrongAnswer(caller); setTimeout(function() { finishExercise(quizzData) }, 1500); } } function finishExercise(quizzData) { /** * The game is finished: display dialog and update main interface. * */ var chapter, exercise, correct, incorrect; [correct, incorrect] = [quizzData['correct'], quizzData['incorrect']]; [chapter, exercise] = document.getElementById('game-area').currentLevel; let starScore = updateStarRating(chapter, exercise, correct, incorrect); document.getElementById('myCanvas').style.display = "none"; let infoBox = document.getElementById('canvas-data'); infoBox.hidden = false; infoBox.innerHTML = `Bravo ! Vous venez de finir cet exercice. <br> Vous avez donné ${correct} bonne(s) réponse(s) et ${incorrect} mauvaise(s) réponse(s). <br> Votre score est de ${starScore}.` updateExerciseProgressBar(true); updateChapterProgress(); saveProgress(); // if it's a drawing exercise we also disable the bottom buttons document.getElementById('drawing-correct-answer').disabled = true; document.getElementById('drawing-incorrect-answer').disabled = true; } function toggleGameAreaModal() { var gameArea = document.getElementById('game-area'); if (gameArea.className.indexOf('open') > -1) { // indexOf returns -1 when the string is not found gameArea.className = gameArea.className.replace('open', ''); enableScroll(); // deactivate interactive drawing when modal dialog is closed sketcher.config({ interactive: false }); sketcher.clear(); } else { // the else here means that the string was not found gameArea.className = gameArea.className + ' open'; disableScroll(); } } // eslint-disable-next-line no-unused-vars function setupLevels() { /** * Parse level descriptions and insert nested level layout into HTML. */ var root = document.getElementById('levels-container'); for (let chapterIndex in LEVELS) { // create level heading var levelRoot = document.createElement('details'); levelRoot.id = `details-chapter${chapterIndex}`; levelRoot.open = true; var levelSummary = document.createElement('summary'); var levelHeader = document.createElement('em') levelHeader.innerHTML = 'Chapitre ' + (parseInt(chapterIndex) + 1); levelHeader.innerHTML += ` <span class="chapter-progress" id="chapter-progress-${chapterIndex}">0%</span>` levelSummary.appendChild(levelHeader) levelRoot.appendChild(levelSummary) // chapter description // level's new letters var levelLetters = []; var transcribedLevelLetters = []; for (let letter of LEVELS[chapterIndex][0][1]) { levelLetters.push(LETTER_MAPPING[letter]); transcribedLevelLetters.push(letter); } // eslint-disable-next-line no-undef levelLetters = [...new Set(levelLetters)]; // eslint-disable-next-line no-undef transcribedLevelLetters = [...new Set(transcribedLevelLetters)]; var div = document.createElement('div'); div.innerHTML = "Nouvelles lettres dans ce chapitre :"; div.className = 'exercise' levelRoot.appendChild(div); var ul = document.createElement('ul'); div.appendChild(ul) for (let letter in levelLetters) { let li = document.createElement('li'); li.innerHTML = `<span class='arabic'>${levelLetters[letter]}</span>, transcrit par ${transcribedLevelLetters[letter]}, prononcé <audio controls> <source src="${LETTER_SOUNDS[transcribedLevelLetters[letter]]}" type="audio/mpeg"> Your browser does not support the audio element.</audio>` ul.appendChild(li); } let validWords = []; for (let word in WORD_SOUNDS) { for (let letter of levelLetters) { if (word.indexOf(letter) != -1) { validWords.push(word); break; } } } div = document.createElement('div'); div.innerHTML = "Mots du lexique s'écrivant avec les lettres introduites dans ce chapitre :"; div.className = 'exercise' levelRoot.appendChild(div); ul = document.createElement('ul'); div.appendChild(ul) for (let word of validWords) { let li = document.createElement('li'); li.innerHTML = `<span class='arabic_smaller'>${word}</span> <audio controls> <source src="${WORD_SOUNDS[word]}" type="audio/mpeg"> Your browser does not support the audio element. </audio> ` ul.appendChild(li); } // create level exercices for (let exerciseIndex in LEVELS[chapterIndex]) { let items = LEVELS[chapterIndex][exerciseIndex] let taskType = items[0]; let taskLetters = items[1]; if (taskType == 'recognition') { let div = document.createElement('div') levelRoot.appendChild(div) div.className = 'exercise' var header = document.createElement('h3') header.appendChild(document.createTextNode('Exercice ' + (parseInt(chapterIndex) + 1) + '.' + (parseInt(exerciseIndex) + 1) + ' : ' + ' Reconnaître les lettres ' + taskLetters .join(' - '))) div.append(header) var linkNode = document.createElement('button') linkNode.appendChild(document.createTextNode('Démarrer le niveau !')) // eslint-disable-next-line no-unused-vars linkNode.addEventListener('click', function(e) { runLevel(chapterIndex, exerciseIndex) }) linkNode.className = 'start-game ' + `start-chapter${chapterIndex}` div.appendChild(linkNode) var stars = document.createElement('div') stars.innerHTML = 'Score : ' + STAR_MAPPING[0] stars.id = `score-chapter${chapterIndex}-exercise${exerciseIndex}` div.appendChild(stars) } else if (taskType == 'drawing') { div = document.createElement('div') levelRoot.appendChild(div) div.className = 'exercise' header = document.createElement('h3') header.appendChild(document.createTextNode('Exercice ' + (parseInt(chapterIndex) + 1) + '.' + (parseInt(exerciseIndex) + 1) + ' : ' + ' Dessiner les lettres ' + taskLetters .join(' - '))) div.append(header) linkNode = document.createElement('button') linkNode.appendChild(document.createTextNode('Démarrer le niveau !')) // eslint-disable-next-line no-unused-vars linkNode.addEventListener('click', function(e) { runLevel(chapterIndex, exerciseIndex) }) linkNode.className = 'start-game ' + `start-chapter${chapterIndex}`; div.appendChild(linkNode) stars = document.createElement('div') stars.innerHTML = 'Score : ' + STAR_MAPPING[0] stars.id = `score-chapter${chapterIndex}-exercise${exerciseIndex}` div.appendChild(stars) } else { console.log('Could not recognize task type: ' + taskType); } } root.appendChild(levelRoot); } // assigning something to our sketchable // eslint-disable-next-line no-undef sketcher = new Sketchable(document.getElementById('myCanvas')); sketcher.config({ interactive: false }); // disabling swipping / scrolling while drawing // https://stackoverflow.com/questions/49047414/disable-scroll-swipe-action-for-html-canvas-drawing-on-ios var canvas_dom = document.getElementById('myCanvas') canvas_dom.addEventListener("touchstart", function(event) { event.preventDefault() }) canvas_dom.addEventListener("touchmove", function(event) { event.preventDefault() }) canvas_dom.addEventListener("touchend", function(event) { event.preventDefault() }) canvas_dom.addEventListener("touchcancel", function(event) { event.preventDefault() }) // update available chapters updateChapterProgress(); // reload previously saved progress loadProgress(); } function shuffleArray(inputArray) { /* Returns a shuffled copy of an array. Adapted from https://medium.com/@nitinpatel_20236/how-to-shuffle-correctly-shuffle-an-array-in-javascript-15ea3f84bfb */ let array = [...inputArray]; // shallow copy of array for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * i); const temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } function runLevel(chapterIndex, exerciseIndex) { /** * Starts a new level defined by chapter and exercise index. */ toggleGameAreaModal(); document.getElementById('myCanvas').style.display = "block"; document.getElementById('canvas-data').hidden = true; var exercise = LEVELS[chapterIndex][exerciseIndex] var taskType = exercise[0]; var taskLetters = exercise[1]; if (taskType == 'recognition') { document.getElementById('game-area').hidden = false; document.getElementById('game-area').currentLevel = [chapterIndex, exerciseIndex] document.getElementById('game-area').taskLetters = taskLetters var buttonArea = document.getElementById('button-area'); // clearing old children while (buttonArea.firstChild) { buttonArea.removeChild(buttonArea.firstChild); } // shuffling taskletters var shuffledTaskLetters = shuffleArray(taskLetters); // adding a button for each letter in the current level for (let i = 0; i < taskLetters .length; i++) { let button = document.createElement('button'); button.innerHTML = shuffledTaskLetters[i]; button.className = 'quizz-button'; buttonArea.appendChild(button); button.addEventListener("click", validateRecognitionAnswer); } // initializing quizz data document.getElementById('game-area').quizzData = { 'total': 32, 'correct': 0, 'incorrect': 0 }; // generating a new quizz question generateNewRecognitionQuestion(); } else if (taskType == 'drawing') { document.getElementById('game-area').hidden = false; document.getElementById('game-area').currentLevel = [chapterIndex, exerciseIndex] document.getElementById('game-area').taskLetters = taskLetters buttonArea = document.getElementById('button-area'); // clearing old children while (buttonArea.firstChild) { buttonArea.removeChild(buttonArea.firstChild); } // creating buttons / text regions for drawing interactions let p = document.createElement('p'); p.id = 'drawing-text-area'; buttonArea.appendChild(p); let button = document.createElement('button'); button.innerHTML = 'Montrer'; button.id = 'drawing-show-answer'; button.className = 'quizz-button'; button.addEventListener('click', showDrawingAnswer) buttonArea.appendChild(button); button = document.createElement('button'); button.innerHTML = '&#10003;' button.id = 'drawing-correct-answer' button.className = 'quizz-button'; button.disabled = true; button.addEventListener('click', validateDrawingAnswer); buttonArea.appendChild(button); button = document.createElement('button'); button.innerHTML = '&#10005;'; button.id = 'drawing-incorrect-answer' button.className = 'quizz-button'; button.disabled = true; button.addEventListener('click', validateDrawingAnswer); buttonArea.appendChild(button); // initializing quizz data document.getElementById('game-area').quizzData = { 'total': 32, 'correct': 0, 'incorrect': 0 }; // generating a new quizz question generateNewDrawingQuestion(); } } function updateStarRating(chapterIndex, exerciseIndex, correct) { // updates the score rating let score; if (correct == 32) { score = 5 } else if (correct >= 30) { score = 4 } else if (correct >= 28) { score = 3 } else if (correct >= 16) { score = 2 } else if (correct >= 8) { score = 1 } else { score = 0 } let previousStars = document.getElementById(`score-chapter${chapterIndex}-exercise${exerciseIndex}`).innerHTML.split('Score : ')[1] let previousScore = REVERSE_STAR_MAPPING[previousStars] if (previousScore < score) { document.getElementById(`score-chapter${chapterIndex}-exercise${exerciseIndex}`).innerHTML = 'Score : ' + STAR_MAPPING[score] } return STAR_MAPPING[score]; } function generateNewDrawingQuestion() { // generates a new question for a drawing task let taskLetters = document.getElementById('game-area').taskLetters let randomAnswer if (document.getElementById('game-area').hasAttributes('answer')) { // generate a new random letter that is not the same as the previous one let previousValue = document.getElementById('game-area').answer; let possibletaskLetters = taskLetters .filter(function(value) { return value != previousValue; }); randomAnswer = possibletaskLetters[randInt(possibletaskLetters .length)]; } else { // generate any new random letter the first time we start the game randomAnswer = taskLetters[randInt(taskLetters .length)]; } // saving the new answer for later document.getElementById('game-area').answer = randomAnswer; // writing new drawing question document.getElementById('drawing-text-area').innerHTML = 'La lettre à dessiner est : ' + randomAnswer; updateExerciseProgressBar(); sketcher.config({ interactive: true, graphics: DRAW_INTERACTIVE, }); document.getElementById('drawing-show-answer').disabled = false; document.getElementById('drawing-correct-answer').disabled = true; document.getElementById('drawing-incorrect-answer').disabled = true; clearCanvas(); } // eslint-disable-next-line no-unused-vars function showDrawingAnswer(e) { // displays the expected letter on the canvas and allows the user to validate his answer drawLetterOnCanvas(LETTER_MAPPING[document.getElementById('game-area').answer], false); document.getElementById('drawing-correct-answer').disabled = false; document.getElementById('drawing-incorrect-answer').disabled = false; document.getElementById('drawing-show-answer').disabled = true; } function validateDrawingAnswer(e) { var caller = e.target || e.srcElement; if (caller.id == 'drawing-correct-answer') { document.getElementById('game-area').quizzData['correct'] += 1; } else { document.getElementById('game-area').quizzData['incorrect'] += 1; } let quizzData = document.getElementById('game-area').quizzData; if (quizzData['correct'] + quizzData['incorrect'] < quizzData['total']) { generateNewDrawingQuestion(); } else { // the game is finished: display dialog and update main interface finishExercise(quizzData); } } // eslint-disable-next-line no-unused-vars function updateChapterProgress() { /** * Updates the HTML headers of each chapters in percentage. Also unlocks the chapters as a function of progress. */ var previousChapterCompleted = true; for (let chapterIndex in LEVELS) { // do the unlocking of chapters based on previous value for (let elem of document.getElementsByClassName(`start-chapter${chapterIndex}`)) { if (previousChapterCompleted) { elem.disabled = false; } else { elem.disabled = true; } } // close details of already finished chapters if (previousChapterCompleted && chapterIndex !== "0") { document.getElementById(`details-chapter${parseInt(chapterIndex) - 1}`).open = false; } let exercicesInChapter = LEVELS[chapterIndex].length; let aboveThreeStars = 0; let aboveFiveStars = 0; for (let exerciseIndex in LEVELS[chapterIndex]) { let previousStars = document.getElementById(`score-chapter${chapterIndex}-exercise${exerciseIndex}`).innerHTML.split('Score : ')[1]; let currentScore = REVERSE_STAR_MAPPING[previousStars] if (currentScore >= 3) { aboveThreeStars += 1; } if (currentScore === 5) { aboveFiveStars += 1; } } // update chapter progress document.getElementById(`chapter-progress-${chapterIndex}`).innerHTML = `${Math.round(aboveThreeStars/ exercicesInChapter * 100)}%`; if (aboveFiveStars === exercicesInChapter) { document.getElementById(`chapter-progress-${chapterIndex}`).innerHTML += ' PERFECT'; } // update the completion indicator for setting the next chapters if (aboveThreeStars === exercicesInChapter) { previousChapterCompleted = true; } else { previousChapterCompleted = false; } } } function loadProgress() { /** * Reloads previous progress data if it exists. */ if (localStorage.getItem('progress') !== null) { console.log('Found existing storage data.'); console.log(localStorage.progress); let split = localStorage.progress.split(','); if (split.length > 1) { let ids = []; let scores = []; for (let i in split) { if (i % 2 === 0) { ids.push(split[i]); } else { scores.push(split[i]); } } for (let i in ids) { document.getElementById(ids[i]).innerHTML = scores[i]; } } } updateChapterProgress(); } function saveProgress() { /** * Saves progress data to browser local storage. */ let savedValues = []; for (let chapterIndex in LEVELS) { for (let exerciseIndex in LEVELS[chapterIndex]) { let id = `score-chapter${chapterIndex}-exercise${exerciseIndex}`; let currentScore = document.getElementById(id).innerHTML; savedValues.push([ [id, currentScore] ]); } } localStorage.progress = savedValues; } // eslint-disable-next-line no-unused-vars function clearProgressAndReset() { /** * Erases locally saved progress and reset all chapter progress to zero. */ localStorage.progress = null; for (let chapterIndex in LEVELS) { for (let exerciseIndex in LEVELS[chapterIndex]) { let id = `score-chapter${chapterIndex}-exercise${exerciseIndex}`; document.getElementById(id).innerHTML = `Score : ${STAR_MAPPING[0]}`; } } updateChapterProgress(); document.getElementById('details-chapter0').open = true; } // eslint-disable-next-line no-unused-vars function unlockAllLevels() { // cheat code for testing purposes only :) for (let chapterIndex in LEVELS) { for (let exerciseIndex in LEVELS[chapterIndex]) { updateStarRating(chapterIndex, exerciseIndex, 32); } } updateChapterProgress(); }
import Icon from '@conveyal/woonerf/components/icon' import Pure from '@conveyal/woonerf/components/pure' import React, {PropTypes} from 'react' import {Navbar, Button, ButtonToolbar, Checkbox} from 'react-bootstrap' import {Link} from 'react-router' import SidebarNavItem from './SidebarNavItem' import SidebarPopover from './SidebarPopover' import JobMonitor from './JobMonitor' import {getConfigProperty} from '../util/config' export default class Sidebar extends Pure { static propTypes = { expanded: PropTypes.bool, jobMonitor: PropTypes.object, username: PropTypes.string, userPicture: PropTypes.string, login: PropTypes.func, logout: PropTypes.func, resetPassword: PropTypes.func, setJobMonitorVisible: PropTypes.func, removeRetiredJob: PropTypes.func, setSidebarExpanded: PropTypes.func, startJobMonitor: PropTypes.func } state = { visiblePopover: null } componentWillReceiveProps (nextProps) { if (!this.props.jobMonitor.timer && nextProps.jobMonitor.timer) { this.setState({ visiblePopover: 'job' }) } } _clickChangePassword = () => { this.setState({visiblePopover: null}) this.props.resetPassword() } _clickLogOut = () => { this.setState({visiblePopover: null}) this.props.logout() } _clickRevokeToken = () => { this.setState({visiblePopover: null}) this.props.revokeToken() } _closePopover = () => this.setState({visiblePopover: null}) _select = (key) => this.setState({visiblePopover: (key === this.state.visiblePopover) ? null : key}) _selectHelp = () => this._select('help') _selectJob = () => this._select('job') _selectUser = () => this._select('user') _toggleLabels = () => this.props.setSidebarExpanded(!this.props.expanded) _toggleTutorial = () => this.props.setTutorialHidden(!this.props.hideTutorial) render () { const {children, expanded, userPicture} = this.props const navbarStyle = { width: expanded ? 130 : 50, minHeight: '500px' } const hasActiveJobs = this.props.jobMonitor.jobs.length > 0 return ( <div className='Sidebar'> <Navbar inverse style={navbarStyle}> <Brand expanded={expanded === true} /> <div className='TopNav'> {children} </div> <div className='BottomNav'> <SidebarNavItem ref='jobNav' expanded={expanded} icon={hasActiveJobs ? 'refresh' : 'bell'} loading={hasActiveJobs} finished={this.props.jobMonitor.jobs.length === 0 && this.props.jobMonitor.retired.length > 0} label='Server jobs' onClick={this._selectJob} /> <SidebarNavItem ref='userNav' expanded={expanded} icon='user' label='Account' image={userPicture} onClick={this._selectUser} /> <SidebarNavItem ref='settingsNav' expanded={expanded} icon='gear' label='Settings' onClick={this._selectHelp} /> </div> </Navbar> <JobMonitor jobMonitor={this.props.jobMonitor} target={this.refs.jobNav} expanded={this.props.expanded} visible={this.state.visiblePopover === 'job'} close={this._closePopover} removeRetiredJob={this.props.removeRetiredJob} /> <SidebarPopover target={this.refs.userNav} title={this.props.username} expanded={this.props.expanded} visible={this.state.visiblePopover === 'user'} close={this._closePopover}> <ButtonToolbar> <Button bsSize='small' bsStyle='info' onClick={this._clickChangePassword}>Change password </Button> {getConfigProperty('application.dev') ? <Button bsSize='small' bsStyle='info' onClick={this._clickRevokeToken}><Icon type='sign-out' /> Revoke token </Button> : null } <Button bsSize='small' bsStyle='info' onClick={this._clickLogOut}><Icon type='sign-out' /> Log out </Button> </ButtonToolbar> </SidebarPopover> <SidebarPopover target={this.refs.settingsNav} title='Settings' expanded={this.props.expanded} visible={this.state.visiblePopover === 'help'} close={this._closePopover}> <div> <Checkbox ref='showLabelsCheckbox' checked={this.props.expanded} onChange={this._toggleLabels}> Show Sidebar Labels </Checkbox> <Checkbox ref='showTutorialCheckbox' checked={this.props.hideTutorial} onChange={this._toggleTutorial}> Hide editor tutorial </Checkbox> </div> </SidebarPopover> </div> ) } } class Brand extends Pure { static propTypes = { expanded: PropTypes.bool.isRequired } render () { const {expanded} = this.props return ( <Link to='/home'> <div className='LogoContainer'> <div className='Logo' /> {expanded && <div className='LogoLabel'>Transit<br />Café</div>} <div className='clearfix' /> </div> </Link> ) } }
import codecs from setuptools import setup lines = codecs.open('README', 'r', 'utf-8').readlines()[3:] lines.append('\n') lines.extend(codecs.open('CHANGES', 'r', 'utf-8').readlines()[1:]) desc = ''.join(lines).lstrip() import translitcodec version = translitcodec.__version__ setup(name='translitcodec', version=version, description='Unicode to 8-bit charset transliteration codec', long_description=desc, long_description_content_type='text/x-rst', author='Jason Kirtland', author_email='jek@discorporate.us', url='https://github.com/claudep/translitcodec', packages=['translitcodec'], license='MIT License', python_requires='>=3', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', ], )
/** * Tms Source Handler * @author Paul Schmidt */ Mapbender.Geo.TmsSourceHandler = Class({ 'extends': Mapbender.Geo.SourceHandler }, { 'private object defaultOptions': { }, 'private string layerNameIdent': 'identifier', 'public function create': function(sourceOpts) { var rootLayer = sourceOpts.configuration.children[0]; // if (sourceOpts.configuration.status !== 'ok') { //deactivate corrupte or unreachable sources // rootLayer.options.treeOptions.selected = false; // rootLayer.options.treeOptions.allow.selected = false; // } function _setProperties(layer, parent, id, num, proxy) { /* set unic id for a layer */ layer.options.origId = layer.options.id; layer.options.id = parent ? parent.options.id + "_" + num : id + "_" + num; if (proxy && layer.options.legend) { if (layer.options.legend.graphic) { layer.options.legend.graphic = Mapbender.Util.addProxy(layer.options.legend.graphic); } else if (layer.options.legend.url) { layer.options.legend.url = Mapbender.Util.addProxy(layer.options.legend.url); } } if (layer.children) { for (var i = 0; i < layer.children.length; i++) { _setProperties(layer.children[i], layer, id, i, proxy); } } } _setProperties(rootLayer, null, sourceOpts.id, 0, sourceOpts.configuration.options.proxy); var proj = Mapbender.Model.getCurrentProj(); var layer = this.findLayerEpsg(sourceOpts.configuration.layers, proj.projCode, true); if (!layer) { // find first layer with epsg from srs list to initialize. var allsrs = Mapbender.Model.getAllSrs(); for (var i = 0; i < allsrs.length; i++) { layer = this.findLayerEpsg(sourceOpts.configuration.layers, allsrs[i].name, true); if (layer) { break; } } } rootLayer['children'] = [layer]; var layerOptions = this.createLayerOptions(layer, sourceOpts.configuration.options.proxy, null); // hide layer without start srs -> remove name var mqLayerDef = { type: 'tms', isBaseLayer: false, opacity: sourceOpts.configuration.options.opacity, visible: sourceOpts.configuration.options.visible, attribution: sourceOpts.configuration.options.attribution }; $.extend(layerOptions, mqLayerDef, this.defaultOptions); return layerOptions; }, 'public function postCreate': function(source, mqLayer) { this.changeProjection(source, Mapbender.Model.getCurrentProj()); }, 'private function createLayerOptions': function(layer, proxy, olLayer) { var layerOptions = { label: layer.options.title, layer: layer.options.identifier, tileOrigin: OpenLayers.LonLat.fromArray(layer.options.tilematrixset.origin), tileSize: new OpenLayers.Size(layer.options.tilematrixset.tileSize[0], layer.options.tilematrixset.tileSize[1]), url: proxy ? Mapbender.Util.addProxy(layer.options.url) : layer.options.url }; if (olLayer) { layerOptions['format'] = olLayer.format === layer.options.format ? olLayer.format : layer.options.format; layerOptions['formatSuffix'] = olLayer.format === layer.options.format ? olLayer.formatSuffix : layer.options.format.substring(layer.options.format.indexOf('/') + 1); layerOptions['params'] = { LAYERS: [layer.options.identifier] }; } return layerOptions; }, 'private function findLayerEpsg': function(layers, epsg, clone) { for (var i = 0; i < layers.length; i++) { if (epsg === layers[i].options.tilematrixset.supportedCrs) { return clone ? $.extend(true, {}, layers[i]) : layers[i]; } } return null; }, 'public function onLoadStart': function(source) { this.enable(source, 'loadError'); }, 'public function onLoadError': function(imgEl, sourceId, projection, callback) { this['super']('onLoadError', imgEl, sourceId, projection, callback); }, 'private function enable': function(source, tagname) { var options = { layers: {} }; if (source.configuration.children[0][tagname]) { options.layers[source.configuration.children[0].options.id] = { options: { treeOptions: { selected: source.configuration.children[0][tagname].selected, allow: { selected: source.configuration.children[0][tagname].allow.selected } } } }; delete(source.configuration.children[0][tagname]); var toChangeOptions = { change: { options: { children: options.layers, type: "selected" }, sourceIdx: { id: source.id } } }; Mapbender.Model.changeSource(toChangeOptions); } }, 'private function disable': function(source, tagname) { source.configuration.children[0][tagname] = { selected: source.configuration.children[0].options.treeOptions.selected, allow: { selected: source.configuration.children[0].options.treeOptions.allow.selected } }; var options = { layers: {} }; options.layers[source.configuration.children[0].options.id] = { options: { treeOptions: { selected: false, allow: { selected: false } } } }; var toChangeOptions = { change: { options: { children: options.layers, type: "selected" }, sourceIdx: { id: source.id } } }; Mapbender.Model.changeSource(toChangeOptions); }, 'public function featureInfoUrl': function(mqLayer, x, y) { }, 'public function createSourceDefinitions': function(xml, options) { // TODO ??? }, 'public function getPrintConfig': function(layer, bounds, scale, isProxy) { var source = Mapbender.Model.findSource({ollid: layer.id}); var tmslayer = this.findLayer(source[0], {identifier:layer.layername}); var url = layer.url + '1.0.0/' + layer.layername; var printConfig = { type: 'tms', url: isProxy ? Mapbender.Util.removeProxy(url) : url, options: tmslayer.layer.options, zoom: Mapbender.Model.getZoomFromScale(scale) }; return printConfig; }, 'public function changeProjection': function(source, projection) { var layer = this.findLayerEpsg(source.configuration.layers, projection.projCode, true); if (layer) { var mqLayer = Mapbender.Model.getMqLayer(source); var layerOptions = this.createLayerOptions(layer, source.configuration.options.proxy, mqLayer.olLayer); $.extend(mqLayer.olLayer, layerOptions); this.enable(source, 'nosrs'); } else {// deactivate layer this.disable(source, 'nosrs'); } } }); Mapbender.source['tms'] = new Mapbender.Geo.TmsSourceHandler(); if ($.MapQuery.Layer.types['tms']) { $.MapQuery.Layer.types['tms'] = function(options) { var o = $.extend(true, {}, $.fn.mapQuery.defaults.layer.all, $.fn.mapQuery.defaults.layer.tms, options); var label = options.label || undefined; var url = options.url || undefined; var params = { layername: o.layer, type: o.format, tileOrigin: o.tileOrigin, isBaseLayer: o.isBaseLayer }; return { layer: new OpenLayers.Layer.TMS(label, url, params), options: o }; } }
// Source: https://thefrugaldeveloper.life/posts/building-an-eleventy-boilerplate-pt-2 exports.data = { permalink: "/sitemap.xml", eleventyExcludeFromCollections: true, robots: { ignore: true } }; exports.render = function(data) { let all = data.collections.all.filter(page => !page.data.sitemap || !page.data.sitemap.ignore) all = all.concat(data.collections.tagsList.filter(tag => !all.find(page => page.url === `/tags/${tag.replace(" ", "-").toLowerCase()}/`)).map(tag => ({ date: new Date(), url: `/tags/${tag.replace(" ", "-").toLowerCase()}` }))) all = all.concat(data.collections.archiveList.filter(archive => !all.find(page => page.url === `/archive/${archive.replace(" ", "-").toLowerCase()}/`)).map(archive => ({ date: new Date(), url: `/archive/${archive.replace(" ", "-").toLowerCase()}` }))) return `<?xml version="1.0" encoding="utf-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> ${[...all, { url: "/resume.html", date: new Date() },{ url: "/resume-en.html", date: new Date() },{ url: "/timeline.html", date: new Date() },{ url: "/timeline-en.html", date: new Date() }].map(page => `<url> <loc>${data.site.url}${page.url}</loc> <lastmod>${page.date.toISOString()}</lastmod> </url>`).join("")} </urlset>`; };
import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App.jsx"; import { ThirdwebWeb3Provider } from "@3rdweb/hooks"; const supportChainIds = [4]; const connectors = { injected: {}, }; // Render the App component to the DOM ReactDOM.render( <React.StrictMode> <ThirdwebWeb3Provider connectors={connectors} supportChainIds={supportChainIds} > <App /> </ThirdwebWeb3Provider> </React.StrictMode>, document.getElementById("root") );
module.exports = { port: 4401, environments: [ 'http://localhost:4401' ], plugins: [ 'browser', 'mocha-specs', 'mock-requests', 'page-objects' ], mochaSpecs: { directory: './test' }, mockRequests: { directory: './test' }, pageObjects: { directory: './test', include: { tractor: '../../node_modules/@tractor/ui/dist/page-objects/' } } };
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(React.createElement(React.Fragment, null, React.createElement("path", { fill: "none", d: "M0 0h24v24H0V0z" }), React.createElement("g", null, React.createElement("path", { d: "M16 17.01V10h-2v7.01h-3L15 21l4-3.99h-3zM9 3L5 6.99h3V14h2V6.99h3L9 3z" }), React.createElement("path", { d: "M16 17.01V10h-2v7.01h-3L15 21l4-3.99h-3zM9 3L5 6.99h3V14h2V6.99h3L9 3z" }))), 'SwapVertOutlined');
macDetailCallback("70b3d5441000/36",[{"a":"Sigma Business Center, Building A Nivel 2 San Pedro San Jose CR 11501","o":"Videoport S.A.","d":"2018-07-15","t":"add","s":"ieee","c":"CR"}]);
import { HorizontalBar, mixins } from 'vue-chartjs' // import { HorizontalBar} from 'vue-chartjs' export default { extends: HorizontalBar, mixins: [mixins.reactiveProp], props: ['options'], mounted() { console.log('Mounted') this.renderLineChart() }, computed: { chartData1: function () { console.log('Computed') return this.chartData } }, methods: { renderLineChart: function () { console.log('Methods') this.renderChart(this.chartData, this.options) } }, watch: { chartData: () => { console.log('Watch') this._chart.destroy() this.renderLineChart() } }, }
/* eslint-disable no-console */ const register = () => { if (process.env.NODE_ENV !== 'production') return; if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/sw.js') .then((registration) => { console.info('SW registered:', registration); }) .catch((error) => { console.error('SW registration failed:', error); }); }); } }; export default register;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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 * as ko from 'knockout'; import { MULTI_NAME as SIMPLE_ACE_MULTI } from 'ko/components/simpleAceEditor/ko.simpleAceEditor'; import { NAME as CONTEXT_SELECTOR } from 'ko/components/ko.contextSelector'; import { NAME as DROP_DOWN } from 'ko/components/ko.dropDown'; import { NAME as EXECUTABLE_ACTIONS } from 'apps/notebook2/components/ko.executableActions'; import { NAME as SIMPLE_RESULT_GRID } from 'apps/notebook2/components/resultGrid/ko.simpleResultGrid'; import componentUtils from 'ko/components/componentUtils'; import DisposableComponent from 'ko/components/DisposableComponent'; import Executor from 'apps/notebook2/execution/executor'; import SqlExecutable from 'apps/notebook2/execution/sqlExecutable'; import sqlStatementsParser from 'parse/sqlStatementsParser'; import { CONFIG_REFRESHED_EVENT, filterEditorConnectors } from 'utils/hueConfig'; export const NAME = 'quick-query-context'; // prettier-ignore const TEMPLATE = ` <div class="context-popover-flex-fill" style="overflow: auto;"> <div style="display: inline-block" data-bind=" component: { name: '${ DROP_DOWN }', params: { value: interpreter, labelAttribute: 'displayName', entries: availableInterpreters, linkTitle: 'Active connector' } } "></div> <!-- ko if: interpreter() --> <div class="margin-left-10" style="display: inline-block" data-bind=" component: { name: '${ CONTEXT_SELECTOR }', params: { sourceType: interpreter().type, compute: compute, namespace: namespace, availableDatabases: availableDatabases, database: database, hideLabels: true } } "></div> <!-- /ko --> <!-- ko ifnot: loadingContext --> <!-- ko with: interpreter --> <div style="margin: 10px;" data-bind=" component: { name: '${ SIMPLE_ACE_MULTI }', params: { autocomplete: $parent.autocomplete, value: $parent.statement, lines: 3, aceOptions: { minLines: 3, maxLines: 5 }, mode: dialect, database: $parent.database, availableDatabases: $parent.availableDatabases, namespace: $parent.namespace, compute: $parent.compute, executor: $parent.executor, activeExecutable: $parent.activeExecutable } } "></div> <div data-bind=" component: { name: '${ EXECUTABLE_ACTIONS }', params: { activeExecutable: $parent.activeExecutable } } "></div> <div data-bind=" component: { name: '${ SIMPLE_RESULT_GRID }', params: { activeExecutable: $parent.activeExecutable } } "></div> <!-- /ko --> <!-- /ko --> </div> `; class QuickQueryContext extends DisposableComponent { constructor(params) { super(params); this.availableInterpreters = ko.observableArray(); this.interpreter = ko.observable(); this.availableDatabases = ko.observableArray(); this.database = ko.observable(); this.activeExecutable = ko.observable(); // TODO: Switch over to connector in ko.simpleAceEditor this.namespace = ko.observable(); this.compute = ko.observable(); this.statement = ko.observable(); this.loadingContext = ko.pureComputed( () => !this.namespace() || !this.compute() || !this.database() ); this.dialect = ko.pureComputed(() => this.interpreter() && this.interpreter().dialect); this.type = ko.pureComputed(() => this.interpreter() && this.interpreter().type); this.defaultLimit = ko.observable(10); this.executor = new Executor({ sourceType: this.type, namespace: this.namespace, compute: this.compute, connector: this.interpreter, defaultLimit: this.defaultLimit }); this.autocomplete = ko.pureComputed( () => this.interpreter() && { type: this.interpreter().dialect } ); this.updateFromConfig(); this.subscribe(CONFIG_REFRESHED_EVENT, this.updateFromConfig.bind(this)); let refreshExecutableThrottle = -1; const refreshExecutable = () => { window.clearTimeout(refreshExecutableThrottle); refreshExecutableThrottle = window.setTimeout(() => { const parsedStatement = sqlStatementsParser.parse(this.statement() || '')[0]; const executable = new SqlExecutable({ executor: this.executor, parsedStatement: parsedStatement, database: this.database() }); this.activeExecutable(executable); this.executor.setExecutables([executable]); }, 200); }; this.subscribe(this.statement, refreshExecutable); this.subscribe(this.database, refreshExecutable); } updateFromConfig() { const configuredSqlConnectors = filterEditorConnectors(connector => connector.is_sql); this.availableInterpreters(configuredSqlConnectors); const found = this.interpreter() && this.availableInterpreters().some(interpreter => { if (interpreter.type === this.interpreter().type) { this.interpreter(interpreter); return true; } }); if (!found) { this.interpreter( this.availableInterpreters().length ? this.availableInterpreters()[0] : undefined ); } } } componentUtils.registerComponent(NAME, QuickQueryContext, TEMPLATE);
module.exports = { name: 'variables', aliases: [ 'vars' ], description: 'See the variables for the Modules', category: 'Information', execute: async (message, client, args) => { let r = require('../../models/Guild'); let guild = await r.findOne({ id: message.channel.guild.id }); let prefix = guild.prefix; let twotime = new Intl.DateTimeFormat('default', { hour12: true, hour: 'numeric', minute: 'numeric' }).format(new Date()); message.channel.createMessage({ // embed: { // fields: [ // { // name: '**Custom Commands**', // value: `#1 - The first argument provided on the commands usage\n#2 - The second argument provided on the commands usage\n#3 - The third argument provided on the commands usage\n#4 - The fourth argument provided on the commands usage\n#5 - The first argument provided on the commands usage\n##+ - All of the arguments provided on the commands usage` // } // ] // }, embed: { author: { name: client.user.username, icon_url: client.user.avatarURL }, title: 'Variables for Losts Modules', description: `__Examples:__\n{member} - ${message.member.mention}\n{memberID} - ${message.member .id}\n{serverName} - ${message.channel.guild.name}\n{serverID} - ${message.channel.guild .id}\n{username} - ${message.member.username}\n{size} - ${message.channel.guild .memberCount}\n{send:702241622926295092}\n{24-time} - ${new Date() .toLocaleTimeString() .slice(0, 5)}\n{12-time} - ${twotime}`, fields: [ { name: '**Join**', value: '{member} - The mention of the member who joined\n{username} - The username of the member who joined\n{serverName} - The name of the server\n{size} - The current size of the server' }, { name: '**Leave**', value: '{username} - The members username who left\n{serverName} - The name of the server\n{size} - The current size of the server\n' }, { name: '**Custom Commands**', value: '{member} - The mention of the member who used the embed\n{delete} - Delete the command usage\n{username} - The username of the user using the command\n{memberID} - The ID of the member using the command\n{serverName} - The name of the server\n{serverID} - The ID of the server\n{size} - The current size of the server\n{send:channelID} - The ID of the channel to response of the command\n{24-time} - The current time in the 24 hour format\n{12-time} - The current time in the 12 hour format' } ] } }); } };
_slugify_strip_re = /[^\w\s-]/g; _slugify_hyphenate_re = /[-\s]+/g; function slugify(s) { s = s.replace(_slugify_strip_re, '').trim().toLowerCase(); s = s.replace(_slugify_hyphenate_re, '-'); return s; }
const {BrowserWindow} = require('electron'); const url = require('url'); const path = require('path'); const {autoUpdater} = require("electron-updater"); let win; exports.init = () => { autoUpdater.on('update-available', (ev, info) => { win = new BrowserWindow({ width: 400, height: 200, icon: `${__dirname}/browser/img/icon.png`, maxWidth: 400, maxHeight: 200 }) win.setTitle('IG:dm software update') win.loadURL(url.format({ pathname: path.join(__dirname, 'browser/autoupdate.html'), protocol: 'file:', slashes: true })) win.on('closed', () => win = null) }) autoUpdater.on('error', (ev, err) => { win.webContents.send('error', 'Update has failed! :('); }) autoUpdater.on('download-progress', (ev, data) => { win.webContents.send('download-progress', data); }) autoUpdater.on('update-downloaded', (ev, info) => autoUpdater.quitAndInstall()); autoUpdater.checkForUpdates(); }
const express = require('express') const route = express.Router() const Handler = require('../middlewares/handlers/url.handler') const Controller = require('../controllers/url.controller') route.post('/create', Handler.handleCreate, Controller.create ) route.get('/top5', Handler.handleGetTop5, Controller.GetTop5) route.get('/hits', Controller.GetAllHits) module.exports = route
const plugin = require('tailwindcss/plugin') const colors = require('tailwindcss/colors') module.exports = { purge: {content: ['./public/**/*.html', './src/**/*.vue']}, darkMode: 'class', // false or 'media' or 'class' theme: { colors, extend: {}, }, variants: { extend: { padding: ['cursor'], margin: ['cursor'], borderWidth: ['cursor'], textColor: ['cursor','focus-within'], textOpacity: ['cursor'], backgroundOpacity: ['cursor'], borderOpacity: ['cursor'], backgroundColor: ['cursor'], borderColor: ['cursor'], boxShadow: ['cursor'], opacity: ['cursor'], scale: ['cursor'], translate: ['cursor'], display: ['cursor'], ringColor: ['cursor'], ringOffsetColor: ['cursor'], ringOffsetWidth: ['cursor'], ringOpacity: ['cursor'], ringWidth: ['cursor'], }, }, plugins: [ plugin(function ({addVariant, e}) { addVariant('cursor', ({modifySelectors, separator}) => { modifySelectors(({className}) => { return `.${e(`cursor${separator}${className}`)}:focus-within, .${e(`cursor${separator}${className}`)}:focus, .${e(`cursor${separator}${className}`)}:hover, .${e(`cursor${separator}${className}`)}:focus-within` }) }) }), ], }
import _ from 'underscore'; import lodashGet from 'lodash/get'; import React from 'react'; import PropTypes from 'prop-types'; import {ScrollView, View} from 'react-native'; import {withOnyx} from 'react-native-onyx'; import styles from '../../styles/styles'; import withLocalize, {withLocalizePropTypes} from '../../components/withLocalize'; import reimbursementAccountPropTypes from './reimbursementAccountPropTypes'; import compose from '../../libs/compose'; import ONYXKEYS from '../../ONYXKEYS'; import FormAlertWithSubmitButton from '../../components/FormAlertWithSubmitButton'; import CONST from '../../CONST'; const propTypes = { /** ACH data for the withdrawal account actively being set up */ reimbursementAccount: reimbursementAccountPropTypes, /** Called when the form is submitted */ onSubmit: PropTypes.func.isRequired, ...withLocalizePropTypes, }; const defaultProps = { reimbursementAccount: {}, }; class ReimbursementAccountForm extends React.Component { render() { const isErrorVisible = _.size(lodashGet(this.props, 'reimbursementAccount.errors', {})) > 0 || lodashGet(this.props, 'reimbursementAccount.errorModalMessage', '').length > 0 // @TODO once all validation errors show in multiples we can remove this check || lodashGet(this.props, 'reimbursementAccount.error', '').length > 0; const currentStep = lodashGet( this.props, 'reimbursementAccount.achData.currentStep', CONST.BANK_ACCOUNT.STEP.BANK_ACCOUNT, ); return ( <ScrollView style={[styles.w100, styles.flex1]} ref={el => this.form = el} contentContainerStyle={styles.flexGrow1} keyboardShouldPersistTaps="handled" > {/* Form elements */} <View style={[styles.mh5, styles.mb5]}> {this.props.children} </View> <FormAlertWithSubmitButton isAlertVisible={isErrorVisible} buttonText={currentStep === CONST.BANK_ACCOUNT.STEP.VALIDATION ? this.props.translate('validationStep.buttonText') : this.props.translate('common.saveAndContinue')} onSubmit={this.props.onSubmit} onFixTheErrorsLinkPressed={() => { this.form.scrollTo({y: 0, animated: true}); }} message={this.props.reimbursementAccount.errorModalMessage} isMessageHtml={this.props.reimbursementAccount.isErrorModalMessageHtml} /> </ScrollView> ); } } ReimbursementAccountForm.propTypes = propTypes; ReimbursementAccountForm.defaultProps = defaultProps; export default compose( withLocalize, withOnyx({ reimbursementAccount: { key: ONYXKEYS.REIMBURSEMENT_ACCOUNT, }, }), )(ReimbursementAccountForm);
/** * This is a modified version of shallow populate that supports Arrays of nested objects for keyThere fields. */ const assert = require('assert') const { getByDot, setByDot } = require('feathers-hooks-common') const defaults = { include: undefined } module.exports = function (options) { options = Object.assign({}, defaults, options) // Make an array of includes const includes = [].concat(options.include || []) if (!includes.length) { throw new Error('shallowPopulate hook: You must provide one or more relationships in the `include` option.') } const requiredIncludeAttrs = [ 'service', 'nameAs', 'keyHere', 'keyThere', 'asArray', 'params' ] includes.forEach(include => { // Create default `asArray` property if (!Object.prototype.hasOwnProperty.call(include, 'asArray')) { include.asArray = true } // Create default `params` property if (!Object.prototype.hasOwnProperty.call(include, 'params')) { include.params = {} } try { assert.deepStrictEqual(requiredIncludeAttrs.sort(), Object.keys(include).sort()) } catch (error) { throw new Error('shallowPopulate hook: Every `include` must contain `service`, `nameAs`, `keyHere`, and `keyThere` properties') } }) const requiredKeyMappings = includes.reduce((includes, include) => { if (!includes[include.keyHere]) { includes[include.keyHere] = include } return includes }, {}) return function shallowPopulate(context) { const { app, type } = context let data = type === 'before' ? context.data : (context.result.data || context.result) data = [].concat(data || []) if (!data.length) { return Promise.resolve(context) } // data1: { // id: '11', // name: 'Dumb Stuff', // trackIds: ['111', '222', '333'] // } // const byKeyHere = { // trackIds: { // '111': [data1, data2], // '222': [data1], // '333': [data1] // } // } const dataMap = data.reduce((byKeyHere, current) => { Object.keys(requiredKeyMappings).forEach(key => { byKeyHere[key] = byKeyHere[key] || {} const keyHere = getByDot(current, key) if (keyHere) { if (Array.isArray(keyHere)) { if (!requiredKeyMappings[key].asArray) { mapData(byKeyHere, key, keyHere[0], current) } else { keyHere.forEach(hereKey => mapData(byKeyHere, key, hereKey, current)) } } else { mapData(byKeyHere, key, keyHere, current) } } }) return byKeyHere }, {}) // const dataMap = { // keyHere: { // trackIds: { // 1: [{}] // } // }, // keyThere: { // foo: [...keyHeres].map(here => { // here[nameAs] = tracksResponse[index] // }) // } // } const paramSets = includes.map(i => { const keysHere = Object.keys(dataMap[i.keyHere]) || [] return { query: { [i.keyThere]: { $in: keysHere } } } }) const requests = includes.map((i, index) => app.service(i.service).find(Object.assign({}, paramSets[index], { paginate: false }, i.params))) return Promise.all(requests) .then(responses => { responses.forEach((response, index) => { const include = includes[index] const relatedItems = response.data || response data.forEach(item => { const keyHere = getByDot(item, include.keyHere) if (keyHere) { if (Array.isArray(keyHere)) { if (!include.asArray) { setByDot(item, include.nameAs, getRelatedItems(keyHere[0], relatedItems, include)) } else { setByDot(item, include.nameAs, getRelatedItems(keyHere, relatedItems, include)) } } else { setByDot(item, include.nameAs, getRelatedItems(keyHere, relatedItems, include)) } } }) }) return Promise.resolve(context) }) } } function getRelatedItems(ids, relatedItems, include) { const { keyThere, asArray } = include ids = [].concat(ids || []) return relatedItems.reduce((items, currentItem) => { ids.forEach(id => { id = typeof id === 'number' ? id : id.toString() let currentId // Allow populating on nested array of objects like key[0].name, key[1].name // If keyThere includes a dot, we're looking for a nested prop. This checks if that nested prop is an array. // If it's an array, we assume it to be an array of objects. // It splits the key only on the first dot which allows populating on nested keys inside the array of objects. if (keyThere.includes('.') && Array.isArray(currentItem[keyThere.slice(0, keyThere.indexOf('.'))])) { // The name of the array is everything leading up to the first dot. const arrayName = keyThere.split('.')[0] // The rest will be handed to getByDot as the path to the prop const nestedProp = keyThere.slice(keyThere.indexOf('.') + 1) // Map over the array to grab each nestedProp's value. currentId = currentItem[arrayName].map(nestedItem => { const keyThereVal = getByDot(nestedItem, nestedProp) return typeof keyThereVal === 'number' ? keyThereVal : keyThereVal.toString() }) } else { const keyThereVal = getByDot(currentItem, keyThere) currentId = typeof keyThereVal === 'number' ? keyThereVal : keyThereVal.toString() } if (asArray) { if (currentId.includes(id)) { items.push(currentItem) } } else { if (currentId.includes(id)) { items = currentItem } } }) return items }, asArray ? [] : {}) } function mapData(byKeyHere, key, keyHere, current) { byKeyHere[key][keyHere] = byKeyHere[key][keyHere] || [] byKeyHere[key][keyHere].push(current) return byKeyHere }
const { assert } = require('chai'); const domain = require('../../../lib/urlExtract'); describe('domain extract', () => { it('save should equal local host when supplied with http link', () => { assert.equal(domain.extract('http://localhost/'), 'localhost'); }); it('save should equal local host when supplied with https link', () => { assert.equal(domain.extract('https://localhost/'), 'localhost'); }); it('save should equal local host when supplied with no http link', () => { assert.equal(domain.extract('localhost'), 'localhost'); }); it('should return empty string when nothing is passed', () => { assert.equal(domain.extract(), undefined); }); });
# # Copyright (C) 2016 Transaction Processing Performance Council (TPC) and/or # its contributors. # # This file is part of a software package distributed by the TPC. # # The contents of this file have been developed by the TPC, and/or have been # licensed to the TPC under one or more contributor license agreements. # # This file is subject to the terms and conditions outlined in the End-User # License Agreement (EULA) which can be found in this distribution (EULA.txt) # and is available at the following URL: # http://www.tpc.org/TPC_Documents_Current_Versions/txt/EULA.txt # # Unless required by applicable law or agreed to in writing, this software # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied, and the user bears the entire risk as # to quality and performance as well as the entire cost of service or repair # in case of defect. See the EULA for more details. # #Copyright 2015 Intel Corporation All Rights Reserved. # #The source code contained or described herein and all documents related to the source code ("Material") are owned by Intel Corporation or its suppliers or licensors. Title to the Material remains with Intel Corporation or its suppliers and licensors. The Material contains trade secrets and proprietary and confidential information of Intel or its suppliers and licensors. The Material is protected by worldwide copyright and trade secret laws and treaty provisions. No part of the Material may be used, copied, reproduced, modified, published, uploaded, posted, transmitted, distributed, or disclosed in any way without Intel's prior express written permission. # #No license under any patent, copyright, trade secret or other intellectual property right is granted to or conferred upon you by disclosure or delivery of the Materials, either expressly, by implication, inducement, estoppel or otherwise. Any license under such intellectual property rights must be express and approved by Intel in writing. import sys import logging import traceback import os import time from time import strftime timeout = long(sys.argv[1]) if __name__ == "__main__": # requires data to be in format <user_sk>\t<timestamp>\t<item_sk>, clustered by user_sk and sorted by <timestamp> ascending line = '' current_uid = '' last_click_time = '' perUser_sessionID_counter = 1 sessionID = '' try: # algorithm expects input lines to be clustered by user_sk and sorted by <timestamp> ascending for line in sys.stdin: user_sk, tstamp_str, item_sk = line.strip().split("\t") tstamp = long(tstamp_str) # reset if next partition beginns if current_uid != user_sk: current_uid = user_sk last_click_time = tstamp perUser_sessionID_counter = long(1) #sessionID = user_sk + "_" + tstamp_str + "_1" sessionID = user_sk + "_1" # time between clicks exceeds session timeout? # tstamp must be guaranteed to be >= last_click_time by hive (sorted ascending) if tstamp - last_click_time > timeout: perUser_sessionID_counter = perUser_sessionID_counter + 1 # we should not require the session's start time as part of the sessionID. hives "distribute by x" is defined to pipe every line for the same X to the same reducer ( same instance of this script) #Hive uses the columns in Distribute By to distribute the rows among reducers. All rows with the same Distribute By columns will go to the same reducer. However, Distribute By does not guarantee clustering or sorting properties on the distributed keys. #sessionID = user_sk + "_" + tstamp_str + "_" + str(perUser_sessionID_counter) sessionID = user_sk + "_" + str(perUser_sessionID_counter) last_click_time =tstamp print "%s\t%s" % (item_sk, sessionID ) #print item_sk +"\t"+ sessionID except: ## should only happen if input format is not correct, like 4 instead of 3 tab separated values logging.basicConfig(level=logging.DEBUG, filename=strftime("/tmp/bigbench_q30-sessionize.py_%Y%m%d-%H%M%S.log")) logging.info("sys.argv[1] timeout: " +str(timeout) + " line from hive: \"" + line + "\"") logging.exception("Oops:") raise sys.exit(1)
'use strict'; /* declare and assign variables as described in the comments pay close attention to how each variable is used! - is a variable assigned a value when it is declared? - is a variable reassigned later in the script? your challenge is to decide whether to use let or to use const - use let if the variable is declared without an assignment or the variable is ever reassigned later in the script - use const if the variable is declared with a value and never reassigned */ let x = 'a'; console.log(x); // should print 'a' let y = 'b'; console.log(y); // should print 'b' console.log(x); // should print 'a' let z; console.log(z); // should print undefined console.log(y); // should print 'b' z = 'c'; console.log(z); // should print 'c' y=y+'d'; console.log(y); // should print 'bd' console.log(x); // should print 'a'
import React from 'react' const DEFAULT_SIZE = 24 export default ({ fill = 'currentColor', width = DEFAULT_SIZE, height = DEFAULT_SIZE, style = {}, ...props }) => ( <svg viewBox={ `0 0 ${ DEFAULT_SIZE } ${ DEFAULT_SIZE }` } style={{ fill, width, height, ...style }} { ...props } > <path d="M12,2C17.52,2 22,6.48 22,12C22,13.1 21.1,14 20,14H4C2.9,14 2,13.1 2,12C2,6.48 6.48,2 12,2M12,8C13.1,8 14,7.1 14,6C14,4.9 13.1,4 12,4C10.9,4 10,4.9 10,6C10,7.1 10.9,8 12,8M17,12C18.1,12 19,11.1 19,10C19,8.9 18.1,8 17,8C15.9,8 15,8.9 15,10C15,11.1 15.9,12 17,12M7,12C8.1,12 9,11.1 9,10C9,8.9 8.1,8 7,8C5.9,8 5,8.9 5,10C5,11.1 5.9,12 7,12M15,15L16.27,19.45L16.35,20C16.35,21.1 15.45,22 14.35,22H9.65C8.55,22 7.65,21.1 7.65,20L7.73,19.45L9,15H15Z" /> </svg> )
import typing import logging import json as json_mod from ucloud.core import exc from ucloud.core.transport import utils from ucloud.core.utils.compat import str logger = logging.getLogger(__name__) class Request: def __init__( self, url: str, method: str = "GET", params: dict = None, data: dict = None, json: dict = None, headers: dict = None, **kwargs ): self.url = url self.method = method self.params = params self.data = data self.json = json self.headers = headers self.request_time = 0 def payload(self): payload = (self.params or {}).copy() payload.update(self.data or {}) payload.update(self.json or {}) return payload REQUEST_UUID_HEADER_KEY = "X-UCLOUD-REQUEST-UUID" class Response: def __init__( self, url: str, method: str, request: Request = None, status_code: int = None, reason: str = None, headers: dict = None, content: bytes = None, encoding: str = None, **kwargs ): self.url = url self.method = method self.request = request self.status_code = status_code self.reason = reason self.content = content self.encoding = encoding self.response_time = 0 self.headers = headers or {} self.request_uuid = self.headers.get(REQUEST_UUID_HEADER_KEY) def json(self, **kwargs) -> typing.Optional[dict]: """ json will return the bytes of content """ if not self.content: return None try: return self._decode_json(**kwargs) except Exception as e: raise exc.InvalidResponseException( self.content, str(e), request_uuid=self.request_uuid ) @property def text(self): """ text will return the unicode string of content, see `requests.Response.text` """ if not self.content: return str("") # Decode unicode from given encoding. try: content = str(self.content, self.encoding, errors="replace") except (LookupError, TypeError): content = str(self.content, errors="replace") return content def _decode_json(self, **kwargs): encoding = utils.guess_json_utf(self.content) if encoding is not None: try: return json_mod.loads(self.content.decode(encoding), **kwargs) except UnicodeDecodeError: pass return json_mod.loads(self.text, **kwargs) class SSLOption: def __init__( self, ssl_verify: bool = True, ssl_cacert: str = None, ssl_cert: str = None, ssl_key: str = None, ): self.ssl_verify = ssl_verify self.ssl_cacert = ssl_cacert self.ssl_cert = ssl_cert self.ssl_key = ssl_key class Transport: """ the abstract class of transport implementation """ def send(self, req: Request, **options: typing.Any) -> Response: raise NotImplementedError
import { IntegerEditor } from './integer.js' export class StepperEditor extends IntegerEditor { build () { super.build() this.input.setAttribute('type', 'number') if (!this.input.getAttribute('step')) { this.input.setAttribute('step', '1') } const stepperButtons = this.theme.getStepperButtons(this.input) this.control.appendChild(stepperButtons) this.stepperDown = this.control.querySelector('.stepper-down') this.stepperUp = this.control.querySelector('.stepper-up') } enable () { super.enable() this.stepperDown.removeAttribute('disabled') this.stepperUp.removeAttribute('disabled') } disable () { super.disable() this.stepperDown.setAttribute('disabled', true) this.stepperUp.setAttribute('disabled', true) } }
from sympy import * from sympy.physics.vector import * from sympy.vector import * R = CoordSys3D('R') t = Symbol('t') a = -sin(t)*R.i + cos(t)*R.j + 0*R.k b = -cos(t)*R.i + -sin(t)*R.j + 0*R.k # same print(simplify(dot(a, b))) print(simplify(a & b)) # same print(simplify(a ^ b)) print(simplify(cross(a, b)))
/** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ define([], function () { 'use strict'; /** * Patch for CVE-2015-9251 (XSS vulnerability). * Can safely remove only when jQuery UI is upgraded to >= 3.3.x. * https://www.cvedetails.com/cve/CVE-2015-9251/ */ function ajaxResponsePatch(jQuery) { jQuery.ajaxPrefilter(function (s) { if (s.crossDomain) { s.contents.script = false; } }); } return function ($) { var majorVersion = $.fn.jquery.split('.')[0]; if (majorVersion >= 3) { console.warn('jQuery patch for CVE-2015-9251 is no longer necessary, and should be removed'); } ajaxResponsePatch($); return $; }; });
#!/usr/bin/env python """Bootstrap setuptools installation To use setuptools in your package's setup.py, include this file in the same directory and add this to the top of your setup.py:: from ez_setup import use_setuptools use_setuptools() To require a specific version of setuptools, set a download mirror, or use an alternate download directory, simply supply the appropriate options to ``use_setuptools()``. This file can also be run as a script to install or upgrade setuptools. """ import os import shutil import sys import tempfile import zipfile import optparse import subprocess import platform import textwrap import contextlib from distutils import log try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen try: from site import USER_SITE except ImportError: USER_SITE = None DEFAULT_VERSION = "12.0.4" DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/" def _python_cmd(*args): """ Return True if the command succeeded. """ args = (sys.executable,) + args return subprocess.call(args) == 0 def _install(archive_filename, install_args=()): with archive_context(archive_filename): # installing log.warn('Installing Setuptools') if not _python_cmd('setup.py', 'install', *install_args): log.warn('Something went wrong during the installation.') log.warn('See the error message above.') # exitcode will be 2 return 2 def _build_egg(egg, archive_filename, to_dir): with archive_context(archive_filename): # building an egg log.warn('Building a Setuptools egg in %s', to_dir) _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) # returning the result log.warn(egg) if not os.path.exists(egg): raise IOError('Could not build the egg.') class ContextualZipFile(zipfile.ZipFile): """ Supplement ZipFile class to support context manager for Python 2.6 """ def __enter__(self): return self def __exit__(self, type, value, traceback): self.close() def __new__(cls, *args, **kwargs): """ Construct a ZipFile or ContextualZipFile as appropriate """ if hasattr(zipfile.ZipFile, '__exit__'): return zipfile.ZipFile(*args, **kwargs) return super(ContextualZipFile, cls).__new__(cls) @contextlib.contextmanager def archive_context(filename): # extracting the archive tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) with ContextualZipFile(filename) as archive: archive.extractall() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) yield finally: os.chdir(old_wd) shutil.rmtree(tmpdir) def _do_download(version, download_base, to_dir, download_delay): egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg' % (version, sys.version_info[0], sys.version_info[1])) if not os.path.exists(egg): archive = download_setuptools(version, download_base, to_dir, download_delay) _build_egg(egg, archive, to_dir) sys.path.insert(0, egg) # Remove previously-imported pkg_resources if present (see # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details). if 'pkg_resources' in sys.modules: del sys.modules['pkg_resources'] import setuptools setuptools.bootstrap_install_from = egg def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15): to_dir = os.path.abspath(to_dir) rep_modules = 'pkg_resources', 'setuptools' imported = set(sys.modules).intersection(rep_modules) try: import pkg_resources except ImportError: return _do_download(version, download_base, to_dir, download_delay) try: pkg_resources.require("setuptools>=" + version) return except pkg_resources.DistributionNotFound: return _do_download(version, download_base, to_dir, download_delay) except pkg_resources.VersionConflict as VC_err: if imported: msg = textwrap.dedent(""" The required version of setuptools (>={version}) is not available, and can't be installed while this script is running. Please install a more recent version first, using 'easy_install -U setuptools'. (Currently using {VC_err.args[0]!r}) """).format(VC_err=VC_err, version=version) sys.stderr.write(msg) sys.exit(2) # otherwise, reload ok del pkg_resources, sys.modules['pkg_resources'] return _do_download(version, download_base, to_dir, download_delay) def _clean_check(cmd, target): """ Run the command to download target. If the command fails, clean up before re-raising the error. """ try: subprocess.check_call(cmd) except subprocess.CalledProcessError: if os.access(target, os.F_OK): os.unlink(target) raise def download_file_powershell(url, target): """ Download the file at url to target using Powershell (which will validate trust). Raise an exception if the command cannot complete. """ target = os.path.abspath(target) ps_cmd = ( "[System.Net.WebRequest]::DefaultWebProxy.Credentials = " "[System.Net.CredentialCache]::DefaultCredentials; " "(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)" % vars() ) cmd = [ 'powershell', '-Command', ps_cmd, ] _clean_check(cmd, target) def has_powershell(): if platform.system() != 'Windows': return False cmd = ['powershell', '-Command', 'echo test'] with open(os.path.devnull, 'wb') as devnull: try: subprocess.check_call(cmd, stdout=devnull, stderr=devnull) except Exception: return False return True download_file_powershell.viable = has_powershell def download_file_curl(url, target): cmd = ['curl', url, '--silent', '--output', target] _clean_check(cmd, target) def has_curl(): cmd = ['curl', '--version'] with open(os.path.devnull, 'wb') as devnull: try: subprocess.check_call(cmd, stdout=devnull, stderr=devnull) except Exception: return False return True download_file_curl.viable = has_curl def download_file_wget(url, target): cmd = ['wget', url, '--quiet', '--output-document', target] _clean_check(cmd, target) def has_wget(): cmd = ['wget', '--version'] with open(os.path.devnull, 'wb') as devnull: try: subprocess.check_call(cmd, stdout=devnull, stderr=devnull) except Exception: return False return True download_file_wget.viable = has_wget def download_file_insecure(url, target): """ Use Python to download the file, even though it cannot authenticate the connection. """ src = urlopen(url) try: # Read all the data in one block. data = src.read() finally: src.close() # Write all the data in one block to avoid creating a partial file. with open(target, "wb") as dst: dst.write(data) download_file_insecure.viable = lambda: True def get_best_downloader(): downloaders = ( download_file_powershell, download_file_curl, download_file_wget, download_file_insecure, ) viable_downloaders = (dl for dl in downloaders if dl.viable()) return next(viable_downloaders, None) def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): """ Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an sdist for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. ``downloader_factory`` should be a function taking no arguments and returning a function for downloading a URL to a target. """ # making sure we use the absolute path to_dir = os.path.abspath(to_dir) zip_name = "setuptools-%s.zip" % version url = download_base + zip_name saveto = os.path.join(to_dir, zip_name) if not os.path.exists(saveto): # Avoid repeated downloads log.warn("Downloading %s", url) downloader = downloader_factory() downloader(url, saveto) return os.path.realpath(saveto) def _build_install_args(options): """ Build the arguments to 'python setup.py install' on the setuptools package """ return ['--user'] if options.user_install else [] def _parse_args(): """ Parse the command line for options """ parser = optparse.OptionParser() parser.add_option( '--user', dest='user_install', action='store_true', default=False, help='install in user site package (requires Python 2.6 or later)') parser.add_option( '--download-base', dest='download_base', metavar="URL", default=DEFAULT_URL, help='alternative URL from where to download the setuptools package') parser.add_option( '--insecure', dest='downloader_factory', action='store_const', const=lambda: download_file_insecure, default=get_best_downloader, help='Use internal, non-validating downloader' ) parser.add_option( '--version', help="Specify which version to download", default=DEFAULT_VERSION, ) options, args = parser.parse_args() # positional arguments are ignored return options def main(): """Install or upgrade setuptools and EasyInstall""" options = _parse_args() archive = download_setuptools( version=options.version, download_base=options.download_base, downloader_factory=options.downloader_factory, ) return _install(archive, _build_install_args(options)) if __name__ == '__main__': sys.exit(main())
module.exports = (sequelize, DataTypes) => sequelize.define('classes', { name: { type: DataTypes.STRING, allowNull: false }, github: DataTypes.STRING, company: DataTypes.STRING, start: DataTypes.DATE, finish: DataTypes.DATE })
var stampit = require('stampit'); module.exports = stampit() .refs({ }) .init(function () { this.log = { }; var levels = [ 'error', 'warn', 'info', 'debug', 'trace']; var init = function () { if (!this.logEnabled) { this.log.error = function () { }; this.log.warn = function () { }; this.log.info = function () { }; this.log.debug = function () { }; this.log.trace = function () { }; // deprecated this.logInfo = function () { }; this.logError = function () { }; } else { this.log.error = log('error'); this.log.warn = log('warn'); this.log.info = log('info'); this.log.debug = log('debug'); this.log.trace = log('trace'); // deprecated this.logInfo = log('info'); this.logError = log('error'); } if (!this.logLevel) { this.logLevel = 'info'; } else { this.logLevel = this.logLevel.toLowerCase(); } }.bind(this); var inLogLevel = function (level) { var logLevelIndex = levels.indexOf(this.logLevel), levelIndex = levels.indexOf(level); return logLevelIndex >= levelIndex; }.bind(this); var log = function (level) { return function () { if (!inLogLevel(level)) { return; } var args = Array.prototype.slice.call(arguments); if (this.logLabel) { args.splice(0, 0, this.logLabel); } args.splice(0, 0, level.toUpperCase() + ' :'); if (this.logTimestamp) { args.splice(0, 0, new Date()); } var stack; if (level === 'trace') { stack = new Error().stack; args.push(stack); } console.log.apply(null, args); }.bind(this); }.bind(this); init(); });
import client from '../api/apolloclient' import { viewrisksGraphQL } from '../_graphql'; export const viewallrisksService = { getRisks }; function getRisks(risk_type_id, records_count, fetchAfterCursor) { const variables = { risktypeid : risk_type_id, first: records_count, after: fetchAfterCursor }; return new Promise((resolve, reject) => { client.query({query: viewrisksGraphQL.GET_RISKS_QUERY, variables}).then(response => { const {data: {riskinstances = null }} = response console.log('riskinstance') console.log(riskinstances) if(riskinstances !== null) { console.log('service output') console.log(riskinstances) resolve(riskinstances) } else { const strError = 'No data found for Risks' reject(strError) } }).catch(error => { console.log('Error in getRisks') reject(error) }) }) }
import { useLocation } from 'react-router-dom'; import Button from "./Button"; const Header = ({title, onAdd, showAdd}) => { const location = useLocation(); return ( <header className='header'> <h1>{title}</h1> {location.pathname === '/' && (<Button onClick={onAdd} color={showAdd ? 'red' : 'green'} text={showAdd ? 'Close' : 'Add'}/>)} </header> ) }; Header.defaultProps = { title: 'Task Tracker' }; export default Header;
var r = require("requirejs") define(["q", "js/runtime-anf", "./../evaluator/eval-matchers", "../../src/js/base/repl-lib", "js/ffi-helpers", "compiler/compile-structs.arr"], function(Q, rtLib, e, repl, ffiLib, compileStructs) { var J = require('jasmine-node'); var rt; var P; var same; var err; var aRepl; var ffi; var replCount = 0; function getVal(rt, result) { if(!rt.isSuccessResult(result)) { console.error("Tried to getVal of non-SuccessResult: ", result, result.exn ? result.exn.stack : "No stack"); throw result.exn; } return rt.getField(result.result, "answer"); } function getChecks(rt, result) { if(!rt.isSuccessResult(result)) { console.error("Tried to getChecks of non-SuccessResult: ", result, result.exn); throw result.exn; } return ffi.toArray(rt.getField(result.result, "checks")); } function performTest() { beforeEach(function(done) { rt = rtLib.makeRuntime({ stdout: function(str) { process.stdout.write(str); } }); P = e.makeEvalCheckers(this, rt); same = P.checkEvalsTo; err = P.checkError; ffi = ffiLib(rt, rt.namespace); var envP = Q.defer(); rt.loadModules(rt.namespace, [compileStructs], function(cs) { envP.resolve(rt.getField(cs, "standard-builtins")); }); aRepl = envP.promise.then(function(env) { done(); return repl.create(rt, rt.namespace, env, { name: "repl-test" + replCount++}); }); aRepl.fail(function(err) { console.error("Failed to create repl: ", err); }); }); describe("repl", function() { it("should initialize and run simple programs", function(done) { aRepl.then(function(aRepl) { var rt = aRepl.runtime; aRepl.restartInteractions("x = 10\nx").then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.makeNumber(10)); return aRepl.run("x"); }).then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.makeNumber(10)); return aRepl.run("y"); }).then(function(replResult) { expect(replResult).toPassPredicate(rt.isFailureResult); return aRepl.run("y = lam(): x + 1 end"); }).then(function(replResult) { expect(replResult).toPassPredicate(rt.isSuccessResult); return aRepl.run("y()"); }).then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.makeNumber(11)); done(); }).catch(function(err) { console.error("Failure: ", err); fail(); }); }); }, 10000); it("should not allow unbound ids, even in functions", function(done) { aRepl.then(function(aRepl) { var rt = aRepl.runtime; aRepl.restartInteractions(""); aRepl.run("fun even(a): if a == 1: false else: odd(a - 1) end end") .then(function(replResult) { expect(replResult).toPassPredicate(rt.isFailureResult); }); aRepl.run("fun odd(a): if a == 1: true else: even(a - 1) end end") .then(function(replResult) { expect(replResult).toPassPredicate(rt.isFailureResult); done(); }); }); }); it("should not allow unbound ids, even in functions", function(done) { aRepl.then(function(aRepl) { var rt = aRepl.runtime; aRepl.restartInteractions(""); aRepl.run("import lists as L") .then(function(replResult) { expect(replResult).toPassPredicate(rt.isSuccessResult); }); aRepl.run("is-object(L)") .then(function(replResult) { expect(replResult).toPassPredicate(rt.isSuccessResult); done(); }); }); }); it("should include check results", function(done) { aRepl.then(function(aRepl) { var rt = aRepl.runtime; aRepl.restartInteractions("check: 1 is 1;\ncheck: 2 is 2;") .then(function(replResult) { expect(getChecks(rt, replResult).length).toBe(2); return aRepl.run("check: 4 is 5 end") }).then(function(replResult) { expect(getChecks(rt, replResult).length).toBe(1); done(); }).catch(function(err) { console.error("Failed in testing checks: ", err); fail(); }); }); }); it("should allow for shadowing only with the 'shadow' keyword", function(done) { aRepl.then(function(aRepl) { var rt = aRepl.runtime; aRepl.restartInteractions("x = 5") .then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.namespace.get("nothing")); return aRepl.run("x = 10") }).then(function(replResult) { expect(replResult).toPassPredicate(rt.isFailureResult); return aRepl.run("shadow x = 10") }).then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.namespace.get("nothing")); return aRepl.run("x") }).then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.makeNumber(10)); done(); }).catch(function(err) { console.error("Failed in testing shadowing: ", err); fail(); }); }); }, 20000); it("should not allow forward references", function(done) { aRepl.then(function(aRepl) { var rt = aRepl.runtime; aRepl.restartInteractions("") .then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.namespace.get("nothing")); return aRepl.run("fun f(): forward-reference end") }).then(function(replResult) { expect(replResult).toPassPredicate(rt.isFailureResult); done(); }).catch(function(err) { console.error("Failed in testing forward references ", err); fail(); }); }); }); it("should have builtin modules available at the repl", function(done) { aRepl.then(function(aRepl) { var rt = aRepl.runtime; aRepl.restartInteractions("") .then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.namespace.get("nothing")); return aRepl.run("x :: lists.List = empty") }).then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.namespace.get("nothing")); done(); }).catch(function(err) { console.error("Failed in testing builtin-modules binding: ", err, err.exn.dict.reason); fail(); }); }); }); it("should bind type names", function(done) { aRepl.then(function(aRepl) { var rt = aRepl.runtime; aRepl.restartInteractions("data D: | var1 end") .then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.namespace.get("nothing")); return aRepl.run("x :: D = var1") }).then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.namespace.get("nothing")); done(); }).catch(function(err) { console.error("Failed in testing typename binding: ", err); fail(); }); }); }, 15000); it("should allow recursive references in the same block", function(done) { aRepl.then(function(aRepl) { var rt = aRepl.runtime; aRepl.restartInteractions("") .then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.namespace.get("nothing")); return aRepl.run("fun f(): g(4) end\nfun g(x): x end\nf()"); }).then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.makeNumber(4)); done(); }).catch(function(err) { console.error("Failed in testing recursive references ", err); fail(); }); }); }, 30000); it("should allow restarting of interactions to clear state", function(done) { aRepl.then(function(aRepl) { var rt = aRepl.runtime; aRepl.restartInteractions("x = 5") .then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.namespace.get("nothing")); return aRepl.run("x = 10") }).then(function(replResult) { expect(replResult).toPassPredicate(rt.isFailureResult); return aRepl.restartInteractions("not-x = 5"); }).then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.namespace.get("nothing")); return aRepl.run("x = 22"); }).then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.namespace.get("nothing")); return aRepl.run("x"); }).then(function(replResult) { expect(getVal(rt, replResult)).toBeSameAs(rt, rt.makeNumber(22)); done(); }).catch(function(err) { console.error("Failed in testing restarting interactions: ", err); fail(); }); }); }, 30000); it("should allow stopping", function(done) { aRepl.then(function(aRepl) { var rt = aRepl.runtime; aRepl.restartInteractions("fun fact(n): if n < 1: 1 else: n * fact(n - 1);;").then(function(replResult) { setTimeout(function() { aRepl.stop(); }, 1000); return aRepl.run("fact(100000)"); }).then(function(result) { expect(result).toPassPredicate(rt.isFailureResult) expect(result.exn.exn).toPassPredicate(rt.ffi.isUserBreak); done(); }).fail(function(err) { fail(); }); }); }); it("should allow stopping nested inside tasks", function(done) { aRepl.then(function(aRepl) { var rt = aRepl.runtime; aRepl.restartInteractions("fun fact(n): if n < 1: 1 else: n * fact(n - 1);;").then(function(replResult) { setTimeout(function() { aRepl.stop(); }, 1000); return aRepl.run("run-task(lam(): fact(100000)\n 'done' end)"); }).then(function(result) { expect(result).toPassPredicate(rt.isFailureResult); expect(result.exn.exn).toPassPredicate(rt.ffi.isUserBreak); done(); }).fail(function(err) { fail(); }); }); }, 10000); }); } return { performTest: performTest }; });
const admin = require("firebase-admin"); const functions = require("firebase-functions"); const db = admin.firestore(); module.exports.processSignUp = functions.auth.user().onCreate(async user => { //check user qualification let customClaims; const usersRef = db.collection("invites"); const snapshot = await usersRef.where("inviteeEmail", "==", user.email).get(); //if user is invited to be an admin, set up admin claim to true if (!snapshot.empty) { customClaims = { admin: true }; admin.auth().setCustomUserClaims(user.uid, customClaims); createFirestoreUser(user); //if user is not invited but has a BU email, set up admin claim to be false(student) } else if (user.email && user.email.endsWith("@bu.edu")) { customClaims = { admin: false }; admin.auth().setCustomUserClaims(user.uid, customClaims); createFirestoreUser(user); //else delete the account } else { admin.auth().deleteUser(user.uid); } return; }); function createFirestoreUser(user) { db.collection("users") .doc(user.uid) .set({ displayName: user.displayName, uid: user.uid, email: user.email, photoURL: user.photoURL, applications: {} }); }
/** * Original by Samuel Flores * * Adds the following new token classes: * constant, builtin, variable, symbol, regex */ Prism.languages.ruby = Prism.languages.extend('clike', { 'comment': /#(?!\{[^\r\n]*?\})[^\r\n]*(\r?\n|$)/, 'keyword': /\b(alias|and|BEGIN|begin|break|case|class|def|define_method|defined|do|each|else|elsif|END|end|ensure|false|for|if|in|module|new|next|nil|not|or|raise|redo|require|rescue|retry|return|self|super|then|throw|true|undef|unless|until|when|while|yield)\b/, 'builtin': /\b(Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Stat|File|Fixnum|Fload|Hash|Integer|IO|MatchData|Method|Module|NilClass|Numeric|Object|Proc|Range|Regexp|String|Struct|TMS|Symbol|ThreadGroup|Thread|Time|TrueClass)\b/, 'constant': /\b[A-Z][a-zA-Z_0-9]*[?!]?\b/ }); Prism.languages.insertBefore('ruby', 'keyword', { 'regex': { pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/, lookbehind: true }, 'variable': /[@$]+\b[a-zA-Z_][a-zA-Z_0-9]*[?!]?\b/, 'symbol': /:\b[a-zA-Z_][a-zA-Z_0-9]*[?!]?\b/ }); Prism.languages.ruby.string = { pattern: /("|')(#\{[^}]+\}|\\\n|\\?.)*?\1/, inside: { 'interpolation': { pattern: /#\{[^}]+\}/, inside: { 'delimiter': { pattern: /^#\{|\}$/, alias: 'tag' }, rest: Prism.util.clone(Prism.languages.ruby) } } } };
/** @type {import('@docusaurus/types').DocusaurusConfig} */ module.exports = { title: "SiraUtil Documentation", tagline: "The best modding utility for Beat Saber", url: "https://wiki.project-sira.tech", baseUrl: "/", onBrokenLinks: "throw", onBrokenMarkdownLinks: "warn", favicon: "img/favicon.ico", organizationName: "projectsira", projectName: "sirautil-docs", themeConfig: { navbar: { title: "SiraUtil", logo: { alt: "SIRA Logo", src: "img/logo.png", }, items: [ { type: "doc", docId: "about/what-is-sirautil", position: "left", label: "Guide", }, ], }, }, presets: [ [ "@docusaurus/preset-classic", { docs: { sidebarPath: require.resolve("./sidebars.js"), // Please change this to your repo. editUrl: "https://github.com/ProjectSIRA/SiraUtil-Docs/tree/main", }, theme: { customCss: require.resolve("./src/css/custom.css"), }, }, ], ], };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties'); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _Input = require('../Input'); var _Input2 = _interopRequireDefault(_Input); var _FormControl = require('../Form/FormControl'); var _FormControl2 = _interopRequireDefault(_FormControl); var _FormHelperText = require('../Form/FormHelperText'); var _FormHelperText2 = _interopRequireDefault(_FormHelperText); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var babelPluginFlowReactPropTypes_proptype_Node = require('react').babelPluginFlowReactPropTypes_proptype_Node || require('prop-types').any; // @inheritedComponent FormControl var babelPluginFlowReactPropTypes_proptype_Props = { autoComplete: require('prop-types').string, autoFocus: require('prop-types').bool, className: require('prop-types').string, defaultValue: require('prop-types').string, disabled: require('prop-types').bool, error: require('prop-types').bool, FormHelperTextProps: require('prop-types').object, fullWidth: require('prop-types').bool, helperText: typeof babelPluginFlowReactPropTypes_proptype_Node === 'function' ? babelPluginFlowReactPropTypes_proptype_Node : require('prop-types').shape(babelPluginFlowReactPropTypes_proptype_Node), helperTextClassName: require('prop-types').string, id: require('prop-types').string, inputClassName: require('prop-types').string, InputClassName: require('prop-types').string, InputLabelProps: require('prop-types').object, inputProps: require('prop-types').object, InputProps: require('prop-types').object, inputRef: require('prop-types').func, label: typeof babelPluginFlowReactPropTypes_proptype_Node === 'function' ? babelPluginFlowReactPropTypes_proptype_Node : require('prop-types').shape(babelPluginFlowReactPropTypes_proptype_Node), labelClassName: require('prop-types').string, multiline: require('prop-types').bool, name: require('prop-types').string, placeholder: require('prop-types').string, required: require('prop-types').bool, rootRef: require('prop-types').func, rows: require('prop-types').oneOfType([require('prop-types').string, require('prop-types').number]), rowsMax: require('prop-types').oneOfType([require('prop-types').string, require('prop-types').number]), type: require('prop-types').string, value: require('prop-types').oneOfType([require('prop-types').string, require('prop-types').number]), margin: require('prop-types').oneOf(['none', 'dense', 'normal']) }; function TextField(props) { var autoComplete = props.autoComplete, autoFocus = props.autoFocus, className = props.className, defaultValue = props.defaultValue, disabled = props.disabled, error = props.error, id = props.id, inputClassName = props.inputClassName, InputClassName = props.InputClassName, inputPropsProp = props.inputProps, InputProps = props.InputProps, inputRef = props.inputRef, label = props.label, labelClassName = props.labelClassName, InputLabelProps = props.InputLabelProps, helperText = props.helperText, helperTextClassName = props.helperTextClassName, FormHelperTextProps = props.FormHelperTextProps, fullWidth = props.fullWidth, required = props.required, type = props.type, multiline = props.multiline, name = props.name, placeholder = props.placeholder, rootRef = props.rootRef, rows = props.rows, rowsMax = props.rowsMax, value = props.value, other = (0, _objectWithoutProperties3.default)(props, ['autoComplete', 'autoFocus', 'className', 'defaultValue', 'disabled', 'error', 'id', 'inputClassName', 'InputClassName', 'inputProps', 'InputProps', 'inputRef', 'label', 'labelClassName', 'InputLabelProps', 'helperText', 'helperTextClassName', 'FormHelperTextProps', 'fullWidth', 'required', 'type', 'multiline', 'name', 'placeholder', 'rootRef', 'rows', 'rowsMax', 'value']); var inputProps = inputPropsProp; if (inputClassName) { inputProps = (0, _extends3.default)({ className: inputClassName }, inputProps); } return _react2.default.createElement( _FormControl2.default, (0, _extends3.default)({ fullWidth: fullWidth, ref: rootRef, className: className, error: error, required: required }, other), label && _react2.default.createElement( _Input.InputLabel, (0, _extends3.default)({ htmlFor: id, className: labelClassName }, InputLabelProps), label ), _react2.default.createElement(_Input2.default, (0, _extends3.default)({ autoComplete: autoComplete, autoFocus: autoFocus, className: InputClassName, defaultValue: defaultValue, disabled: disabled, multiline: multiline, name: name, rows: rows, rowsMax: rowsMax, type: type, value: value, id: id, inputProps: inputProps, inputRef: inputRef, placeholder: placeholder }, InputProps)), helperText && _react2.default.createElement( _FormHelperText2.default, (0, _extends3.default)({ className: helperTextClassName }, FormHelperTextProps), helperText ) ); } TextField.propTypes = process.env.NODE_ENV !== "production" ? babelPluginFlowReactPropTypes_proptype_Props : {}; TextField.defaultProps = { required: false }; exports.default = TextField;
import React, { createRef, useContext, useEffect } from "react"; import { findNodeHandle, Text } from "react-native"; import { RawButton } from "react-native-gesture-handler"; import { NativeAdContext } from "./context"; const CallToActionView = (props) => { const { nativeAd, nativeAdView, setNativeAdView, setNativeAd } = useContext( NativeAdContext ); const callToActionRef = createRef(); const _onLayout = () => { if (!nativeAdView) return; let handle = findNodeHandle(callToActionRef.current); nativeAdView.setNativeProps({ callToAction: handle, }); }; useEffect(() => { _onLayout(); }, [nativeAd, nativeAdView]); return ( <RawButton ref={callToActionRef} onLayout={_onLayout} style={[ { paddingVertical: 8, paddingHorizontal: 12, backgroundColor: "#5DADE2", justifyContent: "center", alignItems: "center", borderRadius: 5, elevation: 10, }, props.style, ]} > <Text allowFontScaling={props.allowFontScaling ? props.allowFontScaling : false} style={[props.textStyle]}> {nativeAd ? props.allCaps ? nativeAd.callToAction?.toUpperCase() : nativeAd.callToAction : null} </Text> </RawButton> ); }; export default CallToActionView;
define([ "./_BusyButtonMixin", "dijit/form/ComboButton", "dojo/_base/declare" ], function(_BusyButtonMixin, ComboButton, declare){ return declare("dojox.form.BusyComboButton", [ComboButton, _BusyButtonMixin], {}); });
/** * Chartist SVG module for simple SVG DOM abstraction * * @module Chartist.Svg */ /* global Chartist */ (function(window, document, Chartist) { 'use strict'; /** * Chartist.Svg creates a new SVG object wrapper with a starting element. You can use the wrapper to fluently create sub-elements and modify them. * * @memberof Chartist.Svg * @constructor * @param {String|Element} name The name of the SVG element to create or an SVG dom element which should be wrapped into Chartist.Svg * @param {Object} attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added. * @param {String} className This class or class list will be added to the SVG element * @param {Object} parent The parent SVG wrapper object where this newly created wrapper and it's element will be attached to as child * @param {Boolean} insertFirst If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element */ function Svg(name, attributes, className, parent, insertFirst) { // If Svg is getting called with an SVG element we just return the wrapper if(name instanceof Element) { this._node = name; } else { this._node = document.createElementNS(Chartist.namespaces.svg, name); // If this is an SVG element created then custom namespace if(name === 'svg') { this.attr({ 'xmlns:ct': Chartist.namespaces.ct }); } } if(attributes) { this.attr(attributes); } if(className) { this.addClass(className); } if(parent) { if (insertFirst && parent._node.firstChild) { parent._node.insertBefore(this._node, parent._node.firstChild); } else { parent._node.appendChild(this._node); } } } /** * Set attributes on the current SVG element of the wrapper you're currently working on. * * @memberof Chartist.Svg * @param {Object|String} attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added. If this parameter is a String then the function is used as a getter and will return the attribute value. * @param {String} ns If specified, the attribute will be obtained using getAttributeNs. In order to write namepsaced attributes you can use the namespace:attribute notation within the attributes object. * @return {Object|String} The current wrapper object will be returned so it can be used for chaining or the attribute value if used as getter function. */ function attr(attributes, ns) { if(typeof attributes === 'string') { if(ns) { return this._node.getAttributeNS(ns, attributes); } else { return this._node.getAttribute(attributes); } } Object.keys(attributes).forEach(function(key) { // If the attribute value is undefined we can skip this one if(attributes[key] === undefined) { return; } if (key.indexOf(':') !== -1) { var namespacedAttribute = key.split(':'); this._node.setAttributeNS(Chartist.namespaces[namespacedAttribute[0]], key, attributes[key]); } else { this._node.setAttribute(key, attributes[key]); } }.bind(this)); return this; } /** * Create a new SVG element whose wrapper object will be selected for further operations. This way you can also create nested groups easily. * * @memberof Chartist.Svg * @param {String} name The name of the SVG element that should be created as child element of the currently selected element wrapper * @param {Object} [attributes] An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added. * @param {String} [className] This class or class list will be added to the SVG element * @param {Boolean} [insertFirst] If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element * @return {Chartist.Svg} Returns a Chartist.Svg wrapper object that can be used to modify the containing SVG data */ function elem(name, attributes, className, insertFirst) { return new Chartist.Svg(name, attributes, className, this, insertFirst); } /** * Returns the parent Chartist.SVG wrapper object * * @memberof Chartist.Svg * @return {Chartist.Svg} Returns a Chartist.Svg wrapper around the parent node of the current node. If the parent node is not existing or it's not an SVG node then this function will return null. */ function parent() { return this._node.parentNode instanceof SVGElement ? new Chartist.Svg(this._node.parentNode) : null; } /** * This method returns a Chartist.Svg wrapper around the root SVG element of the current tree. * * @memberof Chartist.Svg * @return {Chartist.Svg} The root SVG element wrapped in a Chartist.Svg element */ function root() { var node = this._node; while(node.nodeName !== 'svg') { node = node.parentNode; } return new Chartist.Svg(node); } /** * Find the first child SVG element of the current element that matches a CSS selector. The returned object is a Chartist.Svg wrapper. * * @memberof Chartist.Svg * @param {String} selector A CSS selector that is used to query for child SVG elements * @return {Chartist.Svg} The SVG wrapper for the element found or null if no element was found */ function querySelector(selector) { var foundNode = this._node.querySelector(selector); return foundNode ? new Chartist.Svg(foundNode) : null; } /** * Find the all child SVG elements of the current element that match a CSS selector. The returned object is a Chartist.Svg.List wrapper. * * @memberof Chartist.Svg * @param {String} selector A CSS selector that is used to query for child SVG elements * @return {Chartist.Svg.List} The SVG wrapper list for the element found or null if no element was found */ function querySelectorAll(selector) { var foundNodes = this._node.querySelectorAll(selector); return foundNodes.length ? new Chartist.Svg.List(foundNodes) : null; } /** * This method creates a foreignObject (see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject) that allows to embed HTML content into a SVG graphic. With the help of foreignObjects you can enable the usage of regular HTML elements inside of SVG where they are subject for SVG positioning and transformation but the Browser will use the HTML rendering capabilities for the containing DOM. * * @memberof Chartist.Svg * @param {Node|String} content The DOM Node, or HTML string that will be converted to a DOM Node, that is then placed into and wrapped by the foreignObject * @param {String} [attributes] An object with properties that will be added as attributes to the foreignObject element that is created. Attributes with undefined values will not be added. * @param {String} [className] This class or class list will be added to the SVG element * @param {Boolean} [insertFirst] Specifies if the foreignObject should be inserted as first child * @return {Chartist.Svg} New wrapper object that wraps the foreignObject element */ function foreignObject(content, attributes, className, insertFirst) { // If content is string then we convert it to DOM // TODO: Handle case where content is not a string nor a DOM Node if(typeof content === 'string') { var container = document.createElement('div'); container.innerHTML = content; content = container.firstChild; } // Adding namespace to content element content.setAttribute('xmlns', Chartist.namespaces.xmlns); // Creating the foreignObject without required extension attribute (as described here // http://www.w3.org/TR/SVG/extend.html#ForeignObjectElement) var fnObj = this.elem('foreignObject', attributes, className, insertFirst); // Add content to foreignObjectElement fnObj._node.appendChild(content); return fnObj; } /** * This method adds a new text element to the current Chartist.Svg wrapper. * * @memberof Chartist.Svg * @param {String} t The text that should be added to the text element that is created * @return {Chartist.Svg} The same wrapper object that was used to add the newly created element */ function text(t) { this._node.appendChild(document.createTextNode(t)); return this; } /** * This method will clear all child nodes of the current wrapper object. * * @memberof Chartist.Svg * @return {Chartist.Svg} The same wrapper object that got emptied */ function empty() { while (this._node.firstChild) { this._node.removeChild(this._node.firstChild); } return this; } /** * This method will cause the current wrapper to remove itself from its parent wrapper. Use this method if you'd like to get rid of an element in a given DOM structure. * * @memberof Chartist.Svg * @return {Chartist.Svg} The parent wrapper object of the element that got removed */ function remove() { this._node.parentNode.removeChild(this._node); return this.parent(); } /** * This method will replace the element with a new element that can be created outside of the current DOM. * * @memberof Chartist.Svg * @param {Chartist.Svg} newElement The new Chartist.Svg object that will be used to replace the current wrapper object * @return {Chartist.Svg} The wrapper of the new element */ function replace(newElement) { this._node.parentNode.replaceChild(newElement._node, this._node); return newElement; } /** * This method will append an element to the current element as a child. * * @memberof Chartist.Svg * @param {Chartist.Svg} element The Chartist.Svg element that should be added as a child * @param {Boolean} [insertFirst] Specifies if the element should be inserted as first child * @return {Chartist.Svg} The wrapper of the appended object */ function append(element, insertFirst) { if(insertFirst && this._node.firstChild) { this._node.insertBefore(element._node, this._node.firstChild); } else { this._node.appendChild(element._node); } return this; } /** * Returns an array of class names that are attached to the current wrapper element. This method can not be chained further. * * @memberof Chartist.Svg * @return {Array} A list of classes or an empty array if there are no classes on the current element */ function classes() { return this._node.getAttribute('class') ? this._node.getAttribute('class').trim().split(/\s+/) : []; } /** * Adds one or a space separated list of classes to the current element and ensures the classes are only existing once. * * @memberof Chartist.Svg * @param {String} names A white space separated list of class names * @return {Chartist.Svg} The wrapper of the current element */ function addClass(names) { this._node.setAttribute('class', this.classes(this._node) .concat(names.trim().split(/\s+/)) .filter(function(elem, pos, self) { return self.indexOf(elem) === pos; }).join(' ') ); return this; } /** * Removes one or a space separated list of classes from the current element. * * @memberof Chartist.Svg * @param {String} names A white space separated list of class names * @return {Chartist.Svg} The wrapper of the current element */ function removeClass(names) { var removedClasses = names.trim().split(/\s+/); this._node.setAttribute('class', this.classes(this._node).filter(function(name) { return removedClasses.indexOf(name) === -1; }).join(' ')); return this; } /** * Removes all classes from the current element. * * @memberof Chartist.Svg * @return {Chartist.Svg} The wrapper of the current element */ function removeAllClasses() { this._node.setAttribute('class', ''); return this; } /** * Get element height using `getBoundingClientRect` * * @memberof Chartist.Svg * @return {Number} The elements height in pixels */ function height() { return this._node.getBoundingClientRect().height; } /** * Get element width using `getBoundingClientRect` * * @memberof Chartist.Core * @return {Number} The elements width in pixels */ function width() { return this._node.getBoundingClientRect().width; } /** * The animate function lets you animate the current element with SMIL animations. You can add animations for multiple attributes at the same time by using an animation definition object. This object should contain SMIL animation attributes. Please refer to http://www.w3.org/TR/SVG/animate.html for a detailed specification about the available animation attributes. Additionally an easing property can be passed in the animation definition object. This can be a string with a name of an easing function in `Chartist.Svg.Easing` or an array with four numbers specifying a cubic Bézier curve. * **An animations object could look like this:** * ```javascript * element.animate({ * opacity: { * dur: 1000, * from: 0, * to: 1 * }, * x1: { * dur: '1000ms', * from: 100, * to: 200, * easing: 'easeOutQuart' * }, * y1: { * dur: '2s', * from: 0, * to: 100 * } * }); * ``` * **Automatic unit conversion** * For the `dur` and the `begin` animate attribute you can also omit a unit by passing a number. The number will automatically be converted to milli seconds. * **Guided mode** * The default behavior of SMIL animations with offset using the `begin` attribute is that the attribute will keep it's original value until the animation starts. Mostly this behavior is not desired as you'd like to have your element attributes already initialized with the animation `from` value even before the animation starts. Also if you don't specify `fill="freeze"` on an animate element or if you delete the animation after it's done (which is done in guided mode) the attribute will switch back to the initial value. This behavior is also not desired when performing simple one-time animations. For one-time animations you'd want to trigger animations immediately instead of relative to the document begin time. That's why in guided mode Chartist.Svg will also use the `begin` property to schedule a timeout and manually start the animation after the timeout. If you're using multiple SMIL definition objects for an attribute (in an array), guided mode will be disabled for this attribute, even if you explicitly enabled it. * If guided mode is enabled the following behavior is added: * - Before the animation starts (even when delayed with `begin`) the animated attribute will be set already to the `from` value of the animation * - `begin` is explicitly set to `indefinite` so it can be started manually without relying on document begin time (creation) * - The animate element will be forced to use `fill="freeze"` * - The animation will be triggered with `beginElement()` in a timeout where `begin` of the definition object is interpreted in milli seconds. If no `begin` was specified the timeout is triggered immediately. * - After the animation the element attribute value will be set to the `to` value of the animation * - The animate element is deleted from the DOM * * @memberof Chartist.Svg * @param {Object} animations An animations object where the property keys are the attributes you'd like to animate. The properties should be objects again that contain the SMIL animation attributes (usually begin, dur, from, and to). The property begin and dur is auto converted (see Automatic unit conversion). You can also schedule multiple animations for the same attribute by passing an Array of SMIL definition objects. Attributes that contain an array of SMIL definition objects will not be executed in guided mode. * @param {Boolean} guided Specify if guided mode should be activated for this animation (see Guided mode). If not otherwise specified, guided mode will be activated. * @param {Object} eventEmitter If specified, this event emitter will be notified when an animation starts or ends. * @return {Chartist.Svg} The current element where the animation was added */ function animate(animations, guided, eventEmitter) { if(guided === undefined) { guided = true; } Object.keys(animations).forEach(function createAnimateForAttributes(attribute) { function createAnimate(animationDefinition, guided) { var attributeProperties = {}, animate, timeout, easing; // Check if an easing is specified in the definition object and delete it from the object as it will not // be part of the animate element attributes. if(animationDefinition.easing) { // If already an easing Bézier curve array we take it or we lookup a easing array in the Easing object easing = animationDefinition.easing instanceof Array ? animationDefinition.easing : Chartist.Svg.Easing[animationDefinition.easing]; delete animationDefinition.easing; } // If numeric dur or begin was provided we assume milli seconds animationDefinition.begin = Chartist.ensureUnit(animationDefinition.begin, 'ms'); animationDefinition.dur = Chartist.ensureUnit(animationDefinition.dur, 'ms'); if(easing) { animationDefinition.calcMode = 'spline'; animationDefinition.keySplines = easing.join(' '); animationDefinition.keyTimes = '0;1'; } // Adding "fill: freeze" if we are in guided mode and set initial attribute values if(guided) { animationDefinition.fill = 'freeze'; // Animated property on our element should already be set to the animation from value in guided mode attributeProperties[attribute] = animationDefinition.from; this.attr(attributeProperties); // In guided mode we also set begin to indefinite so we can trigger the start manually and put the begin // which needs to be in ms aside timeout = Chartist.quantity(animationDefinition.begin || 0).value; animationDefinition.begin = 'indefinite'; } animate = this.elem('animate', Chartist.extend({ attributeName: attribute }, animationDefinition)); if(guided) { // If guided we take the value that was put aside in timeout and trigger the animation manually with a timeout setTimeout(function() { // If beginElement fails we set the animated attribute to the end position and remove the animate element // This happens if the SMIL ElementTimeControl interface is not supported or any other problems occured in // the browser. (Currently FF 34 does not support animate elements in foreignObjects) try { animate._node.beginElement(); } catch(err) { // Set animated attribute to current animated value attributeProperties[attribute] = animationDefinition.to; this.attr(attributeProperties); // Remove the animate element as it's no longer required animate.remove(); } }.bind(this), timeout); } if(eventEmitter) { animate._node.addEventListener('beginEvent', function handleBeginEvent() { eventEmitter.emit('animationBegin', { element: this, animate: animate._node, params: animationDefinition }); }.bind(this)); } animate._node.addEventListener('endEvent', function handleEndEvent() { if(eventEmitter) { eventEmitter.emit('animationEnd', { element: this, animate: animate._node, params: animationDefinition }); } if(guided) { // Set animated attribute to current animated value attributeProperties[attribute] = animationDefinition.to; this.attr(attributeProperties); // Remove the animate element as it's no longer required animate.remove(); } }.bind(this)); } // If current attribute is an array of definition objects we create an animate for each and disable guided mode if(animations[attribute] instanceof Array) { animations[attribute].forEach(function(animationDefinition) { createAnimate.bind(this)(animationDefinition, false); }.bind(this)); } else { createAnimate.bind(this)(animations[attribute], guided); } }.bind(this)); return this; } Chartist.Svg = Chartist.Class.extend({ constructor: Svg, attr: attr, elem: elem, parent: parent, root: root, querySelector: querySelector, querySelectorAll: querySelectorAll, foreignObject: foreignObject, text: text, empty: empty, remove: remove, replace: replace, append: append, classes: classes, addClass: addClass, removeClass: removeClass, removeAllClasses: removeAllClasses, height: height, width: width, animate: animate }); /** * This method checks for support of a given SVG feature like Extensibility, SVG-animation or the like. Check http://www.w3.org/TR/SVG11/feature for a detailed list. * * @memberof Chartist.Svg * @param {String} feature The SVG 1.1 feature that should be checked for support. * @return {Boolean} True of false if the feature is supported or not */ Chartist.Svg.isSupported = function(feature) { return document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#' + feature, '1.1'); }; /** * This Object contains some standard easing cubic bezier curves. Then can be used with their name in the `Chartist.Svg.animate`. You can also extend the list and use your own name in the `animate` function. Click the show code button to see the available bezier functions. * * @memberof Chartist.Svg */ var easingCubicBeziers = { easeInSine: [0.47, 0, 0.745, 0.715], easeOutSine: [0.39, 0.575, 0.565, 1], easeInOutSine: [0.445, 0.05, 0.55, 0.95], easeInQuad: [0.55, 0.085, 0.68, 0.53], easeOutQuad: [0.25, 0.46, 0.45, 0.94], easeInOutQuad: [0.455, 0.03, 0.515, 0.955], easeInCubic: [0.55, 0.055, 0.675, 0.19], easeOutCubic: [0.215, 0.61, 0.355, 1], easeInOutCubic: [0.645, 0.045, 0.355, 1], easeInQuart: [0.895, 0.03, 0.685, 0.22], easeOutQuart: [0.165, 0.84, 0.44, 1], easeInOutQuart: [0.77, 0, 0.175, 1], easeInQuint: [0.755, 0.05, 0.855, 0.06], easeOutQuint: [0.23, 1, 0.32, 1], easeInOutQuint: [0.86, 0, 0.07, 1], easeInExpo: [0.95, 0.05, 0.795, 0.035], easeOutExpo: [0.19, 1, 0.22, 1], easeInOutExpo: [1, 0, 0, 1], easeInCirc: [0.6, 0.04, 0.98, 0.335], easeOutCirc: [0.075, 0.82, 0.165, 1], easeInOutCirc: [0.785, 0.135, 0.15, 0.86], easeInBack: [0.6, -0.28, 0.735, 0.045], easeOutBack: [0.175, 0.885, 0.32, 1.275], easeInOutBack: [0.68, -0.55, 0.265, 1.55] }; Chartist.Svg.Easing = easingCubicBeziers; /** * This helper class is to wrap multiple `Chartist.Svg` elements into a list where you can call the `Chartist.Svg` functions on all elements in the list with one call. This is helpful when you'd like to perform calls with `Chartist.Svg` on multiple elements. * An instance of this class is also returned by `Chartist.Svg.querySelectorAll`. * * @memberof Chartist.Svg * @param {Array<Node>|NodeList} nodeList An Array of SVG DOM nodes or a SVG DOM NodeList (as returned by document.querySelectorAll) * @constructor */ function SvgList(nodeList) { var list = this; this.svgElements = []; for(var i = 0; i < nodeList.length; i++) { this.svgElements.push(new Chartist.Svg(nodeList[i])); } // Add delegation methods for Chartist.Svg Object.keys(Chartist.Svg.prototype).filter(function(prototypeProperty) { return ['constructor', 'parent', 'querySelector', 'querySelectorAll', 'replace', 'append', 'classes', 'height', 'width'].indexOf(prototypeProperty) === -1; }).forEach(function(prototypeProperty) { list[prototypeProperty] = function() { var args = Array.prototype.slice.call(arguments, 0); list.svgElements.forEach(function(element) { Chartist.Svg.prototype[prototypeProperty].apply(element, args); }); return list; }; }); } Chartist.Svg.List = Chartist.Class.extend({ constructor: SvgList }); }(window, document, Chartist));
var _ = require('lodash'), pack = require('./src/pack'), unpack = require('./src/unpack'); module.exports = { pack: pack.pack, unpack: unpack.unpack };
const {createCompetition,getCompetition,getAllCompetitions,deleteCompetition} = require("../controllers/competition.controller") const express = require("express"); const router = express.Router(); const { authenticate } = require("../middlewares/auth.middleware"); const { uploadFile } = require("../utils/fileUpload.utils") const upload = uploadFile("competitionImages") router.get("/competitions/:competitionId",authenticate,getCompetition) router.get("/competitions",authenticate,getAllCompetitions) router.post("/competitions/new",[upload.single('CoverPhoto'),authenticate],createCompetition) router.delete("/competitions/:competitionId",authenticate,deleteCompetition) module.exports=router
import React from "react"; import theme from "theme"; import { Theme, Link, Section, Box } from "@quarkly/widgets"; import { Helmet } from "react-helmet"; import { GlobalQuarklyPageStyles } from "global-page-styles"; import { Override } from "@quarkly/components"; import * as Components from "components"; export default (() => { return <Theme theme={theme}> <GlobalQuarklyPageStyles pageUrl={"index/interface/dashboard/restore-project"} /> <Helmet> <title> Quarkly export </title> <meta name={"description"} content={"Web site created using quarkly.io"} /> <link rel={"shortcut icon"} href={"https://uploads.quarkly.io/readme/cra/favicon-32x32.ico"} type={"image/x-icon"} /> </Helmet> <Components.MobileMenu> <Override slot="menu"> <Override slot="item-404" display="none" /> </Override> </Components.MobileMenu> <Components.Header /> <Box display="flex" quarkly-title="Content"> <Components.SidebarMenu /> <Section background="--color-white" padding="24px 0 64px 0"> <Override slot="SectionContent" max-width="760px" /> <Components.HelpHeader2> Восстановление удаленного проекта </Components.HelpHeader2> <Components.HelpGroup> <Components.HelpImageBlockCapture> <Override slot="helpImageBlock" src="https://test-upl.quarkly.io/607d3473b99fb9001fcbcc16/images/docs-new-dashboard-restore-project.png?v=2021-05-15T08:15:05.691Z" /> <Override slot="text"> Пункт "Restore" в контекстном меню восстанавливает проект </Override> </Components.HelpImageBlockCapture> <Components.HelpParagraph> После первого удаления проекта он перемещается в Archived. Редактировать проект в этом разделе нельзя. Чтобы появилась возможность редактировать проект, нужно его восстановить. Как восстановить проект: </Components.HelpParagraph> <Components.HelpListNumbered> <Components.HelpListItem> Перейдите в раздел Archived </Components.HelpListItem> <Components.HelpListItem> Выберите проект, который хотите восстановить </Components.HelpListItem> <Components.HelpListItem> Вызовите контекстное меню проекта на правую кнопку мыши </Components.HelpListItem> <Components.HelpListItem> Выберите пункт "Restore" </Components.HelpListItem> </Components.HelpListNumbered> </Components.HelpGroup> <Components.HelpPrevNextButton /> </Section> </Box> <Components.FooterHigh /> <Link font={"--capture"} font-size={"10px"} position={"fixed"} bottom={"12px"} right={"12px"} z-index={"4"} border-radius={"4px"} padding={"5px 12px 4px"} background-color={"--dark"} opacity={"0.6"} hover-opacity={"1"} color={"--light"} cursor={"pointer"} transition={"--opacityOut"} quarkly-title={"Badge"} text-decoration-line={"initial"} href={"https://quarkly.io/"} target={"_blank"} > Made on Quarkly </Link> </Theme>; });
const Context = require('android.content.Context'); const Inflater = require('android.view.LayoutInflater'); const Activity = require('android.app.Activity'); const LinearLayout = require('android.widget.LinearLayout'); const AppCompatActivity = require('androidx.appcompat.app.AppCompatActivity'); const activity = new Activity(Ti.Android.currentActivity); const View = require("android.view.View"); const Toolbar = require("androidx.appcompat.widget.Toolbar"); const appCompatActivity = new AppCompatActivity(Ti.Android.currentActivity); const resID = activity.getResources().getIdentifier('toolbar_layout', 'layout', activity.getPackageName()); const inflater = Inflater.cast(activity.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)); const view = inflater.inflate(resIDFromString('toolbar_layout', 'layout'), null); const toolbar = Toolbar.cast(view.findViewById(resIDFromString('toolbar', 'id'))); const content = LinearLayout.cast(view.findViewById(resIDFromString('content', 'id'))); function resIDFromString(variableName, resourceName) { return activity.getResources().getIdentifier(variableName, resourceName, activity.getPackageName()); } // // add a complete Titanium XML to the native view var tiView = Alloy.createController("/content").getView(); content.addView(tiView, 0); appCompatActivity.setSupportActionBar(toolbar); appCompatActivity.getSupportActionBar().setHomeButtonEnabled(true); appCompatActivity.getSupportActionBar().setDisplayHomeAsUpEnabled(true); appCompatActivity.getSupportActionBar().setDisplayShowHomeEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener({ onClick: function(e) { $.third.close(); } })); $.third.add(view); $.third.addEventListener("open", function(e) {}); $.third.open();
define("Cedtory/mods/xss",function(require,exports,module){ var defaultWhiteList = { h1: [], h2: [], h3: [], h4: [], h5: [], h6: [], hr: [], span: [], strong: [], b: [], i: [], br: [], p: [], pre: [], code: [], a: ['target', 'href', 'title'], img: ['src', 'alt', 'title', 'width', 'height'], div: [], table: ['width', 'border'], tr: ['rowspan'], td: ['width', 'colspan'], th: ['width', 'colspan'], tbody: [], ul: [], li: [], ol: [], dl: [], dt: [], em: [], cite: [], section:[], header: [], footer: [], blockquote: [], audio: ['autoplay', 'controls', 'loop', 'preload', 'src'], video: ['autoplay', 'controls', 'loop', 'preload', 'src', 'height', 'width'] }; var REGEXP_LT = /</g; var REGEXP_GT = />/g; var REGEXP_QUOTE = /"/g; var REGEXP_ATTR_NAME = /[^a-zA-Z0-9_:\.\-]/img; var REGEXP_ATTR_VALUE = /&#([a-zA-Z0-9]*);?/img; var REGEXP_DEFAULT_ON_TAG_ATTR_1 = /\/\*|\* var REGEXP_DEFAULT_ON_TAG_ATTR_2 = /^[\s"'`]*((j\s*a\s*v\s*a|v\s*b|l\s*i\s*v\s*e)\s*s\s*c\s*r\s*i\s*p\s*t\s*|m\s*o\s*c\s*h\s*a):/ig; var REGEXP_DEFAULT_ON_TAG_ATTR_3 = /\/\*|\* var REGEXP_DEFAULT_ON_TAG_ATTR_4 = /((j\s*a\s*v\s*a|v\s*b|l\s*i\s*v\s*e)\s*s\s*c\s*r\s*i\s*p\s*t\s*|m\s*o\s*c\s*h\s*a):/ig; function defaultOnTagAttr (tag, attr, value) { if (attr === 'href' || attr === 'src') { REGEXP_DEFAULT_ON_TAG_ATTR_1.lastIndex = 0; if (REGEXP_DEFAULT_ON_TAG_ATTR_1.test(value)) { return '#'; } REGEXP_DEFAULT_ON_TAG_ATTR_2.lastIndex = 0; if (REGEXP_DEFAULT_ON_TAG_ATTR_2.test(value)) { return '#'; } } else if (attr === 'style') { REGEXP_DEFAULT_ON_TAG_ATTR_3.lastIndex = 0; if (REGEXP_DEFAULT_ON_TAG_ATTR_3.test(value)) { return '#'; } REGEXP_DEFAULT_ON_TAG_ATTR_4.lastIndex = 0; if (REGEXP_DEFAULT_ON_TAG_ATTR_4.test(value)) { return ''; } } } function defaultOnIgnoreTag (tag, html, options) { return noTag(html); } function noTag (text) { return text.replace(REGEXP_LT, '&lt;').replace(REGEXP_GT, '&gt;'); } function replaceUnicode (str, code) { return String.fromCharCode(parseInt(code)); } function FilterXSS (options) { 'use strict'; this.options = options = options || {}; this.whiteList = options.whiteList || exports.whiteList; this.onTagAttr = options.onTagAttr || exports.onTagAttr; this.onIgnoreTag = options.onIgnoreTag || exports.onIgnoreTag; } FilterXSS.prototype.filterAttributes = function (tagName, attrs) { 'use strict'; tagName = tagName.toLowerCase(); var me = this; var whites = this.whiteList[tagName]; var lastPos = 0; var _attrs = ''; var tmpName = false; var hasSprit = false; var addAttr = function (name, value) { name = name.trim(); if (!hasSprit && name === '/') { hasSprit = true; return; }; name = name.replace(REGEXP_ATTR_NAME, '').toLowerCase(); if (name.length < 1) return; if (whites.indexOf(name) !== -1) { if (value) { value = value.trim().replace(REGEXP_QUOTE, '&quote;'); value = value.replace(REGEXP_ATTR_VALUE, replaceUnicode); var _value = ''; for (var i = 0, len = value.length; i < len; i++) { _value += value.charCodeAt(i) < 32 ? ' ' : value.charAt(i); } value = _value.trim(); var newValue = me.onTagAttr(tagName, name, value); if (typeof newValue !== 'undefined') { value = newValue; } } _attrs += name + (value ? '="' + value + '"' : '') + ' '; } }; for (var i = 0, len = attrs.length; i < len; i++) { var c = attrs.charAt(i); if (tmpName === false && c === '=') { tmpName = attrs.slice(lastPos, i); lastPos = i + 1; continue; } if (tmpName !== false) { if (i === lastPos && (c === '"' || c === "'")) { var j = attrs.indexOf(c, i + 1); if (j === -1) { break; } else { var v = attrs.slice(lastPos + 1, j).trim(); addAttr(tmpName, v); tmpName = false; i = j; lastPos = i + 1; continue; } } } if (c === ' ') { var v = attrs.slice(lastPos, i).trim(); if (tmpName === false) { addAttr(v); } else { addAttr(tmpName, v); } tmpName = false; lastPos = i + 1; continue; } } if (lastPos < attrs.length) { if (tmpName === false) { addAttr(attrs.slice(lastPos)); } else { addAttr(tmpName, attrs.slice(lastPos)); } } if (hasSprit) _attrs += '/'; return _attrs.trim(); }; FilterXSS.prototype.addNewTag = function (tag, currentPos, targetPos) { 'use strict'; var rethtml = ''; var spos = tag.slice(0, 2) === '</' ? 2 : 1; var i = tag.indexOf(' '); if (i === -1) { var tagName = tag.slice(spos, tag.length - 1).trim(); } else { var tagName = tag.slice(spos, i + 1).trim(); } tagName = tagName.toLowerCase(); if (tagName in this.whiteList) { if (i === -1) { rethtml += tag.slice(0, spos) + tagName + '>'; } else { var attrs = this.filterAttributes(tagName, tag.slice(i + 1, tag.length - 1).trim()); rethtml += tag.slice(0, spos) + tagName + (attrs.length > 0 ? ' ' + attrs : '') + '>'; } } else { var options = { isClosing: (spos === 2), position: targetPos, originalPosition: currentPos - tag.length + 1 }; var tagHtml = this.onIgnoreTag(tagName, tag, options); if (typeof tagHtml === 'undefined') { tagHtml = noTag(tag); } rethtml += tagHtml; } return rethtml; }; FilterXSS.prototype.process = function (html) { 'use strict'; var rethtml = ''; var lastPos = 0; var tagStart = false; var quoteStart = false; var currentPos = 0; for (var currentPos = 0, len = html.length; currentPos < len; currentPos++) { var c = html.charAt(currentPos); if (tagStart === false) { if (c === '<') { tagStart = currentPos; continue; } } else { if (quoteStart === false) { if (c === '<') { rethtml += noTag(html.slice(lastPos, currentPos)); tagStart = currentPos; lastPos = currentPos; continue; } if (c === '>') { rethtml += noTag(html.slice(lastPos, tagStart)); rethtml += this.addNewTag(html.slice(tagStart, currentPos + 1), currentPos, rethtml.length); lastPos = currentPos + 1; tagStart = false; continue; } if (c === '"' || c === "'") { quoteStart = c; continue; } } else { if (c === quoteStart) { quoteStart = false; continue; } } } } if (lastPos < html.length) { rethtml += noTag(html.substr(lastPos)); } return rethtml; }; function filterXSS (html, options) { var xss = new FilterXSS(options); return xss.process(html); }; exports = module.exports = filterXSS; exports.FilterXSS = FilterXSS; exports.whiteList = defaultWhiteList; exports.onTagAttr = defaultOnTagAttr; exports.onIgnoreTag = defaultOnIgnoreTag; utils = {}; utils.tagFilter = function (tags, next) { if (typeof(next) !== 'function') { next = function () {}; } var hidden = []; var posStart = false; return { onIgnoreTag: function (tag, html, options) { if (tags.indexOf(tag) !== -1) { var ret = '[removed]'; if (posStart !== false && options.isClosing) { var end = options.position + ret.length; hidden.push([posStart, end]); posStart = false; } else { posStart = options.position; } return ret; } else { return next(tag, html, options); } }, filter: function (html) { var rethtml = ''; var lastPos = 0; hidden.forEach(function (pos) { rethtml += html.slice(lastPos, pos[0]); lastPos = pos[1]; }); rethtml += html.slice(lastPos); return rethtml; } }; }; exports.utils = utils; });
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([[17],{"0a4f":function(t,e){},3605:function(t,e,a){"use strict";var o=a("0a4f"),n=a.n(o);e["default"]=n.a},"3ec7":function(t,e,a){"use strict";a.r(e);var o=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("div",[a("transition",{attrs:{appear:"","enter-active-class":"animated fadeIn"}},[a("q-table",{staticClass:"my-sticky-header-column-table shadow-24",attrs:{data:t.table_list,"row-key":"id",separator:t.separator,loading:t.loading,filter:t.filter,columns:t.columns,"hide-bottom":"",pagination:t.pagination,"no-data-label":"No data","no-results-label":"No data you want","table-style":{height:t.height},flat:"",bordered:""},on:{"update:pagination":function(e){t.pagination=e}},scopedSlots:t._u([{key:"top",fn:function(){return[a("q-btn-group",{attrs:{push:""}},[a("q-btn",{attrs:{label:t.$t("new"),icon:"add"},on:{click:function(e){t.newForm=!0}}},[a("q-tooltip",{attrs:{"content-class":"bg-amber text-black shadow-4",offset:[10,10],"content-style":"font-size: 12px"}},[t._v("\n "+t._s(t.$t("newtip"))+"\n ")])],1),a("q-btn",{attrs:{label:t.$t("refresh"),icon:"refresh"},on:{click:function(e){return t.reFresh()}}},[a("q-tooltip",{attrs:{"content-class":"bg-amber text-black shadow-4",offset:[10,10],"content-style":"font-size: 12px"}},[t._v("\n "+t._s(t.$t("refreshtip"))+"\n ")])],1)],1),a("q-space"),a("q-input",{attrs:{outlined:"",rounded:"",dense:"",debounce:"300",color:"primary",placeholder:t.$t("search")},on:{blur:function(e){return t.getSearchList()},keyup:function(e){return!e.type.indexOf("key")&&t._k(e.keyCode,"enter",13,e.key,"Enter")?null:t.getSearchList()}},scopedSlots:t._u([{key:"append",fn:function(){return[a("q-icon",{attrs:{name:"search"},on:{click:function(e){return t.getSearchList()}}})]},proxy:!0}]),model:{value:t.filter,callback:function(e){t.filter=e},expression:"filter"}})]},proxy:!0},{key:"body",fn:function(e){return[a("q-tr",{attrs:{props:e}},[e.row.id===t.editid?[a("q-td",{key:"goods_origin",attrs:{props:e}},[a("q-input",{attrs:{dense:"",outlined:"",square:"",label:t.$t("goods.view_goodslist.goods_origin"),autofocus:"",rules:[function(t){return t&&t.length>0||"Please Enter the Goods Origin"}]},model:{value:t.editFormData.goods_origin,callback:function(e){t.$set(t.editFormData,"goods_origin",e)},expression:"editFormData.goods_origin"}})],1)]:e.row.id!==t.editid?[a("q-td",{key:"goods_origin",attrs:{props:e}},[t._v("\n "+t._s(e.row.goods_origin)+"\n ")])]:t._e(),a("q-td",{key:"creater",attrs:{props:e}},[t._v("\n "+t._s(e.row.creater)+"\n ")]),a("q-td",{key:"create_time",attrs:{props:e}},[t._v("\n "+t._s(e.row.create_time)+"\n ")]),a("q-td",{key:"update_time",attrs:{props:e}},[t._v("\n "+t._s(e.row.update_time)+"\n ")]),t.editMode?t.editMode?[e.row.id===t.editid?[a("q-td",{key:"action",staticStyle:{width:"100px"},attrs:{props:e}},[a("q-btn",{attrs:{round:"",flat:"",push:"",color:"secondary",icon:"check"},on:{click:function(e){return t.editDataSubmit()}}},[a("q-tooltip",{attrs:{"content-class":"bg-amber text-black shadow-4",offset:[10,10],"content-style":"font-size: 12px"}},[t._v("\n "+t._s(t.$t("confirmedit"))+"\n ")])],1),a("q-btn",{attrs:{round:"",flat:"",push:"",color:"red",icon:"close"},on:{click:function(e){return t.editDataCancel()}}},[a("q-tooltip",{attrs:{"content-class":"bg-amber text-black shadow-4",offset:[10,10],"content-style":"font-size: 12px"}},[t._v("\n "+t._s(t.$t("canceledit"))+"\n ")])],1)],1)]:e.row.id!==t.editid?void 0:t._e()]:t._e():[a("q-td",{key:"action",staticStyle:{width:"100px"},attrs:{props:e}},[a("q-btn",{attrs:{round:"",flat:"",push:"",color:"purple",icon:"edit"},on:{click:function(a){return t.editData(e.row)}}},[a("q-tooltip",{attrs:{"content-class":"bg-amber text-black shadow-4",offset:[10,10],"content-style":"font-size: 12px"}},[t._v("\n "+t._s(t.$t("edit"))+"\n ")])],1),a("q-btn",{attrs:{round:"",flat:"",push:"",color:"dark",icon:"delete"},on:{click:function(a){return t.deleteData(e.row.id)}}},[a("q-tooltip",{attrs:{"content-class":"bg-amber text-black shadow-4",offset:[10,10],"content-style":"font-size: 12px"}},[t._v("\n "+t._s(t.$t("delete"))+"\n ")])],1)],1)]],2)]}}])})],1),[a("div",{staticClass:"q-pa-md flex flex-center"},[a("q-btn",{directives:[{name:"show",rawName:"v-show",value:t.pathname_previous,expression:"pathname_previous"}],attrs:{flat:"",push:"",color:"purple",label:t.$t("previous"),icon:"navigate_before"},on:{click:function(e){return t.getListPrevious()}}},[a("q-tooltip",{attrs:{"content-class":"bg-amber text-black shadow-4",offset:[10,10],"content-style":"font-size: 12px"}},[t._v("\n "+t._s(t.$t("previous"))+"\n ")])],1),a("q-btn",{directives:[{name:"show",rawName:"v-show",value:t.pathname_next,expression:"pathname_next"}],attrs:{flat:"",push:"",color:"purple",label:t.$t("next"),"icon-right":"navigate_next"},on:{click:function(e){return t.getListNext()}}},[a("q-tooltip",{attrs:{"content-class":"bg-amber text-black shadow-4",offset:[10,10],"content-style":"font-size: 12px"}},[t._v("\n "+t._s(t.$t("next"))+"\n ")])],1),a("q-btn",{directives:[{name:"show",rawName:"v-show",value:!t.pathname_previous&&!t.pathname_next,expression:"!pathname_previous && !pathname_next"}],attrs:{flat:"",push:"",color:"dark",label:t.$t("no_data")}})],1)],a("q-dialog",{model:{value:t.newForm,callback:function(e){t.newForm=e},expression:"newForm"}},[a("q-card",{staticClass:"shadow-24"},[a("q-bar",{staticClass:"bg-light-blue-10 text-white rounded-borders",staticStyle:{height:"50px"}},[a("div",[t._v(t._s(t.$t("newtip")))]),a("q-space"),a("q-btn",{directives:[{name:"close-popup",rawName:"v-close-popup"}],attrs:{dense:"",flat:"",icon:"close"}},[a("q-tooltip",{attrs:{"content-class":"bg-amber text-black shadow-4"}},[t._v(t._s(t.$t("index.close")))])],1)],1),a("q-card-section",{staticClass:"scroll",staticStyle:{"max-height":"325px",width:"400px"}},[a("q-input",{attrs:{dense:"",outlined:"",square:"",label:t.$t("goods.view_goodslist.goods_origin"),autofocus:"",rules:[function(t){return t&&t.length>0||"Please Enter the Goods Origin"}]},on:{keyup:function(e){return!e.type.indexOf("key")&&t._k(e.keyCode,"enter",13,e.key,"Enter")?null:t.newDataSubmit()}},model:{value:t.newFormData.goods_origin,callback:function(e){t.$set(t.newFormData,"goods_origin",e)},expression:"newFormData.goods_origin"}})],1),a("div",{staticStyle:{float:"right",padding:"15px 15px 15px 0"}},[a("q-btn",{staticStyle:{"margin-right":"25px"},attrs:{color:"white","text-color":"black"},on:{click:function(e){return t.newDataCancel()}}},[t._v(t._s(t.$t("cancel")))]),a("q-btn",{attrs:{color:"primary"},on:{click:function(e){return t.newDataSubmit()}}},[t._v(t._s(t.$t("submit")))])],1)],1)],1),a("q-dialog",{model:{value:t.deleteForm,callback:function(e){t.deleteForm=e},expression:"deleteForm"}},[a("q-card",{staticClass:"shadow-24"},[a("q-bar",{staticClass:"bg-light-blue-10 text-white rounded-borders",staticStyle:{height:"50px"}},[a("div",[t._v(t._s(t.$t("delete")))]),a("q-space"),a("q-btn",{directives:[{name:"close-popup",rawName:"v-close-popup"}],attrs:{dense:"",flat:"",icon:"close"}},[a("q-tooltip",[t._v(t._s(t.$t("index.close")))])],1)],1),a("q-card-section",{staticClass:"scroll",staticStyle:{"max-height":"325px",width:"400px"}},[t._v("\n "+t._s(t.$t("deletetip"))+"\n ")]),a("div",{staticStyle:{float:"right",padding:"15px 15px 15px 0"}},[a("q-btn",{staticStyle:{"margin-right":"25px"},attrs:{color:"white","text-color":"black"},on:{click:function(e){return t.deleteDataCancel()}}},[t._v(t._s(t.$t("cancel")))]),a("q-btn",{attrs:{color:"primary"},on:{click:function(e){return t.deleteDataSubmit()}}},[t._v(t._s(t.$t("submit")))])],1)],1)],1)],2)},n=[],i=a("3004"),s={name:"Pagegoodsorigin",data(){return{openid:"",login_name:"",authin:"0",pathname:"goodsorigin/",pathname_previous:"",pathname_next:"",separator:"cell",loading:!1,height:"",table_list:[],columns:[{name:"goods_origin",required:!0,label:this.$t("goods.view_origin.goods_origin"),align:"left",field:"goods_origin"},{name:"creater",label:this.$t("creater"),field:"creater",align:"center"},{name:"create_time",label:this.$t("createtime"),field:"create_time",align:"center"},{name:"update_time",label:this.$t("updatetime"),field:"update_time",align:"center"},{name:"action",label:this.$t("action"),align:"right"}],filter:"",pagination:{page:1,rowsPerPage:"30"},newForm:!1,newFormData:{goods_origin:"",creater:""},editid:0,editFormData:{},editMode:!1,deleteForm:!1,deleteid:0}},methods:{getList(){var t=this;t.$q.localStorage.has("auth")&&Object(i["e"])(t.pathname,{}).then((e=>{t.table_list=e.results,t.pathname_previous=e.previous,t.pathname_next=e.next})).catch((e=>{t.$q.notify({message:e.detail,icon:"close",color:"negative"})}))},getSearchList(){var t=this;t.$q.localStorage.has("auth")&&Object(i["e"])(t.pathname+"?goods_origin__icontains="+t.filter,{}).then((e=>{t.table_list=e.results,t.pathname_previous=e.previous,t.pathname_next=e.next})).catch((e=>{t.$q.notify({message:e.detail,icon:"close",color:"negative"})}))},getListPrevious(){var t=this;t.$q.localStorage.has("auth")&&Object(i["e"])(t.pathname_previous,{}).then((e=>{t.table_list=e.results,t.pathname_previous=e.previous,t.pathname_next=e.next})).catch((e=>{t.$q.notify({message:e.detail,icon:"close",color:"negative"})}))},getListNext(){var t=this;t.$q.localStorage.has("auth")&&Object(i["e"])(t.pathname_next,{}).then((e=>{t.table_list=e.results,t.pathname_previous=e.previous,t.pathname_next=e.next})).catch((e=>{t.$q.notify({message:e.detail,icon:"close",color:"negative"})}))},reFresh(){var t=this;t.getList()},newDataSubmit(){var t=this;t.newFormData.creater=t.login_name,Object(i["h"])(t.pathname,t.newFormData).then((e=>{t.getList(),t.newDataCancel(),t.$q.notify({message:"Success Create",icon:"check",color:"green"})})).catch((e=>{t.$q.notify({message:e.detail,icon:"close",color:"negative"})}))},newDataCancel(){var t=this;t.newForm=!1,t.newFormData={goods_origin:"",creater:""}},editData(t){var e=this;e.editMode=!0,e.editid=t.id,e.editFormData={goods_origin:t.goods_origin,creater:e.login_name}},editDataSubmit(){var t=this;Object(i["i"])(t.pathname+t.editid+"/",t.editFormData).then((e=>{t.editDataCancel(),t.getList(),t.$q.notify({message:"Success Edit Data",icon:"check",color:"green"})})).catch((e=>{t.$q.notify({message:e.detail,icon:"close",color:"negative"})}))},editDataCancel(){var t=this;t.editMode=!1,t.editid=0,t.editFormData={goods_origin:"",creater:""}},deleteData(t){var e=this;e.deleteForm=!0,e.deleteid=t},deleteDataSubmit(){var t=this;Object(i["d"])(t.pathname+t.deleteid+"/").then((e=>{t.deleteDataCancel(),t.getList(),t.$q.notify({message:"Success Edit Data",icon:"check",color:"green"})})).catch((e=>{t.$q.notify({message:e.detail,icon:"close",color:"negative"})}))},deleteDataCancel(){var t=this;t.deleteForm=!1,t.deleteid=0}},created(){var t=this;t.$q.localStorage.has("openid")?t.openid=t.$q.localStorage.getItem("openid"):(t.openid="",t.$q.localStorage.set("openid","")),t.$q.localStorage.has("login_name")?t.login_name=t.$q.localStorage.getItem("login_name"):(t.login_name="",t.$q.localStorage.set("login_name","")),t.$q.localStorage.has("auth")?(t.authin="1",t.getList()):t.authin="0"},mounted(){var t=this;t.$q.platform.is.electron?t.height=String(t.$q.screen.height-290)+"px":t.height=t.$q.screen.height-290+"px"},updated(){},destroyed(){}},r=s,l=a("42e1"),c=a("3605"),d=a("eaac"),p=a("e7a9"),u=a("9c40"),g=a("05c0"),h=a("2c91"),m=a("27f9"),_=a("0016"),f=a("bd08"),b=a("db86"),v=a("24e8"),q=a("f09f"),x=a("d847"),w=a("a370"),y=a("7f67"),k=a("eebe"),$=a.n(k),S=Object(l["a"])(r,o,n,!1,null,null,null);"function"===typeof c["default"]&&Object(c["default"])(S);e["default"]=S.exports;$()(S,"components",{QTable:d["a"],QBtnGroup:p["a"],QBtn:u["a"],QTooltip:g["a"],QSpace:h["a"],QInput:m["a"],QIcon:_["a"],QTr:f["a"],QTd:b["a"],QDialog:v["a"],QCard:q["a"],QBar:x["a"],QCardSection:w["a"]}),$()(S,"directives",{ClosePopup:y["a"]})}}]);
import torch import torch.nn as nn from torchvision import models import torch.nn.functional as F class REBNCONV(nn.Module): def __init__(self,in_ch=3,out_ch=3,dirate=1): super(REBNCONV,self).__init__() self.conv_s1 = nn.Conv2d(in_ch,out_ch,3,padding=1*dirate,dilation=1*dirate) self.bn_s1 = nn.BatchNorm2d(out_ch) self.relu_s1 = nn.ReLU(inplace=True) def forward(self,x): hx = x xout = self.relu_s1(self.bn_s1(self.conv_s1(hx))) return xout ## upsample tensor 'src' to have the same spatial size with tensor 'tar' def _upsample_like(src,tar): src = F.upsample(src,size=tar.shape[2:],mode='bilinear') return src ### RSU-7 ### class RSU7(nn.Module):#UNet07DRES(nn.Module): def __init__(self, in_ch=3, mid_ch=12, out_ch=3): super(RSU7,self).__init__() self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool3 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool4 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool5 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv6 = REBNCONV(mid_ch,mid_ch,dirate=1) self.rebnconv7 = REBNCONV(mid_ch,mid_ch,dirate=2) self.rebnconv6d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv5d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) def forward(self,x): hx = x hxin = self.rebnconvin(hx) hx1 = self.rebnconv1(hxin) hx = self.pool1(hx1) hx2 = self.rebnconv2(hx) hx = self.pool2(hx2) hx3 = self.rebnconv3(hx) hx = self.pool3(hx3) hx4 = self.rebnconv4(hx) hx = self.pool4(hx4) hx5 = self.rebnconv5(hx) hx = self.pool5(hx5) hx6 = self.rebnconv6(hx) hx7 = self.rebnconv7(hx6) hx6d = self.rebnconv6d(torch.cat((hx7,hx6),1)) hx6dup = _upsample_like(hx6d,hx5) hx5d = self.rebnconv5d(torch.cat((hx6dup,hx5),1)) hx5dup = _upsample_like(hx5d,hx4) hx4d = self.rebnconv4d(torch.cat((hx5dup,hx4),1)) hx4dup = _upsample_like(hx4d,hx3) hx3d = self.rebnconv3d(torch.cat((hx4dup,hx3),1)) hx3dup = _upsample_like(hx3d,hx2) hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1)) hx2dup = _upsample_like(hx2d,hx1) hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1)) return hx1d + hxin ### RSU-6 ### class RSU6(nn.Module):#UNet06DRES(nn.Module): def __init__(self, in_ch=3, mid_ch=12, out_ch=3): super(RSU6,self).__init__() self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool3 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool4 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=1) self.rebnconv6 = REBNCONV(mid_ch,mid_ch,dirate=2) self.rebnconv5d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) def forward(self,x): hx = x hxin = self.rebnconvin(hx) hx1 = self.rebnconv1(hxin) hx = self.pool1(hx1) hx2 = self.rebnconv2(hx) hx = self.pool2(hx2) hx3 = self.rebnconv3(hx) hx = self.pool3(hx3) hx4 = self.rebnconv4(hx) hx = self.pool4(hx4) hx5 = self.rebnconv5(hx) hx6 = self.rebnconv6(hx5) hx5d = self.rebnconv5d(torch.cat((hx6,hx5),1)) hx5dup = _upsample_like(hx5d,hx4) hx4d = self.rebnconv4d(torch.cat((hx5dup,hx4),1)) hx4dup = _upsample_like(hx4d,hx3) hx3d = self.rebnconv3d(torch.cat((hx4dup,hx3),1)) hx3dup = _upsample_like(hx3d,hx2) hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1)) hx2dup = _upsample_like(hx2d,hx1) hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1)) return hx1d + hxin ### RSU-5 ### class RSU5(nn.Module):#UNet05DRES(nn.Module): def __init__(self, in_ch=3, mid_ch=12, out_ch=3): super(RSU5,self).__init__() self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool3 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1) self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=2) self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) def forward(self,x): hx = x hxin = self.rebnconvin(hx) hx1 = self.rebnconv1(hxin) hx = self.pool1(hx1) hx2 = self.rebnconv2(hx) hx = self.pool2(hx2) hx3 = self.rebnconv3(hx) hx = self.pool3(hx3) hx4 = self.rebnconv4(hx) hx5 = self.rebnconv5(hx4) hx4d = self.rebnconv4d(torch.cat((hx5,hx4),1)) hx4dup = _upsample_like(hx4d,hx3) hx3d = self.rebnconv3d(torch.cat((hx4dup,hx3),1)) hx3dup = _upsample_like(hx3d,hx2) hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1)) hx2dup = _upsample_like(hx2d,hx1) hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1)) return hx1d + hxin ### RSU-4 ### class RSU4(nn.Module):#UNet04DRES(nn.Module): def __init__(self, in_ch=3, mid_ch=12, out_ch=3): super(RSU4,self).__init__() self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1) self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=2) self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) def forward(self,x): hx = x hxin = self.rebnconvin(hx) hx1 = self.rebnconv1(hxin) hx = self.pool1(hx1) hx2 = self.rebnconv2(hx) hx = self.pool2(hx2) hx3 = self.rebnconv3(hx) hx4 = self.rebnconv4(hx3) hx3d = self.rebnconv3d(torch.cat((hx4,hx3),1)) hx3dup = _upsample_like(hx3d,hx2) hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1)) hx2dup = _upsample_like(hx2d,hx1) hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1)) return hx1d + hxin ### RSU-4F ### class RSU4F(nn.Module):#UNet04FRES(nn.Module): def __init__(self, in_ch=3, mid_ch=12, out_ch=3): super(RSU4F,self).__init__() self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=2) self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=4) self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=8) self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=4) self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=2) self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) def forward(self,x): hx = x hxin = self.rebnconvin(hx) hx1 = self.rebnconv1(hxin) hx2 = self.rebnconv2(hx1) hx3 = self.rebnconv3(hx2) hx4 = self.rebnconv4(hx3) hx3d = self.rebnconv3d(torch.cat((hx4,hx3),1)) hx2d = self.rebnconv2d(torch.cat((hx3d,hx2),1)) hx1d = self.rebnconv1d(torch.cat((hx2d,hx1),1)) return hx1d + hxin ##### U^2-Net #### class U2NET(nn.Module): def __init__(self, in_ch=3, out_ch=8): super(U2NET, self).__init__() self.stage1 = RSU7(in_ch, 32, 64) self.pool12 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage2 = RSU6(64, 32, 128) self.pool23 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage3 = RSU5(128, 64, 256) self.pool34 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage4 = RSU4(256, 128, 512) self.pool45 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage5 = RSU4F(512, 256, 512) self.pool56 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage6 = RSU4F(512, 256, 512) # decoder self.stage5d = RSU4F(1024, 256, 512) self.stage4d = RSU4(1024, 128, 256) self.stage3d = RSU5(512, 64, 128) self.stage2d = RSU6(256, 32, 64) self.stage1d = RSU7(128, 16, 64) self.side1 = nn.Conv2d(64, out_ch, 3, padding=1) self.side2 = nn.Conv2d(64, out_ch, 3, padding=1) self.side3 = nn.Conv2d(128, out_ch, 3, padding=1) self.side4 = nn.Conv2d(256, out_ch, 3, padding=1) self.side5 = nn.Conv2d(512, out_ch, 3, padding=1) self.side6 = nn.Conv2d(512, out_ch, 3, padding=1) self.outconv = nn.Conv2d(48, out_ch, 1) def forward(self, x): hx = x # stage 1 hx1 = self.stage1(hx) hx = self.pool12(hx1) # stage 2 hx2 = self.stage2(hx) hx = self.pool23(hx2) # stage 3 hx3 = self.stage3(hx) hx = self.pool34(hx3) # stage 4 hx4 = self.stage4(hx) hx = self.pool45(hx4) # stage 5 hx5 = self.stage5(hx) hx = self.pool56(hx5) # stage 6 hx6 = self.stage6(hx) hx6up = _upsample_like(hx6,hx5) # -------------------- decoder -------------------- hx5d = self.stage5d(torch.cat((hx6up,hx5),1)) hx5dup = _upsample_like(hx5d,hx4) hx4d = self.stage4d(torch.cat((hx5dup,hx4),1)) hx4dup = _upsample_like(hx4d,hx3) hx3d = self.stage3d(torch.cat((hx4dup,hx3),1)) hx3dup = _upsample_like(hx3d,hx2) hx2d = self.stage2d(torch.cat((hx3dup,hx2),1)) hx2dup = _upsample_like(hx2d,hx1) hx1d = self.stage1d(torch.cat((hx2dup,hx1),1)) # side output d1 = self.side1(hx1d) d2 = self.side2(hx2d) d2 = _upsample_like(d2, d1) d3 = self.side3(hx3d) d3 = _upsample_like(d3, d1) d4 = self.side4(hx4d) d4 = _upsample_like(d4, d1) d5 = self.side5(hx5d) d5 = _upsample_like(d5, d1) d6 = self.side6(hx6) d6 = _upsample_like(d6, d1) d0 = self.outconv(torch.cat((d1, d2, d3, d4, d5, d6), 1)) return F.sigmoid(d0), F.sigmoid(d1), F.sigmoid(d2), F.sigmoid(d3), F.sigmoid(d4), F.sigmoid(d5), F.sigmoid(d6) ### U^2-Net small ### class U2NETP(nn.Module): def __init__(self,in_ch=3,out_ch=1): super(U2NETP,self).__init__() self.stage1 = RSU7(in_ch,16,64) self.pool12 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage2 = RSU6(64,16,64) self.pool23 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage3 = RSU5(64,16,64) self.pool34 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage4 = RSU4(64,16,64) self.pool45 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage5 = RSU4F(64,16,64) self.pool56 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage6 = RSU4F(64,16,64) # decoder self.stage5d = RSU4F(128,16,64) self.stage4d = RSU4(128,16,64) self.stage3d = RSU5(128,16,64) self.stage2d = RSU6(128,16,64) self.stage1d = RSU7(128,16,64) self.side1 = nn.Conv2d(64,out_ch,3,padding=1) self.side2 = nn.Conv2d(64,out_ch,3,padding=1) self.side3 = nn.Conv2d(64,out_ch,3,padding=1) self.side4 = nn.Conv2d(64,out_ch,3,padding=1) self.side5 = nn.Conv2d(64,out_ch,3,padding=1) self.side6 = nn.Conv2d(64,out_ch,3,padding=1) self.outconv = nn.Conv2d(6,out_ch,1) def forward(self,x): hx = x #stage 1 hx1 = self.stage1(hx) hx = self.pool12(hx1) #stage 2 hx2 = self.stage2(hx) hx = self.pool23(hx2) #stage 3 hx3 = self.stage3(hx) hx = self.pool34(hx3) #stage 4 hx4 = self.stage4(hx) hx = self.pool45(hx4) #stage 5 hx5 = self.stage5(hx) hx = self.pool56(hx5) #stage 6 hx6 = self.stage6(hx) hx6up = _upsample_like(hx6,hx5) #decoder hx5d = self.stage5d(torch.cat((hx6up,hx5),1)) hx5dup = _upsample_like(hx5d,hx4) hx4d = self.stage4d(torch.cat((hx5dup,hx4),1)) hx4dup = _upsample_like(hx4d,hx3) hx3d = self.stage3d(torch.cat((hx4dup,hx3),1)) hx3dup = _upsample_like(hx3d,hx2) hx2d = self.stage2d(torch.cat((hx3dup,hx2),1)) hx2dup = _upsample_like(hx2d,hx1) hx1d = self.stage1d(torch.cat((hx2dup,hx1),1)) #side output d1 = self.side1(hx1d) d2 = self.side2(hx2d) d2 = _upsample_like(d2,d1) d3 = self.side3(hx3d) d3 = _upsample_like(d3,d1) d4 = self.side4(hx4d) d4 = _upsample_like(d4,d1) d5 = self.side5(hx5d) d5 = _upsample_like(d5,d1) d6 = self.side6(hx6) d6 = _upsample_like(d6,d1) d0 = self.outconv(torch.cat((d1,d2,d3,d4,d5,d6),1)) return F.sigmoid(d0), F.sigmoid(d1), F.sigmoid(d2), F.sigmoid(d3), F.sigmoid(d4), F.sigmoid(d5), F.sigmoid(d6)
from .minigames import MiniGames __red_end_user_data_statement__ = 'This cog does not store user data.' def setup(bot): bot.add_cog(MiniGames(bot))
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/Reference Release: R5 Version: 4.5.0 Build ID: 0d95498 Last updated: 2021-04-03T00:34:11.075+00:00 """ from pydantic import Field from . import fhirtypes from . import datatype class Reference(datatype.DataType): """Disclaimer: Any field name ends with ``__ext`` doesn't part of Resource StructureDefinition, instead used to enable Extensibility feature for FHIR Primitive Data Types. A reference from one resource to another. """ resource_type = Field("Reference", const=True) display: fhirtypes.String = Field( None, alias="display", title="Text alternative for the resource", description=( "Plain text narrative that identifies the resource in addition to the " "resource reference." ), # if property is element of this resource. element_property=True, ) display__ext: fhirtypes.FHIRPrimitiveExtensionType = Field( None, alias="_display", title="Extension field for ``display``." ) identifier: fhirtypes.IdentifierType = Field( None, alias="identifier", title="Logical reference, when literal reference is not known", description=( "An identifier for the target resource. This is used when there is no " "way to reference the other resource directly, either because the " "entity it represents is not available through a FHIR server, or " "because there is no way for the author of the resource to convert a " "known identifier to an actual location. There is no requirement that a" " Reference.identifier point to something that is actually exposed as a" " FHIR instance, but it SHALL point to a business concept that would be" " expected to be exposed as a FHIR instance, and that instance would " "need to be of a FHIR resource type allowed by the reference." ), # if property is element of this resource. element_property=True, ) reference: fhirtypes.String = Field( None, alias="reference", title="Literal reference, Relative, internal or absolute URL", description=( "A reference to a location at which the other resource is found. The " "reference may be a relative reference, in which case it is relative to" " the service base URL, or an absolute URL that resolves to the " "location where the resource is found. The reference may be version " "specific or not. If the reference is not to a FHIR RESTful server, " "then it should be assumed to be version specific. Internal fragment " "references (start with '#') refer to contained resources." ), # if property is element of this resource. element_property=True, ) reference__ext: fhirtypes.FHIRPrimitiveExtensionType = Field( None, alias="_reference", title="Extension field for ``reference``." ) type: fhirtypes.Uri = Field( None, alias="type", title='Type the reference refers to (e.g. "Patient")', description=( "The expected type of the target of the reference. If both " "Reference.type and Reference.reference are populated and " "Reference.reference is a FHIR URL, both SHALL be consistent. The type" " is the Canonical URL of Resource Definition that is the type this " "reference refers to. References are URLs that are relative to " 'http://hl7.org/fhir/StructureDefinition/ e.g. "Patient" is a reference' " to http://hl7.org/fhir/StructureDefinition/Patient. Absolute URLs are" " only allowed for logical models (and can only be used in references " "in logical models, not resources)." ), # if property is element of this resource. element_property=True, ) type__ext: fhirtypes.FHIRPrimitiveExtensionType = Field( None, alias="_type", title="Extension field for ``type``." ) @classmethod def elements_sequence(cls): """returning all elements names from ``Reference`` according specification, with preserving original sequence order. """ return ["id", "extension", "reference", "type", "identifier", "display"]