code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _css = require('antd/lib/message/style/css'); var _message = require('antd/lib/message'); var _message2 = _interopRequireDefault(_message); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactDom = require('react-dom'); var _reactDom2 = _interopRequireDefault(_reactDom); var _draftJsWhkfzyx = require('draft-js-whkfzyx'); var _decoratorStyle = require('./decoratorStyle.css'); var _decoratorStyle2 = _interopRequireDefault(_decoratorStyle); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ImageSpan = function (_Component) { _inherits(ImageSpan, _Component); function ImageSpan(props) { _classCallCheck(this, ImageSpan); var _this = _possibleConstructorReturn(this, (ImageSpan.__proto__ || Object.getPrototypeOf(ImageSpan)).call(this, props)); var entity = _draftJsWhkfzyx.Entity.get(_this.props.entityKey); var _entity$getData = entity.getData(), width = _entity$getData.width, height = _entity$getData.height; _this.state = { width: width, height: height, imageSrc: '' }; _this.onImageClick = _this._onImageClick.bind(_this); _this.onDoubleClick = _this._onDoubleClick.bind(_this); return _this; } _createClass(ImageSpan, [{ key: 'componentDidMount', value: function componentDidMount() { var _this2 = this; var _state = this.state, width = _state.width, height = _state.height; var entity = _draftJsWhkfzyx.Entity.get(this.props.entityKey); var image = new Image(); var _entity$getData2 = entity.getData(), src = _entity$getData2.src; src = src.replace(/[?#&].*$/g, ""); this.setState({ imageSrc: src }); image.src = this.state.imageSrc; image.onload = function () { if (width == null || height == null) { _this2.setState({ width: image.width, height: image.height }); _draftJsWhkfzyx.Entity.mergeData(_this2.props.entityKey, { width: image.width, height: image.height, originalWidth: image.width, originalHeight: image.height }); } }; } }, { key: 'render', value: function render() { var _this3 = this; var _state2 = this.state, width = _state2.width, height = _state2.height; var key = this.props.entityKey; var entity = _draftJsWhkfzyx.Entity.get(key); var _entity$getData3 = entity.getData(), src = _entity$getData3.src; var imageStyle = { verticalAlign: 'bottom', backgroundImage: 'url("' + this.state.imageSrc + '")', backgroundSize: width + 'px ' + height + 'px', lineHeight: height + 'px', fontSize: height + 'px', width: width, height: height, letterSpacing: width }; return _react2.default.createElement( 'div', { className: 'editor-inline-image', onClick: this._onClick }, _react2.default.createElement('img', { src: '' + this.state.imageSrc, className: 'media-image', onClick: function onClick(event) { _this3.onImageClick(event, key);event.stopPropagation(); }, onDoubleClick: this.onDoubleClick }) ); } }, { key: '_onDoubleClick', value: function _onDoubleClick() { var currentPicture = _reactDom2.default.findDOMNode(this).querySelector("img"); var pictureWidth = currentPicture.naturalWidth; var pictureSrc = currentPicture.src; } }, { key: '_onImageClick', value: function _onImageClick(e, key) { var currentPicture = _reactDom2.default.findDOMNode(this).querySelector("img"); var pictureWidth = currentPicture.naturalWidth; var editorState = _draftJsWhkfzyx.EditorState.createEmpty(); var selection = editorState.getSelection(); var blockTree = editorState.getBlockTree(this.props.children[0].key); if (pictureWidth == 0) { _message2.default.error("图片地址错误!"); } else if (pictureWidth > 650) { _message2.default.error("图片尺寸过大将会导致用户流量浪费!请调整至最大650px。", 10); } } }, { key: '_handleResize', value: function _handleResize(event, data) { var _data$size = data.size, width = _data$size.width, height = _data$size.height; this.setState({ width: width, height: height }); _draftJsWhkfzyx.Entity.mergeData(this.props.entityKey, { width: width, height: height }); } }]); return ImageSpan; }(_react.Component); exports.default = ImageSpan; ImageSpan.defaultProps = { children: null, entityKey: "", className: "" };
WHKFZYX-Tool/react-lz-editor-whkfzyx
publish/editor/decorators/ImageSpan.js
JavaScript
mit
6,306
using System; using System.Collections.Generic; using System.IO; using Verse.EncoderDescriptors.Tree; namespace Verse.Schemas.Protobuf { internal class Writer : IWriter<WriterState, ProtobufValue> { public WriterState Start(Stream stream, ErrorEvent error) { throw new NotImplementedException(); } public void Stop(WriterState state) { throw new NotImplementedException(); } public void WriteAsArray<TEntity>(WriterState state, IEnumerable<TEntity> elements, WriterCallback<WriterState, ProtobufValue, TEntity> writer) { throw new NotImplementedException(); } public void WriteAsObject<TEntity>(WriterState state, TEntity entity, IReadOnlyDictionary<string, WriterCallback<WriterState, ProtobufValue, TEntity>> fields) { throw new NotImplementedException(); } public void WriteAsValue(WriterState state, ProtobufValue value) { throw new NotImplementedException(); } } }
r3c/Verse
Verse/src/Schemas/Protobuf/Writer.cs
C#
mit
969
# -*- coding: utf-8 -*- module Gtk # message_detail_viewプラグインなどで使われている、ヘッダ部分のユーザ情報。 # コンストラクタにはUserではなくMessageなど、userを保持しているDivaを渡すことに注意。 # このウィジェットによって表示されるタイムスタンプをクリックすると、 # コンストラクタに渡されたModelのperma_linkを開くようになっている。 class DivaHeaderWidget < Gtk::EventBox extend Memoist def initialize(model, *args, intent_token: nil) type_strict model => Diva::Model super(*args) ssc_atonce(:visibility_notify_event, &widget_style_setter) add(Gtk::VBox.new(false, 0). closeup(Gtk::HBox.new(false, 0). closeup(icon(model.user).top). closeup(Gtk::VBox.new(false, 0). closeup(idname(model.user).left). closeup(Gtk::Label.new(model.user[:name]).left))). closeup(post_date(model, intent_token).right)) end private def background_color style = Gtk::Style.new() style.set_bg(Gtk::STATE_NORMAL, 0xFFFF, 0xFFFF, 0xFFFF) style end def icon(user) icon_alignment = Gtk::Alignment.new(0.5, 0, 0, 0) .set_padding(*[UserConfig[:profile_icon_margin]]*4) icon = Gtk::EventBox.new. add(icon_alignment.add(Gtk::WebIcon.new(user.icon_large, UserConfig[:profile_icon_size], UserConfig[:profile_icon_size]))) icon.ssc(:button_press_event, &icon_opener(user.icon_large)) icon.ssc_atonce(:realize, &cursor_changer(Gdk::Cursor.new(Gdk::Cursor::HAND2))) icon.ssc_atonce(:visibility_notify_event, &widget_style_setter) icon end def idname(user) label = Gtk::EventBox.new. add(Gtk::Label.new. set_markup("<b><u><span foreground=\"#0000ff\">#{Pango.escape(user.idname)}</span></u></b>")) label.ssc(:button_press_event, &profile_opener(user)) label.ssc_atonce(:realize, &cursor_changer(Gdk::Cursor.new(Gdk::Cursor::HAND2))) label.ssc_atonce(:visibility_notify_event, &widget_style_setter) label end def post_date(model, intent_token) label = Gtk::EventBox.new. add(Gtk::Label.new(model.created.strftime('%Y/%m/%d %H:%M:%S'))) label.ssc(:button_press_event, &(intent_token ? intent_forwarder(intent_token) : message_opener(model))) label.ssc_atonce(:realize, &cursor_changer(Gdk::Cursor.new(Gdk::Cursor::HAND2))) label.ssc_atonce(:visibility_notify_event, &widget_style_setter) label end def icon_opener(url) proc do Plugin.call(:open, url) true end end def profile_opener(user) type_strict user => Diva::Model proc do Plugin.call(:open, user) true end end def intent_forwarder(token) proc do token.forward true end end def message_opener(token) proc do Plugin.call(:open, token) true end end memoize def cursor_changer(cursor) proc do |w| w.window.cursor = cursor false end end memoize def widget_style_setter ->(widget, *_rest) do widget.style = background_color false end end end RetrieverHeaderWidget = DivaHeaderWidget end
katsyoshi/mikutter
core/mui/gtk_retriever_header_widget.rb
Ruby
mit
3,407
(function () { 'use strict'; angular .module("myApp.presents") .factory("dataGiftService", dataGiftService); function dataGiftService($mdToast, $mdDialog) { var dataGiftService = { notification: notification, pleaseWaitDialog: pleaseWaitDialog }; function notification(status, msg, time) { if (angular.isUndefined(time)) time = 3000; $mdToast.show( $mdToast.simple() .textContent(msg) .position("top right") .hideDelay(time) .theme(status) ); } function pleaseWaitDialog(msg, parentEl) { if (angular.isUndefined(parentEl)) { parentEl = angular.element(document.body); } $mdDialog.show({ parent: parentEl, template: '<md-dialog class="wait-dialog" aria-label="Please wait">' + ' <md-dialog-content layout="column" layour-align="center center">' + '<h1 class="text-center">Proszę czekać</h1>' + '<md-content class="text-center">' + msg + '</md-content>'+ ' </md-dialog-content>' + '</md-dialog>' }); } return dataGiftService; } })();
IT-Wolf/present
app/services/data-gift-service.js
JavaScript
mit
1,378
<?php namespace Kraken\Runtime\Supervision\Cmd; use Dazzle\Channel\Channel; use Dazzle\Channel\ChannelInterface; use Dazzle\Channel\Extra\Request; use Kraken\Runtime\Supervision\Solver; use Kraken\Supervision\SolverInterface; use Kraken\Runtime\RuntimeCommand; use Error; use Exception; class CmdEscalate extends Solver implements SolverInterface { /** * @var string[] */ protected $requires = [ 'hash' ]; /** * @var ChannelInterface */ protected $channel; /** * @var string */ protected $parent; /** * */ protected function construct() { $this->channel = $this->runtime->getCore()->make('Kraken\Runtime\Service\ChannelInternal'); $this->parent = $this->runtime->getParent(); } /** * */ protected function destruct() { unset($this->channel); unset($this->parent); } /** * @param Error|Exception $ex * @param mixed[] $params * @return mixed */ protected function solver($ex, $params = []) { $req = $this->createRequest( $this->channel, $this->parent, new RuntimeCommand('cmd:error', [ 'exception' => get_class($ex), 'message' => $ex->getMessage(), 'hash' => $params['hash'] ]) ); return $req->call(); } /** * Create Request. * * @param ChannelInterface $channel * @param string $receiver * @param string $command * @return Request */ protected function createRequest(ChannelInterface $channel, $receiver, $command) { return new Request($channel, $receiver, $command); } }
kraken-php/framework
src/Runtime/src/Supervision/Cmd/CmdEscalate.php
PHP
mit
1,754
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "signverifymessagedialog.h" #include "ui_signverifymessagedialog.h" #include "addressbookpage.h" #include "base58.h" #include "guiutil.h" #include "init.h" #include "main.h" #include "optionsmodel.h" #include "walletmodel.h" #include "wallet.h" #include <QClipboard> #include <string> #include <vector> SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SignVerifyMessageDialog), model(0) { ui->setupUi(this); #if (QT_VERSION >= 0x040700) /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addressIn_SM->setPlaceholderText(tr("Enter a Amerios address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)")); ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); ui->addressIn_VM->setPlaceholderText(tr("Enter a Amerios address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)")); ui->signatureIn_VM->setPlaceholderText(tr("Enter Amerios signature")); #endif GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); ui->addressIn_SM->installEventFilter(this); ui->messageIn_SM->installEventFilter(this); ui->signatureOut_SM->installEventFilter(this); ui->addressIn_VM->installEventFilter(this); ui->messageIn_VM->installEventFilter(this); ui->signatureIn_VM->installEventFilter(this); ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont()); ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont()); } SignVerifyMessageDialog::~SignVerifyMessageDialog() { delete ui; } void SignVerifyMessageDialog::setModel(WalletModel *model) { this->model = model; } void SignVerifyMessageDialog::setAddress_SM(const QString &address) { ui->addressIn_SM->setText(address); ui->messageIn_SM->setFocus(); } void SignVerifyMessageDialog::setAddress_VM(const QString &address) { ui->addressIn_VM->setText(address); ui->messageIn_VM->setFocus(); } void SignVerifyMessageDialog::showTab_SM(bool fShow) { ui->tabWidget->setCurrentIndex(0); if (fShow) this->show(); } void SignVerifyMessageDialog::showTab_VM(bool fShow) { ui->tabWidget->setCurrentIndex(1); if (fShow) this->show(); } void SignVerifyMessageDialog::on_addressBookButton_SM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_SM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_pasteButton_SM_clicked() { setAddress_SM(QApplication::clipboard()->text()); } void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() { /* Clear old signature to ensure users don't get confused on error with an old signature displayed */ ui->signatureOut_SM->clear(); CBitcoinAddress addr(ui->addressIn_SM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if (!ctx.isValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); return; } CKey key; if (!pwalletMain->GetKey(keyID, key)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Private key for the entered address is not available.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_SM->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>")); return; } ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>")); ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()))); } void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked() { QApplication::clipboard()->setText(ui->signatureOut_SM->text()); } void SignVerifyMessageDialog::on_clearButton_SM_clicked() { ui->addressIn_SM->clear(); ui->messageIn_SM->clear(); ui->signatureOut_SM->clear(); ui->statusLabel_SM->clear(); ui->addressIn_SM->setFocus(); } void SignVerifyMessageDialog::on_addressBookButton_VM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_VM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked() { CBitcoinAddress addr(ui->addressIn_VM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } bool fInvalid = false; std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid); if (fInvalid) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_VM->document()->toPlainText().toStdString(); CPubKey pubkey; if (!pubkey.RecoverCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again.")); return; } if (!(CBitcoinAddress(pubkey.GetID()) == addr)) { ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>")); return; } ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>")); } void SignVerifyMessageDialog::on_clearButton_VM_clicked() { ui->addressIn_VM->clear(); ui->signatureIn_VM->clear(); ui->messageIn_VM->clear(); ui->statusLabel_VM->clear(); ui->addressIn_VM->setFocus(); } bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) { if (ui->tabWidget->currentIndex() == 0) { /* Clear status message on focus change */ ui->statusLabel_SM->clear(); /* Select generated signature */ if (object == ui->signatureOut_SM) { ui->signatureOut_SM->selectAll(); return true; } } else if (ui->tabWidget->currentIndex() == 1) { /* Clear status message on focus change */ ui->statusLabel_VM->clear(); } } return QDialog::eventFilter(object, event); }
codecvlc/amerios
src/qt/signverifymessagedialog.cpp
C++
mit
8,982
/////////////////////////////////////////////////////////////////////////// // Copyright © Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the 'License'); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// define({ "_widgetLabel": "Penyaringan", "geometryServicesNotFound": "Service geometri tidak tersedia.", "unableToDrawBuffer": "Tidak dapat menggambar buffer. Harap coba lagi.", "invalidConfiguration": "Konfigurasi tidak valid.", "clearAOIButtonLabel": "Mulai Ulang", "noGraphicsShapefile": "Shapefile yang diunggah tidak berisi grafis.", "zoomToLocationTooltipText": "Zoom ke lokasi", "noGraphicsToZoomMessage": "Tidak ada grafik yang ditemukan untuk memperbesar.", "placenameWidget": { "placenameLabel": "Cari lokasi" }, "drawToolWidget": { "useDrawToolForAOILabel": "Pilih mode gambar", "toggleSelectability": "Klik untuk beralih selektabilitas", "chooseLayerTitle": "Pilih layer yang dapat dipilih", "selectAllLayersText": "Pilih Semua", "layerSelectionWarningTooltip": "Setidaknya satu layer harus dipilih untuk membuat AOI", "selectToolLabel": "Pilih alat" }, "shapefileWidget": { "shapefileLabel": "Unggah shapefile zip", "uploadShapefileButtonText": "Unggah", "unableToUploadShapefileMessage": "Tidak dapat mengunggah shapefile." }, "coordinatesWidget": { "selectStartPointFromSearchText": "Tentukan titik awal", "addButtonTitle": "Tambah", "deleteButtonTitle": "Hapus", "mapTooltipForStartPoint": "Klik pada peta untuk menentukan titik awal", "mapTooltipForUpdateStartPoint": "Klik pada peta untuk memperbarui titik awal", "locateText": "Temukan", "locateByMapClickText": "Pilih koordinat awal", "enterBearingAndDistanceLabel": "Masukkan poros dan jarak dari titik awal", "bearingTitle": "Poros", "distanceTitle": "Jarak", "planSettingTooltip": "Pengaturan Rencana", "invalidLatLongMessage": "Harap masukkan nilai yang valid." }, "bufferDistanceAndUnit": { "bufferInputTitle": "Jarak buffer (opsional)", "bufferInputLabel": "Tampilkan hasil dalam", "bufferDistanceLabel": "Jarak buffer", "bufferUnitLabel": "Unit buffer" }, "traverseSettings": { "bearingLabel": "Poros", "lengthLabel": "Panjang", "addButtonTitle": "Tambah", "deleteButtonTitle": "Hapus", "deleteBearingAndLengthLabel": "Hapus poros dan baris panjang", "addButtonLabel": "Hapus poros dan panjang" }, "planSettings": { "expandGridTooltipText": "Perluas grid", "collapseGridTooltipText": "Ciutkan grid", "directionUnitLabelText": "Unit Arah", "distanceUnitLabelText": "Unit Jarak dan Panjang", "planSettingsComingSoonText": "Segera Datang" }, "newTraverse": { "invalidBearingMessage": "Poros Tidak Valid.", "invalidLengthMessage": "Panjang Tidak Valid.", "negativeLengthMessage": "Panjang Negatif" }, "reportsTab": { "aoiAreaText": "Area AOI", "downloadButtonTooltip": "Unduh", "printButtonTooltip": "Cetak", "uploadShapefileForAnalysisText": "Unggah shapefile untuk disertakan dalam analisis", "uploadShapefileForButtonText": "Telusuri", "downloadLabelText": "Pilih Format :", "downloadBtnText": "Unduh", "noDetailsAvailableText": "Tidak ada hasil yang ditemukan", "featureCountText": "Jumlah", "featureAreaText": "Area", "featureLengthText": "Panjang", "attributeChooserTooltip": "Pilih atribut untuk ditampilkan", "csv": "CSV", "filegdb": "File Geodatabase", "shapefile": "Shapefile", "noFeaturesFound": "Tidak ada hasil yang ditemukan untuk format file yang dipilih", "selectReportFieldTitle": "Pilih kolom", "noFieldsSelected": "Tidak ada kolom yang dipilih", "intersectingFeatureExceedsMsgOnCompletion": "Penghitungan jumlah maksimum catatan telah tercapai untuk satu atau beberapa layer.", "unableToAnalyzeText": "Tidak dapat menganalisis, jumlah catatan maksimum telah tercapai.", "errorInPrintingReport": "Tidak dapat mencetak laporan. Harap periksa apakah pengaturan laporan valid.", "aoiInformationTitle": "Informasi Area Pilihan (AOI)", "summaryReportTitle": "Ringkasan", "notApplicableText": "T/A", "downloadReportConfirmTitle": "Konfirmasi pengunduhan", "downloadReportConfirmMessage": "Anda yakin ingin mengunduh?", "noDataText": "Tidak Ada Data", "createReplicaFailedMessage": "Operasi unduhan gagal untuk layer berikut: <br/> ${layerNames}", "extractDataTaskFailedMessage": "Operasi mengunduh gagal.", "printLayoutLabelText": "Tata Letak", "printBtnText": "Cetak", "printDialogHint": "Catatan: Judul laporan dan komentar dapat diedit dalam pratinjau laporan.", "unableToDownloadFileGDBText": "Geodatabase file tidak dapat diunduh untuk AOI yang berisi lokasi titik atau garis", "unableToDownloadShapefileText": "Shapefile tidak dapat diunduh untuk AOI yang berisi lokasi titik atau garis", "analysisAreaUnitLabelText": "Tampilkan hasil luas dalam :", "analysisLengthUnitLabelText": "Tampilkan hasil panjang dalam :", "analysisUnitButtonTooltip": "Pilih unit untuk analisis", "analysisCloseBtnText": "Tutup", "areaSquareFeetUnit": "Kaki Persegi", "areaAcresUnit": "Acre", "areaSquareMetersUnit": "Meter Persegi", "areaSquareKilometersUnit": "Kilometer Persegi", "areaHectaresUnit": "Hektare", "lengthFeetUnit": "Kaki", "lengthMilesUnit": "Mil", "lengthMetersUnit": "Meter", "lengthKilometersUnit": "Kilometer", "hectaresAbbr": "hektar", "layerNotVisibleText": "Tidak dapat menganalisis. Layer dimatikan atau di luar rentang visibilitas skala.", "refreshBtnTooltip": "Muat ulang laporan", "featureCSVAreaText": "Area Berpotongan", "featureCSVLengthText": "Panjang Berpotongan", "errorInFetchingPrintTask": "Kesalahan saat mengambil informasi tugas cetak. Silakan coba lagi.", "selectAllLabel": "Pilih Semua", "errorInLoadingProjectionModule": "Kesalahan saat memuat dependensi modul proyeksi. Harap coba mengunduh file kembali.", "expandCollapseIconLabel": "Fitur berpotongan", "intersectedFeatureLabel": "Detail fitur berpotongan", "valueAriaLabel": "Nilai", "countAriaLabel": "Jumlah" } });
tmcgee/cmv-wab-widgets
wab/2.14/widgets/Screening/nls/id/strings.js
JavaScript
mit
6,779
require 'bundler/setup' module Bob end require_relative 'bob/config' require_relative 'bob/engine' config = Bob::Config.load engine = Bob::Engine.new(config) engine.run
hcatlin/bob
lib/bob.rb
Ruby
mit
173
package jxdo.rjava; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Modifier; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; class JCSharp { static String crlf; static ClassLoader clazzLoader; List<String> lstClassNames; public JCSharp(String jarNames) throws Throwable{ if(crlf == null)crlf= System.getProperty("line.separator"); lstClassNames = new ArrayList<String>(); if(clazzLoader == null) clazzLoader = this.getJarClassLoader(jarNames, this.getClass().getClassLoader()); } @SuppressWarnings("unused") private void addClassLaoder(String jarNames) throws Throwable { lstClassNames.clear(); ClassLoader newClazzLoader = this.getJarClassLoader(jarNames, clazzLoader); if(newClazzLoader != clazzLoader)clazzLoader = newClazzLoader; } private ClassLoader getJarClassLoader(String jarNames, ClassLoader parentClassLoader) throws Throwable{ List<URL> lstUrls = new ArrayList<URL>(); for(String jarName : jarNames.split(";")){ //System.out.println(jarName); File file = new File(jarName); if(file.getName().compareToIgnoreCase("jxdo.rjava.jar") == 0)continue; if(!file.exists()) { java.io.FileNotFoundException exp = new java.io.FileNotFoundException(jarName); if(exp.getMessage() == null){ Throwable ta = exp.getCause(); if(ta!=null)throw ta; } throw exp; } this.fillClassNames(jarName); URL jarUrl = new URL("jar", "","file:" + file.getAbsolutePath()+"!/"); lstUrls.add(jarUrl); } if(lstUrls.size()==0) return parentClassLoader; URL[] urls = lstUrls.toArray(new URL[0]); return URLClassLoader.newInstance(urls, parentClassLoader); } private void fillClassNames(String jarFileName) throws Throwable{ JarFile jar = new JarFile(jarFileName); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { String entry = entries.nextElement().getName(); if(!entry.endsWith(".class"))continue; //System.out.println(entry); String clsName = entry.replaceAll(".class", "").replaceAll("/", "."); lstClassNames.add(clsName); } } List<Class<?>> lstClasses; public void fillClasses(String directoryName) throws Throwable{ if(lstClasses == null) lstClasses = new ArrayList<Class<?>>(); else lstClasses.clear(); //System.out.println(directoryName); List<ClassFile> lst = new ArrayList<ClassFile>(); for(int i=0;i<lstClassNames.size();i++){ String name = lstClassNames.get(i); if(name.indexOf("$") > 0){ continue; } ClassFile cd = new ClassFile(); cd.className = name; lst.add(cd); lstClassNames.remove(i); i-=1; } java.io.File f = new File(directoryName); if(!f.exists())f.mkdirs(); lstFileWriters = new ArrayList<FileWriter>(); this.ForEachCoder(lst,directoryName); for(FileWriter fw : lstFileWriters) fw.close(); } List<FileWriter> lstFileWriters; private void ForEachCoder(List<ClassFile> lst, String directoryName){ for(ClassFile cf : lst){ Class<?> clazz = cf.loadClass(); if(clazz == null)continue; //C#¶ËµÄ½Ó¿Ú²»Ö§³ÖǶÌ× boolean isInterface = clazz.isInterface(); FileWriter fwCurrent = isInterface ? cf.getFileWriter(directoryName) : cf.getParent(cf).getFileWriter(directoryName); String tabs = isInterface ? "\t" : cf.getTabs(); if(!lstFileWriters.contains(fwCurrent)) lstFileWriters.add(fwCurrent); JCSharpOuter jcOuter = new JCSharpOuter(clazz, fwCurrent, isInterface ? false : cf.Postion > 0); jcOuter.writerNamespaceStart(tabs); jcOuter.writerDefineStart(); System.out.println(tabs + cf.className); this.ForEachCoder(cf.getNetseds(), directoryName); jcOuter.writerDefineEnd(); jcOuter.writerNamespaceEnd(); } } public class ClassFile{ String className; int Postion = 0; ClassFile Parent; public List<ClassFile> getNetseds(){ List<ClassFile> netseds = new ArrayList<ClassFile>(); for(int i=0;i<lstClassNames.size();i++){ String ns = lstClassNames.get(i); if(!ns.startsWith(className))continue; int level = ns.split("\\$").length - 1; if(level == Postion +1) { ClassFile cd = new ClassFile(); cd.className = ns; cd.Postion = level; cd.Parent = this; netseds.add(cd); lstClassNames.remove(i); i-=1; } } return netseds; } ClassFile cfSearchParent; private ClassFile getParent(ClassFile cf){ if(cfSearchParent == null) searchParent(cf); return cfSearchParent; } private void searchParent(ClassFile cf){ if(cf.Parent == null){ cfSearchParent = cf; return; } searchParent(cf.Parent); //cf.Level += 1; } Class<?> cls; public Class<?> loadClass(){ if(cls == null){ try { cls = clazzLoader.loadClass(this.className); } catch (ClassNotFoundException e) { return null; } int im = cls.getModifiers(); if(!Modifier.isPublic(im)) return null; } return cls; } String _tabs; public String getTabs(){ if(_tabs == null){ String s = "\t"; for(int i=0;i<this.Postion;i++) s += "\t"; _tabs = s; } return _tabs; } FileWriter fw; public FileWriter getFileWriter(String directoryName){ if(fw == null){ String csFileName = className.replace('$', '.'); // if(csFileName.indexOf(".") > -1) // csFileName = csFileName.substring(csFileName.indexOf(".") + 1, csFileName.length() + 2 - csFileName.indexOf(".")); // if(csFileName.indexOf("$") > -1) // csFileName = csFileName.substring(csFileName.indexOf("$") + 1, csFileName.length() + 2 - csFileName.indexOf("$")); File f = new File(directoryName + File.separator + csFileName + ".cs"); if(f.exists())f.delete(); boolean isCreated; try { isCreated = f.createNewFile(); } catch (IOException e) { isCreated = false; } if(!isCreated)return null; try { fw = new FileWriter(f); } catch (IOException e) { return null; } } return fw; } } public static void main(String[] args) throws Throwable { //home // String fname = "E:\\DotNet2010\\NXDO.Mixed\\NXDO.Mixed.V2015\\Tester\\RJavaX64\\bin\\Debug\\jforloaded.jar"; // JCSharp jf = new JCSharp(fname); // jf.fillClasses("E:\\DotNet2010\\NXDO.Mixed\\nxdo.jacoste"); //ltd String fname = "E:\\DotNet2012\\CSharp2Java\\NXDO.Mixed.V2015\\Tester\\RJavaX64\\bin\\Debug\\jforloaded.jar"; JCSharp jf = new JCSharp(fname); jf.fillClasses("E:\\DotNet2012\\CSharp2Java\\nxdo.jacoste"); } }
javasuki/RJava
NXDO.Java.V2015/jxdo.rjava/src/jxdo/rjava/JCSharp.java
Java
mit
6,826
package com.ado.java.odata.pool; import java.sql.Connection; import java.sql.SQLException; public interface Pool { /** * Make a new connection * * @throws SQLException */ Connection makeConnection() throws SQLException; /** * Gets a valid connection from the connection pool * * @return a valid connection from the pool * @throws SQLException */ Connection getConnection() throws SQLException; /** * Return a connection into the connection pool * * @param connection the connection to return to the pool * @throws SQLException */ void returnConnection(Connection connection) throws SQLException; }
AdoHe/ODataSync
src/main/java/com/ado/java/odata/pool/Pool.java
Java
mit
698
using UnityEngine; public class DamageOnCollision : MonoBehaviour { public float damage = 1f; public bool damageSelf = true; void OnCollisionEnter2D(Collision2D collision) { var health = collision.gameObject.GetComponent<HealthProperty>(); if (health != null) { health.Damage(damage); } if (damageSelf) { var rockHealth = GetComponent<HealthProperty>(); if (rockHealth != null) { rockHealth.Damage(damage); } } } }
tedajax/carrot
Assets/Scripts/DamageOnCollision.cs
C#
mit
545
module.exports = ` type SimpleBudgetDetail { account_type: String, account_name: String, fund_name: String, department_name: String, division_name: String, costcenter_name: String, function_name: String, charcode_name: String, organization_name: String, category_name: String, budget_section_name: String, object_name: String, year: Int, budget: Float, actual: Float, full_account_id: String, org_id: String, obj_id: String, fund_id: String, dept_id: String, div_id: String, cost_id: String, func_id: String, charcode: String, category_id: String, budget_section_id: String, proj_id: String, is_proposed: String use_actual: String } type SimpleBudgetSummary { account_type: String, category_name: String, year: Int, total_budget: Float, total_actual: Float use_actual: String } type BudgetCashFlow { account_type: String, category_name: String, category_id: String, dept_id: String, department_name: String, fund_id: String, fund_name: String, budget: Float, year: Int } type BudgetParameters { start_year: Int end_year: Int in_budget_season: Boolean } `;
cityofasheville/simplicity-graphql-server
api/budget/budget_schema.js
JavaScript
mit
1,153
module.exports = client => { console.log(`Reconnecting... [at ${new Date()}]`); };
Boxeh/delet
events/reconnecting.js
JavaScript
mit
88
/** * This class was created by <Vazkii>. It's distributed as * part of the Botania Mod. Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under the * Botania License: http://botaniamod.net/license.php * * File Created @ [Feb 14, 2015, 3:28:54 PM (GMT)] */ package vazkii.botania.api.corporea; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; public final class CorporeaHelper { private static final List<IInventory> empty = Collections.unmodifiableList(new ArrayList()); private static final WeakHashMap<List<ICorporeaSpark>, List<IInventory>> cachedNetworks = new WeakHashMap(); public static final String[] WILDCARD_STRINGS = new String[] { "...", "~", "+", "?" , "*" }; /** * How many items were matched in the last request. If java had "out" params like C# this wouldn't be needed :V */ public static int lastRequestMatches = 0; /** * How many items were extracted in the last request. */ public static int lastRequestExtractions = 0; /** * Gets a list of all the inventories on this spark network. This list is cached for use once every tick, * and if something changes during that tick it'll still have the first result. */ public static List<IInventory> getInventoriesOnNetwork(ICorporeaSpark spark) { ICorporeaSpark master = spark.getMaster(); if(master == null) return empty; List<ICorporeaSpark> network = master.getConnections(); if(cachedNetworks.containsKey(network)) { List<IInventory> cache = cachedNetworks.get(network); if(cache != null) return cache; } List<IInventory> inventories = new ArrayList(); if(network != null) for(ICorporeaSpark otherSpark : network) if(otherSpark != null) { IInventory inv = otherSpark.getInventory(); if(inv != null) inventories.add(inv); } cachedNetworks.put(network, inventories); return inventories; } /** * Gets the amount of available items in the network of the type passed in, checking NBT or not. * The higher level functions that use a List< IInventory > or a Map< IInventory, Integer > should be * called instead if the context for those exists to avoid having to get the values again. */ public static int getCountInNetwork(ItemStack stack, ICorporeaSpark spark, boolean checkNBT) { List<IInventory> inventories = getInventoriesOnNetwork(spark); return getCountInNetwork(stack, inventories, checkNBT); } /** * Gets the amount of available items in the network of the type passed in, checking NBT or not. * The higher level function that use a Map< IInventory, Integer > should be * called instead if the context for this exists to avoid having to get the value again. */ public static int getCountInNetwork(ItemStack stack, List<IInventory> inventories, boolean checkNBT) { Map<IInventory, Integer> map = getInventoriesWithItemInNetwork(stack, inventories, checkNBT); return getCountInNetwork(stack, map, checkNBT); } /** * Gets the amount of available items in the network of the type passed in, checking NBT or not. */ public static int getCountInNetwork(ItemStack stack, Map<IInventory, Integer> inventories, boolean checkNBT) { int count = 0; for(IInventory inv : inventories.keySet()) count += inventories.get(inv); return count; } /** * Gets a Map mapping IInventories to the amount of items of the type passed in that exist * The higher level function that use a List< IInventory > should be * called instead if the context for this exists to avoid having to get the value again. */ public static Map<IInventory, Integer> getInventoriesWithItemInNetwork(ItemStack stack, ICorporeaSpark spark, boolean checkNBT) { List<IInventory> inventories = getInventoriesOnNetwork(spark); return getInventoriesWithItemInNetwork(stack, inventories, checkNBT); } /** * Gets a Map mapping IInventories to the amount of items of the type passed in that exist * The deeper level function that use a List< IInventory > should be * called instead if the context for this exists to avoid having to get the value again. */ public static Map<IInventory, Integer> getInventoriesWithItemInNetwork(ItemStack stack, List<IInventory> inventories, boolean checkNBT) { Map<IInventory, Integer> countMap = new HashMap(); for(IInventory inv : inventories) { int count = 0; for(int i = 0; i < inv.getSizeInventory(); i++) { if(!isValidSlot(inv, i)) continue; ItemStack stackAt = inv.getStackInSlot(i); if(stacksMatch(stack, stackAt, checkNBT)) count += stackAt.stackSize; } if(count > 0) countMap.put(inv, count); } return countMap; } /** * Bridge for requestItem() using an ItemStack. */ public static List<ItemStack> requestItem(ItemStack stack, ICorporeaSpark spark, boolean checkNBT, boolean doit) { return requestItem(stack, stack.stackSize, spark, checkNBT, doit); } /** * Bridge for requestItem() using a String and an item count. */ public static List<ItemStack> requestItem(String name, int count, ICorporeaSpark spark, boolean doit) { return requestItem(name, count, spark, false, doit); } /** * Requests list of ItemStacks of the type passed in from the network, or tries to, checking NBT or not. * This will remove the items from the adequate inventories unless the "doit" parameter is false. * Returns a new list of ItemStacks of the items acquired or an empty list if none was found. * Case itemCount is -1 it'll find EVERY item it can. * <br><br> * The "matcher" parameter has to be an ItemStack or a String, if the first it'll check if the * two stacks are similar using the "checkNBT" parameter, else it'll check if the name of the item * equals or matches (case a regex is passed in) the matcher string. */ public static List<ItemStack> requestItem(Object matcher, int itemCount, ICorporeaSpark spark, boolean checkNBT, boolean doit) { List<ItemStack> stacks = new ArrayList(); CorporeaRequestEvent event = new CorporeaRequestEvent(matcher, itemCount, spark, checkNBT, doit); if(MinecraftForge.EVENT_BUS.post(event)) return stacks; List<IInventory> inventories = getInventoriesOnNetwork(spark); Map<ICorporeaInterceptor, ICorporeaSpark> interceptors = new HashMap(); lastRequestMatches = 0; lastRequestExtractions = 0; int count = itemCount; for(IInventory inv : inventories) { ICorporeaSpark invSpark = getSparkForInventory(inv); if(inv instanceof ICorporeaInterceptor) { ICorporeaInterceptor interceptor = (ICorporeaInterceptor) inv; interceptor.interceptRequest(matcher, itemCount, invSpark, spark, stacks, inventories, doit); interceptors.put(interceptor, invSpark); } for(int i = inv.getSizeInventory() - 1; i >= 0; i--) { if(!isValidSlot(inv, i)) continue; ItemStack stackAt = inv.getStackInSlot(i); if(matcher instanceof ItemStack ? stacksMatch((ItemStack) matcher, stackAt, checkNBT) : matcher instanceof String ? stacksMatch(stackAt, (String) matcher) : false) { int rem = Math.min(stackAt.stackSize, count == -1 ? stackAt.stackSize : count); if(rem > 0) { ItemStack copy = stackAt.copy(); if(rem < copy.stackSize) copy.stackSize = rem; stacks.add(copy); } lastRequestMatches += stackAt.stackSize; lastRequestExtractions += rem; if(doit && rem > 0) { inv.decrStackSize(i, rem); if(invSpark != null) invSpark.onItemExtracted(stackAt); } if(count != -1) count -= rem; } } } for(ICorporeaInterceptor interceptor : interceptors.keySet()) interceptor.interceptRequestLast(matcher, itemCount, interceptors.get(interceptor), spark, stacks, inventories, doit); return stacks; } /** * Gets the spark attached to the inventory passed case it's a TileEntity. */ public static ICorporeaSpark getSparkForInventory(IInventory inv) { if(!(inv instanceof TileEntity)) return null; TileEntity tile = (TileEntity) inv; return getSparkForBlock(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord); } /** * Gets the spark attached to the block in the coords passed in. Note that the coords passed * in are for the block that the spark will be on, not the coords of the spark itself. */ public static ICorporeaSpark getSparkForBlock(World world, int x, int y, int z) { List<ICorporeaSpark> sparks = world.getEntitiesWithinAABB(ICorporeaSpark.class, AxisAlignedBB.getBoundingBox(x, y + 1, z, x + 1, y + 2, z + 1)); return sparks.isEmpty() ? null : sparks.get(0); } /** * Gets if the block in the coords passed in has a spark attached. Note that the coords passed * in are for the block that the spark will be on, not the coords of the spark itself. */ public static boolean doesBlockHaveSpark(World world, int x, int y, int z) { return getSparkForBlock(world, x, y, z) != null; } /** * Gets if the slot passed in can be extracted from by a spark. */ public static boolean isValidSlot(IInventory inv, int slot) { return !(inv instanceof ISidedInventory) || arrayHas(((ISidedInventory) inv).getAccessibleSlotsFromSide(ForgeDirection.UP.ordinal()), slot) && ((ISidedInventory) inv).canExtractItem(slot, inv.getStackInSlot(slot), ForgeDirection.UP.ordinal()); } /** * Gets if two stacks match. */ public static boolean stacksMatch(ItemStack stack1, ItemStack stack2, boolean checkNBT) { return stack1 != null && stack2 != null && stack1.isItemEqual(stack2) && (!checkNBT || ItemStack.areItemStackTagsEqual(stack1, stack2)); } /** * Gets if the name of a stack matches the string passed in. */ public static boolean stacksMatch(ItemStack stack, String s) { if(stack == null) return false; boolean contains = false; for(String wc : WILDCARD_STRINGS) { if(s.endsWith(wc)) { contains = true; s = s.substring(0, s.length() - wc.length()); } else if(s.startsWith(wc)) { contains = true; s = s.substring(wc.length()); } if(contains) break; } String name = stack.getDisplayName().toLowerCase().trim(); return equalOrContain(name, s, contains) || equalOrContain(name + "s", s, contains) || equalOrContain(name + "es", s, contains) || name.endsWith("y") && equalOrContain(name.substring(0, name.length() - 1) + "ies", s, contains); } /** * Clears the cached networks, called once per tick, should not be called outside * of the botania code. */ public static void clearCache() { cachedNetworks.clear(); } /** * Helper method to check if an int array contains an int. */ public static boolean arrayHas(int[] arr, int val) { for (int element : arr) if(element == val) return true; return false; } /** * Helper method to make stacksMatch() less messy. */ public static boolean equalOrContain(String s1, String s2, boolean contain) { return contain ? s1.contains(s2) : s1.equals(s2); } }
goldenapple3/CopperTools
src/api/vazkii/botania/api/corporea/CorporeaHelper.java
Java
mit
11,357
ig.module( 'game.entities.abstract.friendly-unit' ).requires( 'game.entities.abstract.unit' ).defines(function () { FriendlyUnit = Unit.extend({ // Nothing yet! }); });
khellste/defense
lib/game/entities/abstract/friendly-unit.js
JavaScript
mit
174
/** * */ package cn.sefa.test.combinator; /** * @author Lionel * */ public class Result { private String recognized ; private String remaining; private boolean succeeded ; private Result(String recognized , String remaining , boolean succeeded){ this.recognized = recognized; this.remaining = remaining; this.succeeded = succeeded; } /** * @return the recognized */ public String getRecognized() { return recognized; } /** * @param recognized the recognized to set */ public void setRecognized(String recognized) { this.recognized = recognized; } /** * @return the remaining */ public String getRemaining() { return remaining; } public void setRemaining(String remaining) { this.remaining = remaining; } public boolean isSucceeded() { return succeeded; } public void setSucceeded(boolean succeeded) { this.succeeded = succeeded; } public static Result succeed(String recognized , String remaining){ return new Result(recognized,remaining,true); } public static Result fail(){ return new Result("","",false); } }
LLionel/sefa
src/cn/sefa/test/combinator/Result.java
Java
mit
1,109
<?php /* * This file is part of the Persian Framework. * * (c) Farhad Zandmoghadam <farhad.pd@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Core\MVC\Routing; use Core\PF\Exception\RoutingException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\Exception\ResourceNotFoundException; class Router { /** * private (string) $_controller, save controller name */ private $_controller; private $routes; /** * private (string) $_method, save action name */ private $_method; public function __construct() { $routesResource = include ROOT_DIR.'/application/Routes.php'; $this->routes = $routesResource; $default_url = $_SERVER['PHP_SELF']; $default_url = explode('.php/', $default_url); $default_url[1] = isset($default_url[1]) ? $default_url[1] : ''; $context = new RequestContext(); // this is optional and can be done without a Request instance $context->fromRequest(Request::createFromGlobals()); $matcher = new UrlMatcher($this->routes, $context); $parameters = $matcher->match('/'.chop($default_url[1], '/')); $parameter = array(); if(!isset($parameters['_controller'])) { throw new RoutingException('_controller parameter in routes not exists'); } list($getController, $getMethod) = split(':', $parameters['_controller']); $this->_controller = ucfirst($getController); $this->_method = ucfirst($getMethod); if(count($parameters) > 2) { unset($parameters['_controller']); unset($parameters['_rout']); foreach($parameters as $key => $value) { $parameter[] = $value; } } $this->_parameter = $parameter; // check routes pattern exists } /** * Get Controller Parameter * * @return String */ protected function getController() { return $this->_controller; } /** * Get Called action * * @return String * */ protected function getMethod() { return $this->_method; } /** * Get Called actions Arguments * * @return Array * */ protected function getParameter() { return $this->_parameter; } }
zandfarhad/PF1
core/framework/src/Illuminate/Routing/Router.php
PHP
mit
2,353
class NullAcceptCreateColumnToDevices < ActiveRecord::Migration def change change_column :devices, :mac_address, :string, null: true, default: nil change_column :devices, :device_name, :string, null: false change_column :devices, :device_communication, :string, null: true, default: nil end end
coderstable/comfortable_keeper_rails
db/migrate/20161201030709_null_accept_create_column_to_devices.rb
Ruby
mit
323
/** * Ajax函数 */ // 创建一个XMLHttpRequest对象 var createXHR; if (window.XMLHttpRequest) { createXHR = function() { return new XMLHttpRequest(); }; } else if (window.ActiveXObject) { createXHR = function() { return new ActiveXObject('Microsoft.XMLHTTP'); }; } // 发起异步请求,默认为GET请求 function ajax(url, opts) { var type = opts.type || 'get', async = opts.async || true, data = opts.data || null, headers = opts.headers || {}; var xhr = createXHR(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { opts.onsuccess && opts.onsuccess(xhr.responseText); } else { opts.onerror && opts.onerror(); } }; xhr.open(url, type, async); for (var p in headers) { xhr.setRequestHeader(p, headers[p]); } xhr.send(data); }
Alex1990/jscell
ajax.js
JavaScript
mit
920
import { addTimer } from './timer/timer'; import { showProfile } from './profile/profile'; import { showHelp } from './help/help'; import { getAllUsers } from './timer/listUtil/getAllUsers'; import { isWorking } from './timer/listUtil/isWorking'; import { timerTimeout } from './timer/listUtil/timerTimeout'; import { refreshPoints } from './timer/listUtil/refreshPoints'; import { minusStackCalculate } from './timer/listUtil/minusStackCalculate'; import { updUsrList } from './timer/listUtil/updUsrList'; const emojiMap = { '⏺': addTimer, '👤': showProfile, '❓': showHelp }; async function menuGUI(res, bot) { const channel = bot.channel; const timerList = {}; let userList = await getAllUsers(); // eslint-disable-line const menuMsg = await channel.send('', { embed: { description: '`⏺ Start Recording! | 👤 Your Profile | ❓ Need help?`' }, }); // add reactions to message for (const emoji in emojiMap) { await menuMsg.react(emoji); } await channel.send('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬'); await menuMsg.createReactionCollector(async (reaction, user) => { if (user.bot) return false; // run the emoji command logic and remove the reaction if (emojiMap[reaction.emoji.name]) { emojiMap[reaction.emoji.name](bot, user, timerList); } await reaction.remove(user); return false; }); res(); setInterval(() => { timerTimeout(bot, timerList); }, 60000); setInterval(async () => { refreshPoints(timerList); isWorking(userList, timerList); minusStackCalculate(); updUsrList(userList); }, 60000); } module.exports = { init: (bot) => { return new Promise((res) => { menuGUI(res, bot); }); }, };
sedansvan/workrecbot
src/gui/menu/menu.js
JavaScript
mit
1,746
/** * Created by:homelan * User: pijiu3302@outlook.com * Date: 2017/7/31 * Time: 17:38 * */ import React from 'react'; import icons from '../utils/parseIcon'; import {connect} from 'react-redux'; import {lockPlayer} from '../store/action/actionindex'; class LockBar extends React.Component { render() { const {handleClick}=this.props; let styleObj1={}; styleObj1.background='url('+icons.playbar+')'; return ( <div className="updn" > <div className='lock-bg' style={styleObj1}> <a className={this.props.locked?'btn':'btn-unlock'} style={styleObj1} onClick={e=>handleClick(e)}></a> </div> <div className="lock-bg2" style={styleObj1} ></div> </div> ) } } const mapStateToProps=(state)=>{ return {locked:state.locked} } const mapDispatchToProps=(dispatch)=> { return { handleClick: (e) => { dispatch(lockPlayer()) e.preventDefault(); e.stopPropagation() } } }; export default connect(mapStateToProps,mapDispatchToProps)(LockBar);//important /*function mapDispatchToProps(dispatch) { return { handleClick: () => dispatch(lockPlayer()) }; } connect( mapDispatchToProps )(LockBar); */
ponytony/hl-music-player
src/components/lockbar.js
JavaScript
mit
1,212
package com.cgroups.gendata; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Random; public class RandomEntry { private ArrayList<String> words; private ArrayList<Double> weights; Random random = null; private double total_weight; public RandomEntry(){ this.init_menbers(); } /** * @param word_path Path of the file listing the words * @param weights_path Path of the file listing weights of each word */ public RandomEntry(String word_path, String weights_path){ this.init_menbers(); BufferedReader br1 = null; BufferedReader br2 = null; try{ br1 = new BufferedReader(new FileReader(word_path)); br2 = new BufferedReader(new FileReader(weights_path)); while (true){ String line1=null, line2=null; line1 = br1.readLine(); line2 = br2.readLine(); if (line1==null || line2==null) break; double weight; try{ weight = Double.parseDouble(line2); }catch (NumberFormatException e){ continue; } words.add(line1); weights.add(weight); total_weight += weight; } }catch(IOException e){ e.printStackTrace(); }finally{ try{br1.close(); br2.close();} catch (Exception e){} } } /** * @return A random word */ public String getNextWord(){ double rnumber = random.nextDouble(); double offset = rnumber*total_weight; //get the index int i; for (i=0; i<weights.size(); i++){ double weight = weights.get(i); if (weight + 0.000001>=offset) break; offset = offset - weight; } if (i>=0 && i < weights.size()) return words.get(i); return null; } private void init_menbers(){ random = new Random(); words = new ArrayList<String>(); weights = new ArrayList<Double>(); total_weight = 0.0; } public void addWordsWithEqualWeight(String path){ this.addWordsWithEqualWeight(path, 1.0); } public void addWordsWithEqualWeight(String path, double weight){ BufferedReader br = null; try{ br = new BufferedReader(new FileReader(path)); while (true){ String line = br.readLine(); if (line == null) break; if (line.equals("")) continue; this.words.add(line); this.weights.add(weight); this.total_weight += weight; } }catch(IOException e){ e.printStackTrace(); }finally{ try{br.close();} catch(Exception e){} } } public ArrayList<String> getAllWords(){ return this.words; } }
hustcalm/elasticsearch-hotsearch
wap-gen-data/src/com/cgroups/gendata/RandomEntry.java
Java
mit
2,458
package bj174x.bj1740; import java.io.PrintWriter; import java.util.Scanner; /** * Created by jsong on 30/03/2017. * * @hackerrank https://www.hackerrank.com/jsong00505 * @backjoon https://www.acmicpc.net/user/jsong00505 * @github https://github.com/jsong00505 * @linkedin https://www.linkedin.com/in/junesongskorea/ * @email jsong00505@gmail.com * @challenge Power of N */ public class Main { /** * Method Name: findNthNumbers * * @param n a 'n'th position * @return a number at 'n'th position */ static long findNthNumbers(long n) { long result = 0; // the flag checking if the element is the last order boolean isLast = false; long t = 1; while (n > 0) { if ((n & 1) == 1) { result += t; } n = n >> 1; t *= 3; } return result; } public static void main(String[] args) { try (Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); ) { // get n long n = in.nextLong(); // validation assert (n >= 1 && n <= (5 * Math.pow(10, 11))); out.println(findNthNumbers(n)); } catch (Exception e) { e.printStackTrace(); } } }
jsong00505/Coding-Practice
backjoon/src/bj174x/bj1740/Main.java
Java
mit
1,203
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 5 End-User License Agreement and JUCE 5 Privacy Policy (both updated and effective as of the 27th April 2017). End User License Agreement: www.juce.com/juce-5-licence Privacy Policy: www.juce.com/juce-5-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { class CodeDocumentLine { public: CodeDocumentLine (const String::CharPointerType startOfLine, const String::CharPointerType endOfLine, const int lineLen, const int numNewLineChars, const int startInFile) : line (startOfLine, endOfLine), lineStartInFile (startInFile), lineLength (lineLen), lineLengthWithoutNewLines (lineLen - numNewLineChars) { } static void createLines (Array<CodeDocumentLine*>& newLines, StringRef text) { auto t = text.text; int charNumInFile = 0; bool finished = false; while (! (finished || t.isEmpty())) { auto startOfLine = t; auto startOfLineInFile = charNumInFile; int lineLength = 0; int numNewLineChars = 0; for (;;) { auto c = t.getAndAdvance(); if (c == 0) { finished = true; break; } ++charNumInFile; ++lineLength; if (c == '\r') { ++numNewLineChars; if (*t == '\n') { ++t; ++charNumInFile; ++lineLength; ++numNewLineChars; } break; } if (c == '\n') { ++numNewLineChars; break; } } newLines.add (new CodeDocumentLine (startOfLine, t, lineLength, numNewLineChars, startOfLineInFile)); } jassert (charNumInFile == text.length()); } bool endsWithLineBreak() const noexcept { return lineLengthWithoutNewLines != lineLength; } void updateLength() noexcept { lineLength = 0; lineLengthWithoutNewLines = 0; for (auto t = line.getCharPointer();;) { auto c = t.getAndAdvance(); if (c == 0) break; ++lineLength; if (c != '\n' && c != '\r') lineLengthWithoutNewLines = lineLength; } } String line; int lineStartInFile, lineLength, lineLengthWithoutNewLines; }; //============================================================================== CodeDocument::Iterator::Iterator (const CodeDocument& doc) noexcept : document (&doc) {} CodeDocument::Iterator::Iterator (CodeDocument::Position p) noexcept : document (p.owner), line (p.getLineNumber()), position (p.getPosition()) { reinitialiseCharPtr(); for (int i = 0; i < p.getIndexInLine(); ++i) { charPointer.getAndAdvance(); if (charPointer.isEmpty()) { position -= (p.getIndexInLine() - i); break; } } } CodeDocument::Iterator::Iterator() noexcept : document (nullptr) { } CodeDocument::Iterator::~Iterator() noexcept {} bool CodeDocument::Iterator::reinitialiseCharPtr() const { /** You're trying to use a default constructed iterator. Bad idea! */ jassert (document != nullptr); if (charPointer.getAddress() == nullptr) { if (auto* l = document->lines[line]) charPointer = l->line.getCharPointer(); else return false; } return true; } juce_wchar CodeDocument::Iterator::nextChar() noexcept { for (;;) { if (! reinitialiseCharPtr()) return 0; if (auto result = charPointer.getAndAdvance()) { if (charPointer.isEmpty()) { ++line; charPointer = nullptr; } ++position; return result; } ++line; charPointer = nullptr; } } void CodeDocument::Iterator::skip() noexcept { nextChar(); } void CodeDocument::Iterator::skipToEndOfLine() noexcept { if (! reinitialiseCharPtr()) return; position += (int) charPointer.length(); ++line; charPointer = nullptr; } void CodeDocument::Iterator::skipToStartOfLine() noexcept { if (! reinitialiseCharPtr()) return; if (auto* l = document->lines [line]) { auto startPtr = l->line.getCharPointer(); position -= (int) startPtr.lengthUpTo (charPointer); charPointer = startPtr; } } juce_wchar CodeDocument::Iterator::peekNextChar() const noexcept { if (! reinitialiseCharPtr()) return 0; if (auto c = *charPointer) return c; if (auto* l = document->lines [line + 1]) return l->line[0]; return 0; } juce_wchar CodeDocument::Iterator::previousChar() noexcept { if (! reinitialiseCharPtr()) return 0; for (;;) { if (auto* l = document->lines[line]) { if (charPointer != l->line.getCharPointer()) { --position; --charPointer; break; } } if (line == 0) return 0; --line; if (auto* prev = document->lines[line]) charPointer = prev->line.getCharPointer().findTerminatingNull(); } return *charPointer; } juce_wchar CodeDocument::Iterator::peekPreviousChar() const noexcept { if (! reinitialiseCharPtr()) return 0; if (auto* l = document->lines[line]) { if (charPointer != l->line.getCharPointer()) return *(charPointer - 1); if (auto* prev = document->lines[line - 1]) return *(prev->line.getCharPointer().findTerminatingNull() - 1); } return 0; } void CodeDocument::Iterator::skipWhitespace() noexcept { while (CharacterFunctions::isWhitespace (peekNextChar())) skip(); } bool CodeDocument::Iterator::isEOF() const noexcept { return charPointer.getAddress() == nullptr && line >= document->lines.size(); } bool CodeDocument::Iterator::isSOF() const noexcept { return position == 0; } CodeDocument::Position CodeDocument::Iterator::toPosition() const { if (auto* l = document->lines[line]) { reinitialiseCharPtr(); int indexInLine = 0; auto linePtr = l->line.getCharPointer(); while (linePtr != charPointer && ! linePtr.isEmpty()) { ++indexInLine; ++linePtr; } return CodeDocument::Position (*document, line, indexInLine); } if (isEOF()) { if (auto* last = document->lines.getLast()) { auto lineIndex = document->lines.size() - 1; return CodeDocument::Position (*document, lineIndex, last->lineLength); } } return CodeDocument::Position (*document, 0, 0); } //============================================================================== CodeDocument::Position::Position() noexcept { } CodeDocument::Position::Position (const CodeDocument& ownerDocument, const int lineNum, const int index) noexcept : owner (const_cast<CodeDocument*> (&ownerDocument)), line (lineNum), indexInLine (index) { setLineAndIndex (lineNum, index); } CodeDocument::Position::Position (const CodeDocument& ownerDocument, int pos) noexcept : owner (const_cast<CodeDocument*> (&ownerDocument)) { setPosition (pos); } CodeDocument::Position::Position (const Position& other) noexcept : owner (other.owner), characterPos (other.characterPos), line (other.line), indexInLine (other.indexInLine) { jassert (*this == other); } CodeDocument::Position::~Position() { setPositionMaintained (false); } CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) { if (this != &other) { const bool wasPositionMaintained = positionMaintained; if (owner != other.owner) setPositionMaintained (false); owner = other.owner; line = other.line; indexInLine = other.indexInLine; characterPos = other.characterPos; setPositionMaintained (wasPositionMaintained); jassert (*this == other); } return *this; } bool CodeDocument::Position::operator== (const Position& other) const noexcept { jassert ((characterPos == other.characterPos) == (line == other.line && indexInLine == other.indexInLine)); return characterPos == other.characterPos && line == other.line && indexInLine == other.indexInLine && owner == other.owner; } bool CodeDocument::Position::operator!= (const Position& other) const noexcept { return ! operator== (other); } void CodeDocument::Position::setLineAndIndex (const int newLineNum, const int newIndexInLine) { jassert (owner != nullptr); if (owner->lines.size() == 0) { line = 0; indexInLine = 0; characterPos = 0; } else { if (newLineNum >= owner->lines.size()) { line = owner->lines.size() - 1; auto& l = *owner->lines.getUnchecked (line); indexInLine = l.lineLengthWithoutNewLines; characterPos = l.lineStartInFile + indexInLine; } else { line = jmax (0, newLineNum); auto& l = *owner->lines.getUnchecked (line); if (l.lineLengthWithoutNewLines > 0) indexInLine = jlimit (0, l.lineLengthWithoutNewLines, newIndexInLine); else indexInLine = 0; characterPos = l.lineStartInFile + indexInLine; } } } void CodeDocument::Position::setPosition (const int newPosition) { jassert (owner != nullptr); line = 0; indexInLine = 0; characterPos = 0; if (newPosition > 0) { int lineStart = 0; auto lineEnd = owner->lines.size(); for (;;) { if (lineEnd - lineStart < 4) { for (int i = lineStart; i < lineEnd; ++i) { auto& l = *owner->lines.getUnchecked (i); auto index = newPosition - l.lineStartInFile; if (index >= 0 && (index < l.lineLength || i == lineEnd - 1)) { line = i; indexInLine = jmin (l.lineLengthWithoutNewLines, index); characterPos = l.lineStartInFile + indexInLine; } } break; } else { auto midIndex = (lineStart + lineEnd + 1) / 2; if (newPosition >= owner->lines.getUnchecked (midIndex)->lineStartInFile) lineStart = midIndex; else lineEnd = midIndex; } } } } void CodeDocument::Position::moveBy (int characterDelta) { jassert (owner != nullptr); if (characterDelta == 1) { setPosition (getPosition()); // If moving right, make sure we don't get stuck between the \r and \n characters.. if (line < owner->lines.size()) { auto& l = *owner->lines.getUnchecked (line); if (indexInLine + characterDelta < l.lineLength && indexInLine + characterDelta >= l.lineLengthWithoutNewLines + 1) ++characterDelta; } } setPosition (characterPos + characterDelta); } CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const { CodeDocument::Position p (*this); p.moveBy (characterDelta); return p; } CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const { CodeDocument::Position p (*this); p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine()); return p; } juce_wchar CodeDocument::Position::getCharacter() const { if (auto* l = owner->lines [line]) return l->line [getIndexInLine()]; return 0; } String CodeDocument::Position::getLineText() const { if (auto* l = owner->lines [line]) return l->line; return {}; } void CodeDocument::Position::setPositionMaintained (const bool isMaintained) { if (isMaintained != positionMaintained) { positionMaintained = isMaintained; if (owner != nullptr) { if (isMaintained) { jassert (! owner->positionsToMaintain.contains (this)); owner->positionsToMaintain.add (this); } else { // If this happens, you may have deleted the document while there are Position objects that are still using it... jassert (owner->positionsToMaintain.contains (this)); owner->positionsToMaintain.removeFirstMatchingValue (this); } } } } //============================================================================== CodeDocument::CodeDocument() : undoManager (std::numeric_limits<int>::max(), 10000) { } CodeDocument::~CodeDocument() { } String CodeDocument::getAllContent() const { return getTextBetween (Position (*this, 0), Position (*this, lines.size(), 0)); } String CodeDocument::getTextBetween (const Position& start, const Position& end) const { if (end.getPosition() <= start.getPosition()) return {}; auto startLine = start.getLineNumber(); auto endLine = end.getLineNumber(); if (startLine == endLine) { if (auto* line = lines [startLine]) return line->line.substring (start.getIndexInLine(), end.getIndexInLine()); return {}; } MemoryOutputStream mo; mo.preallocate ((size_t) (end.getPosition() - start.getPosition() + 4)); auto maxLine = jmin (lines.size() - 1, endLine); for (int i = jmax (0, startLine); i <= maxLine; ++i) { auto& line = *lines.getUnchecked(i); auto len = line.lineLength; if (i == startLine) { auto index = start.getIndexInLine(); mo << line.line.substring (index, len); } else if (i == endLine) { len = end.getIndexInLine(); mo << line.line.substring (0, len); } else { mo << line.line; } } return mo.toUTF8(); } int CodeDocument::getNumCharacters() const noexcept { if (auto* lastLine = lines.getLast()) return lastLine->lineStartInFile + lastLine->lineLength; return 0; } String CodeDocument::getLine (const int lineIndex) const noexcept { if (auto* line = lines[lineIndex]) return line->line; return {}; } int CodeDocument::getMaximumLineLength() noexcept { if (maximumLineLength < 0) { maximumLineLength = 0; for (auto* l : lines) maximumLineLength = jmax (maximumLineLength, l->lineLength); } return maximumLineLength; } void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition) { deleteSection (startPosition.getPosition(), endPosition.getPosition()); } void CodeDocument::deleteSection (const int start, const int end) { remove (start, end, true); } void CodeDocument::insertText (const Position& position, const String& text) { insertText (position.getPosition(), text); } void CodeDocument::insertText (const int insertIndex, const String& text) { insert (text, insertIndex, true); } void CodeDocument::replaceSection (const int start, const int end, const String& newText) { insertText (end, newText); deleteSection (start, end); } void CodeDocument::applyChanges (const String& newContent) { const String corrected (StringArray::fromLines (newContent) .joinIntoString (newLineChars)); TextDiff diff (getAllContent(), corrected); for (auto& c : diff.changes) { if (c.isDeletion()) remove (c.start, c.start + c.length, true); else insert (c.insertedText, c.start, true); } } void CodeDocument::replaceAllContent (const String& newContent) { remove (0, getNumCharacters(), true); insert (newContent, 0, true); } bool CodeDocument::loadFromStream (InputStream& stream) { remove (0, getNumCharacters(), false); insert (stream.readEntireStreamAsString(), 0, false); setSavePoint(); clearUndoHistory(); return true; } bool CodeDocument::writeToStream (OutputStream& stream) { for (auto* l : lines) { auto temp = l->line; // use a copy to avoid bloating the memory footprint of the stored string. const char* utf8 = temp.toUTF8(); if (! stream.write (utf8, strlen (utf8))) return false; } return true; } void CodeDocument::setNewLineCharacters (const String& newChars) noexcept { jassert (newChars == "\r\n" || newChars == "\n" || newChars == "\r"); newLineChars = newChars; } void CodeDocument::newTransaction() { undoManager.beginNewTransaction (String()); } void CodeDocument::undo() { newTransaction(); undoManager.undo(); } void CodeDocument::redo() { undoManager.redo(); } void CodeDocument::clearUndoHistory() { undoManager.clearUndoHistory(); } void CodeDocument::setSavePoint() noexcept { indexOfSavedState = currentActionIndex; } bool CodeDocument::hasChangedSinceSavePoint() const noexcept { return currentActionIndex != indexOfSavedState; } //============================================================================== static inline int getCharacterType (juce_wchar character) noexcept { return (CharacterFunctions::isLetterOrDigit (character) || character == '_') ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1); } CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const noexcept { auto p = position; const int maxDistance = 256; int i = 0; while (i < maxDistance && CharacterFunctions::isWhitespace (p.getCharacter()) && (i == 0 || (p.getCharacter() != '\n' && p.getCharacter() != '\r'))) { ++i; p.moveBy (1); } if (i == 0) { auto type = getCharacterType (p.getCharacter()); while (i < maxDistance && type == getCharacterType (p.getCharacter())) { ++i; p.moveBy (1); } while (i < maxDistance && CharacterFunctions::isWhitespace (p.getCharacter()) && (i == 0 || (p.getCharacter() != '\n' && p.getCharacter() != '\r'))) { ++i; p.moveBy (1); } } return p; } CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const noexcept { auto p = position; const int maxDistance = 256; int i = 0; bool stoppedAtLineStart = false; while (i < maxDistance) { auto c = p.movedBy (-1).getCharacter(); if (c == '\r' || c == '\n') { stoppedAtLineStart = true; if (i > 0) break; } if (! CharacterFunctions::isWhitespace (c)) break; p.moveBy (-1); ++i; } if (i < maxDistance && ! stoppedAtLineStart) { auto type = getCharacterType (p.movedBy (-1).getCharacter()); while (i < maxDistance && type == getCharacterType (p.movedBy (-1).getCharacter())) { p.moveBy (-1); ++i; } } return p; } void CodeDocument::findTokenContaining (const Position& pos, Position& start, Position& end) const noexcept { auto isTokenCharacter = [] (juce_wchar c) { return CharacterFunctions::isLetterOrDigit (c) || c == '.' || c == '_'; }; end = pos; while (isTokenCharacter (end.getCharacter())) end.moveBy (1); start = end; while (start.getIndexInLine() > 0 && isTokenCharacter (start.movedBy (-1).getCharacter())) start.moveBy (-1); } void CodeDocument::findLineContaining (const Position& pos, Position& s, Position& e) const noexcept { s.setLineAndIndex (pos.getLineNumber(), 0); e.setLineAndIndex (pos.getLineNumber() + 1, 0); } void CodeDocument::checkLastLineStatus() { while (lines.size() > 0 && lines.getLast()->lineLength == 0 && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak())) { // remove any empty lines at the end if the preceding line doesn't end in a newline. lines.removeLast(); } const CodeDocumentLine* const lastLine = lines.getLast(); if (lastLine != nullptr && lastLine->endsWithLineBreak()) { // check that there's an empty line at the end if the preceding one ends in a newline.. lines.add (new CodeDocumentLine (StringRef(), StringRef(), 0, 0, lastLine->lineStartInFile + lastLine->lineLength)); } } //============================================================================== void CodeDocument::addListener (CodeDocument::Listener* l) { listeners.add (l); } void CodeDocument::removeListener (CodeDocument::Listener* l) { listeners.remove (l); } //============================================================================== struct CodeDocument::InsertAction : public UndoableAction { InsertAction (CodeDocument& doc, const String& t, const int pos) noexcept : owner (doc), text (t), insertPos (pos) { } bool perform() override { owner.currentActionIndex++; owner.insert (text, insertPos, false); return true; } bool undo() override { owner.currentActionIndex--; owner.remove (insertPos, insertPos + text.length(), false); return true; } int getSizeInUnits() override { return text.length() + 32; } CodeDocument& owner; const String text; const int insertPos; JUCE_DECLARE_NON_COPYABLE (InsertAction) }; void CodeDocument::insert (const String& text, const int insertPos, const bool undoable) { if (text.isNotEmpty()) { if (undoable) { undoManager.perform (new InsertAction (*this, text, insertPos)); } else { Position pos (*this, insertPos); auto firstAffectedLine = pos.getLineNumber(); auto* firstLine = lines[firstAffectedLine]; auto textInsideOriginalLine = text; if (firstLine != nullptr) { auto index = pos.getIndexInLine(); textInsideOriginalLine = firstLine->line.substring (0, index) + textInsideOriginalLine + firstLine->line.substring (index); } maximumLineLength = -1; Array<CodeDocumentLine*> newLines; CodeDocumentLine::createLines (newLines, textInsideOriginalLine); jassert (newLines.size() > 0); auto* newFirstLine = newLines.getUnchecked (0); newFirstLine->lineStartInFile = firstLine != nullptr ? firstLine->lineStartInFile : 0; lines.set (firstAffectedLine, newFirstLine); if (newLines.size() > 1) lines.insertArray (firstAffectedLine + 1, newLines.getRawDataPointer() + 1, newLines.size() - 1); int lineStart = newFirstLine->lineStartInFile; for (int i = firstAffectedLine; i < lines.size(); ++i) { auto& l = *lines.getUnchecked (i); l.lineStartInFile = lineStart; lineStart += l.lineLength; } checkLastLineStatus(); auto newTextLength = text.length(); for (auto* p : positionsToMaintain) if (p->getPosition() >= insertPos) p->setPosition (p->getPosition() + newTextLength); listeners.call ([&] (Listener& l) { l.codeDocumentTextInserted (text, insertPos); }); } } } //============================================================================== struct CodeDocument::DeleteAction : public UndoableAction { DeleteAction (CodeDocument& doc, int start, int end) noexcept : owner (doc), startPos (start), endPos (end), removedText (doc.getTextBetween (CodeDocument::Position (doc, start), CodeDocument::Position (doc, end))) { } bool perform() override { owner.currentActionIndex++; owner.remove (startPos, endPos, false); return true; } bool undo() override { owner.currentActionIndex--; owner.insert (removedText, startPos, false); return true; } int getSizeInUnits() override { return (endPos - startPos) + 32; } CodeDocument& owner; const int startPos, endPos; const String removedText; JUCE_DECLARE_NON_COPYABLE (DeleteAction) }; void CodeDocument::remove (const int startPos, const int endPos, const bool undoable) { if (endPos <= startPos) return; if (undoable) { undoManager.perform (new DeleteAction (*this, startPos, endPos)); } else { Position startPosition (*this, startPos); Position endPosition (*this, endPos); maximumLineLength = -1; auto firstAffectedLine = startPosition.getLineNumber(); auto endLine = endPosition.getLineNumber(); auto& firstLine = *lines.getUnchecked (firstAffectedLine); if (firstAffectedLine == endLine) { firstLine.line = firstLine.line.substring (0, startPosition.getIndexInLine()) + firstLine.line.substring (endPosition.getIndexInLine()); firstLine.updateLength(); } else { auto& lastLine = *lines.getUnchecked (endLine); firstLine.line = firstLine.line.substring (0, startPosition.getIndexInLine()) + lastLine.line.substring (endPosition.getIndexInLine()); firstLine.updateLength(); int numLinesToRemove = endLine - firstAffectedLine; lines.removeRange (firstAffectedLine + 1, numLinesToRemove); } for (int i = firstAffectedLine + 1; i < lines.size(); ++i) { auto& l = *lines.getUnchecked (i); auto& previousLine = *lines.getUnchecked (i - 1); l.lineStartInFile = previousLine.lineStartInFile + previousLine.lineLength; } checkLastLineStatus(); auto totalChars = getNumCharacters(); for (auto* p : positionsToMaintain) { if (p->getPosition() > startPosition.getPosition()) p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos)); if (p->getPosition() > totalChars) p->setPosition (totalChars); } listeners.call ([=] (Listener& l) { l.codeDocumentTextDeleted (startPos, endPos); }); } } //============================================================================== //============================================================================== #if JUCE_UNIT_TESTS struct CodeDocumentTest : public UnitTest { CodeDocumentTest() : UnitTest ("CodeDocument", UnitTestCategories::text) {} void runTest() override { const juce::String jabberwocky ("'Twas brillig, and the slithy toves\n" "Did gyre and gimble in the wabe;\n" "All mimsy were the borogoves,\n" "And the mome raths outgrabe.\n\n" "'Beware the Jabberwock, my son!\n" "The jaws that bite, the claws that catch!\n" "Beware the Jubjub bird, and shun\n" "The frumious Bandersnatch!'"); { beginTest ("Basic checks"); CodeDocument d; d.replaceAllContent (jabberwocky); expectEquals (d.getNumLines(), 9); expect (d.getLine (0).startsWith ("'Twas brillig")); expect (d.getLine (2).startsWith ("All mimsy")); expectEquals (d.getLine (4), String ("\n")); } { beginTest ("Insert/replace/delete"); CodeDocument d; d.replaceAllContent (jabberwocky); d.insertText (CodeDocument::Position (d, 0, 6), "very "); expect (d.getLine (0).startsWith ("'Twas very brillig"), "Insert text within a line"); d.replaceSection (74, 83, "Quite hungry"); expectEquals (d.getLine (2), String ("Quite hungry were the borogoves,\n"), "Replace section at start of line"); d.replaceSection (11, 18, "cold"); expectEquals (d.getLine (0), String ("'Twas very cold, and the slithy toves\n"), "Replace section within a line"); d.deleteSection (CodeDocument::Position (d, 2, 0), CodeDocument::Position (d, 2, 6)); expectEquals (d.getLine (2), String ("hungry were the borogoves,\n"), "Delete section within a line"); d.deleteSection (CodeDocument::Position (d, 2, 6), CodeDocument::Position (d, 5, 11)); expectEquals (d.getLine (2), String ("hungry Jabberwock, my son!\n"), "Delete section across multiple line"); } { beginTest ("Line splitting and joining"); CodeDocument d; d.replaceAllContent (jabberwocky); expectEquals (d.getNumLines(), 9); const String splitComment ("Adding a newline should split a line into two."); d.insertText (49, "\n"); expectEquals (d.getNumLines(), 10, splitComment); expectEquals (d.getLine (1), String ("Did gyre and \n"), splitComment); expectEquals (d.getLine (2), String ("gimble in the wabe;\n"), splitComment); const String joinComment ("Removing a newline should join two lines."); d.deleteSection (CodeDocument::Position (d, 0, 35), CodeDocument::Position (d, 1, 0)); expectEquals (d.getNumLines(), 9, joinComment); expectEquals (d.getLine (0), String ("'Twas brillig, and the slithy tovesDid gyre and \n"), joinComment); expectEquals (d.getLine (1), String ("gimble in the wabe;\n"), joinComment); } { beginTest ("Undo/redo"); CodeDocument d; d.replaceAllContent (jabberwocky); d.newTransaction(); d.insertText (30, "INSERT1"); d.newTransaction(); d.insertText (70, "INSERT2"); d.undo(); expect (d.getAllContent().contains ("INSERT1"), "1st edit should remain."); expect (! d.getAllContent().contains ("INSERT2"), "2nd edit should be undone."); d.redo(); expect (d.getAllContent().contains ("INSERT2"), "2nd edit should be redone."); d.newTransaction(); d.deleteSection (25, 90); expect (! d.getAllContent().contains ("INSERT1"), "1st edit should be deleted."); expect (! d.getAllContent().contains ("INSERT2"), "2nd edit should be deleted."); d.undo(); expect (d.getAllContent().contains ("INSERT1"), "1st edit should be restored."); expect (d.getAllContent().contains ("INSERT2"), "1st edit should be restored."); d.undo(); d.undo(); expectEquals (d.getAllContent(), jabberwocky, "Original document should be restored."); } { beginTest ("Positions"); CodeDocument d; d.replaceAllContent (jabberwocky); { const String comment ("Keeps negative positions inside document."); CodeDocument::Position p1 (d, 0, -3); CodeDocument::Position p2 (d, -8); expectEquals (p1.getLineNumber(), 0, comment); expectEquals (p1.getIndexInLine(), 0, comment); expectEquals (p1.getCharacter(), juce_wchar ('\''), comment); expectEquals (p2.getLineNumber(), 0, comment); expectEquals (p2.getIndexInLine(), 0, comment); expectEquals (p2.getCharacter(), juce_wchar ('\''), comment); } { const String comment ("Moving by character handles newlines correctly."); CodeDocument::Position p1 (d, 0, 35); p1.moveBy (1); expectEquals (p1.getLineNumber(), 1, comment); expectEquals (p1.getIndexInLine(), 0, comment); p1.moveBy (75); expectEquals (p1.getLineNumber(), 3, comment); } { const String comment1 ("setPositionMaintained tracks position."); const String comment2 ("setPositionMaintained tracks position following undos."); CodeDocument::Position p1 (d, 3, 0); p1.setPositionMaintained (true); expectEquals (p1.getCharacter(), juce_wchar ('A'), comment1); d.newTransaction(); d.insertText (p1, "INSERT1"); expectEquals (p1.getCharacter(), juce_wchar ('A'), comment1); expectEquals (p1.getLineNumber(), 3, comment1); expectEquals (p1.getIndexInLine(), 7, comment1); d.undo(); expectEquals (p1.getIndexInLine(), 0, comment2); d.newTransaction(); d.insertText (15, "\n"); expectEquals (p1.getLineNumber(), 4, comment1); d.undo(); expectEquals (p1.getLineNumber(), 3, comment2); } } { beginTest ("Iterators"); CodeDocument d; d.replaceAllContent (jabberwocky); { const String comment1 ("Basic iteration."); const String comment2 ("Reverse iteration."); const String comment3 ("Reverse iteration stops at doc start."); const String comment4 ("Check iteration across line boundaries."); CodeDocument::Iterator it (d); expectEquals (it.peekNextChar(), juce_wchar ('\''), comment1); expectEquals (it.nextChar(), juce_wchar ('\''), comment1); expectEquals (it.nextChar(), juce_wchar ('T'), comment1); expectEquals (it.nextChar(), juce_wchar ('w'), comment1); expectEquals (it.peekNextChar(), juce_wchar ('a'), comment2); expectEquals (it.previousChar(), juce_wchar ('w'), comment2); expectEquals (it.previousChar(), juce_wchar ('T'), comment2); expectEquals (it.previousChar(), juce_wchar ('\''), comment2); expectEquals (it.previousChar(), juce_wchar (0), comment3); expect (it.isSOF(), comment3); while (it.peekNextChar() != juce_wchar ('D')) // "Did gyre..." it.nextChar(); expectEquals (it.nextChar(), juce_wchar ('D'), comment3); expectEquals (it.peekNextChar(), juce_wchar ('i'), comment3); expectEquals (it.previousChar(), juce_wchar ('D'), comment3); expectEquals (it.previousChar(), juce_wchar ('\n'), comment3); expectEquals (it.previousChar(), juce_wchar ('s'), comment3); } { const String comment1 ("Iterator created from CodeDocument::Position objects."); const String comment2 ("CodeDocument::Position created from Iterator objects."); const String comment3 ("CodeDocument::Position created from EOF Iterator objects."); CodeDocument::Position p (d, 6, 0); // "The jaws..." CodeDocument::Iterator it (p); expectEquals (it.nextChar(), juce_wchar ('T'), comment1); expectEquals (it.nextChar(), juce_wchar ('h'), comment1); expectEquals (it.previousChar(), juce_wchar ('h'), comment1); expectEquals (it.previousChar(), juce_wchar ('T'), comment1); expectEquals (it.previousChar(), juce_wchar ('\n'), comment1); expectEquals (it.previousChar(), juce_wchar ('!'), comment1); const auto p2 = it.toPosition(); expectEquals (p2.getLineNumber(), 5, comment2); expectEquals (p2.getIndexInLine(), 30, comment2); while (! it.isEOF()) it.nextChar(); const auto p3 = it.toPosition(); expectEquals (p3.getLineNumber(), d.getNumLines() - 1, comment3); expectEquals (p3.getIndexInLine(), d.getLine (d.getNumLines() - 1).length(), comment3); } } } }; static CodeDocumentTest codeDocumentTests; #endif } // namespace juce
Ultraschall/Soundboard
src/JuceLibraryCode/modules/juce_gui_extra/code_editor/juce_CodeDocument.cpp
C++
mit
38,484
<?php use yii\db\Schema; use yii\db\Migration; class m140924_133309_dropcols extends Migration { public function up() { $this->dropColumn('address', 'otherStreet'); $this->dropColumn('address', 'otherCity'); $this->dropColumn('address', 'otherZip'); } public function down() { echo "m140924_133309_dropcols cannot be reverted.\n"; return false; } }
chovajsa/billio
console/migrations/m140924_133309_dropcols.php
PHP
mit
409
<?php class ChartPage extends RunnerPage { /** * The name of the dashboard the List is displayed on * It's set up correctly in dash mode only */ public $dashElementName = ""; /** * The corresponding dashboard name * It's set up correctly in dash mode only */ public $dashTName = ""; /** * show message block */ public $show_message_block = false; /** * @constructor */ function ChartPage(&$params = "") { parent::RunnerPage($params); $this->jsSettings['tableSettings'][ $this->tName ]['simpleSearchActive'] = $this->searchClauseObj->simpleSearchActive; } /** * Set the page's session prefix */ protected function assignSessionPrefix() { if( $this->mode == CHART_DASHBOARD ) $this->sessionPrefix = $this->dashTName."_".$this->tName; else $this->sessionPrefix = $this->tName; } /** * Set session variables */ public function setSessionVariables() { parent::setSessionVariables(); // SearchClause class stuff $agregateFields = $this->pSet->getListOfFieldsByExprType(true); $this->searchClauseObj->haveAgregateFields = count($agregateFields) > 0; $_SESSION[ $this->sessionPrefix.'_advsearch' ] = serialize( $this->searchClauseObj ); } /** * Build the activated Search panel */ public function buildSearchPanel() { if( $this->mode == CHART_DASHBOARD ) return; parent::buildSearchPanel(); } /** * Process the page */ public function process() { // Before Process event if( $this->eventsObject->exists("BeforeProcessChart") ) $this->eventsObject->BeforeProcessChart( $this ); $this->doCommonAssignments(); $this->addButtonHandlers(); $this->addCommonJs(); $this->commonAssign(); // display the 'Back to Master' link and master table info $this->displayMasterTableInfo(); $this->showPage(); } /** * Get where clause for an active master-detail relationship * @return string */ public function getMasterTableSQLClause() { if( $this->mode == CHART_DASHBOARD ) return ""; return parent::getMasterTableSQLClause(); } /** * */ public function doCommonAssignments() // TODO: make it protected { $this->xt->assign("id", $this->id); //set the Search panel $this->xt->assign("searchPanel", true); if( $this->isShowMenu() ) $this->xt->assign("menu_block", true); $this->xt->assign("chart_block", true); $this->xt->assign("asearch_link", true); $this->xt->assign("exportpdflink_attrs", "onclick='chart.saveAsPDF();'"); $this->xt->assign("advsearchlink_attrs", "id=\"advButton".$this->id."\""); if( !GetChartXML( $this->shortTableName ) ) $this->xt->assign("chart_block", false); if( ($this->mode == CHART_SIMPLE || $this->mode == CHART_DASHBOARD) && $this->pSet->noRecordsOnFirstPage() && !$this->searchClauseObj->isSearchFunctionalityActivated() ) { $this->show_message_block = true; $this->xt->displayBrickHidden("chart"); $this->xt->assign("chart_block", false); $this->xt->assign("message_block", true); $this->xt->assign("message", "No records found"); } $this->assignChartElement(); if( $this->isDynamicPerm && IsAdmin() ) { $this->xt->assign("adminarea_link", true); $this->xt->assign("adminarealink_attrs", "id=\"adminArea".$id."\""); } $this->xt->assign("changepwd_link", $_SESSION["AccessLevel"] != ACCESS_LEVEL_GUEST && $_SESSION["fromFacebook"] == false); $this->xt->assign("changepwdlink_attrs", "onclick=\"window.location.href='".GetTableLink("changepwd")."';return false;\""); $this->body['begin'].= GetBaseScriptsForPage( $this->isDisplayLoading ); if( !isMobile() ) $this->body['begin'].= "<div id=\"search_suggest\" class=\"search_suggest\"></div>"; // assign body end $this->body['end'] = array(); AssignMethod($this->body['end'], "assignBodyEnd", $this); $this->xt->assignbyref('body', $this->body); } /** * Set the chart xt variable */ public function assignChartElement() { //set params for the 'xt_showchart' method showing the chart $chartXtParams = array( "id" => $this->id, "table" => $this->tName, "ctype" => $this->pSet->getChartType(), "resize" => $this->mode !== CHART_SIMPLE && $this->mode != CHART_DASHBOARD, "chartname" => $this->shortTableName, "chartPreview" => $this->mode !== CHART_SIMPLE && $this->mode != CHART_DASHBOARD ); if( $this->mode == CHART_DASHBOARD || $this->mode == CHART_DASHDETAILS) { $dashSet = new ProjectSettings( $this->dashTName ); $dashElementData = $dashSet->getDashboardElementData( $this->dashElementName ); if( isset($dashElementData["width"]) || isset($dashElementData["height"]) ) //#10119 { $chartXtParams["dashResize"] = true; $chartXtParams["dashWidth"] = $dashElementData["width"]; $chartXtParams["dashHeight"] = $dashElementData["height"]; } if( $this->mode == CHART_DASHBOARD ) { $chartXtParams["dash"] = true; $chartXtParams["dashTName"] = $this->dashTName; $chartXtParams["dashElementName"] = $this->dashElementName; } } $this->xt->assign_function( $this->shortTableName."_chart", "xt_showchart", $chartXtParams ); } public function showPage() { if( $this->eventsObject->exists("BeforeShowChart") ) $this->eventsObject->BeforeShowChart($this->xt, $this->templatefile, $this); if( $this->mode == CHART_DETAILS || $this->mode == CHART_DASHBOARD || $this->mode == CHART_DASHDETAILS ) { $this->addControlsJSAndCSS(); $this->fillSetCntrlMaps(); $this->xt->unassign("header"); $this->xt->unassign("footer"); $this->body["begin"] = ""; $this->body["end"] = ""; $this->xt->assign("body", $this->body); $bricksExcept = array("chart"); $this->xt->hideAllBricksExcept($bricksExcept); if( $this->show_message_block ) $this->xt->assign("message_block", true); $this->displayAJAX($this->templatefile, $this->id + 1); exit(); } if( $this->mode == CHART_POPUPDETAILS ) //currently unused { $bricksExcept = array("grid","pagination"); $this->xt->unassign('header'); $this->xt->unassign('footer'); $this->body["begin"] = ''; $this->body["end"] = ''; $this->xt->hideAllBricksExcept($bricksExcept); $this->xt->prepare_template($this->templatefile); $respArr = array(); $respArr['success'] = true; $respArr['body'] = $this->xt->fetch_loaded("body"); $respArr['counter'] = postvalue('counter'); $this->xt->assign("container_master", false); echo printJSON($respArr); exit(); } $this->display( $this->templatefile ); } } ?>
tony19760619/PHPRunnerProjects
Jobs/output/classes/chartpage.php
PHP
mit
6,600
# coding=utf-8 """ Collect the elasticsearch stats for the local node #### Dependencies * urlib2 """ import urllib2 import re try: import json json # workaround for pyflakes issue #13 except ImportError: import simplejson as json import diamond.collector RE_LOGSTASH_INDEX = re.compile('^(.*)-\d\d\d\d\.\d\d\.\d\d$') class ElasticSearchCollector(diamond.collector.Collector): def get_default_config_help(self): config_help = super(ElasticSearchCollector, self).get_default_config_help() config_help.update({ 'host': "", 'port': "", 'stats': "Available stats: \n" + " - jvm (JVM information) \n" + " - thread_pool (Thread pool information) \n" + " - indices (Individual index stats)\n", 'logstash_mode': "If 'indices' stats are gathered, remove " + "the YYYY.MM.DD suffix from the index name " + "(e.g. logstash-adm-syslog-2014.01.03) and use that " + "as a bucket for all 'day' index stats.", }) return config_help def get_default_config(self): """ Returns the default collector settings """ config = super(ElasticSearchCollector, self).get_default_config() config.update({ 'host': '127.0.0.1', 'port': 9200, 'path': 'elasticsearch', 'stats': ['jvm', 'thread_pool', 'indices'], 'logstash_mode': False, }) return config def _get(self, path): url = 'http://%s:%i/%s' % ( self.config['host'], int(self.config['port']), path) try: response = urllib2.urlopen(url) except Exception, err: self.log.error("%s: %s", url, err) return False try: return json.load(response) except (TypeError, ValueError): self.log.error("Unable to parse response from elasticsearch as a" + " json object") return False def _copy_one_level(self, metrics, prefix, data, filter=lambda key: True): for key, value in data.iteritems(): if filter(key): metric_path = '%s.%s' % (prefix, key) self._set_or_sum_metric(metrics, metric_path, value) def _copy_two_level(self, metrics, prefix, data, filter=lambda key: True): for key1, d1 in data.iteritems(): self._copy_one_level(metrics, '%s.%s' % (prefix, key1), d1, filter) def _index_metrics(self, metrics, prefix, index): if self.config['logstash_mode']: """Remove the YYYY.MM.DD bit from logstash indices. This way we keep using the same metric naming and not polute our metrics system (e.g. Graphite) with new metrics every day.""" m = RE_LOGSTASH_INDEX.match(prefix) if m: prefix = m.group(1) # keep a telly of the number of indexes self._set_or_sum_metric(metrics, '%s.indexes_in_group' % prefix, 1) self._add_metric(metrics, '%s.docs.count' % prefix, index, ['docs', 'count']) self._add_metric(metrics, '%s.docs.deleted' % prefix, index, ['docs', 'deleted']) self._add_metric(metrics, '%s.datastore.size' % prefix, index, ['store', 'size_in_bytes']) # publish all 'total' and 'time_in_millis' stats self._copy_two_level( metrics, prefix, index, lambda key: key.endswith('total') or key.endswith('time_in_millis')) def _add_metric(self, metrics, metric_path, data, data_path): """If the path specified by data_path (a list) exists in data, add to metrics. Use when the data path may not be present""" current_item = data for path_element in data_path: current_item = current_item.get(path_element) if current_item is None: return self._set_or_sum_metric(metrics, metric_path, current_item) def _set_or_sum_metric(self, metrics, metric_path, value): """If we already have a datapoint for this metric, lets add the value. This is used when the logstash mode is enabled.""" if metric_path in metrics: metrics[metric_path] += value else: metrics[metric_path] = value def collect(self): if json is None: self.log.error('Unable to import json') return {} result = self._get('_nodes/_local/stats?all=true') if not result: return metrics = {} node = result['nodes'].keys()[0] data = result['nodes'][node] # # http connections to ES metrics['http.current'] = data['http']['current_open'] # # indices indices = data['indices'] metrics['indices.docs.count'] = indices['docs']['count'] metrics['indices.docs.deleted'] = indices['docs']['deleted'] metrics['indices.datastore.size'] = indices['store']['size_in_bytes'] transport = data['transport'] metrics['transport.rx.count'] = transport['rx_count'] metrics['transport.rx.size'] = transport['rx_size_in_bytes'] metrics['transport.tx.count'] = transport['tx_count'] metrics['transport.tx.size'] = transport['tx_size_in_bytes'] # elasticsearch < 0.90RC2 if 'cache' in indices: cache = indices['cache'] self._add_metric(metrics, 'cache.bloom.size', cache, ['bloom_size_in_bytes']) self._add_metric(metrics, 'cache.field.evictions', cache, ['field_evictions']) self._add_metric(metrics, 'cache.field.size', cache, ['field_size_in_bytes']) metrics['cache.filter.count'] = cache['filter_count'] metrics['cache.filter.evictions'] = cache['filter_evictions'] metrics['cache.filter.size'] = cache['filter_size_in_bytes'] self._add_metric(metrics, 'cache.id.size', cache, ['id_cache_size_in_bytes']) # elasticsearch >= 0.90RC2 if 'filter_cache' in indices: cache = indices['filter_cache'] metrics['cache.filter.evictions'] = cache['evictions'] metrics['cache.filter.size'] = cache['memory_size_in_bytes'] self._add_metric(metrics, 'cache.filter.count', cache, ['count']) # elasticsearch >= 0.90RC2 if 'id_cache' in indices: cache = indices['id_cache'] self._add_metric(metrics, 'cache.id.size', cache, ['memory_size_in_bytes']) # elasticsearch >= 0.90 if 'fielddata' in indices: fielddata = indices['fielddata'] self._add_metric(metrics, 'fielddata.size', fielddata, ['memory_size_in_bytes']) self._add_metric(metrics, 'fielddata.evictions', fielddata, ['evictions']) # # process mem/cpu (may not be present, depending on access restrictions) self._add_metric(metrics, 'process.cpu.percent', data, ['process', 'cpu', 'percent']) self._add_metric(metrics, 'process.mem.resident', data, ['process', 'mem', 'resident_in_bytes']) self._add_metric(metrics, 'process.mem.share', data, ['process', 'mem', 'share_in_bytes']) self._add_metric(metrics, 'process.mem.virtual', data, ['process', 'mem', 'total_virtual_in_bytes']) # # filesystem (may not be present, depending on access restrictions) if 'fs' in data and 'data' in data['fs'] and data['fs']['data']: fs_data = data['fs']['data'][0] self._add_metric(metrics, 'disk.reads.count', fs_data, ['disk_reads']) self._add_metric(metrics, 'disk.reads.size', fs_data, ['disk_read_size_in_bytes']) self._add_metric(metrics, 'disk.writes.count', fs_data, ['disk_writes']) self._add_metric(metrics, 'disk.writes.size', fs_data, ['disk_write_size_in_bytes']) # # jvm if 'jvm' in self.config['stats']: jvm = data['jvm'] mem = jvm['mem'] for k in ('heap_used', 'heap_committed', 'non_heap_used', 'non_heap_committed'): metrics['jvm.mem.%s' % k] = mem['%s_in_bytes' % k] for pool, d in mem['pools'].iteritems(): pool = pool.replace(' ', '_') metrics['jvm.mem.pools.%s.used' % pool] = d['used_in_bytes'] metrics['jvm.mem.pools.%s.max' % pool] = d['max_in_bytes'] metrics['jvm.threads.count'] = jvm['threads']['count'] gc = jvm['gc'] collection_count = 0 collection_time_in_millis = 0 for collector, d in gc['collectors'].iteritems(): metrics['jvm.gc.collection.%s.count' % collector] = d[ 'collection_count'] collection_count += d['collection_count'] metrics['jvm.gc.collection.%s.time' % collector] = d[ 'collection_time_in_millis'] collection_time_in_millis += d['collection_time_in_millis'] # calculate the totals, as they're absent in elasticsearch > 0.90.10 if 'collection_count' in gc: metrics['jvm.gc.collection.count'] = gc['collection_count'] else: metrics['jvm.gc.collection.count'] = collection_count k = 'collection_time_in_millis' if k in gc: metrics['jvm.gc.collection.time'] = gc[k] else: metrics['jvm.gc.collection.time'] = collection_time_in_millis # # thread_pool if 'thread_pool' in self.config['stats']: self._copy_two_level(metrics, 'thread_pool', data['thread_pool']) # # network self._copy_two_level(metrics, 'network', data['network']) if 'indices' in self.config['stats']: # # individual index stats result = self._get('_stats?clear=true&docs=true&store=true&' + 'indexing=true&get=true&search=true') if not result: return _all = result['_all'] self._index_metrics(metrics, 'indices._all', _all['primaries']) if 'indices' in _all: indices = _all['indices'] elif 'indices' in result: # elasticsearch >= 0.90RC2 indices = result['indices'] else: return for name, index in indices.iteritems(): self._index_metrics(metrics, 'indices.%s' % name, index['primaries']) for key in metrics: self.publish(key, metrics[key])
metamx/Diamond
src/collectors/elasticsearch/elasticsearch.py
Python
mit
11,323
<?php function removeSpecialChars($suaString) { $string = preg_replace( '/[`^~\'"]/', null, iconv( 'UTF-8', 'ASCII//TRANSLIT', $suaString ) ); $string = htmlspecialchars($string); return $string; }
max10rogerio/easyJob
api/functions.php
PHP
mit
205
import Html from "./Html"; import { YatinSelectMin, YatinSelectMax } from "../parts/YatinSelect"; export default class YatinSection extends Html { constructor(min="", max="") { super(); var $yatinSection = $(` <section class="yatin-section"> <h2>¥家賃</h2> <div class="center"></div> </section> `); var selectMin = new YatinSelectMin(min); var selectMax = new YatinSelectMax(max); $yatinSection.find(".center").append( selectMin.getHtml() ); $yatinSection.find(".center").append( $(`<div class="kara">〜</div>`) ); $yatinSection.find(".center").append( selectMax.getHtml() ); this.$html = $yatinSection } }
nakamura-yuta-i7/ietopia-appli
src/pages/parts/YatinSection.js
JavaScript
mit
700
# frozen_string_literal: true require "#{Rails.root}/lib/analytics/histogram_plotter" class OresPlotController < ApplicationController def course_plot @course = Course.find_by slug: params[:id] @ores_changes_plot = HistogramPlotter.plot(course: @course, opts: { simple: true }) render json: { plot_path: @ores_changes_plot } end end
alpha721/WikiEduDashboard
app/controllers/ores_plot_controller.rb
Ruby
mit
351
import java.io.IOException; import java.io.FileInputStream; public class UsingFileInputStream{ public static void main(String[] main) throws IOException{ FileInputStream fis=new FileInputStream("file.txt"); int i; while((i=fis.read())!=-1){ System.out.print((char)i); } fis.close(); } }
AlphaBAT69/Java-Programs
IOPackage/UsingFileInputStream.java
Java
mit
302
import { Fun, Optional } from '@ephox/katamari'; import { PlatformDetection } from '@ephox/sand'; import { fromRawEvent } from '../../impl/FilteredEvent'; import { EventHandler, EventUnbinder } from '../events/Types'; import { SugarElement } from '../node/SugarElement'; import * as Scroll from './Scroll'; export interface Bounds { readonly x: number; readonly y: number; readonly width: number; readonly height: number; readonly right: number; readonly bottom: number; } const get = (_win?: Window): Optional<VisualViewport> => { const win = _win === undefined ? window : _win; if (PlatformDetection.detect().browser.isFirefox()) { // TINY-7984: Firefox 91 is returning incorrect values for visualViewport.pageTop, so disable it for now return Optional.none(); } else { return Optional.from(win.visualViewport); } }; const bounds = (x: number, y: number, width: number, height: number): Bounds => ({ x, y, width, height, right: x + width, bottom: y + height }); const getBounds = (_win?: Window): Bounds => { const win = _win === undefined ? window : _win; const doc = win.document; const scroll = Scroll.get(SugarElement.fromDom(doc)); return get(win).fold( () => { const html = win.document.documentElement; // Don't use window.innerWidth/innerHeight here, as we don't want to include scrollbars // since the right/bottom position is based on the edge of the scrollbar not the window const width = html.clientWidth; const height = html.clientHeight; return bounds(scroll.left, scroll.top, width, height); }, (visualViewport) => // iOS doesn't update the pageTop/pageLeft when element.scrollIntoView() is called, so we need to fallback to the // scroll position which will always be less than the page top/left values when page top/left are accurate/correct. bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height) ); }; const bind = (name: string, callback: EventHandler, _win?: Window): EventUnbinder => get(_win).map((visualViewport) => { const handler = (e: Event) => callback(fromRawEvent(e)); visualViewport.addEventListener(name, handler); return { unbind: () => visualViewport.removeEventListener(name, handler) }; }).getOrThunk(() => ({ unbind: Fun.noop })); export { bind, get, getBounds };
tinymce/tinymce
modules/sugar/src/main/ts/ephox/sugar/api/view/WindowVisualViewport.ts
TypeScript
mit
2,461
<?php defined('BASEPATH') OR exit('No direct script access allowed'); $this->load->view("/usefulScreens/header"); $this->load->view("/usefulScreens/menu"); $this->load->view("/usefulScreens/body"); $this->load->view("/usefulScreens/footer"); //if(!empty($create)) //$this->load->view("/telas/" . $create);
EmersonPereiraOliveira/ProjetoPW2
application/views/home.php
PHP
mit
313
//go:build go1.16 // +build go1.16 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. package armhanaonazure_test import ( "context" "log" "time" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/hanaonazure/armhanaonazure" ) // x-ms-original-file: specification/hanaonazure/resource-manager/Microsoft.HanaOnAzure/preview/2020-02-07-preview/examples/SapMonitors_List.json func ExampleSapMonitorsClient_List() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armhanaonazure.NewSapMonitorsClient("<subscription-id>", cred, nil) pager := client.List(nil) for { nextResult := pager.NextPage(ctx) if err := pager.Err(); err != nil { log.Fatalf("failed to advance page: %v", err) } if !nextResult { break } for _, v := range pager.PageResponse().Value { log.Printf("Pager result: %#v\n", v) } } } // x-ms-original-file: specification/hanaonazure/resource-manager/Microsoft.HanaOnAzure/preview/2020-02-07-preview/examples/SapMonitors_Get.json func ExampleSapMonitorsClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armhanaonazure.NewSapMonitorsClient("<subscription-id>", cred, nil) res, err := client.Get(ctx, "<resource-group-name>", "<sap-monitor-name>", nil) if err != nil { log.Fatal(err) } log.Printf("Response result: %#v\n", res.SapMonitorsClientGetResult) } // x-ms-original-file: specification/hanaonazure/resource-manager/Microsoft.HanaOnAzure/preview/2020-02-07-preview/examples/SapMonitors_Create.json func ExampleSapMonitorsClient_BeginCreate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armhanaonazure.NewSapMonitorsClient("<subscription-id>", cred, nil) poller, err := client.BeginCreate(ctx, "<resource-group-name>", "<sap-monitor-name>", armhanaonazure.SapMonitor{ Location: to.StringPtr("<location>"), Tags: map[string]*string{ "key": to.StringPtr("value"), }, Properties: &armhanaonazure.SapMonitorProperties{ EnableCustomerAnalytics: to.BoolPtr(true), LogAnalyticsWorkspaceArmID: to.StringPtr("<log-analytics-workspace-arm-id>"), LogAnalyticsWorkspaceID: to.StringPtr("<log-analytics-workspace-id>"), LogAnalyticsWorkspaceSharedKey: to.StringPtr("<log-analytics-workspace-shared-key>"), MonitorSubnet: to.StringPtr("<monitor-subnet>"), }, }, nil) if err != nil { log.Fatal(err) } res, err := poller.PollUntilDone(ctx, 30*time.Second) if err != nil { log.Fatal(err) } log.Printf("Response result: %#v\n", res.SapMonitorsClientCreateResult) } // x-ms-original-file: specification/hanaonazure/resource-manager/Microsoft.HanaOnAzure/preview/2020-02-07-preview/examples/SapMonitors_Delete.json func ExampleSapMonitorsClient_BeginDelete() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armhanaonazure.NewSapMonitorsClient("<subscription-id>", cred, nil) poller, err := client.BeginDelete(ctx, "<resource-group-name>", "<sap-monitor-name>", nil) if err != nil { log.Fatal(err) } _, err = poller.PollUntilDone(ctx, 30*time.Second) if err != nil { log.Fatal(err) } } // x-ms-original-file: specification/hanaonazure/resource-manager/Microsoft.HanaOnAzure/preview/2020-02-07-preview/examples/SapMonitors_PatchTags_Delete.json func ExampleSapMonitorsClient_Update() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armhanaonazure.NewSapMonitorsClient("<subscription-id>", cred, nil) res, err := client.Update(ctx, "<resource-group-name>", "<sap-monitor-name>", armhanaonazure.Tags{ Tags: map[string]*string{}, }, nil) if err != nil { log.Fatal(err) } log.Printf("Response result: %#v\n", res.SapMonitorsClientUpdateResult) }
Azure/azure-sdk-for-go
sdk/resourcemanager/hanaonazure/armhanaonazure/ze_generated_example_sapmonitors_client_test.go
GO
mit
4,610
<?php declare(strict_types = 1); namespace Innmind\Neo4j\ONM\CommandBus; use Innmind\Neo4j\ONM\Manager; use Innmind\CommandBus\CommandBus; final class Flush implements CommandBus { private CommandBus $handle; private Manager $manager; public function __construct(CommandBus $handle, Manager $manager) { $this->handle = $handle; $this->manager = $manager; } public function __invoke(object $command): void { ($this->handle)($command); $this->manager->flush(); } }
Innmind/neo4j-onm
src/CommandBus/Flush.php
PHP
mit
532
require 'active_support/security_utils' require 'vendor/box' require 'jeweler/client' require 'jeweler/connection' require 'jeweler/writeable' require 'jeweler/resource' require 'jeweler/singleton_resource' require 'jeweler/finders' require 'jeweler/collection' require 'jeweler/errors' require 'keyline/errors' require 'keyline/event' require 'keyline/resources/printery' require 'keyline/resources/document_callback' require 'keyline/resources/means_of_production' require 'keyline/resources/user' require 'keyline/resources/person' require 'keyline/resources/organization' require 'keyline/resources/address_announcement' require 'keyline/resources/assignment' require 'keyline/resources/business_unit' require 'keyline/resources/carrier' require 'keyline/resources/order' require 'keyline/resources/print_data_file' require 'keyline/resources/print_data_erratum' require 'keyline/resources/product' require 'keyline/resources/packaging' require 'keyline/resources/pick' require 'keyline/resources/address' require 'keyline/resources/origin_address' require 'keyline/resources/production_flow_modification' require 'keyline/resources/production_path' require 'keyline/resources/imposing' require 'keyline/resources/master_signature' require 'keyline/resources/signature' require 'keyline/resources/component' require 'keyline/resources/finishing' require 'keyline/resources/finishing_property' require 'keyline/resources/variant' require 'keyline/resources/circulation' require 'keyline/resources/substrate' require 'keyline/resources/desired_substrate_properties' require 'keyline/resources/material' require 'keyline/resources/material_quote' require 'keyline/resources/material_storage_area' require 'keyline/resources/material_preset' require 'keyline/resources/stock_finishing' require 'keyline/resources/stock_substrate' require 'keyline/resources/stock_color' require 'keyline/resources/stock_folding_pattern' require 'keyline/resources/stock_product' require 'keyline/resources/shipment' require 'keyline/resources/parcel' require 'keyline/resources/stock_task' require 'keyline/resources/raw_material_requirement' require 'keyline/resources/processing_requirement' require 'keyline/resources/task' require 'keyline/resources/material_demand' require 'keyline/resources/production/product' require 'keyline/resources/production/print_data_file' require 'keyline/resources/production/packaging' require 'keyline/resources/production/selected_production_path' require 'keyline/resources/production/component' require 'keyline/resources/production/finishing' require 'keyline/resources/production/finishing_property' require 'keyline/resources/production/variant' require 'keyline/resources/production/material_preset' require 'keyline/resources/production/stock_finishing' require 'keyline/resources/production/substrate' require 'keyline/resources/production/imposing' require 'keyline/resources/production/master_signature' require 'keyline/resources/production/signature' require 'keyline/resources/production/material_demand' require 'keyline/resources/production/task' require 'keyline/resources/production/task_execution' require 'keyline/resources/production/means_of_production' require 'keyline/resources/production/order' require 'keyline/resources/production/customer' require 'keyline/resources/production/sheet' require 'keyline/resources/invoice' require 'keyline/resources/customer_invoice' require 'keyline/resources/credit_note' require 'keyline/resources/reversal_invoice' require 'keyline/resources/recipient' require 'keyline/resources/contact' require 'keyline/resources/line_item' require 'keyline/resources/accounting_category' require 'keyline/resources/payment_term' module Keyline class Client include Jeweler::Client base_collections :parcels, :orders, :organizations, :people, :materials, :material_storage_areas, :stock_substrates, :stock_finishings, :stock_products, :stock_tasks, :stock_colors, :stock_folding_patterns, :business_units, :invoices, :customer_invoices, :credit_notes, :reversal_invoices, :users, :products def initialize(options = {}) super( host: options[:host], token: options[:token], base_uri: '/api/v2/', timeout: options[:timeout] || 5, open_timeout: options[:open_timeout] || 10 ) end def printery @printery ||= Keyline::Printery.new(self, self.perform_request(:get, '/configuration/printery')).tap do |printery| printery.extend(Jeweler::SingletonResource) end end def production_products Jeweler::Collection.new( self, -> { self.perform_request(:get, Keyline::Production::Product.path_for_index(nil)) }, Keyline::Production::Product ) end def production_tasks Jeweler::Collection.new( self, -> { self.perform_request(:get, Keyline::Production::Task.path_for_index(nil)) }, Keyline::Production::Task ) end def logistics_shipments Jeweler::Collection.new( self, -> { self.perform_request(:get, Keyline::Logistics::Shipment.path_for_index(nil)) }, Keyline::Logistics::Shipment ) end end end
crispymtn/keyline-gem
lib/keyline/client.rb
Ruby
mit
5,211
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsShallowCompare = require('react-addons-shallow-compare'); var _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _NodeCaret = require('./NodeCaret'); var _NodeCaret2 = _interopRequireDefault(_NodeCaret); var _styles = require('./styles'); var _styles2 = _interopRequireDefault(_styles); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var isDirectory = function isDirectory(type) { return type === 'directory'; }; var Node = function (_Component) { _inherits(Node, _Component); function Node() { _classCallCheck(this, Node); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Node).call(this)); _this.state = {}; return _this; } // shouldComponentUpdate(nextProps, nextState, nextContext) { // const shouldUpdate = shallowCompare(this, nextProps, nextState) // // // console.log('update', shouldUpdate, nextProps.node.path) // // return shouldUpdate // } _createClass(Node, [{ key: 'render', value: function render() { var _this2 = this; var _props = this.props; var node = _props.node; var metadata = _props.metadata; var depth = _props.depth; var type = node.type; var name = node.name; var path = node.path; var expanded = metadata.expanded; var selected = metadata.selected; var hover = this.state.hover; return _react2.default.createElement( 'div', { style: (0, _styles.getPaddedStyle)(depth, selected, hover), onMouseEnter: function onMouseEnter() { return _this2.setState({ hover: true }); }, onMouseLeave: function onMouseLeave() { return _this2.setState({ hover: false }); } }, isDirectory(type) && _react2.default.createElement(_NodeCaret2.default, { expanded: expanded }), _react2.default.createElement( 'div', { style: _styles2.default.nodeText }, name ) ); } }]); return Node; }(_react.Component); exports.default = Node;
goodman001/20170927express
frontend/node_modules/react-file-tree/lib/tree/NodeContent.js
JavaScript
mit
3,861
/// <reference path="../custom_typings/ambient.d.ts" /> import * as gulp from "gulp"; import * as runSequence from "run-sequence"; /* Build task for deployment */ gulp.task("build:prod", done => build(["typescript:prod", "sass", "html"], done)); /* Build task for dev environment */ gulp.task("build:dev", done => build(["typescript:dev:bundle", "typescript:dev", "sass", "html"], done)); function build(tasks: string[], done: any) { runSequence("clean", tasks, done) }
lukeautry/typescript-bundler
build/tasks/build.ts
TypeScript
mit
477
<?php /** * Created by PhpStorm. * User: tahaturk25 * Date: 29.8.2017 * Time: 21:55 */ namespace AppBundle\Repository; use AppBundle\Entity\Department; use Doctrine\ORM\EntityRepository; class DepartmentRepository extends EntityRepository { /** * @return Department[] */ public function findAllNotDeleted() { return $this->createQueryBuilder("d") ->andWhere("d.delCase = :deleted") ->setParameter("deleted",false) ->orderBy("d.name","ASC") ->getQuery() ->execute() ; } }
th-turk/NetGSM-Intership
src/AppBundle/Repository/DepartmentRepository.php
PHP
mit
585
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _2.Rotate_and_Sum { class Program { static void Main(string[] args) { var array = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); var rotation = int.Parse(Console.ReadLine()); int[] sum = new int[array.Length]; for (int i = 0; i < rotation; i++) { RotationArray(array, sum); } Console.WriteLine(string.Join(" ",sum)); } public static void RotationArray (int[] input, int[] sum) { var last = input.Length - 1; for (var i = 0; i < input.Length - 1; i += 1) { input[i] ^= input[last]; input[last] ^= input[i]; input[i] ^= input[last]; } for (int i = 0; i < input.Length; i++) { sum[i] += input[i]; } } } }
vasilchavdarov/SoftUniHomework
Projects/Array Exercises/2. Rotate and Sum/Program.cs
C#
mit
1,086
#include "benchmark/benchmark.h" #include "c4/log.hpp" #include "c4/allocator.hpp" #include "../list_types.hpp" namespace bm = benchmark; namespace c4 { template< class List > void BM_ListPushBack(bm::State& st) { List li; using T = typename List::value_type; T v{}; size_t count = 0; while(st.KeepRunning()) { for(int i = 0, e = st.range(0); i < e; ++i) { if(li.size() == li.max_size()) li.clear(); li.push_back(v); ++count; } li.clear(); } st.SetComplexityN(st.range(0)); st.SetItemsProcessed(count); st.SetBytesProcessed(count * sizeof(T)); } BENCHMARK_TEMPLATE(BM_ListPushBack, split_list__paged_rt< int C4_COMMA int32_t >) ->RangeMultiplier(2) ->Range(4, 1<<19) ->Complexity(); } // end namespace c4 BENCHMARK_MAIN()
biojppm/c4stl
bm/list/push_back/split_list__paged_rt__int__int32_t.cpp
C++
mit
849
class Dorsale::BillingMachine::PdfFileGenerator < Dorsale::Service attr_reader :document def initialize(document) @document = document # I have no idea why I need to do that, # if I don't do that, CarrierWare do not stores the file. # The reload() method don't work either. # The problem appears only on server, not in console. # I think CarrierWave do not work anymore after first save. @document = document.class.find(document.id) if document.persisted? end def call document.pdf_file = file document.save! if document.persisted? document end private def pdf_klass if document.is_a?(::Dorsale::BillingMachine::Invoice) return ::Dorsale::BillingMachine.invoice_pdf_model end if document.is_a?(::Dorsale::BillingMachine::Quotation) return ::Dorsale::BillingMachine.quotation_pdf_model end end def pdf_data @pdf_data ||= pdf_klass.new(document).tap(&:build).render_with_attachments end def file @file ||= StringIO.new(pdf_data) end class StringIO < ::StringIO def original_filename @original_filename ||= "#{SecureRandom.uuid}.pdf" end end end
agilidee/dorsale
app/services/dorsale/billing_machine/pdf_file_generator.rb
Ruby
mit
1,170
using System; using Xamarin.Forms; namespace NControl.Controls { /// <summary> /// Font material design label. /// </summary> public class FontMaterialDesignLabel: Label { /// <summary> /// The name of the font. /// </summary> public const string FontName = "Material Design Icons"; /// <summary> /// Initializes a new instance of the <see cref="NControl.Controls.FontMaterialDesignLabel"/> class. /// </summary> public FontMaterialDesignLabel () { FontFamily = FontName; FontSize = 18; HorizontalTextAlignment= TextAlignment.Center; VerticalTextAlignment = TextAlignment.Center; } public static readonly string MDAccessPoint = "\uf002"; public static readonly string MDAccessPointNetwork = "\uf003"; public static readonly string MDAccount = "\uf004"; public static readonly string MDAccountAlert = "\uf005"; public static readonly string MDAccountBox = "\uf006"; public static readonly string MDAccountBoxOutline = "\uf007"; public static readonly string MDAccountCardDetails = "\uf5d2"; public static readonly string MDAccountCheck = "\uf008"; public static readonly string MDAccountCircle = "\uf009"; public static readonly string MDAccountConvert = "\uf00a"; public static readonly string MDAccountEdit = "\uf6bb"; public static readonly string MDAccountKey = "\uf00b"; public static readonly string MDAccountLocation = "\uf00c"; public static readonly string MDAccountMinus = "\uf00d"; public static readonly string MDAccountMultiple = "\uf00e"; public static readonly string MDAccountMultipleMinus = "\uf5d3"; public static readonly string MDAccountMultipleOutline = "\uf00f"; public static readonly string MDAccountMultiplePlus = "\uf010"; public static readonly string MDAccountNetwork = "\uf011"; public static readonly string MDAccountOff = "\uf012"; public static readonly string MDAccountOutline = "\uf013"; public static readonly string MDAccountPlus = "\uf014"; public static readonly string MDAccountRemove = "\uf015"; public static readonly string MDAccountSearch = "\uf016"; public static readonly string MDAccountSettings = "\uf630"; public static readonly string MDAccountSettingsVariant = "\uf631"; public static readonly string MDAccountStar = "\uf017"; public static readonly string MDAccountStarVariant = "\uf018"; public static readonly string MDAccountSwitch = "\uf019"; public static readonly string MDAdjust = "\uf01a"; public static readonly string MDAirConditioner = "\uf01b"; public static readonly string MDAirballoon = "\uf01c"; public static readonly string MDAirplane = "\uf01d"; public static readonly string MDAirplaneLanding = "\uf5d4"; public static readonly string MDAirplaneOff = "\uf01e"; public static readonly string MDAirplaneTakeoff = "\uf5d5"; public static readonly string MDAirplay = "\uf01f"; public static readonly string MDAlarm = "\uf020"; public static readonly string MDAlarmCheck = "\uf021"; public static readonly string MDAlarmMultiple = "\uf022"; public static readonly string MDAlarmOff = "\uf023"; public static readonly string MDAlarmPlus = "\uf024"; public static readonly string MDAlarmSnooze = "\uf68d"; public static readonly string MDAlbum = "\uf025"; public static readonly string MDAlert = "\uf026"; public static readonly string MDAlertBox = "\uf027"; public static readonly string MDAlertCircle = "\uf028"; public static readonly string MDAlertCircleOutline = "\uf5d6"; public static readonly string MDAlertOctagon = "\uf029"; public static readonly string MDAlertOctagram = "\uf6bc"; public static readonly string MDAlertOutline = "\uf02a"; public static readonly string MDAllInclusive = "\uf6bd"; public static readonly string MDAlpha = "\uf02b"; public static readonly string MDAlphabetical = "\uf02c"; public static readonly string MDAltimeter = "\uf5d7"; public static readonly string MDAmazon = "\uf02d"; public static readonly string MDAmazonClouddrive = "\uf02e"; public static readonly string MDAmbulance = "\uf02f"; public static readonly string MDAmplifier = "\uf030"; public static readonly string MDAnchor = "\uf031"; public static readonly string MDAndroid = "\uf032"; public static readonly string MDAndroidDebugBridge = "\uf033"; public static readonly string MDAndroidStudio = "\uf034"; public static readonly string MDAngular = "\uf6b1"; public static readonly string MDAngularjs = "\uf6be"; public static readonly string MDAnimation = "\uf5d8"; public static readonly string MDApple = "\uf035"; public static readonly string MDAppleFinder = "\uf036"; public static readonly string MDAppleIos = "\uf037"; public static readonly string MDAppleKeyboardCaps = "\uf632"; public static readonly string MDAppleKeyboardCommand = "\uf633"; public static readonly string MDAppleKeyboardControl = "\uf634"; public static readonly string MDAppleKeyboardOption = "\uf635"; public static readonly string MDAppleKeyboardShift = "\uf636"; public static readonly string MDAppleMobileme = "\uf038"; public static readonly string MDAppleSafari = "\uf039"; public static readonly string MDApplication = "\uf614"; public static readonly string MDApps = "\uf03b"; public static readonly string MDArchive = "\uf03c"; public static readonly string MDArrangeBringForward = "\uf03d"; public static readonly string MDArrangeBringToFront = "\uf03e"; public static readonly string MDArrangeSendBackward = "\uf03f"; public static readonly string MDArrangeSendToBack = "\uf040"; public static readonly string MDArrowAll = "\uf041"; public static readonly string MDArrowBottomLeft = "\uf042"; public static readonly string MDArrowBottomRight = "\uf043"; public static readonly string MDArrowCompress = "\uf615"; public static readonly string MDArrowCompressAll = "\uf044"; public static readonly string MDArrowDown = "\uf045"; public static readonly string MDArrowDownBold = "\uf046"; public static readonly string MDArrowDownBoldCircle = "\uf047"; public static readonly string MDArrowDownBoldCircleOutline = "\uf048"; public static readonly string MDArrowDownBoldHexagonOutline = "\uf049"; public static readonly string MDArrowDownBox = "\uf6bf"; public static readonly string MDArrowDownDropCircle = "\uf04a"; public static readonly string MDArrowDownDropCircleOutline = "\uf04b"; public static readonly string MDArrowExpand = "\uf616"; public static readonly string MDArrowExpandAll = "\uf04c"; public static readonly string MDArrowLeft = "\uf04d"; public static readonly string MDArrowLeftBold = "\uf04e"; public static readonly string MDArrowLeftBoldCircle = "\uf04f"; public static readonly string MDArrowLeftBoldCircleOutline = "\uf050"; public static readonly string MDArrowLeftBoldHexagonOutline = "\uf051"; public static readonly string MDArrowLeftBox = "\uf6c0"; public static readonly string MDArrowLeftDropCircle = "\uf052"; public static readonly string MDArrowLeftDropCircleOutline = "\uf053"; public static readonly string MDArrowRight = "\uf054"; public static readonly string MDArrowRightBold = "\uf055"; public static readonly string MDArrowRightBoldCircle = "\uf056"; public static readonly string MDArrowRightBoldCircleOutline = "\uf057"; public static readonly string MDArrowRightBoldHexagonOutline = "\uf058"; public static readonly string MDArrowRightBox = "\uf6c1"; public static readonly string MDArrowRightDropCircle = "\uf059"; public static readonly string MDArrowRightDropCircleOutline = "\uf05a"; public static readonly string MDArrowTopLeft = "\uf05b"; public static readonly string MDArrowTopRight = "\uf05c"; public static readonly string MDArrowUp = "\uf05d"; public static readonly string MDArrowUpBold = "\uf05e"; public static readonly string MDArrowUpBoldCircle = "\uf05f"; public static readonly string MDArrowUpBoldCircleOutline = "\uf060"; public static readonly string MDArrowUpBoldHexagonOutline = "\uf061"; public static readonly string MDArrowUpBox = "\uf6c2"; public static readonly string MDArrowUpDropCircle = "\uf062"; public static readonly string MDArrowUpDropCircleOutline = "\uf063"; public static readonly string MDAssistant = "\uf064"; public static readonly string MDAsterisk = "\uf6c3"; public static readonly string MDAt = "\uf065"; public static readonly string MDAttachment = "\uf066"; public static readonly string MDAudiobook = "\uf067"; public static readonly string MDAutoFix = "\uf068"; public static readonly string MDAutoUpload = "\uf069"; public static readonly string MDAutorenew = "\uf06a"; public static readonly string MDAvTimer = "\uf06b"; public static readonly string MDBaby = "\uf06c"; public static readonly string MDBabyBuggy = "\uf68e"; public static readonly string MDBackburger = "\uf06d"; public static readonly string MDBackspace = "\uf06e"; public static readonly string MDBackupRestore = "\uf06f"; public static readonly string MDBandcamp = "\uf674"; public static readonly string MDBank = "\uf070"; public static readonly string MDBarcode = "\uf071"; public static readonly string MDBarcodeScan = "\uf072"; public static readonly string MDBarley = "\uf073"; public static readonly string MDBarrel = "\uf074"; public static readonly string MDBasecamp = "\uf075"; public static readonly string MDBasket = "\uf076"; public static readonly string MDBasketFill = "\uf077"; public static readonly string MDBasketUnfill = "\uf078"; public static readonly string MDBattery = "\uf079"; public static readonly string MDBattery10 = "\uf07a"; public static readonly string MDBattery20 = "\uf07b"; public static readonly string MDBattery30 = "\uf07c"; public static readonly string MDBattery40 = "\uf07d"; public static readonly string MDBattery50 = "\uf07e"; public static readonly string MDBattery60 = "\uf07f"; public static readonly string MDBattery70 = "\uf080"; public static readonly string MDBattery80 = "\uf081"; public static readonly string MDBattery90 = "\uf082"; public static readonly string MDBatteryAlert = "\uf083"; public static readonly string MDBatteryCharging = "\uf084"; public static readonly string MDBatteryCharging100 = "\uf085"; public static readonly string MDBatteryCharging20 = "\uf086"; public static readonly string MDBatteryCharging30 = "\uf087"; public static readonly string MDBatteryCharging40 = "\uf088"; public static readonly string MDBatteryCharging60 = "\uf089"; public static readonly string MDBatteryCharging80 = "\uf08a"; public static readonly string MDBatteryCharging90 = "\uf08b"; public static readonly string MDBatteryMinus = "\uf08c"; public static readonly string MDBatteryNegative = "\uf08d"; public static readonly string MDBatteryOutline = "\uf08e"; public static readonly string MDBatteryPlus = "\uf08f"; public static readonly string MDBatteryPositive = "\uf090"; public static readonly string MDBatteryUnknown = "\uf091"; public static readonly string MDBeach = "\uf092"; public static readonly string MDBeaker = "\uf68f"; public static readonly string MDBeats = "\uf097"; public static readonly string MDBeer = "\uf098"; public static readonly string MDBehance = "\uf099"; public static readonly string MDBell = "\uf09a"; public static readonly string MDBellOff = "\uf09b"; public static readonly string MDBellOutline = "\uf09c"; public static readonly string MDBellPlus = "\uf09d"; public static readonly string MDBellRing = "\uf09e"; public static readonly string MDBellRingOutline = "\uf09f"; public static readonly string MDBellSleep = "\uf0a0"; public static readonly string MDBeta = "\uf0a1"; public static readonly string MDBible = "\uf0a2"; public static readonly string MDBike = "\uf0a3"; public static readonly string MDBing = "\uf0a4"; public static readonly string MDBinoculars = "\uf0a5"; public static readonly string MDBio = "\uf0a6"; public static readonly string MDBiohazard = "\uf0a7"; public static readonly string MDBitbucket = "\uf0a8"; public static readonly string MDBlackMesa = "\uf0a9"; public static readonly string MDBlackberry = "\uf0aa"; public static readonly string MDBlender = "\uf0ab"; public static readonly string MDBlinds = "\uf0ac"; public static readonly string MDBlockHelper = "\uf0ad"; public static readonly string MDBlogger = "\uf0ae"; public static readonly string MDBluetooth = "\uf0af"; public static readonly string MDBluetoothAudio = "\uf0b0"; public static readonly string MDBluetoothConnect = "\uf0b1"; public static readonly string MDBluetoothOff = "\uf0b2"; public static readonly string MDBluetoothSettings = "\uf0b3"; public static readonly string MDBluetoothTransfer = "\uf0b4"; public static readonly string MDBlur = "\uf0b5"; public static readonly string MDBlurLinear = "\uf0b6"; public static readonly string MDBlurOff = "\uf0b7"; public static readonly string MDBlurRadial = "\uf0b8"; public static readonly string MDBomb = "\uf690"; public static readonly string MDBombOff = "\uf6c4"; public static readonly string MDBone = "\uf0b9"; public static readonly string MDBook = "\uf0ba"; public static readonly string MDBookMinus = "\uf5d9"; public static readonly string MDBookMultiple = "\uf0bb"; public static readonly string MDBookMultipleVariant = "\uf0bc"; public static readonly string MDBookOpen = "\uf0bd"; public static readonly string MDBookOpenPageVariant = "\uf5da"; public static readonly string MDBookOpenVariant = "\uf0be"; public static readonly string MDBookPlus = "\uf5db"; public static readonly string MDBookVariant = "\uf0bf"; public static readonly string MDBookmark = "\uf0c0"; public static readonly string MDBookmarkCheck = "\uf0c1"; public static readonly string MDBookmarkMusic = "\uf0c2"; public static readonly string MDBookmarkOutline = "\uf0c3"; public static readonly string MDBookmarkPlus = "\uf0c5"; public static readonly string MDBookmarkPlusOutline = "\uf0c4"; public static readonly string MDBookmarkRemove = "\uf0c6"; public static readonly string MDBoombox = "\uf5dc"; public static readonly string MDBootstrap = "\uf6c5"; public static readonly string MDBorderAll = "\uf0c7"; public static readonly string MDBorderBottom = "\uf0c8"; public static readonly string MDBorderColor = "\uf0c9"; public static readonly string MDBorderHorizontal = "\uf0ca"; public static readonly string MDBorderInside = "\uf0cb"; public static readonly string MDBorderLeft = "\uf0cc"; public static readonly string MDBorderNone = "\uf0cd"; public static readonly string MDBorderOutside = "\uf0ce"; public static readonly string MDBorderRight = "\uf0cf"; public static readonly string MDBorderStyle = "\uf0d0"; public static readonly string MDBorderTop = "\uf0d1"; public static readonly string MDBorderVertical = "\uf0d2"; public static readonly string MDBowTie = "\uf677"; public static readonly string MDBowl = "\uf617"; public static readonly string MDBowling = "\uf0d3"; public static readonly string MDBox = "\uf0d4"; public static readonly string MDBoxCutter = "\uf0d5"; public static readonly string MDBoxShadow = "\uf637"; public static readonly string MDBridge = "\uf618"; public static readonly string MDBriefcase = "\uf0d6"; public static readonly string MDBriefcaseCheck = "\uf0d7"; public static readonly string MDBriefcaseDownload = "\uf0d8"; public static readonly string MDBriefcaseUpload = "\uf0d9"; public static readonly string MDBrightness1 = "\uf0da"; public static readonly string MDBrightness2 = "\uf0db"; public static readonly string MDBrightness3 = "\uf0dc"; public static readonly string MDBrightness4 = "\uf0dd"; public static readonly string MDBrightness5 = "\uf0de"; public static readonly string MDBrightness6 = "\uf0df"; public static readonly string MDBrightness7 = "\uf0e0"; public static readonly string MDBrightnessAuto = "\uf0e1"; public static readonly string MDBroom = "\uf0e2"; public static readonly string MDBrush = "\uf0e3"; public static readonly string MDBuffer = "\uf619"; public static readonly string MDBug = "\uf0e4"; public static readonly string MDBulletinBoard = "\uf0e5"; public static readonly string MDBullhorn = "\uf0e6"; public static readonly string MDBullseye = "\uf5dd"; public static readonly string MDBurstMode = "\uf5de"; public static readonly string MDBus = "\uf0e7"; public static readonly string MDCached = "\uf0e8"; public static readonly string MDCake = "\uf0e9"; public static readonly string MDCakeLayered = "\uf0ea"; public static readonly string MDCakeVariant = "\uf0eb"; public static readonly string MDCalculator = "\uf0ec"; public static readonly string MDCalendar = "\uf0ed"; public static readonly string MDCalendarBlank = "\uf0ee"; public static readonly string MDCalendarCheck = "\uf0ef"; public static readonly string MDCalendarClock = "\uf0f0"; public static readonly string MDCalendarMultiple = "\uf0f1"; public static readonly string MDCalendarMultipleCheck = "\uf0f2"; public static readonly string MDCalendarPlus = "\uf0f3"; public static readonly string MDCalendarQuestion = "\uf691"; public static readonly string MDCalendarRange = "\uf678"; public static readonly string MDCalendarRemove = "\uf0f4"; public static readonly string MDCalendarText = "\uf0f5"; public static readonly string MDCalendarToday = "\uf0f6"; public static readonly string MDCallMade = "\uf0f7"; public static readonly string MDCallMerge = "\uf0f8"; public static readonly string MDCallMissed = "\uf0f9"; public static readonly string MDCallReceived = "\uf0fa"; public static readonly string MDCallSplit = "\uf0fb"; public static readonly string MDCamcorder = "\uf0fc"; public static readonly string MDCamcorderBox = "\uf0fd"; public static readonly string MDCamcorderBoxOff = "\uf0fe"; public static readonly string MDCamcorderOff = "\uf0ff"; public static readonly string MDCamera = "\uf100"; public static readonly string MDCameraBurst = "\uf692"; public static readonly string MDCameraEnhance = "\uf101"; public static readonly string MDCameraFront = "\uf102"; public static readonly string MDCameraFrontVariant = "\uf103"; public static readonly string MDCameraIris = "\uf104"; public static readonly string MDCameraOff = "\uf5df"; public static readonly string MDCameraPartyMode = "\uf105"; public static readonly string MDCameraRear = "\uf106"; public static readonly string MDCameraRearVariant = "\uf107"; public static readonly string MDCameraSwitch = "\uf108"; public static readonly string MDCameraTimer = "\uf109"; public static readonly string MDCandle = "\uf5e2"; public static readonly string MDCandycane = "\uf10a"; public static readonly string MDCar = "\uf10b"; public static readonly string MDCarBattery = "\uf10c"; public static readonly string MDCarConnected = "\uf10d"; public static readonly string MDCarWash = "\uf10e"; public static readonly string MDCards = "\uf638"; public static readonly string MDCardsOutline = "\uf639"; public static readonly string MDCardsPlayingOutline = "\uf63a"; public static readonly string MDCardsVariant = "\uf6c6"; public static readonly string MDCarrot = "\uf10f"; public static readonly string MDCart = "\uf110"; public static readonly string MDCartOff = "\uf66b"; public static readonly string MDCartOutline = "\uf111"; public static readonly string MDCartPlus = "\uf112"; public static readonly string MDCaseSensitiveAlt = "\uf113"; public static readonly string MDCash = "\uf114"; public static readonly string MDCash100 = "\uf115"; public static readonly string MDCashMultiple = "\uf116"; public static readonly string MDCashUsd = "\uf117"; public static readonly string MDCast = "\uf118"; public static readonly string MDCastConnected = "\uf119"; public static readonly string MDCastle = "\uf11a"; public static readonly string MDCat = "\uf11b"; public static readonly string MDCellphone = "\uf11c"; public static readonly string MDCellphoneAndroid = "\uf11d"; public static readonly string MDCellphoneBasic = "\uf11e"; public static readonly string MDCellphoneDock = "\uf11f"; public static readonly string MDCellphoneIphone = "\uf120"; public static readonly string MDCellphoneLink = "\uf121"; public static readonly string MDCellphoneLinkOff = "\uf122"; public static readonly string MDCellphoneSettings = "\uf123"; public static readonly string MDCertificate = "\uf124"; public static readonly string MDChairSchool = "\uf125"; public static readonly string MDChartArc = "\uf126"; public static readonly string MDChartAreaspline = "\uf127"; public static readonly string MDChartBar = "\uf128"; public static readonly string MDChartBubble = "\uf5e3"; public static readonly string MDChartGantt = "\uf66c"; public static readonly string MDChartHistogram = "\uf129"; public static readonly string MDChartLine = "\uf12a"; public static readonly string MDChartPie = "\uf12b"; public static readonly string MDChartScatterplotHexbin = "\uf66d"; public static readonly string MDChartTimeline = "\uf66e"; public static readonly string MDCheck = "\uf12c"; public static readonly string MDCheckAll = "\uf12d"; public static readonly string MDCheckCircle = "\uf5e0"; public static readonly string MDCheckCircleOutline = "\uf5e1"; public static readonly string MDCheckboxBlank = "\uf12e"; public static readonly string MDCheckboxBlankCircle = "\uf12f"; public static readonly string MDCheckboxBlankCircleOutline = "\uf130"; public static readonly string MDCheckboxBlankOutline = "\uf131"; public static readonly string MDCheckboxMarked = "\uf132"; public static readonly string MDCheckboxMarkedCircle = "\uf133"; public static readonly string MDCheckboxMarkedCircleOutline = "\uf134"; public static readonly string MDCheckboxMarkedOutline = "\uf135"; public static readonly string MDCheckboxMultipleBlank = "\uf136"; public static readonly string MDCheckboxMultipleBlankCircle = "\uf63b"; public static readonly string MDCheckboxMultipleBlankCircleOutline = "\uf63c"; public static readonly string MDCheckboxMultipleBlankOutline = "\uf137"; public static readonly string MDCheckboxMultipleMarked = "\uf138"; public static readonly string MDCheckboxMultipleMarkedCircle = "\uf63d"; public static readonly string MDCheckboxMultipleMarkedCircleOutline = "\uf63e"; public static readonly string MDCheckboxMultipleMarkedOutline = "\uf139"; public static readonly string MDCheckerboard = "\uf13a"; public static readonly string MDChemicalWeapon = "\uf13b"; public static readonly string MDChevronDoubleDown = "\uf13c"; public static readonly string MDChevronDoubleLeft = "\uf13d"; public static readonly string MDChevronDoubleRight = "\uf13e"; public static readonly string MDChevronDoubleUp = "\uf13f"; public static readonly string MDChevronDown = "\uf140"; public static readonly string MDChevronLeft = "\uf141"; public static readonly string MDChevronRight = "\uf142"; public static readonly string MDChevronUp = "\uf143"; public static readonly string MDChip = "\uf61a"; public static readonly string MDChurch = "\uf144"; public static readonly string MDCiscoWebex = "\uf145"; public static readonly string MDCity = "\uf146"; public static readonly string MDClipboard = "\uf147"; public static readonly string MDClipboardAccount = "\uf148"; public static readonly string MDClipboardAlert = "\uf149"; public static readonly string MDClipboardArrowDown = "\uf14a"; public static readonly string MDClipboardArrowLeft = "\uf14b"; public static readonly string MDClipboardCheck = "\uf14c"; public static readonly string MDClipboardFlow = "\uf6c7"; public static readonly string MDClipboardOutline = "\uf14d"; public static readonly string MDClipboardText = "\uf14e"; public static readonly string MDClippy = "\uf14f"; public static readonly string MDClock = "\uf150"; public static readonly string MDClockAlert = "\uf5ce"; public static readonly string MDClockEnd = "\uf151"; public static readonly string MDClockFast = "\uf152"; public static readonly string MDClockIn = "\uf153"; public static readonly string MDClockOut = "\uf154"; public static readonly string MDClockStart = "\uf155"; public static readonly string MDClose = "\uf156"; public static readonly string MDCloseBox = "\uf157"; public static readonly string MDCloseBoxOutline = "\uf158"; public static readonly string MDCloseCircle = "\uf159"; public static readonly string MDCloseCircleOutline = "\uf15a"; public static readonly string MDCloseNetwork = "\uf15b"; public static readonly string MDCloseOctagon = "\uf15c"; public static readonly string MDCloseOctagonOutline = "\uf15d"; public static readonly string MDCloseOutline = "\uf6c8"; public static readonly string MDClosedCaption = "\uf15e"; public static readonly string MDCloud = "\uf15f"; public static readonly string MDCloudCheck = "\uf160"; public static readonly string MDCloudCircle = "\uf161"; public static readonly string MDCloudDownload = "\uf162"; public static readonly string MDCloudOutline = "\uf163"; public static readonly string MDCloudOutlineOff = "\uf164"; public static readonly string MDCloudPrint = "\uf165"; public static readonly string MDCloudPrintOutline = "\uf166"; public static readonly string MDCloudSync = "\uf63f"; public static readonly string MDCloudUpload = "\uf167"; public static readonly string MDCodeArray = "\uf168"; public static readonly string MDCodeBraces = "\uf169"; public static readonly string MDCodeBrackets = "\uf16a"; public static readonly string MDCodeEqual = "\uf16b"; public static readonly string MDCodeGreaterThan = "\uf16c"; public static readonly string MDCodeGreaterThanOrEqual = "\uf16d"; public static readonly string MDCodeLessThan = "\uf16e"; public static readonly string MDCodeLessThanOrEqual = "\uf16f"; public static readonly string MDCodeNotEqual = "\uf170"; public static readonly string MDCodeNotEqualVariant = "\uf171"; public static readonly string MDCodeParentheses = "\uf172"; public static readonly string MDCodeString = "\uf173"; public static readonly string MDCodeTags = "\uf174"; public static readonly string MDCodeTagsCheck = "\uf693"; public static readonly string MDCodepen = "\uf175"; public static readonly string MDCoffee = "\uf176"; public static readonly string MDCoffeeOutline = "\uf6c9"; public static readonly string MDCoffeeToGo = "\uf177"; public static readonly string MDCoin = "\uf178"; public static readonly string MDCoins = "\uf694"; public static readonly string MDCollage = "\uf640"; public static readonly string MDColorHelper = "\uf179"; public static readonly string MDComment = "\uf17a"; public static readonly string MDCommentAccount = "\uf17b"; public static readonly string MDCommentAccountOutline = "\uf17c"; public static readonly string MDCommentAlert = "\uf17d"; public static readonly string MDCommentAlertOutline = "\uf17e"; public static readonly string MDCommentCheck = "\uf17f"; public static readonly string MDCommentCheckOutline = "\uf180"; public static readonly string MDCommentMultipleOutline = "\uf181"; public static readonly string MDCommentOutline = "\uf182"; public static readonly string MDCommentPlusOutline = "\uf183"; public static readonly string MDCommentProcessing = "\uf184"; public static readonly string MDCommentProcessingOutline = "\uf185"; public static readonly string MDCommentQuestionOutline = "\uf186"; public static readonly string MDCommentRemoveOutline = "\uf187"; public static readonly string MDCommentText = "\uf188"; public static readonly string MDCommentTextOutline = "\uf189"; public static readonly string MDCompare = "\uf18a"; public static readonly string MDCompass = "\uf18b"; public static readonly string MDCompassOutline = "\uf18c"; public static readonly string MDConsole = "\uf18d"; public static readonly string MDContactMail = "\uf18e"; public static readonly string MDContacts = "\uf6ca"; public static readonly string MDContentCopy = "\uf18f"; public static readonly string MDContentCut = "\uf190"; public static readonly string MDContentDuplicate = "\uf191"; public static readonly string MDContentPaste = "\uf192"; public static readonly string MDContentSave = "\uf193"; public static readonly string MDContentSaveAll = "\uf194"; public static readonly string MDContentSaveSettings = "\uf61b"; public static readonly string MDContrast = "\uf195"; public static readonly string MDContrastBox = "\uf196"; public static readonly string MDContrastCircle = "\uf197"; public static readonly string MDCookie = "\uf198"; public static readonly string MDCopyright = "\uf5e6"; public static readonly string MDCounter = "\uf199"; public static readonly string MDCow = "\uf19a"; public static readonly string MDCreation = "\uf1c9"; public static readonly string MDCreditCard = "\uf19b"; public static readonly string MDCreditCardMultiple = "\uf19c"; public static readonly string MDCreditCardOff = "\uf5e4"; public static readonly string MDCreditCardPlus = "\uf675"; public static readonly string MDCreditCardScan = "\uf19d"; public static readonly string MDCrop = "\uf19e"; public static readonly string MDCropFree = "\uf19f"; public static readonly string MDCropLandscape = "\uf1a0"; public static readonly string MDCropPortrait = "\uf1a1"; public static readonly string MDCropRotate = "\uf695"; public static readonly string MDCropSquare = "\uf1a2"; public static readonly string MDCrosshairs = "\uf1a3"; public static readonly string MDCrosshairsGps = "\uf1a4"; public static readonly string MDCrown = "\uf1a5"; public static readonly string MDCube = "\uf1a6"; public static readonly string MDCubeOutline = "\uf1a7"; public static readonly string MDCubeSend = "\uf1a8"; public static readonly string MDCubeUnfolded = "\uf1a9"; public static readonly string MDCup = "\uf1aa"; public static readonly string MDCupOff = "\uf5e5"; public static readonly string MDCupWater = "\uf1ab"; public static readonly string MDCurrencyBtc = "\uf1ac"; public static readonly string MDCurrencyEur = "\uf1ad"; public static readonly string MDCurrencyGbp = "\uf1ae"; public static readonly string MDCurrencyInr = "\uf1af"; public static readonly string MDCurrencyNgn = "\uf1b0"; public static readonly string MDCurrencyRub = "\uf1b1"; public static readonly string MDCurrencyTry = "\uf1b2"; public static readonly string MDCurrencyUsd = "\uf1b3"; public static readonly string MDCurrencyUsdOff = "\uf679"; public static readonly string MDCursorDefault = "\uf1b4"; public static readonly string MDCursorDefaultOutline = "\uf1b5"; public static readonly string MDCursorMove = "\uf1b6"; public static readonly string MDCursorPointer = "\uf1b7"; public static readonly string MDCursorText = "\uf5e7"; public static readonly string MDDatabase = "\uf1b8"; public static readonly string MDDatabaseMinus = "\uf1b9"; public static readonly string MDDatabasePlus = "\uf1ba"; public static readonly string MDDebugStepInto = "\uf1bb"; public static readonly string MDDebugStepOut = "\uf1bc"; public static readonly string MDDebugStepOver = "\uf1bd"; public static readonly string MDDecimalDecrease = "\uf1be"; public static readonly string MDDecimalIncrease = "\uf1bf"; public static readonly string MDDelete = "\uf1c0"; public static readonly string MDDeleteCircle = "\uf682"; public static readonly string MDDeleteEmpty = "\uf6cb"; public static readonly string MDDeleteForever = "\uf5e8"; public static readonly string MDDeleteSweep = "\uf5e9"; public static readonly string MDDeleteVariant = "\uf1c1"; public static readonly string MDDelta = "\uf1c2"; public static readonly string MDDeskphone = "\uf1c3"; public static readonly string MDDesktopMac = "\uf1c4"; public static readonly string MDDesktopTower = "\uf1c5"; public static readonly string MDDetails = "\uf1c6"; public static readonly string MDDeveloperBoard = "\uf696"; public static readonly string MDDeviantart = "\uf1c7"; public static readonly string MDDialpad = "\uf61c"; public static readonly string MDDiamond = "\uf1c8"; public static readonly string MDDice1 = "\uf1ca"; public static readonly string MDDice2 = "\uf1cb"; public static readonly string MDDice3 = "\uf1cc"; public static readonly string MDDice4 = "\uf1cd"; public static readonly string MDDice5 = "\uf1ce"; public static readonly string MDDice6 = "\uf1cf"; public static readonly string MDDiceD20 = "\uf5ea"; public static readonly string MDDiceD4 = "\uf5eb"; public static readonly string MDDiceD6 = "\uf5ec"; public static readonly string MDDiceD8 = "\uf5ed"; public static readonly string MDDictionary = "\uf61d"; public static readonly string MDDirections = "\uf1d0"; public static readonly string MDDirectionsFork = "\uf641"; public static readonly string MDDiscord = "\uf66f"; public static readonly string MDDisk = "\uf5ee"; public static readonly string MDDiskAlert = "\uf1d1"; public static readonly string MDDisqus = "\uf1d2"; public static readonly string MDDisqusOutline = "\uf1d3"; public static readonly string MDDivision = "\uf1d4"; public static readonly string MDDivisionBox = "\uf1d5"; public static readonly string MDDna = "\uf683"; public static readonly string MDDns = "\uf1d6"; public static readonly string MDDoNotDisturb = "\uf697"; public static readonly string MDDoNotDisturbOff = "\uf698"; public static readonly string MDDolby = "\uf6b2"; public static readonly string MDDomain = "\uf1d7"; public static readonly string MDDotsHorizontal = "\uf1d8"; public static readonly string MDDotsVertical = "\uf1d9"; public static readonly string MDDouban = "\uf699"; public static readonly string MDDownload = "\uf1da"; public static readonly string MDDrag = "\uf1db"; public static readonly string MDDragHorizontal = "\uf1dc"; public static readonly string MDDragVertical = "\uf1dd"; public static readonly string MDDrawing = "\uf1de"; public static readonly string MDDrawingBox = "\uf1df"; public static readonly string MDDribbble = "\uf1e0"; public static readonly string MDDribbbleBox = "\uf1e1"; public static readonly string MDDrone = "\uf1e2"; public static readonly string MDDropbox = "\uf1e3"; public static readonly string MDDrupal = "\uf1e4"; public static readonly string MDDuck = "\uf1e5"; public static readonly string MDDumbbell = "\uf1e6"; public static readonly string MDEarth = "\uf1e7"; public static readonly string MDEarthBox = "\uf6cc"; public static readonly string MDEarthBoxOff = "\uf6cd"; public static readonly string MDEarthOff = "\uf1e8"; public static readonly string MDEdge = "\uf1e9"; public static readonly string MDEject = "\uf1ea"; public static readonly string MDElevationDecline = "\uf1eb"; public static readonly string MDElevationRise = "\uf1ec"; public static readonly string MDElevator = "\uf1ed"; public static readonly string MDEmail = "\uf1ee"; public static readonly string MDEmailAlert = "\uf6ce"; public static readonly string MDEmailOpen = "\uf1ef"; public static readonly string MDEmailOpenOutline = "\uf5ef"; public static readonly string MDEmailOutline = "\uf1f0"; public static readonly string MDEmailSecure = "\uf1f1"; public static readonly string MDEmailVariant = "\uf5f0"; public static readonly string MDEmby = "\uf6b3"; public static readonly string MDEmoticon = "\uf1f2"; public static readonly string MDEmoticonCool = "\uf1f3"; public static readonly string MDEmoticonDead = "\uf69a"; public static readonly string MDEmoticonDevil = "\uf1f4"; public static readonly string MDEmoticonExcited = "\uf69b"; public static readonly string MDEmoticonHappy = "\uf1f5"; public static readonly string MDEmoticonNeutral = "\uf1f6"; public static readonly string MDEmoticonPoop = "\uf1f7"; public static readonly string MDEmoticonSad = "\uf1f8"; public static readonly string MDEmoticonTongue = "\uf1f9"; public static readonly string MDEngine = "\uf1fa"; public static readonly string MDEngineOutline = "\uf1fb"; public static readonly string MDEqual = "\uf1fc"; public static readonly string MDEqualBox = "\uf1fd"; public static readonly string MDEraser = "\uf1fe"; public static readonly string MDEraserVariant = "\uf642"; public static readonly string MDEscalator = "\uf1ff"; public static readonly string MDEthernet = "\uf200"; public static readonly string MDEthernetCable = "\uf201"; public static readonly string MDEthernetCableOff = "\uf202"; public static readonly string MDEtsy = "\uf203"; public static readonly string MDEvStation = "\uf5f1"; public static readonly string MDEvernote = "\uf204"; public static readonly string MDExclamation = "\uf205"; public static readonly string MDExitToApp = "\uf206"; public static readonly string MDExport = "\uf207"; public static readonly string MDEye = "\uf208"; public static readonly string MDEyeOff = "\uf209"; public static readonly string MDEyeOutline = "\uf6cf"; public static readonly string MDEyeOutlineOff = "\uf6d0"; public static readonly string MDEyedropper = "\uf20a"; public static readonly string MDEyedropperVariant = "\uf20b"; public static readonly string MDFace = "\uf643"; public static readonly string MDFaceProfile = "\uf644"; public static readonly string MDFacebook = "\uf20c"; public static readonly string MDFacebookBox = "\uf20d"; public static readonly string MDFacebookMessenger = "\uf20e"; public static readonly string MDFactory = "\uf20f"; public static readonly string MDFan = "\uf210"; public static readonly string MDFastForward = "\uf211"; public static readonly string MDFastForwardOutline = "\uf6d1"; public static readonly string MDFax = "\uf212"; public static readonly string MDFeather = "\uf6d2"; public static readonly string MDFerry = "\uf213"; public static readonly string MDFile = "\uf214"; public static readonly string MDFileChart = "\uf215"; public static readonly string MDFileCheck = "\uf216"; public static readonly string MDFileCloud = "\uf217"; public static readonly string MDFileDelimited = "\uf218"; public static readonly string MDFileDocument = "\uf219"; public static readonly string MDFileDocumentBox = "\uf21a"; public static readonly string MDFileExcel = "\uf21b"; public static readonly string MDFileExcelBox = "\uf21c"; public static readonly string MDFileExport = "\uf21d"; public static readonly string MDFileFind = "\uf21e"; public static readonly string MDFileHidden = "\uf613"; public static readonly string MDFileImage = "\uf21f"; public static readonly string MDFileImport = "\uf220"; public static readonly string MDFileLock = "\uf221"; public static readonly string MDFileMultiple = "\uf222"; public static readonly string MDFileMusic = "\uf223"; public static readonly string MDFileOutline = "\uf224"; public static readonly string MDFilePdf = "\uf225"; public static readonly string MDFilePdfBox = "\uf226"; public static readonly string MDFilePowerpoint = "\uf227"; public static readonly string MDFilePowerpointBox = "\uf228"; public static readonly string MDFilePresentationBox = "\uf229"; public static readonly string MDFileRestore = "\uf670"; public static readonly string MDFileSend = "\uf22a"; public static readonly string MDFileTree = "\uf645"; public static readonly string MDFileVideo = "\uf22b"; public static readonly string MDFileWord = "\uf22c"; public static readonly string MDFileWordBox = "\uf22d"; public static readonly string MDFileXml = "\uf22e"; public static readonly string MDFilm = "\uf22f"; public static readonly string MDFilmstrip = "\uf230"; public static readonly string MDFilmstripOff = "\uf231"; public static readonly string MDFilter = "\uf232"; public static readonly string MDFilterOutline = "\uf233"; public static readonly string MDFilterRemove = "\uf234"; public static readonly string MDFilterRemoveOutline = "\uf235"; public static readonly string MDFilterVariant = "\uf236"; public static readonly string MDFindReplace = "\uf6d3"; public static readonly string MDFingerprint = "\uf237"; public static readonly string MDFire = "\uf238"; public static readonly string MDFirefox = "\uf239"; public static readonly string MDFish = "\uf23a"; public static readonly string MDFlag = "\uf23b"; public static readonly string MDFlagCheckered = "\uf23c"; public static readonly string MDFlagOutline = "\uf23d"; public static readonly string MDFlagOutlineVariant = "\uf23e"; public static readonly string MDFlagTriangle = "\uf23f"; public static readonly string MDFlagVariant = "\uf240"; public static readonly string MDFlash = "\uf241"; public static readonly string MDFlashAuto = "\uf242"; public static readonly string MDFlashOff = "\uf243"; public static readonly string MDFlashOutline = "\uf6d4"; public static readonly string MDFlashRedEye = "\uf67a"; public static readonly string MDFlashlight = "\uf244"; public static readonly string MDFlashlightOff = "\uf245"; public static readonly string MDFlask = "\uf093"; public static readonly string MDFlaskEmpty = "\uf094"; public static readonly string MDFlaskEmptyOutline = "\uf095"; public static readonly string MDFlaskOutline = "\uf096"; public static readonly string MDFlattr = "\uf246"; public static readonly string MDFlipToBack = "\uf247"; public static readonly string MDFlipToFront = "\uf248"; public static readonly string MDFloppy = "\uf249"; public static readonly string MDFlower = "\uf24a"; public static readonly string MDFolder = "\uf24b"; public static readonly string MDFolderAccount = "\uf24c"; public static readonly string MDFolderDownload = "\uf24d"; public static readonly string MDFolderGoogleDrive = "\uf24e"; public static readonly string MDFolderImage = "\uf24f"; public static readonly string MDFolderLock = "\uf250"; public static readonly string MDFolderLockOpen = "\uf251"; public static readonly string MDFolderMove = "\uf252"; public static readonly string MDFolderMultiple = "\uf253"; public static readonly string MDFolderMultipleImage = "\uf254"; public static readonly string MDFolderMultipleOutline = "\uf255"; public static readonly string MDFolderOutline = "\uf256"; public static readonly string MDFolderPlus = "\uf257"; public static readonly string MDFolderRemove = "\uf258"; public static readonly string MDFolderStar = "\uf69c"; public static readonly string MDFolderUpload = "\uf259"; public static readonly string MDFontAwesome = "\uf03a"; public static readonly string MDFood = "\uf25a"; public static readonly string MDFoodApple = "\uf25b"; public static readonly string MDFoodForkDrink = "\uf5f2"; public static readonly string MDFoodOff = "\uf5f3"; public static readonly string MDFoodVariant = "\uf25c"; public static readonly string MDFootball = "\uf25d"; public static readonly string MDFootballAustralian = "\uf25e"; public static readonly string MDFootballHelmet = "\uf25f"; public static readonly string MDFormatAlignCenter = "\uf260"; public static readonly string MDFormatAlignJustify = "\uf261"; public static readonly string MDFormatAlignLeft = "\uf262"; public static readonly string MDFormatAlignRight = "\uf263"; public static readonly string MDFormatAnnotationPlus = "\uf646"; public static readonly string MDFormatBold = "\uf264"; public static readonly string MDFormatClear = "\uf265"; public static readonly string MDFormatColorFill = "\uf266"; public static readonly string MDFormatColorText = "\uf69d"; public static readonly string MDFormatFloatCenter = "\uf267"; public static readonly string MDFormatFloatLeft = "\uf268"; public static readonly string MDFormatFloatNone = "\uf269"; public static readonly string MDFormatFloatRight = "\uf26a"; public static readonly string MDFormatFont = "\uf6d5"; public static readonly string MDFormatHeader1 = "\uf26b"; public static readonly string MDFormatHeader2 = "\uf26c"; public static readonly string MDFormatHeader3 = "\uf26d"; public static readonly string MDFormatHeader4 = "\uf26e"; public static readonly string MDFormatHeader5 = "\uf26f"; public static readonly string MDFormatHeader6 = "\uf270"; public static readonly string MDFormatHeaderDecrease = "\uf271"; public static readonly string MDFormatHeaderEqual = "\uf272"; public static readonly string MDFormatHeaderIncrease = "\uf273"; public static readonly string MDFormatHeaderPound = "\uf274"; public static readonly string MDFormatHorizontalAlignCenter = "\uf61e"; public static readonly string MDFormatHorizontalAlignLeft = "\uf61f"; public static readonly string MDFormatHorizontalAlignRight = "\uf620"; public static readonly string MDFormatIndentDecrease = "\uf275"; public static readonly string MDFormatIndentIncrease = "\uf276"; public static readonly string MDFormatItalic = "\uf277"; public static readonly string MDFormatLineSpacing = "\uf278"; public static readonly string MDFormatLineStyle = "\uf5c8"; public static readonly string MDFormatLineWeight = "\uf5c9"; public static readonly string MDFormatListBulleted = "\uf279"; public static readonly string MDFormatListBulletedType = "\uf27a"; public static readonly string MDFormatListNumbers = "\uf27b"; public static readonly string MDFormatPageBreak = "\uf6d6"; public static readonly string MDFormatPaint = "\uf27c"; public static readonly string MDFormatParagraph = "\uf27d"; public static readonly string MDFormatPilcrow = "\uf6d7"; public static readonly string MDFormatQuote = "\uf27e"; public static readonly string MDFormatRotate90 = "\uf6a9"; public static readonly string MDFormatSection = "\uf69e"; public static readonly string MDFormatSize = "\uf27f"; public static readonly string MDFormatStrikethrough = "\uf280"; public static readonly string MDFormatStrikethroughVariant = "\uf281"; public static readonly string MDFormatSubscript = "\uf282"; public static readonly string MDFormatSuperscript = "\uf283"; public static readonly string MDFormatText = "\uf284"; public static readonly string MDFormatTextdirectionLToR = "\uf285"; public static readonly string MDFormatTextdirectionRToL = "\uf286"; public static readonly string MDFormatTitle = "\uf5f4"; public static readonly string MDFormatUnderline = "\uf287"; public static readonly string MDFormatVerticalAlignBottom = "\uf621"; public static readonly string MDFormatVerticalAlignCenter = "\uf622"; public static readonly string MDFormatVerticalAlignTop = "\uf623"; public static readonly string MDFormatWrapInline = "\uf288"; public static readonly string MDFormatWrapSquare = "\uf289"; public static readonly string MDFormatWrapTight = "\uf28a"; public static readonly string MDFormatWrapTopBottom = "\uf28b"; public static readonly string MDForum = "\uf28c"; public static readonly string MDForward = "\uf28d"; public static readonly string MDFoursquare = "\uf28e"; public static readonly string MDFridge = "\uf28f"; public static readonly string MDFridgeFilled = "\uf290"; public static readonly string MDFridgeFilledBottom = "\uf291"; public static readonly string MDFridgeFilledTop = "\uf292"; public static readonly string MDFullscreen = "\uf293"; public static readonly string MDFullscreenExit = "\uf294"; public static readonly string MDFunction = "\uf295"; public static readonly string MDGamepad = "\uf296"; public static readonly string MDGamepadVariant = "\uf297"; public static readonly string MDGarage = "\uf6d8"; public static readonly string MDGarageOpen = "\uf6d9"; public static readonly string MDGasCylinder = "\uf647"; public static readonly string MDGasStation = "\uf298"; public static readonly string MDGate = "\uf299"; public static readonly string MDGauge = "\uf29a"; public static readonly string MDGavel = "\uf29b"; public static readonly string MDGenderFemale = "\uf29c"; public static readonly string MDGenderMale = "\uf29d"; public static readonly string MDGenderMaleFemale = "\uf29e"; public static readonly string MDGenderTransgender = "\uf29f"; public static readonly string MDGhost = "\uf2a0"; public static readonly string MDGift = "\uf2a1"; public static readonly string MDGit = "\uf2a2"; public static readonly string MDGithubBox = "\uf2a3"; public static readonly string MDGithubCircle = "\uf2a4"; public static readonly string MDGithubFace = "\uf6da"; public static readonly string MDGlassFlute = "\uf2a5"; public static readonly string MDGlassMug = "\uf2a6"; public static readonly string MDGlassStange = "\uf2a7"; public static readonly string MDGlassTulip = "\uf2a8"; public static readonly string MDGlassdoor = "\uf2a9"; public static readonly string MDGlasses = "\uf2aa"; public static readonly string MDGmail = "\uf2ab"; public static readonly string MDGnome = "\uf2ac"; public static readonly string MDGondola = "\uf685"; public static readonly string MDGoogle = "\uf2ad"; public static readonly string MDGoogleCardboard = "\uf2ae"; public static readonly string MDGoogleChrome = "\uf2af"; public static readonly string MDGoogleCircles = "\uf2b0"; public static readonly string MDGoogleCirclesCommunities = "\uf2b1"; public static readonly string MDGoogleCirclesExtended = "\uf2b2"; public static readonly string MDGoogleCirclesGroup = "\uf2b3"; public static readonly string MDGoogleController = "\uf2b4"; public static readonly string MDGoogleControllerOff = "\uf2b5"; public static readonly string MDGoogleDrive = "\uf2b6"; public static readonly string MDGoogleEarth = "\uf2b7"; public static readonly string MDGoogleGlass = "\uf2b8"; public static readonly string MDGoogleKeep = "\uf6db"; public static readonly string MDGoogleMaps = "\uf5f5"; public static readonly string MDGoogleNearby = "\uf2b9"; public static readonly string MDGooglePages = "\uf2ba"; public static readonly string MDGooglePhotos = "\uf6dc"; public static readonly string MDGooglePhysicalWeb = "\uf2bb"; public static readonly string MDGooglePlay = "\uf2bc"; public static readonly string MDGooglePlus = "\uf2bd"; public static readonly string MDGooglePlusBox = "\uf2be"; public static readonly string MDGoogleTranslate = "\uf2bf"; public static readonly string MDGoogleWallet = "\uf2c0"; public static readonly string MDGradient = "\uf69f"; public static readonly string MDGreasePencil = "\uf648"; public static readonly string MDGrid = "\uf2c1"; public static readonly string MDGridOff = "\uf2c2"; public static readonly string MDGroup = "\uf2c3"; public static readonly string MDGuitarElectric = "\uf2c4"; public static readonly string MDGuitarPick = "\uf2c5"; public static readonly string MDGuitarPickOutline = "\uf2c6"; public static readonly string MDHackernews = "\uf624"; public static readonly string MDHamburger = "\uf684"; public static readonly string MDHandPointingRight = "\uf2c7"; public static readonly string MDHanger = "\uf2c8"; public static readonly string MDHangouts = "\uf2c9"; public static readonly string MDHarddisk = "\uf2ca"; public static readonly string MDHeadphones = "\uf2cb"; public static readonly string MDHeadphonesBox = "\uf2cc"; public static readonly string MDHeadphonesSettings = "\uf2cd"; public static readonly string MDHeadset = "\uf2ce"; public static readonly string MDHeadsetDock = "\uf2cf"; public static readonly string MDHeadsetOff = "\uf2d0"; public static readonly string MDHeart = "\uf2d1"; public static readonly string MDHeartBox = "\uf2d2"; public static readonly string MDHeartBoxOutline = "\uf2d3"; public static readonly string MDHeartBroken = "\uf2d4"; public static readonly string MDHeartHalfOutline = "\uf6dd"; public static readonly string MDHeartHalfPart = "\uf6de"; public static readonly string MDHeartHalfPartOutline = "\uf6df"; public static readonly string MDHeartOutline = "\uf2d5"; public static readonly string MDHeartPulse = "\uf5f6"; public static readonly string MDHelp = "\uf2d6"; public static readonly string MDHelpCircle = "\uf2d7"; public static readonly string MDHelpCircleOutline = "\uf625"; public static readonly string MDHexagon = "\uf2d8"; public static readonly string MDHexagonMultiple = "\uf6e0"; public static readonly string MDHexagonOutline = "\uf2d9"; public static readonly string MDHighway = "\uf5f7"; public static readonly string MDHistory = "\uf2da"; public static readonly string MDHololens = "\uf2db"; public static readonly string MDHome = "\uf2dc"; public static readonly string MDHomeMapMarker = "\uf5f8"; public static readonly string MDHomeModern = "\uf2dd"; public static readonly string MDHomeOutline = "\uf6a0"; public static readonly string MDHomeVariant = "\uf2de"; public static readonly string MDHook = "\uf6e1"; public static readonly string MDHookOff = "\uf6e2"; public static readonly string MDHops = "\uf2df"; public static readonly string MDHospital = "\uf2e0"; public static readonly string MDHospitalBuilding = "\uf2e1"; public static readonly string MDHospitalMarker = "\uf2e2"; public static readonly string MDHotel = "\uf2e3"; public static readonly string MDHouzz = "\uf2e4"; public static readonly string MDHouzzBox = "\uf2e5"; public static readonly string MDHuman = "\uf2e6"; public static readonly string MDHumanChild = "\uf2e7"; public static readonly string MDHumanFemale = "\uf649"; public static readonly string MDHumanGreeting = "\uf64a"; public static readonly string MDHumanHandsdown = "\uf64b"; public static readonly string MDHumanHandsup = "\uf64c"; public static readonly string MDHumanMale = "\uf64d"; public static readonly string MDHumanMaleFemale = "\uf2e8"; public static readonly string MDHumanPregnant = "\uf5cf"; public static readonly string MDImage = "\uf2e9"; public static readonly string MDImageAlbum = "\uf2ea"; public static readonly string MDImageArea = "\uf2eb"; public static readonly string MDImageAreaClose = "\uf2ec"; public static readonly string MDImageBroken = "\uf2ed"; public static readonly string MDImageBrokenVariant = "\uf2ee"; public static readonly string MDImageFilter = "\uf2ef"; public static readonly string MDImageFilterBlackWhite = "\uf2f0"; public static readonly string MDImageFilterCenterFocus = "\uf2f1"; public static readonly string MDImageFilterCenterFocusWeak = "\uf2f2"; public static readonly string MDImageFilterDrama = "\uf2f3"; public static readonly string MDImageFilterFrames = "\uf2f4"; public static readonly string MDImageFilterHdr = "\uf2f5"; public static readonly string MDImageFilterNone = "\uf2f6"; public static readonly string MDImageFilterTiltShift = "\uf2f7"; public static readonly string MDImageFilterVintage = "\uf2f8"; public static readonly string MDImageMultiple = "\uf2f9"; public static readonly string MDImport = "\uf2fa"; public static readonly string MDInbox = "\uf686"; public static readonly string MDInboxArrowDown = "\uf2fb"; public static readonly string MDInboxArrowUp = "\uf3d1"; public static readonly string MDIncognito = "\uf5f9"; public static readonly string MDInfinity = "\uf6e3"; public static readonly string MDInformation = "\uf2fc"; public static readonly string MDInformationOutline = "\uf2fd"; public static readonly string MDInformationVariant = "\uf64e"; public static readonly string MDInstagram = "\uf2fe"; public static readonly string MDInstapaper = "\uf2ff"; public static readonly string MDInternetExplorer = "\uf300"; public static readonly string MDInvertColors = "\uf301"; public static readonly string MDItunes = "\uf676"; public static readonly string MDJeepney = "\uf302"; public static readonly string MDJira = "\uf303"; public static readonly string MDJsfiddle = "\uf304"; public static readonly string MDJson = "\uf626"; public static readonly string MDKeg = "\uf305"; public static readonly string MDKettle = "\uf5fa"; public static readonly string MDKey = "\uf306"; public static readonly string MDKeyChange = "\uf307"; public static readonly string MDKeyMinus = "\uf308"; public static readonly string MDKeyPlus = "\uf309"; public static readonly string MDKeyRemove = "\uf30a"; public static readonly string MDKeyVariant = "\uf30b"; public static readonly string MDKeyboard = "\uf30c"; public static readonly string MDKeyboardBackspace = "\uf30d"; public static readonly string MDKeyboardCaps = "\uf30e"; public static readonly string MDKeyboardClose = "\uf30f"; public static readonly string MDKeyboardOff = "\uf310"; public static readonly string MDKeyboardReturn = "\uf311"; public static readonly string MDKeyboardTab = "\uf312"; public static readonly string MDKeyboardVariant = "\uf313"; public static readonly string MDKodi = "\uf314"; public static readonly string MDLabel = "\uf315"; public static readonly string MDLabelOutline = "\uf316"; public static readonly string MDLambda = "\uf627"; public static readonly string MDLamp = "\uf6b4"; public static readonly string MDLan = "\uf317"; public static readonly string MDLanConnect = "\uf318"; public static readonly string MDLanDisconnect = "\uf319"; public static readonly string MDLanPending = "\uf31a"; public static readonly string MDLanguageC = "\uf671"; public static readonly string MDLanguageCpp = "\uf672"; public static readonly string MDLanguageCsharp = "\uf31b"; public static readonly string MDLanguageCss3 = "\uf31c"; public static readonly string MDLanguageHtml5 = "\uf31d"; public static readonly string MDLanguageJavascript = "\uf31e"; public static readonly string MDLanguagePhp = "\uf31f"; public static readonly string MDLanguagePython = "\uf320"; public static readonly string MDLanguagePythonText = "\uf321"; public static readonly string MDLanguageSwift = "\uf6e4"; public static readonly string MDLanguageTypescript = "\uf6e5"; public static readonly string MDLaptop = "\uf322"; public static readonly string MDLaptopChromebook = "\uf323"; public static readonly string MDLaptopMac = "\uf324"; public static readonly string MDLaptopOff = "\uf6e6"; public static readonly string MDLaptopWindows = "\uf325"; public static readonly string MDLastfm = "\uf326"; public static readonly string MDLaunch = "\uf327"; public static readonly string MDLayers = "\uf328"; public static readonly string MDLayersOff = "\uf329"; public static readonly string MDLeadPencil = "\uf64f"; public static readonly string MDLeaf = "\uf32a"; public static readonly string MDLedOff = "\uf32b"; public static readonly string MDLedOn = "\uf32c"; public static readonly string MDLedOutline = "\uf32d"; public static readonly string MDLedVariantOff = "\uf32e"; public static readonly string MDLedVariantOn = "\uf32f"; public static readonly string MDLedVariantOutline = "\uf330"; public static readonly string MDLibrary = "\uf331"; public static readonly string MDLibraryBooks = "\uf332"; public static readonly string MDLibraryMusic = "\uf333"; public static readonly string MDLibraryPlus = "\uf334"; public static readonly string MDLightbulb = "\uf335"; public static readonly string MDLightbulbOn = "\uf6e7"; public static readonly string MDLightbulbOnOutline = "\uf6e8"; public static readonly string MDLightbulbOutline = "\uf336"; public static readonly string MDLink = "\uf337"; public static readonly string MDLinkOff = "\uf338"; public static readonly string MDLinkVariant = "\uf339"; public static readonly string MDLinkVariantOff = "\uf33a"; public static readonly string MDLinkedin = "\uf33b"; public static readonly string MDLinkedinBox = "\uf33c"; public static readonly string MDLinux = "\uf33d"; public static readonly string MDLock = "\uf33e"; public static readonly string MDLockOpen = "\uf33f"; public static readonly string MDLockOpenOutline = "\uf340"; public static readonly string MDLockOutline = "\uf341"; public static readonly string MDLockPattern = "\uf6e9"; public static readonly string MDLockPlus = "\uf5fb"; public static readonly string MDLogin = "\uf342"; public static readonly string MDLoginVariant = "\uf5fc"; public static readonly string MDLogout = "\uf343"; public static readonly string MDLogoutVariant = "\uf5fd"; public static readonly string MDLooks = "\uf344"; public static readonly string MDLoop = "\uf6ea"; public static readonly string MDLoupe = "\uf345"; public static readonly string MDLumx = "\uf346"; public static readonly string MDMagnet = "\uf347"; public static readonly string MDMagnetOn = "\uf348"; public static readonly string MDMagnify = "\uf349"; public static readonly string MDMagnifyMinus = "\uf34a"; public static readonly string MDMagnifyMinusOutline = "\uf6eb"; public static readonly string MDMagnifyPlus = "\uf34b"; public static readonly string MDMagnifyPlusOutline = "\uf6ec"; public static readonly string MDMailRu = "\uf34c"; public static readonly string MDMailbox = "\uf6ed"; public static readonly string MDMap = "\uf34d"; public static readonly string MDMapMarker = "\uf34e"; public static readonly string MDMapMarkerCircle = "\uf34f"; public static readonly string MDMapMarkerMinus = "\uf650"; public static readonly string MDMapMarkerMultiple = "\uf350"; public static readonly string MDMapMarkerOff = "\uf351"; public static readonly string MDMapMarkerPlus = "\uf651"; public static readonly string MDMapMarkerRadius = "\uf352"; public static readonly string MDMargin = "\uf353"; public static readonly string MDMarkdown = "\uf354"; public static readonly string MDMarker = "\uf652"; public static readonly string MDMarkerCheck = "\uf355"; public static readonly string MDMartini = "\uf356"; public static readonly string MDMaterialUi = "\uf357"; public static readonly string MDMathCompass = "\uf358"; public static readonly string MDMatrix = "\uf628"; public static readonly string MDMaxcdn = "\uf359"; public static readonly string MDMedicalBag = "\uf6ee"; public static readonly string MDMedium = "\uf35a"; public static readonly string MDMemory = "\uf35b"; public static readonly string MDMenu = "\uf35c"; public static readonly string MDMenuDown = "\uf35d"; public static readonly string MDMenuDownOutline = "\uf6b5"; public static readonly string MDMenuLeft = "\uf35e"; public static readonly string MDMenuRight = "\uf35f"; public static readonly string MDMenuUp = "\uf360"; public static readonly string MDMenuUpOutline = "\uf6b6"; public static readonly string MDMessage = "\uf361"; public static readonly string MDMessageAlert = "\uf362"; public static readonly string MDMessageBulleted = "\uf6a1"; public static readonly string MDMessageBulletedOff = "\uf6a2"; public static readonly string MDMessageDraw = "\uf363"; public static readonly string MDMessageImage = "\uf364"; public static readonly string MDMessageOutline = "\uf365"; public static readonly string MDMessagePlus = "\uf653"; public static readonly string MDMessageProcessing = "\uf366"; public static readonly string MDMessageReply = "\uf367"; public static readonly string MDMessageReplyText = "\uf368"; public static readonly string MDMessageSettings = "\uf6ef"; public static readonly string MDMessageSettingsVariant = "\uf6f0"; public static readonly string MDMessageText = "\uf369"; public static readonly string MDMessageTextOutline = "\uf36a"; public static readonly string MDMessageVideo = "\uf36b"; public static readonly string MDMeteor = "\uf629"; public static readonly string MDMicrophone = "\uf36c"; public static readonly string MDMicrophoneOff = "\uf36d"; public static readonly string MDMicrophoneOutline = "\uf36e"; public static readonly string MDMicrophoneSettings = "\uf36f"; public static readonly string MDMicrophoneVariant = "\uf370"; public static readonly string MDMicrophoneVariantOff = "\uf371"; public static readonly string MDMicroscope = "\uf654"; public static readonly string MDMicrosoft = "\uf372"; public static readonly string MDMinecraft = "\uf373"; public static readonly string MDMinus = "\uf374"; public static readonly string MDMinusBox = "\uf375"; public static readonly string MDMinusBoxOutline = "\uf6f1"; public static readonly string MDMinusCircle = "\uf376"; public static readonly string MDMinusCircleOutline = "\uf377"; public static readonly string MDMinusNetwork = "\uf378"; public static readonly string MDMixcloud = "\uf62a"; public static readonly string MDMonitor = "\uf379"; public static readonly string MDMonitorMultiple = "\uf37a"; public static readonly string MDMore = "\uf37b"; public static readonly string MDMotorbike = "\uf37c"; public static readonly string MDMouse = "\uf37d"; public static readonly string MDMouseOff = "\uf37e"; public static readonly string MDMouseVariant = "\uf37f"; public static readonly string MDMouseVariantOff = "\uf380"; public static readonly string MDMoveResize = "\uf655"; public static readonly string MDMoveResizeVariant = "\uf656"; public static readonly string MDMovie = "\uf381"; public static readonly string MDMultiplication = "\uf382"; public static readonly string MDMultiplicationBox = "\uf383"; public static readonly string MDMusicBox = "\uf384"; public static readonly string MDMusicBoxOutline = "\uf385"; public static readonly string MDMusicCircle = "\uf386"; public static readonly string MDMusicNote = "\uf387"; public static readonly string MDMusicNoteBluetooth = "\uf5fe"; public static readonly string MDMusicNoteBluetoothOff = "\uf5ff"; public static readonly string MDMusicNoteEighth = "\uf388"; public static readonly string MDMusicNoteHalf = "\uf389"; public static readonly string MDMusicNoteOff = "\uf38a"; public static readonly string MDMusicNoteQuarter = "\uf38b"; public static readonly string MDMusicNoteSixteenth = "\uf38c"; public static readonly string MDMusicNoteWhole = "\uf38d"; public static readonly string MDNature = "\uf38e"; public static readonly string MDNaturePeople = "\uf38f"; public static readonly string MDNavigation = "\uf390"; public static readonly string MDNearMe = "\uf5cd"; public static readonly string MDNeedle = "\uf391"; public static readonly string MDNestProtect = "\uf392"; public static readonly string MDNestThermostat = "\uf393"; public static readonly string MDNetwork = "\uf6f2"; public static readonly string MDNetworkDownload = "\uf6f3"; public static readonly string MDNetworkQuestion = "\uf6f4"; public static readonly string MDNetworkUpload = "\uf6f5"; public static readonly string MDNewBox = "\uf394"; public static readonly string MDNewspaper = "\uf395"; public static readonly string MDNfc = "\uf396"; public static readonly string MDNfcTap = "\uf397"; public static readonly string MDNfcVariant = "\uf398"; public static readonly string MDNodejs = "\uf399"; public static readonly string MDNote = "\uf39a"; public static readonly string MDNoteMultiple = "\uf6b7"; public static readonly string MDNoteMultipleOutline = "\uf6b8"; public static readonly string MDNoteOutline = "\uf39b"; public static readonly string MDNotePlus = "\uf39c"; public static readonly string MDNotePlusOutline = "\uf39d"; public static readonly string MDNoteText = "\uf39e"; public static readonly string MDNotificationClearAll = "\uf39f"; public static readonly string MDNpm = "\uf6f6"; public static readonly string MDNuke = "\uf6a3"; public static readonly string MDNumeric = "\uf3a0"; public static readonly string MDNumeric0Box = "\uf3a1"; public static readonly string MDNumeric0BoxMultipleOutline = "\uf3a2"; public static readonly string MDNumeric0BoxOutline = "\uf3a3"; public static readonly string MDNumeric1Box = "\uf3a4"; public static readonly string MDNumeric1BoxMultipleOutline = "\uf3a5"; public static readonly string MDNumeric1BoxOutline = "\uf3a6"; public static readonly string MDNumeric2Box = "\uf3a7"; public static readonly string MDNumeric2BoxMultipleOutline = "\uf3a8"; public static readonly string MDNumeric2BoxOutline = "\uf3a9"; public static readonly string MDNumeric3Box = "\uf3aa"; public static readonly string MDNumeric3BoxMultipleOutline = "\uf3ab"; public static readonly string MDNumeric3BoxOutline = "\uf3ac"; public static readonly string MDNumeric4Box = "\uf3ad"; public static readonly string MDNumeric4BoxMultipleOutline = "\uf3ae"; public static readonly string MDNumeric4BoxOutline = "\uf3af"; public static readonly string MDNumeric5Box = "\uf3b0"; public static readonly string MDNumeric5BoxMultipleOutline = "\uf3b1"; public static readonly string MDNumeric5BoxOutline = "\uf3b2"; public static readonly string MDNumeric6Box = "\uf3b3"; public static readonly string MDNumeric6BoxMultipleOutline = "\uf3b4"; public static readonly string MDNumeric6BoxOutline = "\uf3b5"; public static readonly string MDNumeric7Box = "\uf3b6"; public static readonly string MDNumeric7BoxMultipleOutline = "\uf3b7"; public static readonly string MDNumeric7BoxOutline = "\uf3b8"; public static readonly string MDNumeric8Box = "\uf3b9"; public static readonly string MDNumeric8BoxMultipleOutline = "\uf3ba"; public static readonly string MDNumeric8BoxOutline = "\uf3bb"; public static readonly string MDNumeric9Box = "\uf3bc"; public static readonly string MDNumeric9BoxMultipleOutline = "\uf3bd"; public static readonly string MDNumeric9BoxOutline = "\uf3be"; public static readonly string MDNumeric9PlusBox = "\uf3bf"; public static readonly string MDNumeric9PlusBoxMultipleOutline = "\uf3c0"; public static readonly string MDNumeric9PlusBoxOutline = "\uf3c1"; public static readonly string MDNut = "\uf6f7"; public static readonly string MDNutrition = "\uf3c2"; public static readonly string MDOar = "\uf67b"; public static readonly string MDOctagon = "\uf3c3"; public static readonly string MDOctagonOutline = "\uf3c4"; public static readonly string MDOctagram = "\uf6f8"; public static readonly string MDOdnoklassniki = "\uf3c5"; public static readonly string MDOffice = "\uf3c6"; public static readonly string MDOil = "\uf3c7"; public static readonly string MDOilTemperature = "\uf3c8"; public static readonly string MDOmega = "\uf3c9"; public static readonly string MDOnedrive = "\uf3ca"; public static readonly string MDOpacity = "\uf5cc"; public static readonly string MDOpenInApp = "\uf3cb"; public static readonly string MDOpenInNew = "\uf3cc"; public static readonly string MDOpenid = "\uf3cd"; public static readonly string MDOpera = "\uf3ce"; public static readonly string MDOrnament = "\uf3cf"; public static readonly string MDOrnamentVariant = "\uf3d0"; public static readonly string MDOwl = "\uf3d2"; public static readonly string MDPackage = "\uf3d3"; public static readonly string MDPackageDown = "\uf3d4"; public static readonly string MDPackageUp = "\uf3d5"; public static readonly string MDPackageVariant = "\uf3d6"; public static readonly string MDPackageVariantClosed = "\uf3d7"; public static readonly string MDPageFirst = "\uf600"; public static readonly string MDPageLast = "\uf601"; public static readonly string MDPageLayoutBody = "\uf6f9"; public static readonly string MDPageLayoutFooter = "\uf6fa"; public static readonly string MDPageLayoutHeader = "\uf6fb"; public static readonly string MDPageLayoutSidebarLeft = "\uf6fc"; public static readonly string MDPageLayoutSidebarRight = "\uf6fd"; public static readonly string MDPalette = "\uf3d8"; public static readonly string MDPaletteAdvanced = "\uf3d9"; public static readonly string MDPanda = "\uf3da"; public static readonly string MDPandora = "\uf3db"; public static readonly string MDPanorama = "\uf3dc"; public static readonly string MDPanoramaFisheye = "\uf3dd"; public static readonly string MDPanoramaHorizontal = "\uf3de"; public static readonly string MDPanoramaVertical = "\uf3df"; public static readonly string MDPanoramaWideAngle = "\uf3e0"; public static readonly string MDPaperCutVertical = "\uf3e1"; public static readonly string MDPaperclip = "\uf3e2"; public static readonly string MDParking = "\uf3e3"; public static readonly string MDPause = "\uf3e4"; public static readonly string MDPauseCircle = "\uf3e5"; public static readonly string MDPauseCircleOutline = "\uf3e6"; public static readonly string MDPauseOctagon = "\uf3e7"; public static readonly string MDPauseOctagonOutline = "\uf3e8"; public static readonly string MDPaw = "\uf3e9"; public static readonly string MDPawOff = "\uf657"; public static readonly string MDPen = "\uf3ea"; public static readonly string MDPencil = "\uf3eb"; public static readonly string MDPencilBox = "\uf3ec"; public static readonly string MDPencilBoxOutline = "\uf3ed"; public static readonly string MDPencilCircle = "\uf6fe"; public static readonly string MDPencilLock = "\uf3ee"; public static readonly string MDPencilOff = "\uf3ef"; public static readonly string MDPentagon = "\uf6ff"; public static readonly string MDPentagonOutline = "\uf700"; public static readonly string MDPercent = "\uf3f0"; public static readonly string MDPharmacy = "\uf3f1"; public static readonly string MDPhone = "\uf3f2"; public static readonly string MDPhoneBluetooth = "\uf3f3"; public static readonly string MDPhoneClassic = "\uf602"; public static readonly string MDPhoneForward = "\uf3f4"; public static readonly string MDPhoneHangup = "\uf3f5"; public static readonly string MDPhoneInTalk = "\uf3f6"; public static readonly string MDPhoneIncoming = "\uf3f7"; public static readonly string MDPhoneLocked = "\uf3f8"; public static readonly string MDPhoneLog = "\uf3f9"; public static readonly string MDPhoneMinus = "\uf658"; public static readonly string MDPhoneMissed = "\uf3fa"; public static readonly string MDPhoneOutgoing = "\uf3fb"; public static readonly string MDPhonePaused = "\uf3fc"; public static readonly string MDPhonePlus = "\uf659"; public static readonly string MDPhoneSettings = "\uf3fd"; public static readonly string MDPhoneVoip = "\uf3fe"; public static readonly string MDPi = "\uf3ff"; public static readonly string MDPiBox = "\uf400"; public static readonly string MDPiano = "\uf67c"; public static readonly string MDPig = "\uf401"; public static readonly string MDPill = "\uf402"; public static readonly string MDPillar = "\uf701"; public static readonly string MDPin = "\uf403"; public static readonly string MDPinOff = "\uf404"; public static readonly string MDPineTree = "\uf405"; public static readonly string MDPineTreeBox = "\uf406"; public static readonly string MDPinterest = "\uf407"; public static readonly string MDPinterestBox = "\uf408"; public static readonly string MDPistol = "\uf702"; public static readonly string MDPizza = "\uf409"; public static readonly string MDPlaneShield = "\uf6ba"; public static readonly string MDPlay = "\uf40a"; public static readonly string MDPlayBoxOutline = "\uf40b"; public static readonly string MDPlayCircle = "\uf40c"; public static readonly string MDPlayCircleOutline = "\uf40d"; public static readonly string MDPlayPause = "\uf40e"; public static readonly string MDPlayProtectedContent = "\uf40f"; public static readonly string MDPlaylistCheck = "\uf5c7"; public static readonly string MDPlaylistMinus = "\uf410"; public static readonly string MDPlaylistPlay = "\uf411"; public static readonly string MDPlaylistPlus = "\uf412"; public static readonly string MDPlaylistRemove = "\uf413"; public static readonly string MDPlaystation = "\uf414"; public static readonly string MDPlex = "\uf6b9"; public static readonly string MDPlus = "\uf415"; public static readonly string MDPlusBox = "\uf416"; public static readonly string MDPlusBoxOutline = "\uf703"; public static readonly string MDPlusCircle = "\uf417"; public static readonly string MDPlusCircleMultipleOutline = "\uf418"; public static readonly string MDPlusCircleOutline = "\uf419"; public static readonly string MDPlusNetwork = "\uf41a"; public static readonly string MDPlusOne = "\uf41b"; public static readonly string MDPlusOutline = "\uf704"; public static readonly string MDPocket = "\uf41c"; public static readonly string MDPokeball = "\uf41d"; public static readonly string MDPolaroid = "\uf41e"; public static readonly string MDPoll = "\uf41f"; public static readonly string MDPollBox = "\uf420"; public static readonly string MDPolymer = "\uf421"; public static readonly string MDPool = "\uf606"; public static readonly string MDPopcorn = "\uf422"; public static readonly string MDPot = "\uf65a"; public static readonly string MDPotMix = "\uf65b"; public static readonly string MDPound = "\uf423"; public static readonly string MDPoundBox = "\uf424"; public static readonly string MDPower = "\uf425"; public static readonly string MDPowerPlug = "\uf6a4"; public static readonly string MDPowerPlugOff = "\uf6a5"; public static readonly string MDPowerSettings = "\uf426"; public static readonly string MDPowerSocket = "\uf427"; public static readonly string MDPrescription = "\uf705"; public static readonly string MDPresentation = "\uf428"; public static readonly string MDPresentationPlay = "\uf429"; public static readonly string MDPrinter = "\uf42a"; public static readonly string MDPrinter3d = "\uf42b"; public static readonly string MDPrinterAlert = "\uf42c"; public static readonly string MDPrinterSettings = "\uf706"; public static readonly string MDPriorityHigh = "\uf603"; public static readonly string MDPriorityLow = "\uf604"; public static readonly string MDProfessionalHexagon = "\uf42d"; public static readonly string MDProjector = "\uf42e"; public static readonly string MDProjectorScreen = "\uf42f"; public static readonly string MDPublish = "\uf6a6"; public static readonly string MDPulse = "\uf430"; public static readonly string MDPuzzle = "\uf431"; public static readonly string MDQqchat = "\uf605"; public static readonly string MDQrcode = "\uf432"; public static readonly string MDQrcodeScan = "\uf433"; public static readonly string MDQuadcopter = "\uf434"; public static readonly string MDQualityHigh = "\uf435"; public static readonly string MDQuicktime = "\uf436"; public static readonly string MDRadar = "\uf437"; public static readonly string MDRadiator = "\uf438"; public static readonly string MDRadio = "\uf439"; public static readonly string MDRadioHandheld = "\uf43a"; public static readonly string MDRadioTower = "\uf43b"; public static readonly string MDRadioactive = "\uf43c"; public static readonly string MDRadioboxBlank = "\uf43d"; public static readonly string MDRadioboxMarked = "\uf43e"; public static readonly string MDRaspberrypi = "\uf43f"; public static readonly string MDRayEnd = "\uf440"; public static readonly string MDRayEndArrow = "\uf441"; public static readonly string MDRayStart = "\uf442"; public static readonly string MDRayStartArrow = "\uf443"; public static readonly string MDRayStartEnd = "\uf444"; public static readonly string MDRayVertex = "\uf445"; public static readonly string MDRdio = "\uf446"; public static readonly string MDReact = "\uf707"; public static readonly string MDRead = "\uf447"; public static readonly string MDReadability = "\uf448"; public static readonly string MDReceipt = "\uf449"; public static readonly string MDRecord = "\uf44a"; public static readonly string MDRecordRec = "\uf44b"; public static readonly string MDRecycle = "\uf44c"; public static readonly string MDReddit = "\uf44d"; public static readonly string MDRedo = "\uf44e"; public static readonly string MDRedoVariant = "\uf44f"; public static readonly string MDRefresh = "\uf450"; public static readonly string MDRegex = "\uf451"; public static readonly string MDRelativeScale = "\uf452"; public static readonly string MDReload = "\uf453"; public static readonly string MDRemote = "\uf454"; public static readonly string MDRenameBox = "\uf455"; public static readonly string MDReorderHorizontal = "\uf687"; public static readonly string MDReorderVertical = "\uf688"; public static readonly string MDRepeat = "\uf456"; public static readonly string MDRepeatOff = "\uf457"; public static readonly string MDRepeatOnce = "\uf458"; public static readonly string MDReplay = "\uf459"; public static readonly string MDReply = "\uf45a"; public static readonly string MDReplyAll = "\uf45b"; public static readonly string MDReproduction = "\uf45c"; public static readonly string MDResizeBottomRight = "\uf45d"; public static readonly string MDResponsive = "\uf45e"; public static readonly string MDRestart = "\uf708"; public static readonly string MDRestore = "\uf6a7"; public static readonly string MDRewind = "\uf45f"; public static readonly string MDRewindOutline = "\uf709"; public static readonly string MDRhombus = "\uf70a"; public static readonly string MDRhombusOutline = "\uf70b"; public static readonly string MDRibbon = "\uf460"; public static readonly string MDRoad = "\uf461"; public static readonly string MDRoadVariant = "\uf462"; public static readonly string MDRobot = "\uf6a8"; public static readonly string MDRocket = "\uf463"; public static readonly string MDRoomba = "\uf70c"; public static readonly string MDRotate3d = "\uf464"; public static readonly string MDRotateLeft = "\uf465"; public static readonly string MDRotateLeftVariant = "\uf466"; public static readonly string MDRotateRight = "\uf467"; public static readonly string MDRotateRightVariant = "\uf468"; public static readonly string MDRoundedCorner = "\uf607"; public static readonly string MDRouterWireless = "\uf469"; public static readonly string MDRoutes = "\uf46a"; public static readonly string MDRowing = "\uf608"; public static readonly string MDRss = "\uf46b"; public static readonly string MDRssBox = "\uf46c"; public static readonly string MDRuler = "\uf46d"; public static readonly string MDRun = "\uf70d"; public static readonly string MDRunFast = "\uf46e"; public static readonly string MDSale = "\uf46f"; public static readonly string MDSatellite = "\uf470"; public static readonly string MDSatelliteVariant = "\uf471"; public static readonly string MDSaxophone = "\uf609"; public static readonly string MDScale = "\uf472"; public static readonly string MDScaleBalance = "\uf5d1"; public static readonly string MDScaleBathroom = "\uf473"; public static readonly string MDScanner = "\uf6aa"; public static readonly string MDSchool = "\uf474"; public static readonly string MDScreenRotation = "\uf475"; public static readonly string MDScreenRotationLock = "\uf476"; public static readonly string MDScrewdriver = "\uf477"; public static readonly string MDScript = "\uf478"; public static readonly string MDSd = "\uf479"; public static readonly string MDSeal = "\uf47a"; public static readonly string MDSearchWeb = "\uf70e"; public static readonly string MDSeatFlat = "\uf47b"; public static readonly string MDSeatFlatAngled = "\uf47c"; public static readonly string MDSeatIndividualSuite = "\uf47d"; public static readonly string MDSeatLegroomExtra = "\uf47e"; public static readonly string MDSeatLegroomNormal = "\uf47f"; public static readonly string MDSeatLegroomReduced = "\uf480"; public static readonly string MDSeatReclineExtra = "\uf481"; public static readonly string MDSeatReclineNormal = "\uf482"; public static readonly string MDSecurity = "\uf483"; public static readonly string MDSecurityHome = "\uf689"; public static readonly string MDSecurityNetwork = "\uf484"; public static readonly string MDSelect = "\uf485"; public static readonly string MDSelectAll = "\uf486"; public static readonly string MDSelectInverse = "\uf487"; public static readonly string MDSelectOff = "\uf488"; public static readonly string MDSelection = "\uf489"; public static readonly string MDSend = "\uf48a"; public static readonly string MDSerialPort = "\uf65c"; public static readonly string MDServer = "\uf48b"; public static readonly string MDServerMinus = "\uf48c"; public static readonly string MDServerNetwork = "\uf48d"; public static readonly string MDServerNetworkOff = "\uf48e"; public static readonly string MDServerOff = "\uf48f"; public static readonly string MDServerPlus = "\uf490"; public static readonly string MDServerRemove = "\uf491"; public static readonly string MDServerSecurity = "\uf492"; public static readonly string MDSettings = "\uf493"; public static readonly string MDSettingsBox = "\uf494"; public static readonly string MDShapeCirclePlus = "\uf65d"; public static readonly string MDShapePlus = "\uf495"; public static readonly string MDShapePolygonPlus = "\uf65e"; public static readonly string MDShapeRectanglePlus = "\uf65f"; public static readonly string MDShapeSquarePlus = "\uf660"; public static readonly string MDShare = "\uf496"; public static readonly string MDShareVariant = "\uf497"; public static readonly string MDShield = "\uf498"; public static readonly string MDShieldOutline = "\uf499"; public static readonly string MDShopping = "\uf49a"; public static readonly string MDShoppingMusic = "\uf49b"; public static readonly string MDShovel = "\uf70f"; public static readonly string MDShovelOff = "\uf710"; public static readonly string MDShredder = "\uf49c"; public static readonly string MDShuffle = "\uf49d"; public static readonly string MDShuffleDisabled = "\uf49e"; public static readonly string MDShuffleVariant = "\uf49f"; public static readonly string MDSigma = "\uf4a0"; public static readonly string MDSigmaLower = "\uf62b"; public static readonly string MDSignCaution = "\uf4a1"; public static readonly string MDSignal = "\uf4a2"; public static readonly string MDSignal2g = "\uf711"; public static readonly string MDSignal3g = "\uf712"; public static readonly string MDSignal4g = "\uf713"; public static readonly string MDSignalHspa = "\uf714"; public static readonly string MDSignalHspaPlus = "\uf715"; public static readonly string MDSignalVariant = "\uf60a"; public static readonly string MDSilverware = "\uf4a3"; public static readonly string MDSilverwareFork = "\uf4a4"; public static readonly string MDSilverwareSpoon = "\uf4a5"; public static readonly string MDSilverwareVariant = "\uf4a6"; public static readonly string MDSim = "\uf4a7"; public static readonly string MDSimAlert = "\uf4a8"; public static readonly string MDSimOff = "\uf4a9"; public static readonly string MDSitemap = "\uf4aa"; public static readonly string MDSkipBackward = "\uf4ab"; public static readonly string MDSkipForward = "\uf4ac"; public static readonly string MDSkipNext = "\uf4ad"; public static readonly string MDSkipNextCircle = "\uf661"; public static readonly string MDSkipNextCircleOutline = "\uf662"; public static readonly string MDSkipPrevious = "\uf4ae"; public static readonly string MDSkipPreviousCircle = "\uf663"; public static readonly string MDSkipPreviousCircleOutline = "\uf664"; public static readonly string MDSkull = "\uf68b"; public static readonly string MDSkype = "\uf4af"; public static readonly string MDSkypeBusiness = "\uf4b0"; public static readonly string MDSlack = "\uf4b1"; public static readonly string MDSleep = "\uf4b2"; public static readonly string MDSleepOff = "\uf4b3"; public static readonly string MDSmoking = "\uf4b4"; public static readonly string MDSmokingOff = "\uf4b5"; public static readonly string MDSnapchat = "\uf4b6"; public static readonly string MDSnowflake = "\uf716"; public static readonly string MDSnowman = "\uf4b7"; public static readonly string MDSoccer = "\uf4b8"; public static readonly string MDSofa = "\uf4b9"; public static readonly string MDSolid = "\uf68c"; public static readonly string MDSort = "\uf4ba"; public static readonly string MDSortAlphabetical = "\uf4bb"; public static readonly string MDSortAscending = "\uf4bc"; public static readonly string MDSortDescending = "\uf4bd"; public static readonly string MDSortNumeric = "\uf4be"; public static readonly string MDSortVariant = "\uf4bf"; public static readonly string MDSoundcloud = "\uf4c0"; public static readonly string MDSourceBranch = "\uf62c"; public static readonly string MDSourceCommit = "\uf717"; public static readonly string MDSourceCommitEnd = "\uf718"; public static readonly string MDSourceCommitEndLocal = "\uf719"; public static readonly string MDSourceCommitLocal = "\uf71a"; public static readonly string MDSourceCommitNextLocal = "\uf71b"; public static readonly string MDSourceCommitStart = "\uf71c"; public static readonly string MDSourceCommitStartNextLocal = "\uf71d"; public static readonly string MDSourceFork = "\uf4c1"; public static readonly string MDSourceMerge = "\uf62d"; public static readonly string MDSourcePull = "\uf4c2"; public static readonly string MDSpeaker = "\uf4c3"; public static readonly string MDSpeakerOff = "\uf4c4"; public static readonly string MDSpeakerWireless = "\uf71e"; public static readonly string MDSpeedometer = "\uf4c5"; public static readonly string MDSpellcheck = "\uf4c6"; public static readonly string MDSpotify = "\uf4c7"; public static readonly string MDSpotlight = "\uf4c8"; public static readonly string MDSpotlightBeam = "\uf4c9"; public static readonly string MDSpray = "\uf665"; public static readonly string MDSquareInc = "\uf4ca"; public static readonly string MDSquareIncCash = "\uf4cb"; public static readonly string MDStackexchange = "\uf60b"; public static readonly string MDStackoverflow = "\uf4cc"; public static readonly string MDStadium = "\uf71f"; public static readonly string MDStairs = "\uf4cd"; public static readonly string MDStar = "\uf4ce"; public static readonly string MDStarCircle = "\uf4cf"; public static readonly string MDStarHalf = "\uf4d0"; public static readonly string MDStarOff = "\uf4d1"; public static readonly string MDStarOutline = "\uf4d2"; public static readonly string MDSteam = "\uf4d3"; public static readonly string MDSteering = "\uf4d4"; public static readonly string MDStepBackward = "\uf4d5"; public static readonly string MDStepBackward2 = "\uf4d6"; public static readonly string MDStepForward = "\uf4d7"; public static readonly string MDStepForward2 = "\uf4d8"; public static readonly string MDStethoscope = "\uf4d9"; public static readonly string MDSticker = "\uf5d0"; public static readonly string MDStocking = "\uf4da"; public static readonly string MDStop = "\uf4db"; public static readonly string MDStopCircle = "\uf666"; public static readonly string MDStopCircleOutline = "\uf667"; public static readonly string MDStore = "\uf4dc"; public static readonly string MDStore24Hour = "\uf4dd"; public static readonly string MDStove = "\uf4de"; public static readonly string MDSubdirectoryArrowLeft = "\uf60c"; public static readonly string MDSubdirectoryArrowRight = "\uf60d"; public static readonly string MDSubway = "\uf6ab"; public static readonly string MDSubwayVariant = "\uf4df"; public static readonly string MDSunglasses = "\uf4e0"; public static readonly string MDSurroundSound = "\uf5c5"; public static readonly string MDSvg = "\uf720"; public static readonly string MDSwapHorizontal = "\uf4e1"; public static readonly string MDSwapVertical = "\uf4e2"; public static readonly string MDSwim = "\uf4e3"; public static readonly string MDSwitch = "\uf4e4"; public static readonly string MDSword = "\uf4e5"; public static readonly string MDSync = "\uf4e6"; public static readonly string MDSyncAlert = "\uf4e7"; public static readonly string MDSyncOff = "\uf4e8"; public static readonly string MDTab = "\uf4e9"; public static readonly string MDTabUnselected = "\uf4ea"; public static readonly string MDTable = "\uf4eb"; public static readonly string MDTableColumnPlusAfter = "\uf4ec"; public static readonly string MDTableColumnPlusBefore = "\uf4ed"; public static readonly string MDTableColumnRemove = "\uf4ee"; public static readonly string MDTableColumnWidth = "\uf4ef"; public static readonly string MDTableEdit = "\uf4f0"; public static readonly string MDTableLarge = "\uf4f1"; public static readonly string MDTableRowHeight = "\uf4f2"; public static readonly string MDTableRowPlusAfter = "\uf4f3"; public static readonly string MDTableRowPlusBefore = "\uf4f4"; public static readonly string MDTableRowRemove = "\uf4f5"; public static readonly string MDTablet = "\uf4f6"; public static readonly string MDTabletAndroid = "\uf4f7"; public static readonly string MDTabletIpad = "\uf4f8"; public static readonly string MDTag = "\uf4f9"; public static readonly string MDTagFaces = "\uf4fa"; public static readonly string MDTagHeart = "\uf68a"; public static readonly string MDTagMultiple = "\uf4fb"; public static readonly string MDTagOutline = "\uf4fc"; public static readonly string MDTagPlus = "\uf721"; public static readonly string MDTagRemove = "\uf722"; public static readonly string MDTagTextOutline = "\uf4fd"; public static readonly string MDTarget = "\uf4fe"; public static readonly string MDTaxi = "\uf4ff"; public static readonly string MDTeamviewer = "\uf500"; public static readonly string MDTelegram = "\uf501"; public static readonly string MDTelevision = "\uf502"; public static readonly string MDTelevisionGuide = "\uf503"; public static readonly string MDTemperatureCelsius = "\uf504"; public static readonly string MDTemperatureFahrenheit = "\uf505"; public static readonly string MDTemperatureKelvin = "\uf506"; public static readonly string MDTennis = "\uf507"; public static readonly string MDTent = "\uf508"; public static readonly string MDTerrain = "\uf509"; public static readonly string MDTestTube = "\uf668"; public static readonly string MDTextShadow = "\uf669"; public static readonly string MDTextToSpeech = "\uf50a"; public static readonly string MDTextToSpeechOff = "\uf50b"; public static readonly string MDTextbox = "\uf60e"; public static readonly string MDTexture = "\uf50c"; public static readonly string MDTheater = "\uf50d"; public static readonly string MDThemeLightDark = "\uf50e"; public static readonly string MDThermometer = "\uf50f"; public static readonly string MDThermometerLines = "\uf510"; public static readonly string MDThumbDown = "\uf511"; public static readonly string MDThumbDownOutline = "\uf512"; public static readonly string MDThumbUp = "\uf513"; public static readonly string MDThumbUpOutline = "\uf514"; public static readonly string MDThumbsUpDown = "\uf515"; public static readonly string MDTicket = "\uf516"; public static readonly string MDTicketAccount = "\uf517"; public static readonly string MDTicketConfirmation = "\uf518"; public static readonly string MDTicketPercent = "\uf723"; public static readonly string MDTie = "\uf519"; public static readonly string MDTilde = "\uf724"; public static readonly string MDTimelapse = "\uf51a"; public static readonly string MDTimer = "\uf51b"; public static readonly string MDTimer10 = "\uf51c"; public static readonly string MDTimer3 = "\uf51d"; public static readonly string MDTimerOff = "\uf51e"; public static readonly string MDTimerSand = "\uf51f"; public static readonly string MDTimerSandEmpty = "\uf6ac"; public static readonly string MDTimetable = "\uf520"; public static readonly string MDToggleSwitch = "\uf521"; public static readonly string MDToggleSwitchOff = "\uf522"; public static readonly string MDTooltip = "\uf523"; public static readonly string MDTooltipEdit = "\uf524"; public static readonly string MDTooltipImage = "\uf525"; public static readonly string MDTooltipOutline = "\uf526"; public static readonly string MDTooltipOutlinePlus = "\uf527"; public static readonly string MDTooltipText = "\uf528"; public static readonly string MDTooth = "\uf529"; public static readonly string MDTor = "\uf52a"; public static readonly string MDTowerBeach = "\uf680"; public static readonly string MDTowerFire = "\uf681"; public static readonly string MDTrafficLight = "\uf52b"; public static readonly string MDTrain = "\uf52c"; public static readonly string MDTram = "\uf52d"; public static readonly string MDTranscribe = "\uf52e"; public static readonly string MDTranscribeClose = "\uf52f"; public static readonly string MDTransfer = "\uf530"; public static readonly string MDTransitTransfer = "\uf6ad"; public static readonly string MDTranslate = "\uf5ca"; public static readonly string MDTreasureChest = "\uf725"; public static readonly string MDTree = "\uf531"; public static readonly string MDTrello = "\uf532"; public static readonly string MDTrendingDown = "\uf533"; public static readonly string MDTrendingNeutral = "\uf534"; public static readonly string MDTrendingUp = "\uf535"; public static readonly string MDTriangle = "\uf536"; public static readonly string MDTriangleOutline = "\uf537"; public static readonly string MDTrophy = "\uf538"; public static readonly string MDTrophyAward = "\uf539"; public static readonly string MDTrophyOutline = "\uf53a"; public static readonly string MDTrophyVariant = "\uf53b"; public static readonly string MDTrophyVariantOutline = "\uf53c"; public static readonly string MDTruck = "\uf53d"; public static readonly string MDTruckDelivery = "\uf53e"; public static readonly string MDTruckTrailer = "\uf726"; public static readonly string MDTshirtCrew = "\uf53f"; public static readonly string MDTshirtV = "\uf540"; public static readonly string MDTumblr = "\uf541"; public static readonly string MDTumblrReblog = "\uf542"; public static readonly string MDTune = "\uf62e"; public static readonly string MDTuneVertical = "\uf66a"; public static readonly string MDTwitch = "\uf543"; public static readonly string MDTwitter = "\uf544"; public static readonly string MDTwitterBox = "\uf545"; public static readonly string MDTwitterCircle = "\uf546"; public static readonly string MDTwitterRetweet = "\uf547"; public static readonly string MDUbuntu = "\uf548"; public static readonly string MDUmbraco = "\uf549"; public static readonly string MDUmbrella = "\uf54a"; public static readonly string MDUmbrellaOutline = "\uf54b"; public static readonly string MDUndo = "\uf54c"; public static readonly string MDUndoVariant = "\uf54d"; public static readonly string MDUnfoldLess = "\uf54e"; public static readonly string MDUnfoldMore = "\uf54f"; public static readonly string MDUngroup = "\uf550"; public static readonly string MDUnity = "\uf6ae"; public static readonly string MDUntappd = "\uf551"; public static readonly string MDUpdate = "\uf6af"; public static readonly string MDUpload = "\uf552"; public static readonly string MDUsb = "\uf553"; public static readonly string MDVectorArrangeAbove = "\uf554"; public static readonly string MDVectorArrangeBelow = "\uf555"; public static readonly string MDVectorCircle = "\uf556"; public static readonly string MDVectorCircleVariant = "\uf557"; public static readonly string MDVectorCombine = "\uf558"; public static readonly string MDVectorCurve = "\uf559"; public static readonly string MDVectorDifference = "\uf55a"; public static readonly string MDVectorDifferenceAb = "\uf55b"; public static readonly string MDVectorDifferenceBa = "\uf55c"; public static readonly string MDVectorIntersection = "\uf55d"; public static readonly string MDVectorLine = "\uf55e"; public static readonly string MDVectorPoint = "\uf55f"; public static readonly string MDVectorPolygon = "\uf560"; public static readonly string MDVectorPolyline = "\uf561"; public static readonly string MDVectorRectangle = "\uf5c6"; public static readonly string MDVectorSelection = "\uf562"; public static readonly string MDVectorSquare = "\uf001"; public static readonly string MDVectorTriangle = "\uf563"; public static readonly string MDVectorUnion = "\uf564"; public static readonly string MDVerified = "\uf565"; public static readonly string MDVibrate = "\uf566"; public static readonly string MDVideo = "\uf567"; public static readonly string MDVideoOff = "\uf568"; public static readonly string MDVideoSwitch = "\uf569"; public static readonly string MDViewAgenda = "\uf56a"; public static readonly string MDViewArray = "\uf56b"; public static readonly string MDViewCarousel = "\uf56c"; public static readonly string MDViewColumn = "\uf56d"; public static readonly string MDViewDashboard = "\uf56e"; public static readonly string MDViewDay = "\uf56f"; public static readonly string MDViewGrid = "\uf570"; public static readonly string MDViewHeadline = "\uf571"; public static readonly string MDViewList = "\uf572"; public static readonly string MDViewModule = "\uf573"; public static readonly string MDViewParallel = "\uf727"; public static readonly string MDViewQuilt = "\uf574"; public static readonly string MDViewSequential = "\uf728"; public static readonly string MDViewStream = "\uf575"; public static readonly string MDViewWeek = "\uf576"; public static readonly string MDVimeo = "\uf577"; public static readonly string MDVine = "\uf578"; public static readonly string MDViolin = "\uf60f"; public static readonly string MDVisualstudio = "\uf610"; public static readonly string MDVk = "\uf579"; public static readonly string MDVkBox = "\uf57a"; public static readonly string MDVkCircle = "\uf57b"; public static readonly string MDVlc = "\uf57c"; public static readonly string MDVoice = "\uf5cb"; public static readonly string MDVoicemail = "\uf57d"; public static readonly string MDVolumeHigh = "\uf57e"; public static readonly string MDVolumeLow = "\uf57f"; public static readonly string MDVolumeMedium = "\uf580"; public static readonly string MDVolumeOff = "\uf581"; public static readonly string MDVpn = "\uf582"; public static readonly string MDWalk = "\uf583"; public static readonly string MDWallet = "\uf584"; public static readonly string MDWalletGiftcard = "\uf585"; public static readonly string MDWalletMembership = "\uf586"; public static readonly string MDWalletTravel = "\uf587"; public static readonly string MDWan = "\uf588"; public static readonly string MDWashingMachine = "\uf729"; public static readonly string MDWatch = "\uf589"; public static readonly string MDWatchExport = "\uf58a"; public static readonly string MDWatchImport = "\uf58b"; public static readonly string MDWatchVibrate = "\uf6b0"; public static readonly string MDWater = "\uf58c"; public static readonly string MDWaterOff = "\uf58d"; public static readonly string MDWaterPercent = "\uf58e"; public static readonly string MDWaterPump = "\uf58f"; public static readonly string MDWatermark = "\uf612"; public static readonly string MDWeatherCloudy = "\uf590"; public static readonly string MDWeatherFog = "\uf591"; public static readonly string MDWeatherHail = "\uf592"; public static readonly string MDWeatherLightning = "\uf593"; public static readonly string MDWeatherLightningRainy = "\uf67d"; public static readonly string MDWeatherNight = "\uf594"; public static readonly string MDWeatherPartlycloudy = "\uf595"; public static readonly string MDWeatherPouring = "\uf596"; public static readonly string MDWeatherRainy = "\uf597"; public static readonly string MDWeatherSnowy = "\uf598"; public static readonly string MDWeatherSnowyRainy = "\uf67e"; public static readonly string MDWeatherSunny = "\uf599"; public static readonly string MDWeatherSunset = "\uf59a"; public static readonly string MDWeatherSunsetDown = "\uf59b"; public static readonly string MDWeatherSunsetUp = "\uf59c"; public static readonly string MDWeatherWindy = "\uf59d"; public static readonly string MDWeatherWindyVariant = "\uf59e"; public static readonly string MDWeb = "\uf59f"; public static readonly string MDWebcam = "\uf5a0"; public static readonly string MDWebhook = "\uf62f"; public static readonly string MDWebpack = "\uf72a"; public static readonly string MDWechat = "\uf611"; public static readonly string MDWeight = "\uf5a1"; public static readonly string MDWeightKilogram = "\uf5a2"; public static readonly string MDWhatsapp = "\uf5a3"; public static readonly string MDWheelchairAccessibility = "\uf5a4"; public static readonly string MDWhiteBalanceAuto = "\uf5a5"; public static readonly string MDWhiteBalanceIncandescent = "\uf5a6"; public static readonly string MDWhiteBalanceIridescent = "\uf5a7"; public static readonly string MDWhiteBalanceSunny = "\uf5a8"; public static readonly string MDWidgets = "\uf72b"; public static readonly string MDWifi = "\uf5a9"; public static readonly string MDWifiOff = "\uf5aa"; public static readonly string MDWii = "\uf5ab"; public static readonly string MDWiiu = "\uf72c"; public static readonly string MDWikipedia = "\uf5ac"; public static readonly string MDWindowClose = "\uf5ad"; public static readonly string MDWindowClosed = "\uf5ae"; public static readonly string MDWindowMaximize = "\uf5af"; public static readonly string MDWindowMinimize = "\uf5b0"; public static readonly string MDWindowOpen = "\uf5b1"; public static readonly string MDWindowRestore = "\uf5b2"; public static readonly string MDWindows = "\uf5b3"; public static readonly string MDWordpress = "\uf5b4"; public static readonly string MDWorker = "\uf5b5"; public static readonly string MDWrap = "\uf5b6"; public static readonly string MDWrench = "\uf5b7"; public static readonly string MDWunderlist = "\uf5b8"; public static readonly string MDXaml = "\uf673"; public static readonly string MDXbox = "\uf5b9"; public static readonly string MDXboxController = "\uf5ba"; public static readonly string MDXboxControllerOff = "\uf5bb"; public static readonly string MDXda = "\uf5bc"; public static readonly string MDXing = "\uf5bd"; public static readonly string MDXingBox = "\uf5be"; public static readonly string MDXingCircle = "\uf5bf"; public static readonly string MDXml = "\uf5c0"; public static readonly string MDYeast = "\uf5c1"; public static readonly string MDYelp = "\uf5c2"; public static readonly string MDYinYang = "\uf67f"; public static readonly string MDYoutubePlay = "\uf5c3"; public static readonly string MDZipBox = "\uf5c4"; } }
chrfalch/NControl.Controls
NControl.Controls/NControl.Controls/FontMaterialDesignLabel.cs
C#
mit
107,267
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("001.TransportPrice")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("001.TransportPrice")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a9a00a78-475d-492a-9619-a6dadfd83266")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
yangra/SoftUni
ProgrammingBasics/03.SimpleConditions/001.TransportPrice/Properties/AssemblyInfo.cs
C#
mit
1,412
var game = new Phaser.Game(375, 667, Phaser.AUTO, 'gameDiv'); // var game = new Phaser.Game(720, 1280, Phaser.AUTO, 'gameDiv'); game.global = { taps: 0, enemyHP: 0, enemyHPTotal: 0, level: 1, enemyNumber: 1, coins: 0, player: { name: 'mr. hero', level: 1, skillLevel: [0, 0, 0, 0, 0, 0] } }; game.state.add('boot', bootState); game.state.add('load', loadState); game.state.add('menu', menuState); game.state.add('play', playState); game.state.start('boot');
kelvinblade/tap-titans-clone
js/game.js
JavaScript
mit
488
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2022 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <modules/fieldlinessequence/util/fieldlinesstate.h> #include <openspace/json.h> #include <openspace/util/time.h> #include <ghoul/fmt.h> #include <ghoul/logging/logmanager.h> #include <fstream> #include <iomanip> namespace { constexpr const char* _loggerCat = "FieldlinesState"; constexpr const int CurrentVersion = 0; using json = nlohmann::json; } // namespace namespace openspace { /** * Converts all glm::vec3 in _vertexPositions from spherical (radius, latitude, longitude) * coordinates into cartesian coordinates. The longitude and latitude coordinates are * expected to be in degrees. scale is an optional scaling factor. */ void FieldlinesState::convertLatLonToCartesian(float scale) { for (glm::vec3& p : _vertexPositions) { const float r = p.x * scale; const float lat = glm::radians(p.y); const float lon = glm::radians(p.z); const float rCosLat = r * cos(lat); p = glm::vec3(rCosLat * cos(lon), rCosLat* sin(lon), r * sin(lat)); } } void FieldlinesState::scalePositions(float scale) { for (glm::vec3& p : _vertexPositions) { p *= scale; } } bool FieldlinesState::loadStateFromOsfls(const std::string& pathToOsflsFile) { std::ifstream ifs(pathToOsflsFile, std::ifstream::binary); if (!ifs.is_open()) { LERROR("Couldn't open file: " + pathToOsflsFile); return false; } int binFileVersion; ifs.read(reinterpret_cast<char*>(&binFileVersion), sizeof(int)); switch (binFileVersion) { case 0: // No need to put everything in this scope now, as only version 0 exists! break; default: LERROR("VERSION OF BINARY FILE WAS NOT RECOGNIZED!"); return false; } // Define tmp variables to store meta data in size_t nLines; size_t nPoints; size_t nExtras; size_t byteSizeAllNames; // Read single value variables ifs.read(reinterpret_cast<char*>(&_triggerTime), sizeof(double)); ifs.read(reinterpret_cast<char*>(&_model), sizeof(int32_t)); ifs.read(reinterpret_cast<char*>(&_isMorphable), sizeof(bool)); ifs.read(reinterpret_cast<char*>(&nLines), sizeof(uint64_t)); ifs.read(reinterpret_cast<char*>(&nPoints), sizeof(uint64_t)); ifs.read(reinterpret_cast<char*>(&nExtras), sizeof(uint64_t)); ifs.read(reinterpret_cast<char*>(&byteSizeAllNames), sizeof(uint64_t)); _lineStart.resize(nLines); _lineCount.resize(nLines); _vertexPositions.resize(nPoints); _extraQuantities.resize(nExtras); _extraQuantityNames.resize(nExtras); // Read vertex position data ifs.read(reinterpret_cast<char*>(_lineStart.data()), sizeof(int32_t) * nLines); ifs.read(reinterpret_cast<char*>(_lineCount.data()), sizeof(uint32_t) * nLines); ifs.read( reinterpret_cast<char*>(_vertexPositions.data()), 3 * sizeof(float) * nPoints ); // Read all extra quantities for (std::vector<float>& vec : _extraQuantities) { vec.resize(nPoints); ifs.read(reinterpret_cast<char*>(vec.data()), sizeof(float) * nPoints); } // Read all extra quantities' names. Stored as multiple c-strings std::string allNamesInOne; std::vector<char> buffer(byteSizeAllNames); ifs.read(buffer.data(), byteSizeAllNames); allNamesInOne.assign(buffer.data(), byteSizeAllNames); size_t offset = 0; for (size_t i = 0; i < nExtras; ++i) { auto endOfVarName = allNamesInOne.find('\0', offset); endOfVarName -= offset; const std::string varName = allNamesInOne.substr(offset, endOfVarName); offset += varName.size() + 1; _extraQuantityNames[i] = varName; } return true; } bool FieldlinesState::loadStateFromJson(const std::string& pathToJsonFile, fls::Model Model, float coordToMeters) { // --------------------- ENSURE FILE IS VALID, THEN PARSE IT --------------------- // std::ifstream ifs(pathToJsonFile); if (!ifs.is_open()) { LERROR(fmt::format("FAILED TO OPEN FILE: {}", pathToJsonFile)); return false; } json jFile; ifs >> jFile; // -------------------------------------------------------------------------------- // _model = Model; const char* sData = "data"; const char* sTrace = "trace"; // ----- EXTRACT THE EXTRA QUANTITY NAMES & TRIGGER TIME (same for all lines) ----- // { const char* sTime = "time"; const json& jTmp = *(jFile.begin()); // First field line in the file _triggerTime = Time::convertTime(jTmp[sTime]); const char* sColumns = "columns"; const json::value_type& variableNameVec = jTmp[sTrace][sColumns]; const size_t nVariables = variableNameVec.size(); const size_t nPosComponents = 3; // x,y,z if (nVariables < nPosComponents) { LERROR( pathToJsonFile + ": Each field '" + sColumns + "' must contain the variables: 'x', 'y' and 'z' (order is important)." ); return false; } for (size_t i = nPosComponents ; i < nVariables ; ++i) { _extraQuantityNames.push_back(variableNameVec[i]); } } const size_t nExtras = _extraQuantityNames.size(); _extraQuantities.resize(nExtras); size_t lineStartIdx = 0; // Loop through all fieldlines for (json::iterator lineIter = jFile.begin(); lineIter != jFile.end(); ++lineIter) { // The 'data' field in the 'trace' variable contains all vertex positions and the // extra quantities. Each element is an array related to one vertex point. const std::vector<std::vector<float>>& jData = (*lineIter)[sTrace][sData]; const size_t nPoints = jData.size(); for (size_t j = 0; j < nPoints; ++j) { const std::vector<float>& variables = jData[j]; // Expects the x, y and z variables to be stored first! const size_t xIdx = 0; const size_t yIdx = 1; const size_t zIdx = 2; _vertexPositions.push_back( coordToMeters * glm::vec3( variables[xIdx], variables[yIdx], variables[zIdx] ) ); // Add the extra quantites. Stored in the same array as the x,y,z variables. // Hence index of the first extra quantity = 3 for (size_t xtraIdx = 3, k = 0 ; k < nExtras; ++k, ++xtraIdx) { _extraQuantities[k].push_back(variables[xtraIdx]); } } _lineCount.push_back(static_cast<GLsizei>(nPoints)); _lineStart.push_back(static_cast<GLsizei>(lineStartIdx)); lineStartIdx += nPoints; } return true; } /** * \param absPath must be the path to the file (incl. filename but excl. extension!) * Directory must exist! File is created (or overwritten if already existing). * File is structured like this: (for version 0) * 0. int - version number of binary state file! (in case something * needs to be altered in the future, then increase * CurrentVersion) * 1. double - _triggerTime * 2. int - _model * 3. bool - _isMorphable * 4. size_t - Number of lines in the state == _lineStart.size() * == _lineCount.size() * 5. size_t - Total number of vertex points == _vertexPositions.size() * == _extraQuantities[i].size() * 6. size_t - Number of extra quantites == _extraQuantities.size() * == _extraQuantityNames.size() * 7. site_t - Number of total bytes that ALL _extraQuantityNames * consists of (Each such name is stored as a c_str which * means it ends with the null char '\0' ) * 7. std::vector<GLint> - _lineStart * 8. std::vector<GLsizei> - _lineCount * 9. std::vector<glm::vec3> - _vertexPositions * 10. std::vector<float> - _extraQuantities * 11. array of c_str - Strings naming the extra quantities (elements of * _extraQuantityNames). Each string ends with null char '\0' */ void FieldlinesState::saveStateToOsfls(const std::string& absPath) { // ------------------------------- Create the file ------------------------------- // std::string pathSafeTimeString = std::string(Time(_triggerTime).ISO8601()); pathSafeTimeString.replace(13, 1, "-"); pathSafeTimeString.replace(16, 1, "-"); pathSafeTimeString.replace(19, 1, "-"); const std::string& fileName = pathSafeTimeString + ".osfls"; std::ofstream ofs(absPath + fileName, std::ofstream::binary | std::ofstream::trunc); if (!ofs.is_open()) { LERROR(fmt::format( "Failed to save state to binary file: {}{}", absPath, fileName )); return; } // --------- Add each string of _extraQuantityNames into one long string --------- // std::string allExtraQuantityNamesInOne = ""; for (const std::string& str : _extraQuantityNames) { allExtraQuantityNamesInOne += str + '\0'; // Add null char '\0' for easier reading } const size_t nLines = _lineStart.size(); const size_t nPoints = _vertexPositions.size(); const size_t nExtras = _extraQuantities.size(); const size_t nStringBytes = allExtraQuantityNamesInOne.size(); //----------------------------- WRITE EVERYTHING TO FILE ----------------------------- // VERSION OF BINARY FIELDLINES STATE FILE - IN CASE STRUCTURE CHANGES IN THE FUTURE ofs.write(reinterpret_cast<const char*>(&CurrentVersion), sizeof(int)); //-------------------- WRITE META DATA FOR STATE -------------------------------- ofs.write(reinterpret_cast<const char*>(&_triggerTime), sizeof(_triggerTime)); ofs.write(reinterpret_cast<const char*>(&_model), sizeof(int32_t)); ofs.write(reinterpret_cast<const char*>(&_isMorphable), sizeof(bool)); ofs.write(reinterpret_cast<const char*>(&nLines), sizeof(uint64_t)); ofs.write(reinterpret_cast<const char*>(&nPoints), sizeof(uint64_t)); ofs.write(reinterpret_cast<const char*>(&nExtras), sizeof(uint64_t)); ofs.write(reinterpret_cast<const char*>(&nStringBytes), sizeof(uint64_t)); //---------------------- WRITE ALL ARRAYS OF DATA -------------------------------- ofs.write(reinterpret_cast<char*>(_lineStart.data()), sizeof(int32_t) * nLines); ofs.write(reinterpret_cast<char*>(_lineCount.data()), sizeof(uint32_t) * nLines); ofs.write( reinterpret_cast<char*>(_vertexPositions.data()), 3 * sizeof(float) * nPoints ); // Write the data for each vector in _extraQuantities for (std::vector<float>& vec : _extraQuantities) { ofs.write(reinterpret_cast<char*>(vec.data()), sizeof(float) * nPoints); } ofs.write(allExtraQuantityNamesInOne.c_str(), nStringBytes); } // TODO: This should probably be rewritten, but this is the way the files were structured // by CCMC // Structure of File! NO TRAILING COMMAS ALLOWED! // Additional info can be stored within each line as the code only extracts the keys it // needs (time, trace & data) // The key/name of each line ("0" & "1" in the example below) is arbitrary // { // "0":{ // "time": "YYYY-MM-DDTHH:MM:SS.XXX", // "trace": { // "columns": ["x","y","z","s","temperature","rho","j_para"], // "data": [[8.694,127.853,115.304,0.0,0.047,9.249,-5e-10],..., // [8.698,127.253,114.768,0.800,0.0,9.244,-5e-10]] // }, // }, // "1":{ // "time": "YYYY-MM-DDTHH:MM:SS.XXX // "trace": { // "columns": ["x","y","z","s","temperature","rho","j_para"], // "data": [[8.694,127.853,115.304,0.0,0.047,9.249,-5e-10],..., // [8.698,127.253,114.768,0.800,0.0,9.244,-5e-10]] // }, // } // } void FieldlinesState::saveStateToJson(const std::string& absPath) { // Create the file const char* ext = ".json"; std::ofstream ofs(absPath + ext, std::ofstream::trunc); if (!ofs.is_open()) { LERROR(fmt::format( "Failed to save state to json file at location: {}{}", absPath, ext )); return; } LINFO(fmt::format("Saving fieldline state to: {}{}", absPath, ext)); json jColumns = { "x", "y", "z" }; for (const std::string& s : _extraQuantityNames) { jColumns.push_back(s); } json jFile; std::string_view timeStr = Time(_triggerTime).ISO8601(); const size_t nLines = _lineStart.size(); // const size_t nPoints = _vertexPositions.size(); const size_t nExtras = _extraQuantities.size(); size_t pointIndex = 0; for (size_t lineIndex = 0; lineIndex < nLines; ++lineIndex) { json jData = json::array(); for (GLsizei i = 0; i < _lineCount[lineIndex]; i++, ++pointIndex) { const glm::vec3 pos = _vertexPositions[pointIndex]; json jDataElement = { pos.x, pos.y, pos.z }; for (size_t extraIndex = 0; extraIndex < nExtras; ++extraIndex) { jDataElement.push_back(_extraQuantities[extraIndex][pointIndex]); } jData.push_back(jDataElement); } jFile[std::to_string(lineIndex)] = { { "time", timeStr }, { "trace", { { "columns", jColumns }, { "data", jData } }} }; } //----------------------------- WRITE EVERYTHING TO FILE ----------------------------- const int indentationSpaces = 2; ofs << std::setw(indentationSpaces) << jFile << std::endl; LINFO(fmt::format("Saved fieldline state to: {}{}", absPath, ext)); } void FieldlinesState::setModel(fls::Model m) { _model = m; } void FieldlinesState::setTriggerTime(double t) { _triggerTime = t; } // Returns one of the extra quantity vectors, _extraQuantities[index]. // If index is out of scope an empty vector is returned and the referenced bool is false. std::vector<float> FieldlinesState::extraQuantity(size_t index, bool& isSuccessful) const { if (index < _extraQuantities.size()) { isSuccessful = true; return _extraQuantities[index]; } else { isSuccessful = false; LERROR("Provided Index was out of scope!"); return {}; } } // Moves the points in @param line over to _vertexPositions and updates // _lineStart & _lineCount accordingly. void FieldlinesState::addLine(std::vector<glm::vec3>& line) { const size_t nNewPoints = line.size(); const size_t nOldPoints = _vertexPositions.size(); _lineStart.push_back(static_cast<GLint>(nOldPoints)); _lineCount.push_back(static_cast<GLsizei>(nNewPoints)); _vertexPositions.reserve(nOldPoints + nNewPoints); _vertexPositions.insert( _vertexPositions.end(), std::make_move_iterator(line.begin()), std::make_move_iterator(line.end()) ); line.clear(); } void FieldlinesState::appendToExtra(size_t idx, float val) { _extraQuantities[idx].push_back(val); } void FieldlinesState::setExtraQuantityNames(std::vector<std::string> names) { _extraQuantityNames = std::move(names); _extraQuantities.resize(_extraQuantityNames.size()); } const std::vector<std::vector<float>>& FieldlinesState::extraQuantities() const { return _extraQuantities; } const std::vector<std::string>& FieldlinesState::extraQuantityNames() const { return _extraQuantityNames; } const std::vector<GLsizei>& FieldlinesState::lineCount() const { return _lineCount; } const std::vector<GLint>& FieldlinesState::lineStart() const { return _lineStart; } fls::Model FieldlinesState::FieldlinesState::model() const { return _model; } size_t FieldlinesState::nExtraQuantities() const { return _extraQuantities.size(); } double FieldlinesState::triggerTime() const { return _triggerTime; } const std::vector<glm::vec3>& FieldlinesState::vertexPositions() const { return _vertexPositions; } } // namespace openspace
OpenSpace/OpenSpace
modules/fieldlinessequence/util/fieldlinesstate.cpp
C++
mit
18,472
//using Microsoft.CodeAnalysis; //using Microsoft.CodeAnalysis.Diagnostics; //using System.Collections.Immutable; //namespace RefactoringEssentials.CSharp.Diagnostics //{ // [DiagnosticAnalyzer(LanguageNames.CSharp)] // [NotPortedYet] // public class ReferenceEqualsWithValueTypeAnalyzer : DiagnosticAnalyzer // { // static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( // CSharpDiagnosticIDs.ReferenceEqualsWithValueTypeAnalyzerID, // GettextCatalog.GetString("Check for reference equality instead"), // GettextCatalog.GetString("'Object.ReferenceEquals' is always false because it is called with value type"), // DiagnosticAnalyzerCategories.PracticesAndImprovements, // DiagnosticSeverity.Info, // isEnabledByDefault: true, // helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ReferenceEqualsWithValueTypeAnalyzerID) // ); // public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(descriptor); // public override void Initialize(AnalysisContext context) // { // context.EnableConcurrentExecution(); // context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); // //context.RegisterSyntaxNodeAction( // // (nodeContext) => { // // Diagnostic diagnostic; // // if (TryGetDiagnostic (nodeContext, out diagnostic)) { // // nodeContext.ReportDiagnostic(diagnostic); // // } // // }, // // new SyntaxKind[] { SyntaxKind.None } // //); // } // static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic) // { // diagnostic = default(Diagnostic); // //var node = nodeContext.Node as ; // //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ()); // //return true; // return false; // } // // class GatherVisitor : GatherVisitorBase<ReferenceEqualsWithValueTypeAnalyzer> // // { // // public GatherVisitor(SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken) // // : base (semanticModel, addDiagnostic, cancellationToken) // // { // // } // //// public override void VisitInvocationExpression(InvocationExpression invocationExpression) // //// { // //// base.VisitInvocationExpression(invocationExpression); // //// // //// // Quickly determine if this invocation is eligible to speed up the inspector // //// var nameToken = invocationExpression.Target.GetChildByRole(Roles.Identifier); // //// if (nameToken.Name != "ReferenceEquals") // //// return; // //// // //// var resolveResult = ctx.Resolve(invocationExpression) as InvocationResolveResult; // //// if (resolveResult == null || // //// resolveResult.Member.DeclaringTypeDefinition == null || // //// resolveResult.Member.DeclaringTypeDefinition.KnownTypeCode != KnownTypeCode.Object || // //// resolveResult.Member.Name != "ReferenceEquals" || // //// invocationExpression.Arguments.All(arg => ctx.Resolve(arg).Type.IsReferenceType ?? true)) // //// return; // //// // //// var action1 = new CodeAction(ctx.TranslateString("Replace expression with 'false'"), // //// script => script.Replace(invocationExpression, new PrimitiveExpression(false)), invocationExpression); // //// // //// var action2 = new CodeAction(ctx.TranslateString("Use Equals()"), // //// script => script.Replace(invocationExpression.Target, // //// new PrimitiveType("object").Member("Equals")), invocationExpression); // //// // //// AddDiagnosticAnalyzer(new CodeIssue(invocationExpression, // //// ctx.TranslateString("'Object.ReferenceEquals' is always false because it is called with value type"), // //// new [] { action1, action2 })); // //// } // // } // } //}
icsharpcode/RefactoringEssentials
RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/ReferenceEqualsWithValueTypeAnalyzer.cs
C#
mit
4,303
/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#!/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ // connection: 'localDiskDb', /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ migrate: 'safe', schema: true, /** * This method adds records to the database * * To use add a variable 'seedData' in your model and call the * method in the bootstrap.js file */ seed: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); if (!self.seedData) { sails.log.debug('No data avaliable to seed ' + modelName); callback(); return; } self.count().exec(function (err, count) { if (!err && count === 0) { sails.log.debug('Seeding ' + modelName + '...'); if (self.seedData instanceof Array) { self.seedArray(callback); }else{ self.seedObject(callback); } } else { sails.log.debug(modelName + ' had models, so no seed needed'); callback(); } }); }, seedArray: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); self.createEach(self.seedData).exec(function (err, results) { if (err) { sails.log.debug(err); callback(); } else { sails.log.debug(modelName + ' seed planted'); callback(); } }); }, seedObject: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); self.create(self.seedData).exec(function (err, results) { if (err) { sails.log.debug(err); callback(); } else { sails.log.debug(modelName + ' seed planted'); callback(); } }); } };
pantsel/koutroclean
config/models.js
JavaScript
mit
3,129
'use strict'; const mongoose = require('mongoose-q')(require('mongoose')); const League = mongoose.model('League'); function LeagueHandler (leagueService) { this.service = leagueService; } LeagueHandler.prototype.getLeaguesByCountry = function(req, res, next) { return this.service.getByCountry(req.params.country) .then(function(countryLeagues) { return res.status(200).send(countryLeagues) }) .catch(function(err) { next(err) }) }; module.exports = LeagueHandler;
gaskar/fanscount
api/v1/handlers/league.js
JavaScript
mit
533
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ProgramTree; namespace SimpleLang.Visitors { public class CommonlyUsedVarVisitor : AutoVisitor { public string mostCommonlyUsedVar() { throw new NotImplementedException(); } } }
czen/MMCS_CS311
Module7/Visitors/CommonlyUsedVarVisitor.cs
C#
mit
322
using System; namespace Zergatul.Security.Paddings { class PKCS7Padding : SymmetricPadding { public override byte[] GetPadding(int position, int blockSize) { if (position < 0 || position >= blockSize) throw new InvalidOperationException(); byte[] padding = new byte[blockSize - position]; for (int i = 0; i < padding.Length; i++) padding[i] = (byte)padding.Length; return padding; } public override int RemovePadding(byte[] block, int offset, int length) { int fill = block[offset + length - 1]; if (fill > length) return -1; for (int i = offset + length - fill; i > offset + length; i++) if (block[i] != fill) return -1; return length - fill; } } }
Zergatul/ZergatulLib
Zergatul/Security/Paddings/PKCS7Padding.cs
C#
mit
898
app.controller('JoinGameController', function ($scope, $location, authorization, identity, ticTacToeData, notifier) { 'use strict'; $scope.joinGame = function (gameId) { if (identity.isAuthenticated() === true) { ticTacToeData.joinGame(authorization.getAuthorizationHeader(), gameId) .then(function () { notifier.success('Game joined!'); }, function () { notifier.error('Invalid data!'); }); } else { notifier.error('Please login!'); } }; $scope.joinRandomGame = function () { if (identity.isAuthenticated() === true) { ticTacToeData.joinRandomGame(authorization.getAuthorizationHeader()) .then(function () { notifier.success('Game joined!'); }); } else { notifier.error('Please login!'); } } });
svilenbonev/TelerikAcademy
JavaScript-SPA/Tic-Tac-Toe-Game/TicTacToe.Client/app/js/controllers/JoinGameController.js
JavaScript
mit
956
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CityDemo")] [assembly: AssemblyProduct("CityDemo")] [assembly: AssemblyDescription("")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. Only Windows // assemblies support COM. [assembly: ComVisible(false)] // On Windows, the following GUID is for the ID of the typelib if this // project is exposed to COM. On other platforms, it unique identifies the // title storage container when deploying this assembly to the device. [assembly: Guid("6e16bf7a-b58e-47dc-b233-a0c2e87ba3bb")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")]
robnils/Samples
Graphics/CityDemo/CityDemo/CityDemo/Properties/AssemblyInfo.cs
C#
mit
1,321
# Inspired from VecEnv from OpenAI Baselines class VecEnv(object): """ An abstract asynchronous, vectorized environment. """ def __init__(self, num_envs, observation_space, action_space): self.num_envs = num_envs self.observation_space = observation_space self.action_space = action_space def reset(self): """ Reset all the environments and return an array of observations, or a tuple of observation arrays. If step_async is still doing work, that work will be cancelled and step_wait() should not be called until step_async() is invoked again. """ pass def step_async(self, actions): """ Tell all the environments to start taking a step with the given actions. Call step_wait() to get the results of the step. You should not call this if a step_async run is already pending. """ raise NotImplementedError() def step_wait(self): """ Wait for the step taken with step_async(). Returns (obs, rews, dones, infos): - obs: an array of observations, or a tuple of arrays of observations. - rews: an array of rewards - dones: an array of "episode done" booleans - infos: a sequence of info objects """ raise NotImplementedError() def close(self): """ Clean up the environments' resources. """ raise NotImplementedError() def step(self, actions): self.step_async(actions) return self.step_wait() def render(self, mode='human'): logger.warn('Render not defined for %s' % self) def seed(self, i): raise NotImplementedError() @property def unwrapped(self): if isinstance(self, VecEnvWrapper): return self.venv.unwrapped else: return self class CloudpickleWrapper(object): """ Uses cloudpickle to serialize contents (otherwise multiprocessing tries to use pickle) """ def __init__(self, x): self.x = x def __getstate__(self): import cloudpickle return cloudpickle.dumps(self.x) def __setstate__(self, ob): import pickle self.x = pickle.loads(ob)
matthiasplappert/keras-rl
rl/common/vec_env/__init__.py
Python
mit
2,310
/* The MIT License (MIT) * * Copyright (c) 2015 Reinventing Geospatial, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.rgi.suite.tilestoreadapter; import java.io.File; import java.util.Collection; import javax.swing.JComponent; import com.rgi.store.tiles.TileStoreException; import com.rgi.store.tiles.TileStoreReader; import com.rgi.store.tiles.TileStoreWriter; import com.rgi.suite.Settings; /** * Abstract base class for UI adapters for tile store writers * * @author Luke Lambert * */ public abstract class TileStoreWriterAdapter { /** * Constructor * * @param settings * Handle to the application's settings object */ public TileStoreWriterAdapter(final Settings settings) { this.settings = settings; } /** * Use an input file to hint at possible values for the UI elements * * @param inputFile * Input file * @throws TileStoreException * if there's a problem with the tile store */ public abstract void hint(final File inputFile) throws TileStoreException; /** * Provides UI elements to use as input to construct a tile store writer * * @return Returns a matrix of UI elements to build an input form that will * provide the inputs to build a corresponding tile store * writer */ public abstract Collection<Collection<JComponent>> getWriterParameterControls(); /** * Constructs a tile store writer based on the values of the UI elements * * @param tileStoreReader * Tile store reader that may be required to know how to build * a tile scheme for our new tile store writer * @return A {@link TileStoreWriter} * @throws TileStoreException * if construction of the tile store reader fails */ public abstract TileStoreWriter getTileStoreWriter(final TileStoreReader tileStoreReader) throws TileStoreException; /** * In the case of a failed tile store operation (e.g. packaging, or tiling) * call this method to clean up the process started by calling {@link * #getTileStoreWriter(TileStoreReader)} * * @throws TileStoreException * if tile store removal fails */ public abstract void removeStore() throws TileStoreException; protected final Settings settings; }
GitHubRGI/swagd
RGISuite/src/main/java/com/rgi/suite/tilestoreadapter/TileStoreWriterAdapter.java
Java
mit
3,466
import http from 'node:http'; import {expectType} from 'tsd'; import decompressResponse, {UncompressedIncomingMessage} from './index.js'; http.get('localhost', response => { expectType<UncompressedIncomingMessage>(decompressResponse(response)); });
sindresorhus/unzip-response
index.test-d.ts
TypeScript
mit
251
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "bitcoingui.h" #include "csvmodelwriter.h" #include "editaddressdialog.h" #include "guiutil.h" #include "platformstyle.h" #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> AddressBookPage::AddressBookPage(const PlatformStyle *platformStyle, Mode mode, Tabs tab, QWidget *parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), mode(mode), tab(tab) { ui->setupUi(this); if (!platformStyle->getImagesOnButtons()) { ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); } else { ui->newAddress->setIcon(platformStyle->SingleColorIcon(":/icons/add")); ui->copyAddress->setIcon(platformStyle->SingleColorIcon(":/icons/editcopy")); ui->deleteAddress->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); ui->exportButton->setIcon(platformStyle->SingleColorIcon(":/icons/export")); } switch(mode) { case ForSelection: switch(tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); break; case ForEditing: switch(tab) { case SendingTab: setWindowTitle(tr("Sending addresses")); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break; } break; } switch(tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your Aurumcoin address for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your Aurumcoin address for receiving payments. It is recommended to use a new receiving address for each transaction.")); ui->deleteAddress->setVisible(false); break; } // Context menu actions QAction *copyAddressAction = new QAction(tr("&Copy Address"), this); QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *editAction = new QAction(tr("&Edit"), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if(tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *model) { this->model = model; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch(tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!model) return; if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_newAddress_clicked() { if(!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); break; } ui->copyAddress->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); Q_FOREACH (const QModelIndex& index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), tr("There was an error trying to save the address list to %1. Please try again.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
rkarpuzov/Aurumcoin-0.12
src/qt/addressbookpage.cpp
C++
mit
10,106
module FlipTheSwitch class Environment < Struct.new(:name, :features, :parent_name) def initialize(name, features = [], parent_name = nil) super(name, features, parent_name) end def has_parent? parent_name end end end
michaelengland/FlipTheSwitch
lib/flip_the_switch/environment.rb
Ruby
mit
251
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="MVC com CodeIgniter 3 e Bootstrap 3"> <meta name="author" content="Marcelo Garbin"> <title>PHP e MVC com CodeIgniter: Desenvolvimento Web com Framework</title> <!-- Bootstrap core CSS --> <link href="<?php echo base_url('assets/css/bootstrap.min.css'); ?>" rel="stylesheet"> <!-- Custom styles for this template --> <link href="<?php echo base_url('assets/css/style.css'); ?>" rel="stylesheet"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- Fixed navbar --> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?php echo base_url(); ?>"><span class="glyphicon glyphicon-fire"></span> PHP e MVC com CodeIgniter e Bootstrap</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="<?php echo base_url('sobre'); ?>"><span class="glyphicon glyphicon-star-empty"></span> Sobre</a></li> </ul> </div><!--/.nav-collapse --> </div> </nav> <!-- Begin page content --> <div class="container">
marcelogarbin/mvc-com-ci-e-bootstrap
application/views/template/header.php
PHP
mit
1,949
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { workbenchInstantiationService as browserWorkbenchInstantiationService, ITestInstantiationService, TestLifecycleService, TestFilesConfigurationService, TestFileService, TestFileDialogService, TestPathService } from 'vs/workbench/test/browser/workbenchTestServices'; import { Event } from 'vs/base/common/event'; import { ISharedProcessService } from 'vs/platform/ipc/electron-browser/sharedProcessService'; import { NativeWorkbenchEnvironmentService, INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-browser/environmentService'; import { NativeTextFileService, EncodingOracle, IEncodingOverride } from 'vs/workbench/services/textfile/electron-browser/nativeTextFileService'; import { IElectronService } from 'vs/platform/electron/node/electron'; import { INativeOpenDialogOptions } from 'vs/platform/dialogs/node/dialogs'; import { FileOperationError, IFileService } from 'vs/platform/files/common/files'; import { IUntitledTextEditorService } from 'vs/workbench/services/untitled/common/untitledTextEditorService'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IDialogService, IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfigurationService'; import { IProductService } from 'vs/platform/product/common/productService'; import { IFilesConfigurationService } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService'; import { ITextModelService } from 'vs/editor/common/services/resolverService'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { URI } from 'vs/base/common/uri'; import { IReadTextFileOptions, ITextFileStreamContent, ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel'; import { IOpenEmptyWindowOptions, IWindowOpenable, IOpenWindowOptions } from 'vs/platform/windows/common/windows'; import { parseArgs, OPTIONS } from 'vs/platform/environment/node/argv'; import { LogLevel, ILogService } from 'vs/platform/log/common/log'; import { IPathService } from 'vs/workbench/services/path/common/pathService'; import { IWorkingCopyFileService } from 'vs/workbench/services/workingCopy/common/workingCopyFileService'; import { UTF16le, UTF16be, UTF8_with_bom } from 'vs/base/node/encoding'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl'; import { IBackupFileService } from 'vs/workbench/services/backup/common/backup'; import { NodeTestBackupFileService } from 'vs/workbench/services/backup/test/electron-browser/backupFileService.test'; import { IWorkingCopyService } from 'vs/workbench/services/workingCopy/common/workingCopyService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { INativeWindowConfiguration, IOpenedWindow } from 'vs/platform/windows/node/window'; import { TestContextService } from 'vs/workbench/test/common/workbenchTestServices'; export const TestWindowConfiguration: INativeWindowConfiguration = { windowId: 0, machineId: 'testMachineId', sessionId: 'testSessionId', logLevel: LogLevel.Error, mainPid: 0, partsSplashPath: '', appRoot: '', userEnv: {}, execPath: process.execPath, perfEntries: [], ...parseArgs(process.argv, OPTIONS) }; export const TestEnvironmentService = new NativeWorkbenchEnvironmentService(TestWindowConfiguration, process.execPath); export class TestTextFileService extends NativeTextFileService { private resolveTextContentError!: FileOperationError | null; constructor( @IFileService protected fileService: IFileService, @IUntitledTextEditorService untitledTextEditorService: IUntitledTextEditorService, @ILifecycleService lifecycleService: ILifecycleService, @IInstantiationService instantiationService: IInstantiationService, @IModelService modelService: IModelService, @IWorkbenchEnvironmentService environmentService: INativeWorkbenchEnvironmentService, @IDialogService dialogService: IDialogService, @IFileDialogService fileDialogService: IFileDialogService, @ITextResourceConfigurationService textResourceConfigurationService: ITextResourceConfigurationService, @IProductService productService: IProductService, @IFilesConfigurationService filesConfigurationService: IFilesConfigurationService, @ITextModelService textModelService: ITextModelService, @ICodeEditorService codeEditorService: ICodeEditorService, @IPathService athService: IPathService, @IWorkingCopyFileService workingCopyFileService: IWorkingCopyFileService, @ILogService logService: ILogService ) { super( fileService, untitledTextEditorService, lifecycleService, instantiationService, modelService, environmentService, dialogService, fileDialogService, textResourceConfigurationService, productService, filesConfigurationService, textModelService, codeEditorService, athService, workingCopyFileService, logService ); } setResolveTextContentErrorOnce(error: FileOperationError): void { this.resolveTextContentError = error; } async readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent> { if (this.resolveTextContentError) { const error = this.resolveTextContentError; this.resolveTextContentError = null; throw error; } const content = await this.fileService.readFileStream(resource, options); return { resource: content.resource, name: content.name, mtime: content.mtime, ctime: content.ctime, etag: content.etag, encoding: 'utf8', value: await createTextBufferFactoryFromStream(content.value), size: 10 }; } } export class TestNativeTextFileServiceWithEncodingOverrides extends NativeTextFileService { private _testEncoding: TestEncodingOracle | undefined; get encoding(): TestEncodingOracle { if (!this._testEncoding) { this._testEncoding = this._register(this.instantiationService.createInstance(TestEncodingOracle)); } return this._testEncoding; } } class TestEncodingOracle extends EncodingOracle { protected get encodingOverrides(): IEncodingOverride[] { return [ { extension: 'utf16le', encoding: UTF16le }, { extension: 'utf16be', encoding: UTF16be }, { extension: 'utf8bom', encoding: UTF8_with_bom } ]; } protected set encodingOverrides(overrides: IEncodingOverride[]) { } } export class TestSharedProcessService implements ISharedProcessService { _serviceBrand: undefined; getChannel(channelName: string): any { return undefined; } registerChannel(channelName: string, channel: any): void { } async toggleSharedProcessWindow(): Promise<void> { } async whenSharedProcessReady(): Promise<void> { } } export class TestElectronService implements IElectronService { _serviceBrand: undefined; onWindowOpen: Event<number> = Event.None; onWindowMaximize: Event<number> = Event.None; onWindowUnmaximize: Event<number> = Event.None; onWindowFocus: Event<number> = Event.None; onWindowBlur: Event<number> = Event.None; windowCount = Promise.resolve(1); getWindowCount(): Promise<number> { return this.windowCount; } async getWindows(): Promise<IOpenedWindow[]> { return []; } async getActiveWindowId(): Promise<number | undefined> { return undefined; } openWindow(options?: IOpenEmptyWindowOptions): Promise<void>; openWindow(toOpen: IWindowOpenable[], options?: IOpenWindowOptions): Promise<void>; openWindow(arg1?: IOpenEmptyWindowOptions | IWindowOpenable[], arg2?: IOpenWindowOptions): Promise<void> { throw new Error('Method not implemented.'); } async toggleFullScreen(): Promise<void> { } async handleTitleDoubleClick(): Promise<void> { } async isMaximized(): Promise<boolean> { return true; } async maximizeWindow(): Promise<void> { } async unmaximizeWindow(): Promise<void> { } async minimizeWindow(): Promise<void> { } async focusWindow(options?: { windowId?: number | undefined; } | undefined): Promise<void> { } async showMessageBox(options: Electron.MessageBoxOptions): Promise<Electron.MessageBoxReturnValue> { throw new Error('Method not implemented.'); } async showSaveDialog(options: Electron.SaveDialogOptions): Promise<Electron.SaveDialogReturnValue> { throw new Error('Method not implemented.'); } async showOpenDialog(options: Electron.OpenDialogOptions): Promise<Electron.OpenDialogReturnValue> { throw new Error('Method not implemented.'); } async pickFileFolderAndOpen(options: INativeOpenDialogOptions): Promise<void> { } async pickFileAndOpen(options: INativeOpenDialogOptions): Promise<void> { } async pickFolderAndOpen(options: INativeOpenDialogOptions): Promise<void> { } async pickWorkspaceAndOpen(options: INativeOpenDialogOptions): Promise<void> { } async showItemInFolder(path: string): Promise<void> { } async setRepresentedFilename(path: string): Promise<void> { } async setDocumentEdited(edited: boolean): Promise<void> { } async openExternal(url: string): Promise<boolean> { return false; } async updateTouchBar(): Promise<void> { } async newWindowTab(): Promise<void> { } async showPreviousWindowTab(): Promise<void> { } async showNextWindowTab(): Promise<void> { } async moveWindowTabToNewWindow(): Promise<void> { } async mergeAllWindowTabs(): Promise<void> { } async toggleWindowTabsBar(): Promise<void> { } async relaunch(options?: { addArgs?: string[] | undefined; removeArgs?: string[] | undefined; } | undefined): Promise<void> { } async reload(): Promise<void> { } async closeWindow(): Promise<void> { } async closeWindowById(): Promise<void> { } async quit(): Promise<void> { } async openDevTools(options?: Electron.OpenDevToolsOptions | undefined): Promise<void> { } async toggleDevTools(): Promise<void> { } async startCrashReporter(options: Electron.CrashReporterStartOptions): Promise<void> { } async resolveProxy(url: string): Promise<string | undefined> { return undefined; } } export function workbenchInstantiationService(): ITestInstantiationService { const instantiationService = browserWorkbenchInstantiationService({ textFileService: insta => <ITextFileService>insta.createInstance(TestTextFileService), pathService: insta => <IPathService>insta.createInstance(TestNativePathService) }); instantiationService.stub(IElectronService, new TestElectronService()); return instantiationService; } export class TestServiceAccessor { constructor( @ILifecycleService public lifecycleService: TestLifecycleService, @ITextFileService public textFileService: TestTextFileService, @IFilesConfigurationService public filesConfigurationService: TestFilesConfigurationService, @IWorkspaceContextService public contextService: TestContextService, @IModelService public modelService: ModelServiceImpl, @IFileService public fileService: TestFileService, @IElectronService public electronService: TestElectronService, @IFileDialogService public fileDialogService: TestFileDialogService, @IBackupFileService public backupFileService: NodeTestBackupFileService, @IWorkingCopyService public workingCopyService: IWorkingCopyService, @IEditorService public editorService: IEditorService ) { } } export class TestNativePathService extends TestPathService { _serviceBrand: undefined; constructor(@IWorkbenchEnvironmentService environmentService: INativeWorkbenchEnvironmentService) { super(environmentService.userHome); } }
the-ress/vscode
src/vs/workbench/test/electron-browser/workbenchTestServices.ts
TypeScript
mit
12,175
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateReportsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('reports', function($table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->string('ip_address', 45); //The one who reported... $table->text('reason'); $table->timestamps(); $table->softDeletes(); $table->foreign('user_id')->references('id')->on('users'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('reports'); } }
murum/murum_stuff_snap
app/database/migrations/2014_08_09_094324_create_reports_table.php
PHP
mit
683
#include <iostream> using namespace std; main(){ char palavra[] = "."; cin.getline(palavra, 10, '\n'); // irá ler apenas 10 caracteres e vai ser delimitado até encontrar a quebra de linha cout << endl << palavra << endl; }
carlosvilela/Funcoes-Diversas
Cplusplus/CIN.GETLINE-leitura-delimitada.cpp
C++
mit
264
'use strict'; function Level(args) { if(!(this instanceof Level)) return new Level(args); this.context = args.context; this.player = args.player; this.gameplayObjects = args.gameplayObjects; this.outcomeListeners = []; this.finalMessageListeners = []; this.respawnInfoListeners = []; this.victoryMessages = args.victoryMessages; this.failureMessages = args.failureMessages; this.isPaused = true; this.isFinished = false; this.handleRespawnInfo(args.respawnInfo); this.player.setParentLevel(this); this.gameplayObjects.forEach(o => o.beginObservingPlayer(this.player)); } Level.prototype.draw = function() { this.context.clearRect(0, 0, this.context.canvas.width, this.context.canvas.height); this.gameplayObjects.forEach(o => o.draw(this.context)); this.player.draw(this.context); } Level.prototype.update = function(dt) { this.player.update(dt); } Level.prototype.frame = function(dt) { this.update(dt); this.draw(); } Level.prototype.startGameLoop = function() { const gameLoopFrame = now => { if(!this.isPaused) { const dt = now - this.lastFrameTime; this.frame(dt); window.requestAnimationFrame(gameLoopFrame); } this.lastFrameTime = now; } this.isPaused = false; this.lastFrameTime = performance.now(); window.requestAnimationFrame(gameLoopFrame); } Level.prototype.pauseGameLoop = function() { this.isPaused = true; } Level.prototype.addOutcomeListener = function(listener) { this.outcomeListeners.push(listener); } Level.prototype.addFinalMessageListener = function(listener) { this.finalMessageListeners.push(listener); } Level.prototype.addRespawnInfoListener = function(listener) { this.respawnInfoListeners.push(listener); } Level.prototype.generateRespawnInfo = function() { return this.player.generateRespawnInfo(); } Level.prototype.handleRespawnInfo = function(respawnInfo) { this.player.handleRespawnInfo(respawnInfo); } Level.prototype.win = function() { this.finishWithOutcome(true); } Level.prototype.lose = function() { this.finishWithOutcome(false); } Level.prototype.finishWithOutcome = function(outcome) { if(this.isFinished) return; this.isFinished = true; this.pauseGameLoop(); this.player.stop(); this.outcomeListeners.forEach(listener => listener(outcome)); const finalMessage = this.getMessageForOutcome(outcome); this.finalMessageListeners.forEach(listener => listener(finalMessage)); if(!outcome) { const respawnInfo = this.generateRespawnInfo(); Object.freeze(respawnInfo); this.respawnInfoListeners.forEach(listener => listener(respawnInfo)); } } Level.prototype.getMessageForOutcome = function(outcome) { if(outcome) return mathUtils.randomArrayElement(this.victoryMessages); else return mathUtils.randomArrayElement(this.failureMessages); }
djsns/warp
scripts/level.js
JavaScript
mit
2,837
EGA2RGB = [ (0x00, 0x00, 0x00), (0x00, 0x00, 0xAA), (0x00, 0xAA, 0x00), (0x00, 0xAA, 0xAA), (0xAA, 0x00, 0x00), (0xAA, 0x00, 0xAA), (0xAA, 0x55, 0x00), (0xAA, 0xAA, 0xAA), (0x55, 0x55, 0x55), (0x55, 0x55, 0xFF), (0x55, 0xFF, 0x55), (0x55, 0xFF, 0xFF), (0xFF, 0x55, 0x55), (0xFF, 0x55, 0xFF), (0xFF, 0xFF, 0x55), (0xFF, 0xFF, 0xFF), ] def load_shapes(): shapes = [] bytes = open("ULT/SHAPES.EGA").read() for i in range(256): shape = [] for j in range(16): for k in range(8): d = ord(bytes[k + 8 * j + 128 * i]) a, b = divmod(d, 16) shape.append(EGA2RGB[a]) shape.append(EGA2RGB[b]) shapes.append(shape) return shapes
jtauber/ultima4
shapes.py
Python
mit
800
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("PaVe")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PaVe")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("b6e5fdd5-71de-45bd-932a-ace7dc3ade9f")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
taknil/aspostfachverwaltung
Projekt/PaVe/Properties/AssemblyInfo.cs
C#
mit
1,490
package me.rbrickis.mojo.utils; public final class PrimitiveUtils { public static Object toPrimitiveNumber(Number number) { if (number instanceof Byte) { return number.byteValue(); } else if (number instanceof Long) { return number.longValue(); } else if (number instanceof Short) { return number.shortValue(); } else if (number instanceof Integer) { return number.intValue(); } else if (number instanceof Float) { return number.floatValue(); } else if (number instanceof Double) { return number.doubleValue(); } return 0; } public static Object toPrimitiveBoolean(Boolean booleans) { return booleans.booleanValue(); } }
rbrick/Mojo
Core/src/main/java/me/rbrickis/mojo/utils/PrimitiveUtils.java
Java
mit
784
package com.gpshub.api; import android.util.Log; import com.gpshub.utils.Preferences; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class AccountManager { private static final String TAG = AccountManager.class.getSimpleName(); public static final int RESULT_SUCCESS = 1; public static final int RESULT_WRONG_NUMBER = 2; public static final int RESULT_ERROR = 3; public static int login(String url, String driver_id) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("company_hash", "qwerty")); nameValuePairs.add(new BasicNameValuePair("id", driver_id)); String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url + "/actions/drivers.php?" + paramString); try { HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); String responseText = EntityUtils.toString(entity); Log.i(TAG, "login result: " + responseText); if ("OK".equals(responseText)) { Preferences.setServerUrl(url); Preferences.setDriverID(driver_id); return RESULT_SUCCESS; } } catch (IOException e) { return RESULT_ERROR; } return RESULT_WRONG_NUMBER; } public static void logout() { Preferences.wipeAccountSettings(); Log.i(TAG, "logout"); } public static boolean isLoggedIn() { String server_url = Preferences.getServerUrl(); String driver_id = Preferences.getDriverID(); Log.i(TAG, "logged in: server_url: " + server_url + ", driver_id: " + driver_id); return server_url != null && driver_id != null || Preferences.tryMigration(); } }
illusionww/gpsHub
client/app/src/main/java/com/gpshub/api/AccountManager.java
Java
mit
2,355
/****************************************************************************** Copyright (c) 2014 Gorka Suárez García Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "SaveManager.h" #include <System/File.h> #include <System/ForEach.h> #include <Menu/MenuManager.h> #include <Games/AlienParty/AlienManager.h> #include <Games/Checkers/CheckersManager.h> #include <Games/Checkers/CheckersSaveGames.h> #include <Games/Chess/ChessManager.h> #include <Games/Chess/ChessSaveGames.h> #include <Games/Puckman/PuckmanManager.h> #include <Games/Puckman/PuckmanGameData.h> #include <Games/Reversi/ReversiManager.h> #include <Games/Reversi/ReversiSaveGames.h> #include <Games/Snake/SnakeManager.h> #include <Games/Tetraminoes/TetraminoesManager.h> //******************************************************************************** // Defines //******************************************************************************** #define SAVE_DATA_PATH "savedata.bin" //******************************************************************************** // Static //******************************************************************************** bool SaveManager::SaveAfterChanges = true; //******************************************************************************** // InnerData //******************************************************************************** struct CheckersSaveData { CheckersSaveGames saves; }; struct ChessSaveData { ChessSaveGames saves; }; struct PuckmanSaveData { int highScore; }; struct ReversiSaveData { ReversiSaveGames saves; }; struct SnakeSaveData { SnakeManager::RankingArray ranking; }; struct TetraminoesSaveData { TetraminoesManager::RankingArray ranking; }; struct SaveManager::InnerData { // Fields CheckersSaveData checkers; ChessSaveData chess; PuckmanSaveData puckman; ReversiSaveData reversi; SnakeSaveData snake; TetraminoesSaveData tetraminoes; // Methods void Reset(); void Load(); void Save(); }; //-------------------------------------------------------------------------------- void SaveManager::InnerData::Reset() { //SnakeSaveData for (int i = 0; i < SnakeManager::MAX_RANKING_ENTRIES; ++i) { snake.ranking[i] = SnakeManager::RankingEntry(); } //TetraminoesSaveData for (int i = 0; i < TetraminoesManager::MAX_RANKING_ENTRIES; ++i) { tetraminoes.ranking[i] = TetraminoesManager::RankingEntry(); } //CheckersSaveData for (int i = 0; i < CheckersSaveGames::MAX_ENTRIES; ++i) { checkers.saves.data_[i] = CheckersSaveGames::Entry(); } //ReversiSaveData for (int i = 0; i < ReversiSaveGames::MAX_ENTRIES; ++i) { reversi.saves.data_[i] = ReversiSaveGames::Entry(); } //ChessSaveData for (int i = 0; i < ChessSaveGames::MAX_ENTRIES; ++i) { chess.saves.data_[i] = ChessSaveGames::Entry(); } //PuckmanSaveData puckman.highScore = 0; } //-------------------------------------------------------------------------------- void SaveManager::InnerData::Load() { try { File file; if (file.OpenForRead(SAVE_DATA_PATH)) { //SnakeSaveData for (int i = 0; i < SnakeManager::MAX_RANKING_ENTRIES; ++i) { file.Read(snake.ranking[i].Name); file.Read(snake.ranking[i].Score); } //TetraminoesSaveData for (int i = 0; i < TetraminoesManager::MAX_RANKING_ENTRIES; ++i) { file.Read(tetraminoes.ranking[i].Name); file.Read(tetraminoes.ranking[i].Score); } //CheckersSaveData for (int i = 0; i < CheckersSaveGames::MAX_ENTRIES; ++i) { file.Read(checkers.saves.data_[i].used); file.Read(checkers.saves.data_[i].name); file.Read(checkers.saves.data_[i].data.singlePlayer_); file.Read(checkers.saves.data_[i].data.difficulty_); file.Read(checkers.saves.data_[i].data.playerSide_); file.Read(checkers.saves.data_[i].data.winner_); file.Read(checkers.saves.data_[i].data.turn_); file.Read(checkers.saves.data_[i].data.nextPieceToMove_.x); file.Read(checkers.saves.data_[i].data.nextPieceToMove_.y); checkers.saves.data_[i].data.ForEachInBoard([&] (int, int r, int c) { file.Read(checkers.saves.data_[i].data.board_[r][c]); }); int candidatesSize = 0; file.Read(candidatesSize); checkers.saves.data_[i].data.candidates_.clear(); for (int j = 0; j < candidatesSize; ++j) { sf::Vector2i candidate; file.Read(candidate.x); file.Read(candidate.y); checkers.saves.data_[i].data.candidates_.push_back(candidate); } } //ReversiSaveData for (int i = 0; i < ReversiSaveGames::MAX_ENTRIES; ++i) { file.Read(reversi.saves.data_[i].used); file.Read(reversi.saves.data_[i].name); file.Read(reversi.saves.data_[i].data.singlePlayer_); file.Read(reversi.saves.data_[i].data.difficulty_); file.Read(reversi.saves.data_[i].data.playerSide_); file.Read(reversi.saves.data_[i].data.winner_); file.Read(reversi.saves.data_[i].data.turn_); file.Read(reversi.saves.data_[i].data.beginningState_); file.Read(reversi.saves.data_[i].data.whiteSideBlocked_); file.Read(reversi.saves.data_[i].data.blackSideBlocked_); reversi.saves.data_[i].data.ForEachInBoard([&] (int, int r, int c) { file.Read(reversi.saves.data_[i].data.board_[r][c]); }); int candidatesSize = 0; file.Read(candidatesSize); reversi.saves.data_[i].data.candidates_.clear(); for (int j = 0; j < candidatesSize; ++j) { sf::Vector2i candidate; file.Read(candidate.x); file.Read(candidate.y); reversi.saves.data_[i].data.candidates_.push_back(candidate); } } //ChessSaveData for (int i = 0; i < ChessSaveGames::MAX_ENTRIES; ++i) { file.Read(chess.saves.data_[i].used); file.Read(chess.saves.data_[i].name); file.Read(chess.saves.data_[i].data.singlePlayer_); file.Read(chess.saves.data_[i].data.difficulty_); file.Read(chess.saves.data_[i].data.playerSide_); file.Read(chess.saves.data_[i].data.winner_); file.Read(chess.saves.data_[i].data.turn_); file.Read(chess.saves.data_[i].data.whiteCheck_); file.Read(chess.saves.data_[i].data.blackCheck_); chess.saves.data_[i].data.ForEachInPieces( [&] (ChessGameData::Piece &, int idx) { file.Read(chess.saves.data_[i].data.pieces_[idx]); } ); } //PuckmanSaveData file.Read(puckman.highScore); file.Close(); } else { Reset(); } } catch (...) { Reset(); } } //-------------------------------------------------------------------------------- void SaveManager::InnerData::Save() { try { File file; if (file.OpenForWrite(SAVE_DATA_PATH)) { //SnakeSaveData for (int i = 0; i < SnakeManager::MAX_RANKING_ENTRIES; ++i) { file.Write(snake.ranking[i].Name); file.Write(snake.ranking[i].Score); } //TetraminoesSaveData for (int i = 0; i < TetraminoesManager::MAX_RANKING_ENTRIES; ++i) { file.Write(tetraminoes.ranking[i].Name); file.Write(tetraminoes.ranking[i].Score); } //CheckersSaveData for (int i = 0; i < CheckersSaveGames::MAX_ENTRIES; ++i) { file.Write(checkers.saves.data_[i].used); file.Write(checkers.saves.data_[i].name); file.Write(checkers.saves.data_[i].data.singlePlayer_); file.Write(checkers.saves.data_[i].data.difficulty_); file.Write(checkers.saves.data_[i].data.playerSide_); file.Write(checkers.saves.data_[i].data.winner_); file.Write(checkers.saves.data_[i].data.turn_); file.Write(checkers.saves.data_[i].data.nextPieceToMove_.x); file.Write(checkers.saves.data_[i].data.nextPieceToMove_.y); checkers.saves.data_[i].data.ForEachInBoard([&] (int item, int, int) { file.Write(item); }); int candidatesSize = checkers.saves.data_[i].data.candidates_.size(); file.Write(candidatesSize); for (int j = 0; j < candidatesSize; ++j) { file.Write(checkers.saves.data_[i].data.candidates_[j].x); file.Write(checkers.saves.data_[i].data.candidates_[j].y); } } //ReversiSaveData for (int i = 0; i < ReversiSaveGames::MAX_ENTRIES; ++i) { file.Write(reversi.saves.data_[i].used); file.Write(reversi.saves.data_[i].name); file.Write(reversi.saves.data_[i].data.singlePlayer_); file.Write(reversi.saves.data_[i].data.difficulty_); file.Write(reversi.saves.data_[i].data.playerSide_); file.Write(reversi.saves.data_[i].data.winner_); file.Write(reversi.saves.data_[i].data.turn_); file.Write(reversi.saves.data_[i].data.beginningState_); file.Write(reversi.saves.data_[i].data.whiteSideBlocked_); file.Write(reversi.saves.data_[i].data.blackSideBlocked_); reversi.saves.data_[i].data.ForEachInBoard([&] (int item, int, int) { file.Write(item); }); int candidatesSize = reversi.saves.data_[i].data.candidates_.size(); file.Write(candidatesSize); for (int j = 0; j < candidatesSize; ++j) { file.Write(reversi.saves.data_[i].data.candidates_[j].x); file.Write(reversi.saves.data_[i].data.candidates_[j].y); } } //ChessSaveData for (int i = 0; i < ChessSaveGames::MAX_ENTRIES; ++i) { file.Write(chess.saves.data_[i].used); file.Write(chess.saves.data_[i].name); file.Write(chess.saves.data_[i].data.singlePlayer_); file.Write(chess.saves.data_[i].data.difficulty_); file.Write(chess.saves.data_[i].data.playerSide_); file.Write(chess.saves.data_[i].data.winner_); file.Write(chess.saves.data_[i].data.turn_); file.Write(chess.saves.data_[i].data.whiteCheck_); file.Write(chess.saves.data_[i].data.blackCheck_); chess.saves.data_[i].data.ForEachInPieces( [&] (ChessGameData::Piece &, int idx) { file.Write(chess.saves.data_[i].data.pieces_[idx]); } ); } //PuckmanSaveData file.Write(puckman.highScore); file.Close(); } } catch (...) { } } //******************************************************************************** // Methods //******************************************************************************** void SaveManager::Initialize() { if (!initialized_) { data_.reset(new InnerData()); data_->Load(); initialized_ = true; } } //-------------------------------------------------------------------------------- void SaveManager::Release() { if (initialized_) { if (data_) { data_->Save(); data_.reset(nullptr); } initialized_ = false; } } //******************************************************************************** // Checkers Methods //******************************************************************************** void SaveManager::CheckersLoad() { auto * manager = CheckersManager::Instance(); auto & saves = manager->Saves(); saves = data_->checkers.saves; } //-------------------------------------------------------------------------------- void SaveManager::CheckersSave() { auto * manager = CheckersManager::Instance(); data_->checkers.saves = manager->Saves(); if (SaveAfterChanges) { data_->Save(); } } //******************************************************************************** // Chess Methods //******************************************************************************** void SaveManager::ChessLoad() { auto * manager = ChessManager::Instance(); auto & saves = manager->Saves(); saves = data_->chess.saves; } //-------------------------------------------------------------------------------- void SaveManager::ChessSave() { auto * manager = ChessManager::Instance(); data_->chess.saves = manager->Saves(); if (SaveAfterChanges) { data_->Save(); } } //******************************************************************************** // Puckman Methods //******************************************************************************** void SaveManager::PuckmanLoad() { auto * manager = Puckman::Manager::Instance(); manager->DataInstance()->HighScore(data_->puckman.highScore); } //-------------------------------------------------------------------------------- void SaveManager::PuckmanSave() { auto * manager = Puckman::Manager::Instance(); data_->puckman.highScore = manager->DataInstance()->HighScore(); if (SaveAfterChanges) { data_->Save(); } } //******************************************************************************** // Reversi Methods //******************************************************************************** void SaveManager::ReversiLoad() { auto * manager = ReversiManager::Instance(); auto & saves = manager->Saves(); saves = data_->reversi.saves; } //-------------------------------------------------------------------------------- void SaveManager::ReversiSave() { auto * manager = ReversiManager::Instance(); data_->reversi.saves = manager->Saves(); if (SaveAfterChanges) { data_->Save(); } } //******************************************************************************** // Snake Methods //******************************************************************************** void SaveManager::SnakeLoad() { auto * manager = SnakeManager::Instance(); auto & ranking = manager->Ranking(); ranking = data_->snake.ranking; } //-------------------------------------------------------------------------------- void SaveManager::SnakeSave() { auto * manager = SnakeManager::Instance(); data_->snake.ranking = manager->Ranking(); if (SaveAfterChanges) { data_->Save(); } } //******************************************************************************** // Tetraminoes Methods //******************************************************************************** void SaveManager::TetraminoesLoad() { auto * manager = TetraminoesManager::Instance(); auto & ranking = manager->Ranking(); ranking = data_->tetraminoes.ranking; } //-------------------------------------------------------------------------------- void SaveManager::TetraminoesSave() { auto * manager = TetraminoesManager::Instance(); data_->tetraminoes.ranking = manager->Ranking(); if (SaveAfterChanges) { data_->Save(); } } //******************************************************************************** // Singleton pattern ( http://en.wikipedia.org/wiki/Singleton_pattern ) //******************************************************************************** /** * The main instance of the class. */ SaveManager * SaveManager::instance_ = nullptr; //-------------------------------------------------------------------------------- /** * Constructs a new object. */ SaveManager::SaveManager() : initialized_(false), data_(nullptr) {} //-------------------------------------------------------------------------------- /** * The destructor of the object. */ SaveManager::~SaveManager() {} //-------------------------------------------------------------------------------- /** * Gets the main instance of the class. */ SaveManager * SaveManager::Instance() { if (!instance_) { instance_ = new SaveManager(); } return instance_; } //-------------------------------------------------------------------------------- /** * Gets the main instance of the class. */ SaveManager & SaveManager::Reference() { return *(Instance()); }
gorkinovich/GAGC
Source/Games/SaveManager.cpp
C++
mit
18,289
# frozen_string_literal: true require "spec_helper" describe "Get type information" do context "when etag not set" do before { VCR.insert_cassette "esi/universe/types/192" } after { VCR.eject_cassette } let(:options) { {id: 192, language: "en-us"} } subject { EveOnline::ESI::UniverseType.new(options) } specify { expect(subject.scope).to eq(nil) } specify { expect(subject.not_modified?).to eq(false) } specify do expect(subject.as_json).to eq(capacity: 0.0, description: "Medium Projectile Ammo. This ammo uses a similar plasma containment core as hybrid charges except that it is mounted in a standard cannon shell.\r\n\r\n50% reduced optimal range.", graphic_id: 1297, group_id: 83, icon_id: 1297, market_group_id: 112, mass: 1.0, name: "Phased Plasma M", packaged_volume: 0.0125, portion_size: 100, published: true, radius: 1.0, type_id: 192, volume: 0.0125) end specify { expect(subject.dogma_attributes.size).to eq(17) } specify { expect(subject.dogma_attributes.first.as_json).to eq(attribute_id: 128, value: 2.0) } specify { expect(subject.dogma_effects.size).to eq(3) } specify { expect(subject.dogma_effects.first.as_json).to eq(effect_id: 596, is_default: false) } specify { expect(subject.etag).to eq("37a39e7a5f5ecc07b19a3128c319f1198d035aee10052d0a21ccdd94") } specify { expect(subject.error_limit_remain).to eq(100) } specify { expect(subject.error_limit_reset).to eq(30) } end context "when etag is set" do let(:options) do { id: 192, language: "en-us", etag: "37a39e7a5f5ecc07b19a3128c319f1198d035aee10052d0a21ccdd94" } end before { VCR.insert_cassette "esi/universe/types/192_with_etag" } after { VCR.eject_cassette } subject { EveOnline::ESI::UniverseType.new(options) } specify { expect(subject.not_modified?).to eq(true) } specify { expect(subject.etag).to eq("37a39e7a5f5ecc07b19a3128c319f1198d035aee10052d0a21ccdd94") } specify { expect(subject.error_limit_remain).to eq(100) } specify { expect(subject.error_limit_reset).to eq(18) } end end
biow0lf/eve_online
spec/features/universe_type_spec.rb
Ruby
mit
2,603
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateAbsensisTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('absensis', function(Blueprint $table) { $table->increments('id'); $table->string(' kd_karyawan'); $table->string('kd_absen'); $table->date('tanggal'); $table->string('cuti'); $table->string('ijin'); $table->string('sakit'); $table->string ('alpha'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('absensis'); } }
risatya/smartlogicpro
app/database/migrations/2014_06_29_171824_create_absensis_table.php
PHP
mit
673
require("./18.js"); require("./37.js"); require("./74.js"); require("./147.js"); module.exports = 148;
skeiter9/javascript-para-todo_demo
webapp/node_modules/webpack/benchmark/fixtures/148.js
JavaScript
mit
102
package com.daeliin.components.persistence.resource.repository; import com.daeliin.components.core.pagination.Page; import com.daeliin.components.core.pagination.PageRequest; import com.querydsl.core.types.OrderSpecifier; import com.querydsl.core.types.Predicate; import com.querydsl.sql.RelationalPathBase; import com.querydsl.sql.SQLQuery; import com.querydsl.sql.SQLQueryFactory; import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; import java.util.Collection; import java.util.Objects; import java.util.Optional; /** * @param <R> row type */ public class BaseRepository<R> implements PagingRepository<R> { @Inject protected SQLQueryFactory queryFactory; protected final RowOrder rowOrder; protected final RelationalPathBase<R> rowPath; public BaseRepository(RelationalPathBase<R> rowPath) { this.rowPath = Objects.requireNonNull(rowPath); this.rowOrder = new RowOrder(rowPath); } @Override public RelationalPathBase<R> rowPath() { return rowPath; } @Transactional(readOnly = true) @Override public Optional<R> findOne(Predicate predicate) { if (predicate == null) { return Optional.empty(); } return Optional.ofNullable(queryFactory.select(rowPath) .from(rowPath) .where(predicate) .fetchOne()); } @Transactional(readOnly = true) @Override public Collection<R> findAll(Predicate predicate) { SQLQuery<R> query = queryFactory.select(rowPath) .from(rowPath); if (predicate != null) { query = query.where(predicate); } return query.fetch(); } @Transactional(readOnly = true) @Override public Page<R> findAll(PageRequest pageRequest) { return findAll(null, pageRequest); } @Transactional(readOnly = true) @Override public Page<R> findAll(Predicate predicate, PageRequest pageRequest) { long totalItems = count(predicate); long totalPages = rowOrder.computeTotalPages(totalItems, pageRequest.size); OrderSpecifier[] orders = rowOrder.computeOrders(pageRequest); SQLQuery<R> query = queryFactory.select(rowPath) .from(rowPath) .limit(pageRequest.size) .offset(pageRequest.offset) .orderBy(orders); if (predicate != null) { query = query.where(predicate); } return new Page<>(query.fetch(), totalItems, totalPages); } @Transactional(readOnly = true) @Override public Collection<R> findAll() { return queryFactory.select(rowPath) .from(rowPath) .fetch(); } @Transactional(readOnly = true) @Override public long count() { return queryFactory.select(rowPath) .from(rowPath) .fetchCount(); } @Transactional(readOnly = true) @Override public long count(Predicate predicate) { SQLQuery<R> query = queryFactory.select(rowPath) .from(rowPath); if (predicate != null) { query = query.where(predicate); } return query.fetchCount(); } @Transactional @Override public boolean delete(Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate should not be null on a delete, otherwise whole table will be deleted, " + "call deleteAll() instead if it's the desired operation"); } return queryFactory.delete(rowPath).where(predicate).execute() > 0; } @Transactional @Override public boolean deleteAll() { return queryFactory.delete(rowPath).execute() > 0; } }
Daeliin/java-components
components-persistence/src/main/java/com/daeliin/components/persistence/resource/repository/BaseRepository.java
Java
mit
3,785
module Kiv7 module Authenticatable module_function def verify true end end end
robertsosinski/kiv7
lib/kiv7/authenticatable.rb
Ruby
mit
105
<?php namespace Asmolding\Bundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class AsmoldingExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } }
gitsg44/asm
src/Asmolding/Bundle/DependencyInjection/AsmoldingExtension.php
PHP
mit
877
var Leap = require("leapjs"); var keyboard = require('node_keyboard'); //Each var individually declared below so they refence different objects in memory. I.e work independantly. //These vars log when a particular action / gesture last ran. var last_fav = new Date().getTime(); var last_swipe = new Date().getTime(); var last_up = new Date().getTime(); var last_down = new Date().getTime(); var current_time; var delay = 1000; //Number of milliseconds forced between each gesture. var controller = Leap.loop({enableGestures: true}, function(frame){ if(frame.valid && frame.gestures.length > 0){ frame.gestures.forEach(function(gesture){ switch (gesture.type){ case "circle": current_time = new Date().getTime(); if(last_fav+delay < current_time){ keyboard.press(keyboard.Key_Numpad0); keyboard.release(keyboard.Key_Numpad0); console.log("Circle Gesture"); last_fav = new Date().getTime(); } break; case "swipe": current_time = new Date().getTime(); if(last_swipe+delay < current_time){ //Classify swipe as either horizontal or vertical var isHorizontal = Math.abs(gesture.direction[0]) > Math.abs(gesture.direction[1]); //Classify as right-left or up-down if(isHorizontal){ if(gesture.direction[0] > 0){ swipeDirection = "Swipe Right"; keyboard.press(keyboard.Key_Up); //Key_Up keycode and Key_Right keycode are swapped in node_keyboard dependancy keyboard.release(keyboard.Key_Up);//Key_Up keycode and Key_Right keycode are swapped in node_keyboard dependancy } else { swipeDirection = "Swipe Left"; keyboard.press(keyboard.Key_Left); keyboard.release(keyboard.Key_Left); } } else { //vertical if(gesture.direction[1] > 0){ swipeDirection = "Swipe Up"; } else { swipeDirection = "Swipe Down"; } } console.log(swipeDirection); last_swipe = new Date().getTime(); } break; } }); } if(frame.pointables.length == 5){ var pointable = frame.pointables; current_time = new Date().getTime(); if(last_up+delay < current_time){ if(pointable[0].direction[1] > 0.78 && pointable[1].direction[1] > 0.78 && pointable[2].direction[1] > 0.78 && pointable[3].direction[1] > 0.78 && pointable[4].direction[1] > 0.78 ){ console.log("Up Vote"); keyboard.press(keyboard.Key_NumpadAdd); keyboard.release(keyboard.Key_NumpadAdd); last_up = new Date().getTime(); } } if(last_down+delay < current_time){ if(pointable[0].direction[1] < -0.78 && pointable[1].direction[1] < -0.78 && pointable[2].direction[1] < -0.78 && pointable[3].direction[1] < -0.78 && pointable[4].direction[1] < -0.78 ){ console.log("Down Vote"); keyboard.press(keyboard.Key_NumpadSubtract); keyboard.release(keyboard.Key_NumpadSubtract); last_down = new Date().getTime(); } } } }); console.log('Leap Imgur Controller Running');
MaxGiting/leap_imgur
leap.js
JavaScript
mit
3,870
import 'leaflet'; import './main.scss'; import "reflect-metadata"; import "zone.js/dist/zone"; import "zone.js/dist/long-stack-trace-zone"; import { BrowserModule } from "@angular/platform-browser"; import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"; import { Component, NgModule, ComponentRef, Injector, ApplicationRef, ComponentFactoryResolver, Injectable, NgZone } from "@angular/core"; // ########################################### // App component // ########################################### @Component({ selector: "app", template: `<section class="app"><map></map></section>` }) class AppComponent { } // ########################################### // Popup component // ########################################### @Component({ selector: "popup", template: `<section class="popup">Popup Component! :D {{ param }}</section>` }) class PopupComponent { } // ########################################### // $compile for Angular 4! :D // ########################################### @Injectable() class CustomCompileService { private appRef: ApplicationRef; constructor( private injector: Injector, private resolver: ComponentFactoryResolver ) { } configure(appRef) { this.appRef = appRef; } compile(component, onAttach) { const compFactory = this.resolver.resolveComponentFactory(component); let compRef = compFactory.create(this.injector); if (onAttach) onAttach(compRef); this.appRef.attachView(compRef.hostView); compRef.onDestroy(() => this.appRef.detachView(compRef.hostView)); let div = document.createElement('div'); div.appendChild(compRef.location.nativeElement); return div; } } // ########################################### // Leaflet map service // ########################################### @Injectable() class MapService { map: any; baseMaps: any; markersLayer: any; appRef: ApplicationRef; constructor(private compileService: CustomCompileService) { compileService.configure(this.appRef); } init(selector, appRef: ApplicationRef) { this.appRef = appRef; this.baseMaps = { CartoDB: L.tileLayer("http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png", { attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>' }) }; L.Icon.Default.imagePath = '.'; L.Icon.Default.mergeOptions({ iconUrl: require('leaflet/dist/images/marker-icon.png'), shadowUrl: require('leaflet/dist/images/marker-shadow.png') }); this.map = L.map(selector); this.baseMaps.CartoDB.addTo(this.map); this.map.setView([51.505, -0.09], 13); this.markersLayer = new L.FeatureGroup(null); this.markersLayer.clearLayers(); this.markersLayer.addTo(this.map); this.compileService.configure(this.appRef); } addMarker() { var m = L.marker([51.510, -0.09]); m.bindTooltip('Angular 4 marker (PopupComponent)'); m.bindPopup(null); m.on('click', (e) => { m.setPopupContent( this.compileService.compile(PopupComponent, (c) => { c.instance.param = 0; setInterval(() => c.instance.param++, 1000); }) ); }); this.markersLayer.addLayer(m); return m; } } // ########################################### // Map component. These imports must be made // here, they can't be in a service as they // seem to depend on being loaded inside a // component. // ########################################### @Component({ selector: "map", template: `<section class="map"><div id="map"></div></section>`, }) class MapComponent { marker: any; constructor( private appRef: ApplicationRef, private mapService: MapService ) { } ngOnInit() { this.mapService.init('map', this.appRef); this.marker = this.mapService.addMarker(); } } // ########################################### // Main module // ########################################### @NgModule({ imports: [ BrowserModule ], providers: [ MapService, CustomCompileService ], declarations: [ AppComponent, MapComponent, PopupComponent ], entryComponents: [ PopupComponent ], bootstrap: [AppComponent] }) class AppModule { } platformBrowserDynamic().bootstrapModule(AppModule);
darkguy2008/leaflet-angular4-issue
src/app.ts
TypeScript
mit
4,632
<?php namespace App\Http\Controllers\API; use App\Http\Requests\API\PlaylistStoreRequest; use App\Models\Playlist; use Illuminate\Http\Request; class PlaylistController extends Controller { /** * Create a new playlist. * * @param PlaylistStoreRequest $request * * @return \Illuminate\Http\JsonResponse */ public function store(PlaylistStoreRequest $request) { $playlist = auth()->user()->playlists()->create($request->only('name')); $playlist->songs()->sync($request->input('songs')); $playlist->songs = $playlist->songs->fetch('id'); return response()->json($playlist); } /** * Rename a playlist. * * @param \Illuminate\Http\Request $request * @param Playlist $playlist * * @return \Illuminate\Http\JsonResponse */ public function update(Request $request, Playlist $playlist) { $this->authorize('owner', $playlist); $playlist->update($request->only('name')); return response()->json($playlist); } /** * Sync a playlist with songs. * Any songs that are not populated here will be removed from the playlist. * * @param \Illuminate\Http\Request $request * @param Playlist $playlist * * @return \Illuminate\Http\JsonResponse */ public function sync(Request $request, Playlist $playlist) { $this->authorize('owner', $playlist); $playlist->songs()->sync($request->input('songs')); return response()->json(); } /** * Delete a playlist. * * @param Playlist $playlist * * @return \Illuminate\Http\JsonResponse */ public function destroy(Playlist $playlist) { $this->authorize('owner', $playlist); $playlist->delete(); return response()->json(); } }
cchandan/experimental
app/Http/Controllers/API/PlaylistController.php
PHP
mit
1,890
class AzDefinition < OwnedActiveRecord belongs_to :az_base_project belongs_to :matrix, :class_name=>'AzDefinition', :foreign_key=>'copy_of' validates_presence_of :name validates_presence_of :definition include Statuses def validate validate_owner_id_common('definition', 'Project') end def self.get_model_name return "Определние" end def before_create self.set_initial_position end def self.get_by_company(company) return AzDefinition.find_all_by_owner_id(company.id, :conditions => { :az_base_project_id => nil }, :order => :position) end def self.get_seeds return find_all_by_seed(true) end def self.from_az_hash(attributes, project) definition = AzDefinition.new(attributes) definition.az_base_project = project definition.owner = project.owner definition.copy_of = attributes['id'] return definition end def make_copy_definition(owner, project) dup = self.clone dup.copy_of = id dup.owner = owner dup.az_base_project = project dup.seed = false dup.save! return dup end def update_from_source(src) self.name = src.name self.definition = src.definition self.save end def sow(owner) result = nil if self.seed != true return result end definition_to_update = AzDefinition.find(:first, :conditions => {:owner_id => owner.id, :copy_of => self.id}) if definition_to_update == nil self.make_copy_definition(owner, nil) result = [self, 'copied'] else definition_to_update.update_from_source(self) result = [self, 'updated'] end return [result] end def self.update_from_seed(owner) result = [] seeds = AzDefinition.get_seeds seeds.each do |s| res = s.sow(owner) if res != nil result.concat(res) end end return result end def move_up conditions = "position < #{self.position} " if self.az_base_project_id == nil conditions += " AND az_base_project_id is NULL" else conditions += " AND az_base_project_id=#{self.az_base_project_id}" end definition = AzDefinition.find_last_by_owner_id(self.owner_id, :conditions => conditions, :order => 'position asc') if definition == nil return # Мы выше всех end definition.position, self.position = self.position, definition.position definition.save self.save end def move_down conditions = "position > #{self.position} " if self.az_base_project_id == nil conditions += " AND az_base_project_id is NULL" else conditions += " AND az_base_project_id=#{self.az_base_project_id}" end definition = AzDefinition.find_last_by_owner_id(self.owner_id, :conditions => conditions, :order => 'position desc') if definition == nil return # Мы ниже всех end definition.position, self.position = self.position, definition.position definition.save self.save end def set_initial_position d = AzDefinition.find(:last, :order => :id) if d == nil self.position = 1 else self.position = d.id + 1 end end def to_az_hash attrs = attributes #attrs.delete("id") #attrs.delete("created_at") #attrs.delete("updated_at") return attrs end end
stg34/azalo
app/models/az_definition.rb
Ruby
mit
3,347
# -*- coding: utf-8 -*- """ Created on Mon Sep 29 21:25:13 2014 @author: 27182_000 """ # A palindromic number reads the same both ways. The largest palindrome made # from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. import sys ans = 1 for n in range(999,1,-1): for m in range(999,1,-1): num = n*m if str(num) == str(num)[::-1] and num > ans: ans = num print ans
ecotner/Learning-to-fly
Project Euler Python/Problem 04/problem4.py
Python
mit
485
from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Page content') def custom(request): return render(request, 'custom.html', {})
geelweb/geelweb-django-contactform
tests/views.py
Python
mit
202
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Nito.AsyncEx; using NUnit.Framework; using SJP.Schematic.Core; using SJP.Schematic.Core.Extensions; using SJP.Schematic.Tests.Utilities; namespace SJP.Schematic.Oracle.Tests.Integration { internal sealed class OracleDatabaseViewProviderTests : OracleTest { private IDatabaseViewProvider ViewProvider => new OracleDatabaseViewProvider(Connection, IdentifierDefaults, IdentifierResolver); [OneTimeSetUp] public async Task Init() { await DbConnection.ExecuteAsync("create view db_test_view_1 as select 1 as dummy from dual", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("create view view_test_view_1 as select 1 as test from dual", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("create table view_test_table_1 (table_id number)", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("create materialized view view_test_view_2 as select table_id as test from view_test_table_1", CancellationToken.None).ConfigureAwait(false); } [OneTimeTearDown] public async Task CleanUp() { await DbConnection.ExecuteAsync("drop view db_test_view_1", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("drop view view_test_view_1", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("drop materialized view view_test_view_2", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("drop table view_test_table_1", CancellationToken.None).ConfigureAwait(false); } private Task<IDatabaseView> GetViewAsync(Identifier viewName) { if (viewName == null) throw new ArgumentNullException(nameof(viewName)); return GetViewAsyncCore(viewName); } private async Task<IDatabaseView> GetViewAsyncCore(Identifier viewName) { using (await _lock.LockAsync().ConfigureAwait(false)) { if (!_viewsCache.TryGetValue(viewName, out var lazyView)) { lazyView = new AsyncLazy<IDatabaseView>(() => ViewProvider.GetView(viewName).UnwrapSomeAsync()); _viewsCache[viewName] = lazyView; } return await lazyView.ConfigureAwait(false); } } private readonly AsyncLock _lock = new(); private readonly Dictionary<Identifier, AsyncLazy<IDatabaseView>> _viewsCache = new(); [Test] public async Task GetView_WhenViewPresent_ReturnsView() { var viewIsSome = await ViewProvider.GetView("db_test_view_1").IsSome.ConfigureAwait(false); Assert.That(viewIsSome, Is.True); } [Test] public async Task GetView_WhenViewPresent_ReturnsViewWithCorrectName() { var viewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "db_test_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "DB_TEST_VIEW_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(expectedViewName)); } [Test] public async Task GetView_WhenViewPresentGivenLocalNameOnly_ShouldBeQualifiedCorrectly() { var viewName = new Identifier("DB_TEST_VIEW_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "DB_TEST_VIEW_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(expectedViewName)); } [Test] public async Task GetView_WhenViewPresentGivenSchemaAndLocalNameOnly_ShouldBeQualifiedCorrectly() { var viewName = new Identifier(IdentifierDefaults.Schema, "DB_TEST_VIEW_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "DB_TEST_VIEW_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(expectedViewName)); } [Test] public async Task GetView_WhenViewPresentGivenDatabaseAndSchemaAndLocalNameOnly_ShouldBeQualifiedCorrectly() { var viewName = new Identifier(IdentifierDefaults.Database, IdentifierDefaults.Schema, "DB_TEST_VIEW_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "DB_TEST_VIEW_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(expectedViewName)); } [Test] public async Task GetView_WhenViewPresentGivenFullyQualifiedName_ShouldBeQualifiedCorrectly() { var viewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "DB_TEST_VIEW_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(viewName)); } [Test] public async Task GetView_WhenViewPresentGivenFullyQualifiedNameWithDifferentServer_ShouldBeQualifiedCorrectly() { var viewName = new Identifier("A", IdentifierDefaults.Database, IdentifierDefaults.Schema, "db_test_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "DB_TEST_VIEW_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(expectedViewName)); } [Test] public async Task GetView_WhenViewPresentGivenFullyQualifiedNameWithDifferentServerAndDatabase_ShouldBeQualifiedCorrectly() { var viewName = new Identifier("A", "B", IdentifierDefaults.Schema, "db_test_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "DB_TEST_VIEW_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(expectedViewName)); } [Test] public async Task GetView_WhenViewMissing_ReturnsNone() { var viewIsNone = await ViewProvider.GetView("view_that_doesnt_exist").IsNone.ConfigureAwait(false); Assert.That(viewIsNone, Is.True); } [Test] public async Task GetAllViews_WhenEnumerated_ContainsViews() { var hasViews = await ViewProvider.GetAllViews() .AnyAsync() .ConfigureAwait(false); Assert.That(hasViews, Is.True); } [Test] public async Task GetAllViews_WhenEnumerated_ContainsTestView() { const string viewName = "DB_TEST_VIEW_1"; var containsTestView = await ViewProvider.GetAllViews() .AnyAsync(v => string.Equals(v.Name.LocalName, viewName, StringComparison.Ordinal)) .ConfigureAwait(false); Assert.That(containsTestView, Is.True); } [Test] public async Task Definition_PropertyGet_ReturnsCorrectDefinition() { var view = await GetViewAsync("VIEW_TEST_VIEW_1").ConfigureAwait(false); var definition = view.Definition; const string expected = "select 1 as test from dual"; Assert.That(definition, Is.EqualTo(expected)); } [Test] public async Task IsMaterialized_WhenViewIsNotMaterialized_ReturnsFalse() { var view = await GetViewAsync("VIEW_TEST_VIEW_1").ConfigureAwait(false); Assert.That(view.IsMaterialized, Is.False); } [Test] public async Task Columns_WhenViewContainsSingleColumn_ContainsOneValueOnly() { var view = await GetViewAsync("VIEW_TEST_VIEW_1").ConfigureAwait(false); Assert.That(view.Columns, Has.Exactly(1).Items); } [Test] public async Task Columns_WhenViewContainsSingleColumn_ContainsColumnName() { const string expectedColumnName = "TEST"; var view = await GetViewAsync("VIEW_TEST_VIEW_1").ConfigureAwait(false); var containsColumn = view.Columns.Any(c => c.Name == expectedColumnName); Assert.That(containsColumn, Is.True); } [Test] public async Task GetAllViews_WhenEnumerated_ContainsTestMaterializedView() { const string viewName = "VIEW_TEST_VIEW_2"; var containsTestView = await ViewProvider.GetAllViews() .AnyAsync(v => string.Equals(v.Name.LocalName, viewName, StringComparison.Ordinal)) .ConfigureAwait(false); Assert.That(containsTestView, Is.True); } [Test] public async Task Definition_PropertyGet_ReturnsCorrectDefinitionForMaterializedView() { var viewName = new Identifier(IdentifierDefaults.Schema, "VIEW_TEST_VIEW_2"); var view = await GetViewAsync(viewName).ConfigureAwait(false); var definition = view.Definition; const string expected = "select table_id as test from view_test_table_1"; Assert.That(definition, Is.EqualTo(expected)); } [Test] public async Task IsMaterialized_WhenViewIsMaterialized_ReturnsTrue() { var view = await GetViewAsync("VIEW_TEST_VIEW_2").ConfigureAwait(false); Assert.That(view.IsMaterialized, Is.True); } [Test] public async Task Columns_WhenMaterializedViewContainsSingleColumn_ContainsOneValueOnly() { var viewName = new Identifier(IdentifierDefaults.Schema, "VIEW_TEST_VIEW_2"); var view = await GetViewAsync(viewName).ConfigureAwait(false); Assert.That(view.Columns, Has.Exactly(1).Items); } [Test] public async Task Columns_WhenMaterializedViewContainsSingleColumn_ContainsColumnName() { var viewName = new Identifier(IdentifierDefaults.Schema, "VIEW_TEST_VIEW_2"); var view = await GetViewAsync(viewName).ConfigureAwait(false); var containsColumn = view.Columns.Any(c => c.Name == "TEST"); Assert.That(containsColumn, Is.True); } } }
sjp/Schematic
src/SJP.Schematic.Oracle.Tests/Integration/OracleDatabaseViewProviderTests.cs
C#
mit
11,093
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.utils.timezone import utc import datetime class Migration(migrations.Migration): dependencies = [ ('content', '0009_auto_20150829_1417'), ] operations = [ migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('msg_subject', models.CharField(max_length=255, verbose_name='Subject')), ('msg_text', models.TextField(verbose_name='Text')), ('msg_author', models.EmailField(max_length=75, verbose_name='From')), ('recv_date', models.DateTimeField(editable=False, verbose_name='Date Received', default=datetime.datetime(2015, 10, 19, 4, 10, 29, 712166, tzinfo=utc))), ], options={ }, bases=(models.Model,), ), migrations.AlterField( model_name='event', name='pub_date', field=models.DateTimeField(editable=False, verbose_name='Date Published', default=datetime.datetime(2015, 10, 19, 4, 10, 29, 711232, tzinfo=utc)), preserve_default=True, ), migrations.AlterField( model_name='post', name='pub_date', field=models.DateTimeField(editable=False, verbose_name='Date Published', default=datetime.datetime(2015, 10, 19, 4, 10, 29, 711716, tzinfo=utc)), preserve_default=True, ), ]
sfowl/fowllanguage
content/migrations/0010_auto_20151019_1410.py
Python
mit
1,608
''' Manage Ruby gem packages. (see https://rubygems.org/ ) ''' from pyinfra.api import operation from pyinfra.facts.gem import GemPackages from .util.packaging import ensure_packages @operation def packages(packages=None, present=True, latest=False, state=None, host=None): ''' Add/remove/update gem packages. + packages: list of packages to ensure + present: whether the packages should be installed + latest: whether to upgrade packages without a specified version Versions: Package versions can be pinned like gem: ``<pkg>:<version>``. Example: .. code:: python # Note: Assumes that 'gem' is installed. gem.packages( name='Install rspec', packages=['rspec'], ) ''' yield ensure_packages( host, packages, host.get_fact(GemPackages), present, install_command='gem install', uninstall_command='gem uninstall', upgrade_command='gem update', version_join=':', latest=latest, )
Fizzadar/pyinfra
pyinfra/operations/gem.py
Python
mit
1,033
// eslint-disable-next-line function getCookie(cname) { const name = `${cname}=`; const ca = document.cookie.split(';'); for (let i = 0; i < ca.length; i += 1) { let c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1); if (c.indexOf(name) !== -1) return c.substring(name.length, c.length); } return ''; }
interactivelabs/docreviews
src/js/cookies.js
JavaScript
mit
333
package TeamTwoHTMLEditor.command; import TeamTwoHTMLEditor.CommandDistributor; import TeamTwoHTMLEditor.CommandMediator; import TeamTwoHTMLEditor.GUI.EditorFrame; import javax.swing.*; /** * Created with IntelliJ IDEA. User: Kocsen Date: 3/22/13 Time: 2:16 PM */ public class ShutDownCommand implements Command{ private final ActiveContext context; public ShutDownCommand(ActiveContext context){ this.context = context; } /** * Checks if the editor can quit based on the save state of the files. If * all files are saved, the editor quit, else an interruption option pane is * shown to prevent the shutdown operation. * * @param c - Command distributor who has a reference access to the * FileManager */ @Override public void execute(CommandDistributor c, CommandMediator cmd){ if(c.getFileManager().canQuit()){ context.getParent().dispose(); System.out.println("Shutting Down System"); } else{ int n = JOptionPane.showConfirmDialog( context.getParent(), "There are some unsaved files, would you like to quit anyway?", "Unsaved Files", JOptionPane.YES_NO_OPTION); if(n == JOptionPane.YES_OPTION){ context.getParent().dispose(); System.out.println("Shutting Down System"); } else{ } } c.getFileManager().printStatus(); } }
kocsenc/java-swing-htmleditor
src/command/ShutDownCommand.java
Java
mit
1,323
<?php declare(strict_types=1); /* * This file is part of the MediaModule for Zikula. * * (c) Christian Flach <hi@christianflach.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Cmfcmf\Module\MediaModule\MediaType; use Cmfcmf\Module\MediaModule\Entity\Media\AbstractMediaEntity; use Cmfcmf\Module\MediaModule\Entity\Media\MarkdownEntity; use Cmfcmf\Module\MediaModule\Entity\Media\PlaintextEntity; use Michelf\MarkdownExtra; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\UploadedFile; class Markdown extends AbstractFileMediaType implements UploadableMediaTypeInterface { /** * @var MarkdownExtra */ private $markdownExtraParser; /** * {@inheritdoc} */ public function getDisplayName() { return $this->translator->trans('Markdown', [], 'cmfcmfmediamodule'); } /** * {@inheritdoc} */ public function getIcon() { return 'fa-align-right'; } public function setMarkdownParser(MarkdownExtra $markdownExtraParser) { $this->markdownExtraParser = $markdownExtraParser; } public function renderFullpage(AbstractMediaEntity $entity) { /** @var MarkdownEntity $entity */ $raw = file_get_contents($entity->getPath()); $rendered = $this->markdownExtraParser->transform($raw); return $this->renderEngine->render('CmfcmfMediaModule:MediaType/Markdown:fullpage.html.twig', [ 'entity' => $entity, 'rendered' => $rendered, 'raw' => $raw ]); } public function getExtendedMetaInformation(AbstractMediaEntity $entity) { return []; } /** * {@inheritdoc} */ public function canUpload(File $file) { if ('text/plain' === $file->getMimeType()) { if ('md' === $file->getExtension() || ($file instanceof UploadedFile && 'md' === $file->getClientOriginalExtension())) { return 5; } } return 0; } /** * {@inheritdoc} */ public function mightUpload($mimeType, $size, $name) { if ('text/plain' === $mimeType && 'md' === pathinfo($name, PATHINFO_EXTENSION)) { return 5; } return 0; } public function getThumbnail(AbstractMediaEntity $entity, $width, $height, $format = 'html', $mode = 'outbound', $optimize = true) { /** @var PlaintextEntity $entity */ return $this->getIconThumbnailByFileExtension($entity, $width, $height, $format, $mode, $optimize, 'txt'); } public function isEmbeddable() { return false; } }
cmfcmf/MediaModule
MediaType/Markdown.php
PHP
mit
2,756
/* * Kendo UI v2015.1.408 (http://www.telerik.com/kendo-ui) * Copyright 2015 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["kok"] = { name: "kok", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3,2], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ",", ".": ".", groupSize: [3,2], symbol: "%" }, currency: { pattern: ["$ -n","$ n"], decimals: 2, ",": ",", ".": ".", groupSize: [3,2], symbol: "₹" } }, calendars: { standard: { days: { names: ["आयतार","सोमार","मंगळार","बुधवार","बिरेस्तार","सुक्रार","शेनवार"], namesAbbr: ["आय.","सोम.","मंगळ.","बुध.","बिरे.","सुक्र.","शेन."], namesShort: ["आ","स","म","ब","ब","स","श"] }, months: { names: ["जानेवारी","फेब्रुवारी","मार्च","एप्रिल","मे","जून","जुलै","ऑगस्ट","सप्टेंबर","ऑक्टोबर","नोवेम्बर","डिसेंबर"], namesAbbr: ["जाने","फेब्रु","मार्च","एप्रिल","मे","जून","जुलै","ऑग.","सप्टें.","ऑक्टो.","नोवे.","डिसें"] }, AM: ["म.पू.","म.पू.","म.पू."], PM: ["म.नं.","म.नं.","म.नं."], patterns: { d: "dd-MM-yyyy", D: "dd MMMM yyyy", F: "dd MMMM yyyy HH:mm:ss", g: "dd-MM-yyyy HH:mm", G: "dd-MM-yyyy HH:mm:ss", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM, yyyy", Y: "MMMM, yyyy" }, "/": "-", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
hhuynhlam/Ulysses
src/client/vendor/kendo/src/js/cultures/kendo.culture.kok.js
JavaScript
mit
3,125
package me.writeily.pro.settings; import android.app.Activity; import android.app.FragmentManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.v7.app.ActionBarActivity; import me.writeily.pro.AlphanumericPinActivity; import me.writeily.pro.PinActivity; import me.writeily.pro.R; import me.writeily.pro.dialog.FilesystemDialog; import me.writeily.pro.model.Constants; /** * Created by jeff on 2014-04-11. */ public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { WriteilySettingsListener mCallback; ListPreference pinPreference; Context context; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); context = getActivity().getApplicationContext(); pinPreference = (ListPreference) findPreference(getString(R.string.pref_lock_type_key)); updateLockSummary(); // Listen for Pin Preference change pinPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object o) { String lockType = (String) o; if (lockType == null || lockType.equals("") || getString(R.string.pref_no_lock_value).equals(lockType)) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putString(Constants.USER_PIN_KEY, "").apply(); editor.putString(getString(R.string.pref_lock_type_key), getString(R.string.pref_no_lock_value)).apply(); pinPreference.setSummary(PreferenceManager.getDefaultSharedPreferences(context) .getString(getString(R.string.pref_no_lock_value), getString(R.string.pref_no_lock))); return true; } else if (getString(R.string.pref_pin_lock_value).equals(lockType)) { Intent pinIntent = new Intent(context, PinActivity.class); pinIntent.setAction(Constants.SET_PIN_ACTION); startActivityForResult(pinIntent, Constants.SET_PIN_REQUEST_CODE); } else if (getString(R.string.pref_alpha_pin_lock_value).equals(lockType)) { Intent pinIntent = new Intent(context, AlphanumericPinActivity.class); pinIntent.setAction(Constants.SET_PIN_ACTION); startActivityForResult(pinIntent, Constants.SET_PIN_REQUEST_CODE); } return false; } }); // Register PreferenceChangeListener getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); // Workaround for About-Screen Preference aboutScreen = (Preference) findPreference(getString(R.string.pref_about_key)); aboutScreen.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { if (mCallback == null) { return false; } mCallback.onAboutClicked(); return true; } }); setUpStorageDirPreference(); } private void setUpStorageDirPreference() { final Preference rootDir = (Preference) findPreference(getString(R.string.pref_root_directory)); rootDir.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { FragmentManager fragManager = getFragmentManager(); Bundle args = new Bundle(); args.putString(Constants.FILESYSTEM_ACTIVITY_ACCESS_TYPE_KEY, Constants.FILESYSTEM_SELECT_FOLDER_ACCESS_TYPE); FilesystemDialog filesystemDialog = new FilesystemDialog(); filesystemDialog.setArguments(args); filesystemDialog.show(fragManager, Constants.FILESYSTEM_SELECT_FOLDER_TAG); return true; } }); updateRootDirSummary(); } public void updateRootDirSummary() { Preference rootDir = findPreference(getString(R.string.pref_root_directory));; rootDir.setSummary(PreferenceManager.getDefaultSharedPreferences(context).getString(getString(R.string.pref_root_directory), Constants.DEFAULT_WRITEILY_STORAGE_FOLDER)); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Constants.SET_PIN_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { updateLockSummary(); } } } private void updateLockSummary() { Integer currentLockType = Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(context).getString(getString(R.string.pref_lock_type_key), "0")); pinPreference.setSummary(getResources().getStringArray(R.array.possibleLocksStrings)[currentLockType]); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { ActionBarActivity activity = (ActionBarActivity) mCallback; if (activity.getString(R.string.pref_theme_key).equals(key)) { mCallback.onThemeChanged(); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); // Make sure the container has implemented the callback interface try { mCallback = (WriteilySettingsListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + "must implement OnThemeChangedListener"); } } // Needed for callback to container activity public interface WriteilySettingsListener { public void onThemeChanged(); public void onAboutClicked(); } }
plafue/writeily-nightly
app/src/main/java/me/writeily/pro/settings/SettingsFragment.java
Java
mit
6,459
/* * The MIT License (MIT) * * Copyright (c) 2015 QAware GmbH, Munich, Germany * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package de.qaware.campus.secpro.mlr01; import sun.misc.Unsafe; import java.lang.reflect.Field; /** * Special factory to obtain unsafe instance. Ideas and code are taken from * http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/ * * @author mario-leander.reimer */ public final class TheUnsafe { /** * Utility factory class. No instances. */ private TheUnsafe() { } /** * Factory method for Unsafe instances. * * @return an Unsafe instance */ public static Unsafe getInstance() { try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); return (Unsafe) f.get(null); } catch (NoSuchFieldException | SecurityException | IllegalAccessException e) { throw new IllegalStateException(e); } } /** * Convert object to its address in memory. * * @param obj the object * @return the address in memory */ public static long toAddress(Object obj) { Object[] array = new Object[]{obj}; long baseOffset = getInstance().arrayBaseOffset(Object[].class); return normalize(getInstance().getInt(array, baseOffset)); } /** * Convert address to associated object in memory. * * @param address the address * @return the object */ public static Object fromAddress(long address) { Object[] array = new Object[]{null}; long baseOffset = getInstance().arrayBaseOffset(Object[].class); getInstance().putLong(array, baseOffset, address); return array[0]; } /** * Obtain a copy of the given object. No Cloneable required. * * @param obj the object to copy * @return the copy */ public static Object shallowCopy(Object obj) { long size = sizeOf(obj); long start = toAddress(obj); Unsafe instance = getInstance(); long address = instance.allocateMemory(size); instance.copyMemory(start, address, size); return fromAddress(address); } /** * Much simpler sizeOf can be achieved if we just read size value from the class * struct for this object, which located with offset 12 in JVM 1.7 32 bit. * * @param object the object instance * @return the size of the object */ public static long sizeOf(Object object) { Unsafe instance = getInstance(); return instance.getAddress(normalize(instance.getInt(object, 4L)) + 12L); } /** * Normalize is a method for casting signed int to unsigned long, for correct address usage. * * @param value the signed int * @return an unsigned long */ private static long normalize(int value) { if (value >= 0) return value; return (~0L >>> 32) & value; } }
lreimer/secure-programming-101
secpro-mlr01-j/src/main/java/de/qaware/campus/secpro/mlr01/TheUnsafe.java
Java
mit
4,023
/* author: dongchangzhang */ /* time: Thu Apr 20 14:48:28 2017 */ #include "symboltablemanager.h" #include <iostream> SymbolTableManager::SymbolTableManager() { main_table = do_create_new_table(START_INDEX); cursor = main_table; } addr_type SymbolTableManager::install_id(const std::string& id) { return symbol_tables[cursor].install_id(id); } addr_type SymbolTableManager::install_value(int val) { return symbol_tables[cursor].install_value(val); } addr_type SymbolTableManager::install_value(char val) { return symbol_tables[cursor].install_value(val); } void SymbolTableManager::show_addr(addr_type& addr) { symbol_tables[cursor].show_addr(addr); } void SymbolTableManager::show_addr_content(addr_type& addr) { symbol_tables[cursor].show_addr_content(addr); } int SymbolTableManager::get_int(addr_type& addr) { return symbol_tables[cursor].get_int(addr); } char SymbolTableManager::get_char(addr_type& addr) { return symbol_tables[cursor].get_char(addr); } void SymbolTableManager::declare_define_variable(int type, addr_type& addr_id) { addr_type addr; symbol_tables[cursor].declare_define_variable(type, addr_id, addr); } void SymbolTableManager::declare_define_variable(int type, addr_type& addr_id, addr_type& addr_value) { symbol_tables[cursor].declare_define_variable(type, addr_id, addr_value); } void SymbolTableManager::declare_array(int type, addr_type& addr_id, std::vector<int>& array_times) { symbol_tables[cursor].declare_array(type, addr_id, array_times); } addr_type SymbolTableManager::get_array_element_addr(addr_type& addr_id, std::vector<int>& array_times) { return symbol_tables[cursor].get_array_element_addr(addr_id, array_times); } void SymbolTableManager::variable_assignment(addr_type& id, addr_type& value) { symbol_tables[cursor].variable_assignment(id, value); } void SymbolTableManager::array_assignment(addr_type& id, addr_type& value) { symbol_tables[cursor].array_assignment(id, value); } void SymbolTableManager::value_assignment(addr_type& addr, int value) { symbol_tables[cursor].value_assignment(addr, value); } addr_type SymbolTableManager::conver_to_bool(addr_type& addr) { return symbol_tables[cursor].conver_to_bool(addr); }
dongchangzhang/zcc
src/symboltable/symboltablemanager.cpp
C++
mit
2,245
<?php namespace Api\User\Events; use App\Events\Event; use Api\User\Models\User; class UserWasUpdated extends Event { public $user; public function __construct(User $user) { $this->user = $user; } }
enli-io/fusionpbx-api
api/User/Events/UserWasUpdated.php
PHP
mit
227
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SolutionSix")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SolutionSix")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cbed6afb-8352-4030-86d7-0f5abf9793d1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
fmavrodiev/CSharpSoftUni
ExamRetake/SolutionSix/Properties/AssemblyInfo.cs
C#
mit
1,429
module Ecm module Rbac module ApplicationHelper end end end
robotex82/ecm_rbac
app/helpers/ecm/rbac/application_helper.rb
Ruby
mit
72
(function (window) { 'use strict'; /*global define, module, exports, require */ var c3 = { version: "0.4.11" }; var c3_chart_fn, c3_chart_internal_fn, c3_chart_internal_axis_fn; function API(owner) { this.owner = owner; } function inherit(base, derived) { if (Object.create) { derived.prototype = Object.create(base.prototype); } else { var f = function f() {}; f.prototype = base.prototype; derived.prototype = new f(); } derived.prototype.constructor = derived; return derived; } function Chart(config) { var $$ = this.internal = new ChartInternal(this); $$.loadConfig(config); $$.beforeInit(config); $$.init(); $$.afterInit(config); // bind "this" to nested API (function bindThis(fn, target, argThis) { Object.keys(fn).forEach(function (key) { target[key] = fn[key].bind(argThis); if (Object.keys(fn[key]).length > 0) { bindThis(fn[key], target[key], argThis); } }); })(c3_chart_fn, this, this); } function ChartInternal(api) { var $$ = this; $$.d3 = window.d3 ? window.d3 : typeof require !== 'undefined' ? require("d3") : undefined; $$.api = api; $$.config = $$.getDefaultConfig(); $$.data = {}; $$.cache = {}; $$.axes = {}; } c3.generate = function (config) { return new Chart(config); }; c3.chart = { fn: Chart.prototype, internal: { fn: ChartInternal.prototype, axis: { fn: Axis.prototype } } }; c3_chart_fn = c3.chart.fn; c3_chart_internal_fn = c3.chart.internal.fn; c3_chart_internal_axis_fn = c3.chart.internal.axis.fn; c3_chart_internal_fn.beforeInit = function () { // can do something }; c3_chart_internal_fn.afterInit = function () { // can do something }; c3_chart_internal_fn.init = function () { var $$ = this, config = $$.config; $$.initParams(); if (config.data_url) { $$.convertUrlToData(config.data_url, config.data_mimeType, config.data_headers, config.data_keys, $$.initWithData); } else if (config.data_json) { $$.initWithData($$.convertJsonToData(config.data_json, config.data_keys)); } else if (config.data_rows) { $$.initWithData($$.convertRowsToData(config.data_rows)); } else if (config.data_columns) { $$.initWithData($$.convertColumnsToData(config.data_columns)); } else { throw Error('url or json or rows or columns is required.'); } }; c3_chart_internal_fn.initParams = function () { var $$ = this, d3 = $$.d3, config = $$.config; // MEMO: clipId needs to be unique because it conflicts when multiple charts exist $$.clipId = "c3-" + (+new Date()) + '-clip', $$.clipIdForXAxis = $$.clipId + '-xaxis', $$.clipIdForYAxis = $$.clipId + '-yaxis', $$.clipIdForGrid = $$.clipId + '-grid', $$.clipIdForSubchart = $$.clipId + '-subchart', $$.clipPath = $$.getClipPath($$.clipId), $$.clipPathForXAxis = $$.getClipPath($$.clipIdForXAxis), $$.clipPathForYAxis = $$.getClipPath($$.clipIdForYAxis); $$.clipPathForGrid = $$.getClipPath($$.clipIdForGrid), $$.clipPathForSubchart = $$.getClipPath($$.clipIdForSubchart), $$.dragStart = null; $$.dragging = false; $$.flowing = false; $$.cancelClick = false; $$.mouseover = false; $$.transiting = false; $$.color = $$.generateColor(); $$.levelColor = $$.generateLevelColor(); $$.dataTimeFormat = config.data_xLocaltime ? d3.time.format : d3.time.format.utc; $$.axisTimeFormat = config.axis_x_localtime ? d3.time.format : d3.time.format.utc; $$.defaultAxisTimeFormat = $$.axisTimeFormat.multi([ [".%L", function (d) { return d.getMilliseconds(); }], [":%S", function (d) { return d.getSeconds(); }], ["%I:%M", function (d) { return d.getMinutes(); }], ["%I %p", function (d) { return d.getHours(); }], ["%-m/%-d", function (d) { return d.getDay() && d.getDate() !== 1; }], ["%-m/%-d", function (d) { return d.getDate() !== 1; }], ["%-m/%-d", function (d) { return d.getMonth(); }], ["%Y/%-m/%-d", function () { return true; }] ]); $$.hiddenTargetIds = []; $$.hiddenLegendIds = []; $$.focusedTargetIds = []; $$.defocusedTargetIds = []; $$.xOrient = config.axis_rotated ? "left" : "bottom"; $$.yOrient = config.axis_rotated ? (config.axis_y_inner ? "top" : "bottom") : (config.axis_y_inner ? "right" : "left"); $$.y2Orient = config.axis_rotated ? (config.axis_y2_inner ? "bottom" : "top") : (config.axis_y2_inner ? "left" : "right"); $$.subXOrient = config.axis_rotated ? "left" : "bottom"; $$.isLegendRight = config.legend_position === 'right'; $$.isLegendInset = config.legend_position === 'inset'; $$.isLegendTop = config.legend_inset_anchor === 'top-left' || config.legend_inset_anchor === 'top-right'; $$.isLegendLeft = config.legend_inset_anchor === 'top-left' || config.legend_inset_anchor === 'bottom-left'; $$.legendStep = 0; $$.legendItemWidth = 0; $$.legendItemHeight = 0; $$.currentMaxTickWidths = { x: 0, y: 0, y2: 0 }; $$.rotated_padding_left = 30; $$.rotated_padding_right = config.axis_rotated && !config.axis_x_show ? 0 : 30; $$.rotated_padding_top = 5; $$.withoutFadeIn = {}; $$.intervalForObserveInserted = undefined; $$.axes.subx = d3.selectAll([]); // needs when excluding subchart.js }; c3_chart_internal_fn.initChartElements = function () { if (this.initBar) { this.initBar(); } if (this.initLine) { this.initLine(); } if (this.initArc) { this.initArc(); } if (this.initGauge) { this.initGauge(); } if (this.initText) { this.initText(); } }; c3_chart_internal_fn.initWithData = function (data) { var $$ = this, d3 = $$.d3, config = $$.config; var defs, main, binding = true; $$.axis = new Axis($$); if ($$.initPie) { $$.initPie(); } if ($$.initBrush) { $$.initBrush(); } if ($$.initZoom) { $$.initZoom(); } if (!config.bindto) { $$.selectChart = d3.selectAll([]); } else if (typeof config.bindto.node === 'function') { $$.selectChart = config.bindto; } else { $$.selectChart = d3.select(config.bindto); } if ($$.selectChart.empty()) { $$.selectChart = d3.select(document.createElement('div')).style('opacity', 0); $$.observeInserted($$.selectChart); binding = false; } $$.selectChart.html("").classed("c3", true); // Init data as targets $$.data.xs = {}; $$.data.targets = $$.convertDataToTargets(data); if (config.data_filter) { $$.data.targets = $$.data.targets.filter(config.data_filter); } // Set targets to hide if needed if (config.data_hide) { $$.addHiddenTargetIds(config.data_hide === true ? $$.mapToIds($$.data.targets) : config.data_hide); } if (config.legend_hide) { $$.addHiddenLegendIds(config.legend_hide === true ? $$.mapToIds($$.data.targets) : config.legend_hide); } // when gauge, hide legend // TODO: fix if ($$.hasType('gauge')) { config.legend_show = false; } // Init sizes and scales $$.updateSizes(); $$.updateScales(); // Set domains for each scale $$.x.domain(d3.extent($$.getXDomain($$.data.targets))); $$.y.domain($$.getYDomain($$.data.targets, 'y')); $$.y2.domain($$.getYDomain($$.data.targets, 'y2')); $$.subX.domain($$.x.domain()); $$.subY.domain($$.y.domain()); $$.subY2.domain($$.y2.domain()); // Save original x domain for zoom update $$.orgXDomain = $$.x.domain(); // Set initialized scales to brush and zoom if ($$.brush) { $$.brush.scale($$.subX); } if (config.zoom_enabled) { $$.zoom.scale($$.x); } /*-- Basic Elements --*/ // Define svgs $$.svg = $$.selectChart.append("svg") .style("overflow", "hidden") .on('mouseenter', function () { return config.onmouseover.call($$); }) .on('mouseleave', function () { return config.onmouseout.call($$); }); if ($$.config.svg_classname) { $$.svg.attr('class', $$.config.svg_classname); } // Define defs defs = $$.svg.append("defs"); $$.clipChart = $$.appendClip(defs, $$.clipId); $$.clipXAxis = $$.appendClip(defs, $$.clipIdForXAxis); $$.clipYAxis = $$.appendClip(defs, $$.clipIdForYAxis); $$.clipGrid = $$.appendClip(defs, $$.clipIdForGrid); $$.clipSubchart = $$.appendClip(defs, $$.clipIdForSubchart); $$.updateSvgSize(); // Define regions main = $$.main = $$.svg.append("g").attr("transform", $$.getTranslate('main')); if ($$.initSubchart) { $$.initSubchart(); } if ($$.initTooltip) { $$.initTooltip(); } if ($$.initLegend) { $$.initLegend(); } if ($$.initTitle) { $$.initTitle(); } /*-- Main Region --*/ // text when empty main.append("text") .attr("class", CLASS.text + ' ' + CLASS.empty) .attr("text-anchor", "middle") // horizontal centering of text at x position in all browsers. .attr("dominant-baseline", "middle"); // vertical centering of text at y position in all browsers, except IE. // Regions $$.initRegion(); // Grids $$.initGrid(); // Define g for chart area main.append('g') .attr("clip-path", $$.clipPath) .attr('class', CLASS.chart); // Grid lines if (config.grid_lines_front) { $$.initGridLines(); } // Cover whole with rects for events $$.initEventRect(); // Define g for chart $$.initChartElements(); // if zoom privileged, insert rect to forefront // TODO: is this needed? main.insert('rect', config.zoom_privileged ? null : 'g.' + CLASS.regions) .attr('class', CLASS.zoomRect) .attr('width', $$.width) .attr('height', $$.height) .style('opacity', 0) .on("dblclick.zoom", null); // Set default extent if defined if (config.axis_x_extent) { $$.brush.extent($$.getDefaultExtent()); } // Add Axis $$.axis.init(); // Set targets $$.updateTargets($$.data.targets); // Draw with targets if (binding) { $$.updateDimension(); $$.config.oninit.call($$); $$.redraw({ withTransition: false, withTransform: true, withUpdateXDomain: true, withUpdateOrgXDomain: true, withTransitionForAxis: false }); } // Bind resize event $$.bindResize(); // export element of the chart $$.api.element = $$.selectChart.node(); }; c3_chart_internal_fn.smoothLines = function (el, type) { var $$ = this; if (type === 'grid') { el.each(function () { var g = $$.d3.select(this), x1 = g.attr('x1'), x2 = g.attr('x2'), y1 = g.attr('y1'), y2 = g.attr('y2'); g.attr({ 'x1': Math.ceil(x1), 'x2': Math.ceil(x2), 'y1': Math.ceil(y1), 'y2': Math.ceil(y2) }); }); } }; c3_chart_internal_fn.updateSizes = function () { var $$ = this, config = $$.config; var legendHeight = $$.legend ? $$.getLegendHeight() : 0, legendWidth = $$.legend ? $$.getLegendWidth() : 0, legendHeightForBottom = $$.isLegendRight || $$.isLegendInset ? 0 : legendHeight, hasArc = $$.hasArcType(), xAxisHeight = config.axis_rotated || hasArc ? 0 : $$.getHorizontalAxisHeight('x'), subchartHeight = config.subchart_show && !hasArc ? (config.subchart_size_height + xAxisHeight) : 0; $$.currentWidth = $$.getCurrentWidth(); $$.currentHeight = $$.getCurrentHeight(); // for main $$.margin = config.axis_rotated ? { top: $$.getHorizontalAxisHeight('y2') + $$.getCurrentPaddingTop(), right: hasArc ? 0 : $$.getCurrentPaddingRight(), bottom: $$.getHorizontalAxisHeight('y') + legendHeightForBottom + $$.getCurrentPaddingBottom(), left: subchartHeight + (hasArc ? 0 : $$.getCurrentPaddingLeft()) } : { top: 4 + $$.getCurrentPaddingTop(), // for top tick text right: hasArc ? 0 : $$.getCurrentPaddingRight(), bottom: xAxisHeight + subchartHeight + legendHeightForBottom + $$.getCurrentPaddingBottom(), left: hasArc ? 0 : $$.getCurrentPaddingLeft() }; // for subchart $$.margin2 = config.axis_rotated ? { top: $$.margin.top, right: NaN, bottom: 20 + legendHeightForBottom, left: $$.rotated_padding_left } : { top: $$.currentHeight - subchartHeight - legendHeightForBottom, right: NaN, bottom: xAxisHeight + legendHeightForBottom, left: $$.margin.left }; // for legend $$.margin3 = { top: 0, right: NaN, bottom: 0, left: 0 }; if ($$.updateSizeForLegend) { $$.updateSizeForLegend(legendHeight, legendWidth); } $$.width = $$.currentWidth - $$.margin.left - $$.margin.right; $$.height = $$.currentHeight - $$.margin.top - $$.margin.bottom; if ($$.width < 0) { $$.width = 0; } if ($$.height < 0) { $$.height = 0; } $$.width2 = config.axis_rotated ? $$.margin.left - $$.rotated_padding_left - $$.rotated_padding_right : $$.width; $$.height2 = config.axis_rotated ? $$.height : $$.currentHeight - $$.margin2.top - $$.margin2.bottom; if ($$.width2 < 0) { $$.width2 = 0; } if ($$.height2 < 0) { $$.height2 = 0; } // for arc $$.arcWidth = $$.width - ($$.isLegendRight ? legendWidth + 10 : 0); $$.arcHeight = $$.height - ($$.isLegendRight ? 0 : 10); if ($$.hasType('gauge') && !config.gauge_fullCircle) { $$.arcHeight += $$.height - $$.getGaugeLabelHeight(); } if ($$.updateRadius) { $$.updateRadius(); } if ($$.isLegendRight && hasArc) { $$.margin3.left = $$.arcWidth / 2 + $$.radiusExpanded * 1.1; } }; c3_chart_internal_fn.updateTargets = function (targets) { var $$ = this; /*-- Main --*/ //-- Text --// $$.updateTargetsForText(targets); //-- Bar --// $$.updateTargetsForBar(targets); //-- Line --// $$.updateTargetsForLine(targets); //-- Arc --// if ($$.hasArcType() && $$.updateTargetsForArc) { $$.updateTargetsForArc(targets); } /*-- Sub --*/ if ($$.updateTargetsForSubchart) { $$.updateTargetsForSubchart(targets); } // Fade-in each chart $$.showTargets(); }; c3_chart_internal_fn.showTargets = function () { var $$ = this; $$.svg.selectAll('.' + CLASS.target).filter(function (d) { return $$.isTargetToShow(d.id); }) .transition().duration($$.config.transition_duration) .style("opacity", 1); }; c3_chart_internal_fn.redraw = function (options, transitions) { var $$ = this, main = $$.main, d3 = $$.d3, config = $$.config; var areaIndices = $$.getShapeIndices($$.isAreaType), barIndices = $$.getShapeIndices($$.isBarType), lineIndices = $$.getShapeIndices($$.isLineType); var withY, withSubchart, withTransition, withTransitionForExit, withTransitionForAxis, withTransform, withUpdateXDomain, withUpdateOrgXDomain, withTrimXDomain, withLegend, withEventRect, withDimension, withUpdateXAxis; var hideAxis = $$.hasArcType(); var drawArea, drawBar, drawLine, xForText, yForText; var duration, durationForExit, durationForAxis; var waitForDraw, flow; var targetsToShow = $$.filterTargetsToShow($$.data.targets), tickValues, i, intervalForCulling, xDomainForZoom; var xv = $$.xv.bind($$), cx, cy; options = options || {}; withY = getOption(options, "withY", true); withSubchart = getOption(options, "withSubchart", true); withTransition = getOption(options, "withTransition", true); withTransform = getOption(options, "withTransform", false); withUpdateXDomain = getOption(options, "withUpdateXDomain", false); withUpdateOrgXDomain = getOption(options, "withUpdateOrgXDomain", false); withTrimXDomain = getOption(options, "withTrimXDomain", true); withUpdateXAxis = getOption(options, "withUpdateXAxis", withUpdateXDomain); withLegend = getOption(options, "withLegend", false); withEventRect = getOption(options, "withEventRect", true); withDimension = getOption(options, "withDimension", true); withTransitionForExit = getOption(options, "withTransitionForExit", withTransition); withTransitionForAxis = getOption(options, "withTransitionForAxis", withTransition); duration = withTransition ? config.transition_duration : 0; durationForExit = withTransitionForExit ? duration : 0; durationForAxis = withTransitionForAxis ? duration : 0; transitions = transitions || $$.axis.generateTransitions(durationForAxis); // update legend and transform each g if (withLegend && config.legend_show) { $$.updateLegend($$.mapToIds($$.data.targets), options, transitions); } else if (withDimension) { // need to update dimension (e.g. axis.y.tick.values) because y tick values should change // no need to update axis in it because they will be updated in redraw() $$.updateDimension(true); } // MEMO: needed for grids calculation if ($$.isCategorized() && targetsToShow.length === 0) { $$.x.domain([0, $$.axes.x.selectAll('.tick').size()]); } if (targetsToShow.length) { $$.updateXDomain(targetsToShow, withUpdateXDomain, withUpdateOrgXDomain, withTrimXDomain); if (!config.axis_x_tick_values) { tickValues = $$.axis.updateXAxisTickValues(targetsToShow); } } else { $$.xAxis.tickValues([]); $$.subXAxis.tickValues([]); } if (config.zoom_rescale && !options.flow) { xDomainForZoom = $$.x.orgDomain(); } $$.y.domain($$.getYDomain(targetsToShow, 'y', xDomainForZoom)); $$.y2.domain($$.getYDomain(targetsToShow, 'y2', xDomainForZoom)); if (!config.axis_y_tick_values && config.axis_y_tick_count) { $$.yAxis.tickValues($$.axis.generateTickValues($$.y.domain(), config.axis_y_tick_count)); } if (!config.axis_y2_tick_values && config.axis_y2_tick_count) { $$.y2Axis.tickValues($$.axis.generateTickValues($$.y2.domain(), config.axis_y2_tick_count)); } // axes $$.axis.redraw(transitions, hideAxis); // Update axis label $$.axis.updateLabels(withTransition); // show/hide if manual culling needed if ((withUpdateXDomain || withUpdateXAxis) && targetsToShow.length) { if (config.axis_x_tick_culling && tickValues) { for (i = 1; i < tickValues.length; i++) { if (tickValues.length / i < config.axis_x_tick_culling_max) { intervalForCulling = i; break; } } $$.svg.selectAll('.' + CLASS.axisX + ' .tick text').each(function (e) { var index = tickValues.indexOf(e); if (index >= 0) { d3.select(this).style('display', index % intervalForCulling ? 'none' : 'block'); } }); } else { $$.svg.selectAll('.' + CLASS.axisX + ' .tick text').style('display', 'block'); } } // setup drawer - MEMO: these must be called after axis updated drawArea = $$.generateDrawArea ? $$.generateDrawArea(areaIndices, false) : undefined; drawBar = $$.generateDrawBar ? $$.generateDrawBar(barIndices) : undefined; drawLine = $$.generateDrawLine ? $$.generateDrawLine(lineIndices, false) : undefined; xForText = $$.generateXYForText(areaIndices, barIndices, lineIndices, true); yForText = $$.generateXYForText(areaIndices, barIndices, lineIndices, false); // Update sub domain if (withY) { $$.subY.domain($$.getYDomain(targetsToShow, 'y')); $$.subY2.domain($$.getYDomain(targetsToShow, 'y2')); } // xgrid focus $$.updateXgridFocus(); // Data empty label positioning and text. main.select("text." + CLASS.text + '.' + CLASS.empty) .attr("x", $$.width / 2) .attr("y", $$.height / 2) .text(config.data_empty_label_text) .transition() .style('opacity', targetsToShow.length ? 0 : 1); // grid $$.updateGrid(duration); // rect for regions $$.updateRegion(duration); // bars $$.updateBar(durationForExit); // lines, areas and cricles $$.updateLine(durationForExit); $$.updateArea(durationForExit); $$.updateCircle(); // text if ($$.hasDataLabel()) { $$.updateText(durationForExit); } // title if ($$.redrawTitle) { $$.redrawTitle(); } // arc if ($$.redrawArc) { $$.redrawArc(duration, durationForExit, withTransform); } // subchart if ($$.redrawSubchart) { $$.redrawSubchart(withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices); } // circles for select main.selectAll('.' + CLASS.selectedCircles) .filter($$.isBarType.bind($$)) .selectAll('circle') .remove(); // event rects will redrawn when flow called if (config.interaction_enabled && !options.flow && withEventRect) { $$.redrawEventRect(); if ($$.updateZoom) { $$.updateZoom(); } } // update circleY based on updated parameters $$.updateCircleY(); // generate circle x/y functions depending on updated params cx = ($$.config.axis_rotated ? $$.circleY : $$.circleX).bind($$); cy = ($$.config.axis_rotated ? $$.circleX : $$.circleY).bind($$); if (options.flow) { flow = $$.generateFlow({ targets: targetsToShow, flow: options.flow, duration: options.flow.duration, drawBar: drawBar, drawLine: drawLine, drawArea: drawArea, cx: cx, cy: cy, xv: xv, xForText: xForText, yForText: yForText }); } if ((duration || flow) && $$.isTabVisible()) { // Only use transition if tab visible. See #938. // transition should be derived from one transition d3.transition().duration(duration).each(function () { var transitionsToWait = []; // redraw and gather transitions [ $$.redrawBar(drawBar, true), $$.redrawLine(drawLine, true), $$.redrawArea(drawArea, true), $$.redrawCircle(cx, cy, true), $$.redrawText(xForText, yForText, options.flow, true), $$.redrawRegion(true), $$.redrawGrid(true), ].forEach(function (transitions) { transitions.forEach(function (transition) { transitionsToWait.push(transition); }); }); // Wait for end of transitions to call flow and onrendered callback waitForDraw = $$.generateWait(); transitionsToWait.forEach(function (t) { waitForDraw.add(t); }); }) .call(waitForDraw, function () { if (flow) { flow(); } if (config.onrendered) { config.onrendered.call($$); } }); } else { $$.redrawBar(drawBar); $$.redrawLine(drawLine); $$.redrawArea(drawArea); $$.redrawCircle(cx, cy); $$.redrawText(xForText, yForText, options.flow); $$.redrawRegion(); $$.redrawGrid(); if (config.onrendered) { config.onrendered.call($$); } } // update fadein condition $$.mapToIds($$.data.targets).forEach(function (id) { $$.withoutFadeIn[id] = true; }); }; c3_chart_internal_fn.updateAndRedraw = function (options) { var $$ = this, config = $$.config, transitions; options = options || {}; // same with redraw options.withTransition = getOption(options, "withTransition", true); options.withTransform = getOption(options, "withTransform", false); options.withLegend = getOption(options, "withLegend", false); // NOT same with redraw options.withUpdateXDomain = true; options.withUpdateOrgXDomain = true; options.withTransitionForExit = false; options.withTransitionForTransform = getOption(options, "withTransitionForTransform", options.withTransition); // MEMO: this needs to be called before updateLegend and it means this ALWAYS needs to be called) $$.updateSizes(); // MEMO: called in updateLegend in redraw if withLegend if (!(options.withLegend && config.legend_show)) { transitions = $$.axis.generateTransitions(options.withTransitionForAxis ? config.transition_duration : 0); // Update scales $$.updateScales(); $$.updateSvgSize(); // Update g positions $$.transformAll(options.withTransitionForTransform, transitions); } // Draw with new sizes & scales $$.redraw(options, transitions); }; c3_chart_internal_fn.redrawWithoutRescale = function () { this.redraw({ withY: false, withSubchart: false, withEventRect: false, withTransitionForAxis: false }); }; c3_chart_internal_fn.isTimeSeries = function () { return this.config.axis_x_type === 'timeseries'; }; c3_chart_internal_fn.isCategorized = function () { return this.config.axis_x_type.indexOf('categor') >= 0; }; c3_chart_internal_fn.isCustomX = function () { var $$ = this, config = $$.config; return !$$.isTimeSeries() && (config.data_x || notEmpty(config.data_xs)); }; c3_chart_internal_fn.isTimeSeriesY = function () { return this.config.axis_y_type === 'timeseries'; }; c3_chart_internal_fn.getTranslate = function (target) { var $$ = this, config = $$.config, x, y; if (target === 'main') { x = asHalfPixel($$.margin.left); y = asHalfPixel($$.margin.top); } else if (target === 'context') { x = asHalfPixel($$.margin2.left); y = asHalfPixel($$.margin2.top); } else if (target === 'legend') { x = $$.margin3.left; y = $$.margin3.top; } else if (target === 'x') { x = 0; y = config.axis_rotated ? 0 : $$.height; } else if (target === 'y') { x = 0; y = config.axis_rotated ? $$.height : 0; } else if (target === 'y2') { x = config.axis_rotated ? 0 : $$.width; y = config.axis_rotated ? 1 : 0; } else if (target === 'subx') { x = 0; y = config.axis_rotated ? 0 : $$.height2; } else if (target === 'arc') { x = $$.arcWidth / 2; y = $$.arcHeight / 2; } return "translate(" + x + "," + y + ")"; }; c3_chart_internal_fn.initialOpacity = function (d) { return d.value !== null && this.withoutFadeIn[d.id] ? 1 : 0; }; c3_chart_internal_fn.initialOpacityForCircle = function (d) { return d.value !== null && this.withoutFadeIn[d.id] ? this.opacityForCircle(d) : 0; }; c3_chart_internal_fn.opacityForCircle = function (d) { var opacity = this.config.point_show ? 1 : 0; return isValue(d.value) ? (this.isScatterType(d) ? 0.5 : opacity) : 0; }; c3_chart_internal_fn.opacityForText = function () { return this.hasDataLabel() ? 1 : 0; }; c3_chart_internal_fn.xx = function (d) { return d ? this.x(d.x) : null; }; c3_chart_internal_fn.xv = function (d) { var $$ = this, value = d.value; if ($$.isTimeSeries()) { value = $$.parseDate(d.value); } else if ($$.isCategorized() && typeof d.value === 'string') { value = $$.config.axis_x_categories.indexOf(d.value); } return Math.ceil($$.x(value)); }; c3_chart_internal_fn.yv = function (d) { var $$ = this, yScale = d.axis && d.axis === 'y2' ? $$.y2 : $$.y; return Math.ceil(yScale(d.value)); }; c3_chart_internal_fn.subxx = function (d) { return d ? this.subX(d.x) : null; }; c3_chart_internal_fn.transformMain = function (withTransition, transitions) { var $$ = this, xAxis, yAxis, y2Axis; if (transitions && transitions.axisX) { xAxis = transitions.axisX; } else { xAxis = $$.main.select('.' + CLASS.axisX); if (withTransition) { xAxis = xAxis.transition(); } } if (transitions && transitions.axisY) { yAxis = transitions.axisY; } else { yAxis = $$.main.select('.' + CLASS.axisY); if (withTransition) { yAxis = yAxis.transition(); } } if (transitions && transitions.axisY2) { y2Axis = transitions.axisY2; } else { y2Axis = $$.main.select('.' + CLASS.axisY2); if (withTransition) { y2Axis = y2Axis.transition(); } } (withTransition ? $$.main.transition() : $$.main).attr("transform", $$.getTranslate('main')); xAxis.attr("transform", $$.getTranslate('x')); yAxis.attr("transform", $$.getTranslate('y')); y2Axis.attr("transform", $$.getTranslate('y2')); $$.main.select('.' + CLASS.chartArcs).attr("transform", $$.getTranslate('arc')); }; c3_chart_internal_fn.transformAll = function (withTransition, transitions) { var $$ = this; $$.transformMain(withTransition, transitions); if ($$.config.subchart_show) { $$.transformContext(withTransition, transitions); } if ($$.legend) { $$.transformLegend(withTransition); } }; c3_chart_internal_fn.updateSvgSize = function () { var $$ = this, brush = $$.svg.select(".c3-brush .background"); $$.svg.attr('width', $$.currentWidth).attr('height', $$.currentHeight); $$.svg.selectAll(['#' + $$.clipId, '#' + $$.clipIdForGrid]).select('rect') .attr('width', $$.width) .attr('height', $$.height); $$.svg.select('#' + $$.clipIdForXAxis).select('rect') .attr('x', $$.getXAxisClipX.bind($$)) .attr('y', $$.getXAxisClipY.bind($$)) .attr('width', $$.getXAxisClipWidth.bind($$)) .attr('height', $$.getXAxisClipHeight.bind($$)); $$.svg.select('#' + $$.clipIdForYAxis).select('rect') .attr('x', $$.getYAxisClipX.bind($$)) .attr('y', $$.getYAxisClipY.bind($$)) .attr('width', $$.getYAxisClipWidth.bind($$)) .attr('height', $$.getYAxisClipHeight.bind($$)); $$.svg.select('#' + $$.clipIdForSubchart).select('rect') .attr('width', $$.width) .attr('height', brush.size() ? brush.attr('height') : 0); $$.svg.select('.' + CLASS.zoomRect) .attr('width', $$.width) .attr('height', $$.height); // MEMO: parent div's height will be bigger than svg when <!DOCTYPE html> $$.selectChart.style('max-height', $$.currentHeight + "px"); }; c3_chart_internal_fn.updateDimension = function (withoutAxis) { var $$ = this; if (!withoutAxis) { if ($$.config.axis_rotated) { $$.axes.x.call($$.xAxis); $$.axes.subx.call($$.subXAxis); } else { $$.axes.y.call($$.yAxis); $$.axes.y2.call($$.y2Axis); } } $$.updateSizes(); $$.updateScales(); $$.updateSvgSize(); $$.transformAll(false); }; c3_chart_internal_fn.observeInserted = function (selection) { var $$ = this, observer; if (typeof MutationObserver === 'undefined') { window.console.error("MutationObserver not defined."); return; } observer= new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { if (mutation.type === 'childList' && mutation.previousSibling) { observer.disconnect(); // need to wait for completion of load because size calculation requires the actual sizes determined after that completion $$.intervalForObserveInserted = window.setInterval(function () { // parentNode will NOT be null when completed if (selection.node().parentNode) { window.clearInterval($$.intervalForObserveInserted); $$.updateDimension(); if ($$.brush) { $$.brush.update(); } $$.config.oninit.call($$); $$.redraw({ withTransform: true, withUpdateXDomain: true, withUpdateOrgXDomain: true, withTransition: false, withTransitionForTransform: false, withLegend: true }); selection.transition().style('opacity', 1); } }, 10); } }); }); observer.observe(selection.node(), {attributes: true, childList: true, characterData: true}); }; c3_chart_internal_fn.bindResize = function () { var $$ = this, config = $$.config; $$.resizeFunction = $$.generateResize(); $$.resizeFunction.add(function () { config.onresize.call($$); }); if (config.resize_auto) { $$.resizeFunction.add(function () { if ($$.resizeTimeout !== undefined) { window.clearTimeout($$.resizeTimeout); } $$.resizeTimeout = window.setTimeout(function () { delete $$.resizeTimeout; $$.api.flush(); }, 100); }); } $$.resizeFunction.add(function () { config.onresized.call($$); }); if (window.attachEvent) { window.attachEvent('onresize', $$.resizeFunction); } else if (window.addEventListener) { window.addEventListener('resize', $$.resizeFunction, false); } else { // fallback to this, if this is a very old browser var wrapper = window.onresize; if (!wrapper) { // create a wrapper that will call all charts wrapper = $$.generateResize(); } else if (!wrapper.add || !wrapper.remove) { // there is already a handler registered, make sure we call it too wrapper = $$.generateResize(); wrapper.add(window.onresize); } // add this graph to the wrapper, we will be removed if the user calls destroy wrapper.add($$.resizeFunction); window.onresize = wrapper; } }; c3_chart_internal_fn.generateResize = function () { var resizeFunctions = []; function callResizeFunctions() { resizeFunctions.forEach(function (f) { f(); }); } callResizeFunctions.add = function (f) { resizeFunctions.push(f); }; callResizeFunctions.remove = function (f) { for (var i = 0; i < resizeFunctions.length; i++) { if (resizeFunctions[i] === f) { resizeFunctions.splice(i, 1); break; } } }; return callResizeFunctions; }; c3_chart_internal_fn.endall = function (transition, callback) { var n = 0; transition .each(function () { ++n; }) .each("end", function () { if (!--n) { callback.apply(this, arguments); } }); }; c3_chart_internal_fn.generateWait = function () { var transitionsToWait = [], f = function (transition, callback) { var timer = setInterval(function () { var done = 0; transitionsToWait.forEach(function (t) { if (t.empty()) { done += 1; return; } try { t.transition(); } catch (e) { done += 1; } }); if (done === transitionsToWait.length) { clearInterval(timer); if (callback) { callback(); } } }, 10); }; f.add = function (transition) { transitionsToWait.push(transition); }; return f; }; c3_chart_internal_fn.parseDate = function (date) { var $$ = this, parsedDate; if (date instanceof Date) { parsedDate = date; } else if (typeof date === 'string') { parsedDate = $$.dataTimeFormat($$.config.data_xFormat).parse(date); } else if (typeof date === 'number' && !isNaN(date)) { parsedDate = new Date(+date); } if (!parsedDate || isNaN(+parsedDate)) { window.console.error("Failed to parse x '" + date + "' to Date object"); } return parsedDate; }; c3_chart_internal_fn.isTabVisible = function () { var hidden; if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support hidden = "hidden"; } else if (typeof document.mozHidden !== "undefined") { hidden = "mozHidden"; } else if (typeof document.msHidden !== "undefined") { hidden = "msHidden"; } else if (typeof document.webkitHidden !== "undefined") { hidden = "webkitHidden"; } return document[hidden] ? false : true; }; c3_chart_internal_fn.getDefaultConfig = function () { var config = { bindto: '#chart', svg_classname: undefined, size_width: undefined, size_height: undefined, padding_left: undefined, padding_right: undefined, padding_top: undefined, padding_bottom: undefined, resize_auto: true, zoom_enabled: false, zoom_extent: undefined, zoom_privileged: false, zoom_rescale: false, zoom_onzoom: function () {}, zoom_onzoomstart: function () {}, zoom_onzoomend: function () {}, zoom_x_min: undefined, zoom_x_max: undefined, interaction_brighten: true, interaction_enabled: true, onmouseover: function () {}, onmouseout: function () {}, onresize: function () {}, onresized: function () {}, oninit: function () {}, onrendered: function () {}, transition_duration: 350, data_x: undefined, data_xs: {}, data_xFormat: '%Y-%m-%d', data_xLocaltime: true, data_xSort: true, data_idConverter: function (id) { return id; }, data_names: {}, data_classes: {}, data_groups: [], data_axes: {}, data_type: undefined, data_types: {}, data_labels: {}, data_order: 'desc', data_regions: {}, data_color: undefined, data_colors: {}, data_hide: false, data_filter: undefined, data_selection_enabled: false, data_selection_grouped: false, data_selection_isselectable: function () { return true; }, data_selection_multiple: true, data_selection_draggable: false, data_onclick: function () {}, data_onmouseover: function () {}, data_onmouseout: function () {}, data_onselected: function () {}, data_onunselected: function () {}, data_url: undefined, data_headers: undefined, data_json: undefined, data_rows: undefined, data_columns: undefined, data_mimeType: undefined, data_keys: undefined, // configuration for no plot-able data supplied. data_empty_label_text: "", // subchart subchart_show: false, subchart_size_height: 60, subchart_axis_x_show: true, subchart_onbrush: function () {}, // color color_pattern: [], color_threshold: {}, // legend legend_show: true, legend_hide: false, legend_position: 'bottom', legend_inset_anchor: 'top-left', legend_inset_x: 10, legend_inset_y: 0, legend_inset_step: undefined, legend_item_onclick: undefined, legend_item_onmouseover: undefined, legend_item_onmouseout: undefined, legend_equally: false, legend_padding: 0, legend_item_tile_width: 10, legend_item_tile_height: 10, // axis axis_rotated: false, axis_x_show: true, axis_x_type: 'indexed', axis_x_localtime: true, axis_x_categories: [], axis_x_tick_centered: false, axis_x_tick_format: undefined, axis_x_tick_culling: {}, axis_x_tick_culling_max: 10, axis_x_tick_count: undefined, axis_x_tick_fit: true, axis_x_tick_values: null, axis_x_tick_rotate: 0, axis_x_tick_outer: true, axis_x_tick_multiline: true, axis_x_tick_width: null, axis_x_max: undefined, axis_x_min: undefined, axis_x_padding: {}, axis_x_height: undefined, axis_x_extent: undefined, axis_x_label: {}, axis_y_show: true, axis_y_type: undefined, axis_y_max: undefined, axis_y_min: undefined, axis_y_inverted: false, axis_y_center: undefined, axis_y_inner: undefined, axis_y_label: {}, axis_y_tick_format: undefined, axis_y_tick_outer: true, axis_y_tick_values: null, axis_y_tick_rotate: 0, axis_y_tick_count: undefined, axis_y_tick_time_value: undefined, axis_y_tick_time_interval: undefined, axis_y_padding: {}, axis_y_default: undefined, axis_y2_show: false, axis_y2_max: undefined, axis_y2_min: undefined, axis_y2_inverted: false, axis_y2_center: undefined, axis_y2_inner: undefined, axis_y2_label: {}, axis_y2_tick_format: undefined, axis_y2_tick_outer: true, axis_y2_tick_values: null, axis_y2_tick_count: undefined, axis_y2_padding: {}, axis_y2_default: undefined, // grid grid_x_show: false, grid_x_type: 'tick', grid_x_lines: [], grid_y_show: false, // not used // grid_y_type: 'tick', grid_y_lines: [], grid_y_ticks: 10, grid_focus_show: true, grid_lines_front: true, // point - point of each data point_show: true, point_r: 2.5, point_sensitivity: 10, point_focus_expand_enabled: true, point_focus_expand_r: undefined, point_select_r: undefined, // line line_connectNull: false, line_step_type: 'step', // bar bar_width: undefined, bar_width_ratio: 0.6, bar_width_max: undefined, bar_zerobased: true, // area area_zerobased: true, area_above: false, // pie pie_label_show: true, pie_label_format: undefined, pie_label_threshold: 0.05, pie_label_ratio: undefined, pie_expand: {}, pie_expand_duration: 50, // gauge gauge_fullCircle: false, gauge_label_show: true, gauge_label_format: undefined, gauge_min: 0, gauge_max: 100, gauge_startingAngle: -1 * Math.PI/2, gauge_units: undefined, gauge_width: undefined, gauge_expand: {}, gauge_expand_duration: 50, // donut donut_label_show: true, donut_label_format: undefined, donut_label_threshold: 0.05, donut_label_ratio: undefined, donut_width: undefined, donut_title: "", donut_expand: {}, donut_expand_duration: 50, // spline spline_interpolation_type: 'cardinal', // region - region to change style regions: [], // tooltip - show when mouseover on each data tooltip_show: true, tooltip_grouped: true, tooltip_format_title: undefined, tooltip_format_name: undefined, tooltip_format_value: undefined, tooltip_position: undefined, tooltip_contents: function (d, defaultTitleFormat, defaultValueFormat, color) { return this.getTooltipContent ? this.getTooltipContent(d, defaultTitleFormat, defaultValueFormat, color) : ''; }, tooltip_init_show: false, tooltip_init_x: 0, tooltip_init_position: {top: '0px', left: '50px'}, tooltip_onshow: function () {}, tooltip_onhide: function () {}, // title title_text: undefined, title_padding: { top: 0, right: 0, bottom: 0, left: 0 }, title_position: 'top-center', }; Object.keys(this.additionalConfig).forEach(function (key) { config[key] = this.additionalConfig[key]; }, this); return config; }; c3_chart_internal_fn.additionalConfig = {}; c3_chart_internal_fn.loadConfig = function (config) { var this_config = this.config, target, keys, read; function find() { var key = keys.shift(); // console.log("key =>", key, ", target =>", target); if (key && target && typeof target === 'object' && key in target) { target = target[key]; return find(); } else if (!key) { return target; } else { return undefined; } } Object.keys(this_config).forEach(function (key) { target = config; keys = key.split('_'); read = find(); // console.log("CONFIG : ", key, read); if (isDefined(read)) { this_config[key] = read; } }); }; c3_chart_internal_fn.getScale = function (min, max, forTimeseries) { return (forTimeseries ? this.d3.time.scale() : this.d3.scale.linear()).range([min, max]); }; c3_chart_internal_fn.getX = function (min, max, domain, offset) { var $$ = this, scale = $$.getScale(min, max, $$.isTimeSeries()), _scale = domain ? scale.domain(domain) : scale, key; // Define customized scale if categorized axis if ($$.isCategorized()) { offset = offset || function () { return 0; }; scale = function (d, raw) { var v = _scale(d) + offset(d); return raw ? v : Math.ceil(v); }; } else { scale = function (d, raw) { var v = _scale(d); return raw ? v : Math.ceil(v); }; } // define functions for (key in _scale) { scale[key] = _scale[key]; } scale.orgDomain = function () { return _scale.domain(); }; // define custom domain() for categorized axis if ($$.isCategorized()) { scale.domain = function (domain) { if (!arguments.length) { domain = this.orgDomain(); return [domain[0], domain[1] + 1]; } _scale.domain(domain); return scale; }; } return scale; }; c3_chart_internal_fn.getY = function (min, max, domain) { var scale = this.getScale(min, max, this.isTimeSeriesY()); if (domain) { scale.domain(domain); } return scale; }; c3_chart_internal_fn.getYScale = function (id) { return this.axis.getId(id) === 'y2' ? this.y2 : this.y; }; c3_chart_internal_fn.getSubYScale = function (id) { return this.axis.getId(id) === 'y2' ? this.subY2 : this.subY; }; c3_chart_internal_fn.updateScales = function () { var $$ = this, config = $$.config, forInit = !$$.x; // update edges $$.xMin = config.axis_rotated ? 1 : 0; $$.xMax = config.axis_rotated ? $$.height : $$.width; $$.yMin = config.axis_rotated ? 0 : $$.height; $$.yMax = config.axis_rotated ? $$.width : 1; $$.subXMin = $$.xMin; $$.subXMax = $$.xMax; $$.subYMin = config.axis_rotated ? 0 : $$.height2; $$.subYMax = config.axis_rotated ? $$.width2 : 1; // update scales $$.x = $$.getX($$.xMin, $$.xMax, forInit ? undefined : $$.x.orgDomain(), function () { return $$.xAxis.tickOffset(); }); $$.y = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y_default : $$.y.domain()); $$.y2 = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y2_default : $$.y2.domain()); $$.subX = $$.getX($$.xMin, $$.xMax, $$.orgXDomain, function (d) { return d % 1 ? 0 : $$.subXAxis.tickOffset(); }); $$.subY = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y_default : $$.subY.domain()); $$.subY2 = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y2_default : $$.subY2.domain()); // update axes $$.xAxisTickFormat = $$.axis.getXAxisTickFormat(); $$.xAxisTickValues = $$.axis.getXAxisTickValues(); $$.yAxisTickValues = $$.axis.getYAxisTickValues(); $$.y2AxisTickValues = $$.axis.getY2AxisTickValues(); $$.xAxis = $$.axis.getXAxis($$.x, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer); $$.subXAxis = $$.axis.getXAxis($$.subX, $$.subXOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer); $$.yAxis = $$.axis.getYAxis($$.y, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues, config.axis_y_tick_outer); $$.y2Axis = $$.axis.getYAxis($$.y2, $$.y2Orient, config.axis_y2_tick_format, $$.y2AxisTickValues, config.axis_y2_tick_outer); // Set initialized scales to brush and zoom if (!forInit) { if ($$.brush) { $$.brush.scale($$.subX); } if (config.zoom_enabled) { $$.zoom.scale($$.x); } } // update for arc if ($$.updateArc) { $$.updateArc(); } }; c3_chart_internal_fn.getYDomainMin = function (targets) { var $$ = this, config = $$.config, ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets), j, k, baseId, idsInGroup, id, hasNegativeValue; if (config.data_groups.length > 0) { hasNegativeValue = $$.hasNegativeValueInTargets(targets); for (j = 0; j < config.data_groups.length; j++) { // Determine baseId idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; }); if (idsInGroup.length === 0) { continue; } baseId = idsInGroup[0]; // Consider negative values if (hasNegativeValue && ys[baseId]) { ys[baseId].forEach(function (v, i) { ys[baseId][i] = v < 0 ? v : 0; }); } // Compute min for (k = 1; k < idsInGroup.length; k++) { id = idsInGroup[k]; if (! ys[id]) { continue; } ys[id].forEach(function (v, i) { if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasNegativeValue && +v > 0)) { ys[baseId][i] += +v; } }); } } } return $$.d3.min(Object.keys(ys).map(function (key) { return $$.d3.min(ys[key]); })); }; c3_chart_internal_fn.getYDomainMax = function (targets) { var $$ = this, config = $$.config, ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets), j, k, baseId, idsInGroup, id, hasPositiveValue; if (config.data_groups.length > 0) { hasPositiveValue = $$.hasPositiveValueInTargets(targets); for (j = 0; j < config.data_groups.length; j++) { // Determine baseId idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; }); if (idsInGroup.length === 0) { continue; } baseId = idsInGroup[0]; // Consider positive values if (hasPositiveValue && ys[baseId]) { ys[baseId].forEach(function (v, i) { ys[baseId][i] = v > 0 ? v : 0; }); } // Compute max for (k = 1; k < idsInGroup.length; k++) { id = idsInGroup[k]; if (! ys[id]) { continue; } ys[id].forEach(function (v, i) { if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasPositiveValue && +v < 0)) { ys[baseId][i] += +v; } }); } } } return $$.d3.max(Object.keys(ys).map(function (key) { return $$.d3.max(ys[key]); })); }; c3_chart_internal_fn.getYDomain = function (targets, axisId, xDomain) { var $$ = this, config = $$.config, targetsByAxisId = targets.filter(function (t) { return $$.axis.getId(t.id) === axisId; }), yTargets = xDomain ? $$.filterByXDomain(targetsByAxisId, xDomain) : targetsByAxisId, yMin = axisId === 'y2' ? config.axis_y2_min : config.axis_y_min, yMax = axisId === 'y2' ? config.axis_y2_max : config.axis_y_max, yDomainMin = $$.getYDomainMin(yTargets), yDomainMax = $$.getYDomainMax(yTargets), domain, domainLength, padding, padding_top, padding_bottom, center = axisId === 'y2' ? config.axis_y2_center : config.axis_y_center, yDomainAbs, lengths, diff, ratio, isAllPositive, isAllNegative, isZeroBased = ($$.hasType('bar', yTargets) && config.bar_zerobased) || ($$.hasType('area', yTargets) && config.area_zerobased), isInverted = axisId === 'y2' ? config.axis_y2_inverted : config.axis_y_inverted, showHorizontalDataLabel = $$.hasDataLabel() && config.axis_rotated, showVerticalDataLabel = $$.hasDataLabel() && !config.axis_rotated; // MEMO: avoid inverting domain unexpectedly yDomainMin = isValue(yMin) ? yMin : isValue(yMax) ? (yDomainMin < yMax ? yDomainMin : yMax - 10) : yDomainMin; yDomainMax = isValue(yMax) ? yMax : isValue(yMin) ? (yMin < yDomainMax ? yDomainMax : yMin + 10) : yDomainMax; if (yTargets.length === 0) { // use current domain if target of axisId is none return axisId === 'y2' ? $$.y2.domain() : $$.y.domain(); } if (isNaN(yDomainMin)) { // set minimum to zero when not number yDomainMin = 0; } if (isNaN(yDomainMax)) { // set maximum to have same value as yDomainMin yDomainMax = yDomainMin; } if (yDomainMin === yDomainMax) { yDomainMin < 0 ? yDomainMax = 0 : yDomainMin = 0; } isAllPositive = yDomainMin >= 0 && yDomainMax >= 0; isAllNegative = yDomainMin <= 0 && yDomainMax <= 0; // Cancel zerobased if axis_*_min / axis_*_max specified if ((isValue(yMin) && isAllPositive) || (isValue(yMax) && isAllNegative)) { isZeroBased = false; } // Bar/Area chart should be 0-based if all positive|negative if (isZeroBased) { if (isAllPositive) { yDomainMin = 0; } if (isAllNegative) { yDomainMax = 0; } } domainLength = Math.abs(yDomainMax - yDomainMin); padding = padding_top = padding_bottom = domainLength * 0.1; if (typeof center !== 'undefined') { yDomainAbs = Math.max(Math.abs(yDomainMin), Math.abs(yDomainMax)); yDomainMax = center + yDomainAbs; yDomainMin = center - yDomainAbs; } // add padding for data label if (showHorizontalDataLabel) { lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'width'); diff = diffDomain($$.y.range()); ratio = [lengths[0] / diff, lengths[1] / diff]; padding_top += domainLength * (ratio[1] / (1 - ratio[0] - ratio[1])); padding_bottom += domainLength * (ratio[0] / (1 - ratio[0] - ratio[1])); } else if (showVerticalDataLabel) { lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'height'); padding_top += $$.axis.convertPixelsToAxisPadding(lengths[1], domainLength); padding_bottom += $$.axis.convertPixelsToAxisPadding(lengths[0], domainLength); } if (axisId === 'y' && notEmpty(config.axis_y_padding)) { padding_top = $$.axis.getPadding(config.axis_y_padding, 'top', padding_top, domainLength); padding_bottom = $$.axis.getPadding(config.axis_y_padding, 'bottom', padding_bottom, domainLength); } if (axisId === 'y2' && notEmpty(config.axis_y2_padding)) { padding_top = $$.axis.getPadding(config.axis_y2_padding, 'top', padding_top, domainLength); padding_bottom = $$.axis.getPadding(config.axis_y2_padding, 'bottom', padding_bottom, domainLength); } // Bar/Area chart should be 0-based if all positive|negative if (isZeroBased) { if (isAllPositive) { padding_bottom = yDomainMin; } if (isAllNegative) { padding_top = -yDomainMax; } } domain = [yDomainMin - padding_bottom, yDomainMax + padding_top]; return isInverted ? domain.reverse() : domain; }; c3_chart_internal_fn.getXDomainMin = function (targets) { var $$ = this, config = $$.config; return isDefined(config.axis_x_min) ? ($$.isTimeSeries() ? this.parseDate(config.axis_x_min) : config.axis_x_min) : $$.d3.min(targets, function (t) { return $$.d3.min(t.values, function (v) { return v.x; }); }); }; c3_chart_internal_fn.getXDomainMax = function (targets) { var $$ = this, config = $$.config; return isDefined(config.axis_x_max) ? ($$.isTimeSeries() ? this.parseDate(config.axis_x_max) : config.axis_x_max) : $$.d3.max(targets, function (t) { return $$.d3.max(t.values, function (v) { return v.x; }); }); }; c3_chart_internal_fn.getXDomainPadding = function (domain) { var $$ = this, config = $$.config, diff = domain[1] - domain[0], maxDataCount, padding, paddingLeft, paddingRight; if ($$.isCategorized()) { padding = 0; } else if ($$.hasType('bar')) { maxDataCount = $$.getMaxDataCount(); padding = maxDataCount > 1 ? (diff / (maxDataCount - 1)) / 2 : 0.5; } else { padding = diff * 0.01; } if (typeof config.axis_x_padding === 'object' && notEmpty(config.axis_x_padding)) { paddingLeft = isValue(config.axis_x_padding.left) ? config.axis_x_padding.left : padding; paddingRight = isValue(config.axis_x_padding.right) ? config.axis_x_padding.right : padding; } else if (typeof config.axis_x_padding === 'number') { paddingLeft = paddingRight = config.axis_x_padding; } else { paddingLeft = paddingRight = padding; } return {left: paddingLeft, right: paddingRight}; }; c3_chart_internal_fn.getXDomain = function (targets) { var $$ = this, xDomain = [$$.getXDomainMin(targets), $$.getXDomainMax(targets)], firstX = xDomain[0], lastX = xDomain[1], padding = $$.getXDomainPadding(xDomain), min = 0, max = 0; // show center of x domain if min and max are the same if ((firstX - lastX) === 0 && !$$.isCategorized()) { if ($$.isTimeSeries()) { firstX = new Date(firstX.getTime() * 0.5); lastX = new Date(lastX.getTime() * 1.5); } else { firstX = firstX === 0 ? 1 : (firstX * 0.5); lastX = lastX === 0 ? -1 : (lastX * 1.5); } } if (firstX || firstX === 0) { min = $$.isTimeSeries() ? new Date(firstX.getTime() - padding.left) : firstX - padding.left; } if (lastX || lastX === 0) { max = $$.isTimeSeries() ? new Date(lastX.getTime() + padding.right) : lastX + padding.right; } return [min, max]; }; c3_chart_internal_fn.updateXDomain = function (targets, withUpdateXDomain, withUpdateOrgXDomain, withTrim, domain) { var $$ = this, config = $$.config; if (withUpdateOrgXDomain) { $$.x.domain(domain ? domain : $$.d3.extent($$.getXDomain(targets))); $$.orgXDomain = $$.x.domain(); if (config.zoom_enabled) { $$.zoom.scale($$.x).updateScaleExtent(); } $$.subX.domain($$.x.domain()); if ($$.brush) { $$.brush.scale($$.subX); } } if (withUpdateXDomain) { $$.x.domain(domain ? domain : (!$$.brush || $$.brush.empty()) ? $$.orgXDomain : $$.brush.extent()); if (config.zoom_enabled) { $$.zoom.scale($$.x).updateScaleExtent(); } } // Trim domain when too big by zoom mousemove event if (withTrim) { $$.x.domain($$.trimXDomain($$.x.orgDomain())); } return $$.x.domain(); }; c3_chart_internal_fn.trimXDomain = function (domain) { var zoomDomain = this.getZoomDomain(), min = zoomDomain[0], max = zoomDomain[1]; if (domain[0] <= min) { domain[1] = +domain[1] + (min - domain[0]); domain[0] = min; } if (max <= domain[1]) { domain[0] = +domain[0] - (domain[1] - max); domain[1] = max; } return domain; }; c3_chart_internal_fn.isX = function (key) { var $$ = this, config = $$.config; return (config.data_x && key === config.data_x) || (notEmpty(config.data_xs) && hasValue(config.data_xs, key)); }; c3_chart_internal_fn.isNotX = function (key) { return !this.isX(key); }; c3_chart_internal_fn.getXKey = function (id) { var $$ = this, config = $$.config; return config.data_x ? config.data_x : notEmpty(config.data_xs) ? config.data_xs[id] : null; }; c3_chart_internal_fn.getXValuesOfXKey = function (key, targets) { var $$ = this, xValues, ids = targets && notEmpty(targets) ? $$.mapToIds(targets) : []; ids.forEach(function (id) { if ($$.getXKey(id) === key) { xValues = $$.data.xs[id]; } }); return xValues; }; c3_chart_internal_fn.getIndexByX = function (x) { var $$ = this, data = $$.filterByX($$.data.targets, x); return data.length ? data[0].index : null; }; c3_chart_internal_fn.getXValue = function (id, i) { var $$ = this; return id in $$.data.xs && $$.data.xs[id] && isValue($$.data.xs[id][i]) ? $$.data.xs[id][i] : i; }; c3_chart_internal_fn.getOtherTargetXs = function () { var $$ = this, idsForX = Object.keys($$.data.xs); return idsForX.length ? $$.data.xs[idsForX[0]] : null; }; c3_chart_internal_fn.getOtherTargetX = function (index) { var xs = this.getOtherTargetXs(); return xs && index < xs.length ? xs[index] : null; }; c3_chart_internal_fn.addXs = function (xs) { var $$ = this; Object.keys(xs).forEach(function (id) { $$.config.data_xs[id] = xs[id]; }); }; c3_chart_internal_fn.hasMultipleX = function (xs) { return this.d3.set(Object.keys(xs).map(function (id) { return xs[id]; })).size() > 1; }; c3_chart_internal_fn.isMultipleX = function () { return notEmpty(this.config.data_xs) || !this.config.data_xSort || this.hasType('scatter'); }; c3_chart_internal_fn.addName = function (data) { var $$ = this, name; if (data) { name = $$.config.data_names[data.id]; data.name = name !== undefined ? name : data.id; } return data; }; c3_chart_internal_fn.getValueOnIndex = function (values, index) { var valueOnIndex = values.filter(function (v) { return v.index === index; }); return valueOnIndex.length ? valueOnIndex[0] : null; }; c3_chart_internal_fn.updateTargetX = function (targets, x) { var $$ = this; targets.forEach(function (t) { t.values.forEach(function (v, i) { v.x = $$.generateTargetX(x[i], t.id, i); }); $$.data.xs[t.id] = x; }); }; c3_chart_internal_fn.updateTargetXs = function (targets, xs) { var $$ = this; targets.forEach(function (t) { if (xs[t.id]) { $$.updateTargetX([t], xs[t.id]); } }); }; c3_chart_internal_fn.generateTargetX = function (rawX, id, index) { var $$ = this, x; if ($$.isTimeSeries()) { x = rawX ? $$.parseDate(rawX) : $$.parseDate($$.getXValue(id, index)); } else if ($$.isCustomX() && !$$.isCategorized()) { x = isValue(rawX) ? +rawX : $$.getXValue(id, index); } else { x = index; } return x; }; c3_chart_internal_fn.cloneTarget = function (target) { return { id : target.id, id_org : target.id_org, values : target.values.map(function (d) { return {x: d.x, value: d.value, id: d.id}; }) }; }; c3_chart_internal_fn.updateXs = function () { var $$ = this; if ($$.data.targets.length) { $$.xs = []; $$.data.targets[0].values.forEach(function (v) { $$.xs[v.index] = v.x; }); } }; c3_chart_internal_fn.getPrevX = function (i) { var x = this.xs[i - 1]; return typeof x !== 'undefined' ? x : null; }; c3_chart_internal_fn.getNextX = function (i) { var x = this.xs[i + 1]; return typeof x !== 'undefined' ? x : null; }; c3_chart_internal_fn.getMaxDataCount = function () { var $$ = this; return $$.d3.max($$.data.targets, function (t) { return t.values.length; }); }; c3_chart_internal_fn.getMaxDataCountTarget = function (targets) { var length = targets.length, max = 0, maxTarget; if (length > 1) { targets.forEach(function (t) { if (t.values.length > max) { maxTarget = t; max = t.values.length; } }); } else { maxTarget = length ? targets[0] : null; } return maxTarget; }; c3_chart_internal_fn.getEdgeX = function (targets) { var $$ = this; return !targets.length ? [0, 0] : [ $$.d3.min(targets, function (t) { return t.values[0].x; }), $$.d3.max(targets, function (t) { return t.values[t.values.length - 1].x; }) ]; }; c3_chart_internal_fn.mapToIds = function (targets) { return targets.map(function (d) { return d.id; }); }; c3_chart_internal_fn.mapToTargetIds = function (ids) { var $$ = this; return ids ? [].concat(ids) : $$.mapToIds($$.data.targets); }; c3_chart_internal_fn.hasTarget = function (targets, id) { var ids = this.mapToIds(targets), i; for (i = 0; i < ids.length; i++) { if (ids[i] === id) { return true; } } return false; }; c3_chart_internal_fn.isTargetToShow = function (targetId) { return this.hiddenTargetIds.indexOf(targetId) < 0; }; c3_chart_internal_fn.isLegendToShow = function (targetId) { return this.hiddenLegendIds.indexOf(targetId) < 0; }; c3_chart_internal_fn.filterTargetsToShow = function (targets) { var $$ = this; return targets.filter(function (t) { return $$.isTargetToShow(t.id); }); }; c3_chart_internal_fn.mapTargetsToUniqueXs = function (targets) { var $$ = this; var xs = $$.d3.set($$.d3.merge(targets.map(function (t) { return t.values.map(function (v) { return +v.x; }); }))).values(); xs = $$.isTimeSeries() ? xs.map(function (x) { return new Date(+x); }) : xs.map(function (x) { return +x; }); return xs.sort(function (a, b) { return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; }); }; c3_chart_internal_fn.addHiddenTargetIds = function (targetIds) { this.hiddenTargetIds = this.hiddenTargetIds.concat(targetIds); }; c3_chart_internal_fn.removeHiddenTargetIds = function (targetIds) { this.hiddenTargetIds = this.hiddenTargetIds.filter(function (id) { return targetIds.indexOf(id) < 0; }); }; c3_chart_internal_fn.addHiddenLegendIds = function (targetIds) { this.hiddenLegendIds = this.hiddenLegendIds.concat(targetIds); }; c3_chart_internal_fn.removeHiddenLegendIds = function (targetIds) { this.hiddenLegendIds = this.hiddenLegendIds.filter(function (id) { return targetIds.indexOf(id) < 0; }); }; c3_chart_internal_fn.getValuesAsIdKeyed = function (targets) { var ys = {}; targets.forEach(function (t) { ys[t.id] = []; t.values.forEach(function (v) { ys[t.id].push(v.value); }); }); return ys; }; c3_chart_internal_fn.checkValueInTargets = function (targets, checker) { var ids = Object.keys(targets), i, j, values; for (i = 0; i < ids.length; i++) { values = targets[ids[i]].values; for (j = 0; j < values.length; j++) { if (checker(values[j].value)) { return true; } } } return false; }; c3_chart_internal_fn.hasNegativeValueInTargets = function (targets) { return this.checkValueInTargets(targets, function (v) { return v < 0; }); }; c3_chart_internal_fn.hasPositiveValueInTargets = function (targets) { return this.checkValueInTargets(targets, function (v) { return v > 0; }); }; c3_chart_internal_fn.isOrderDesc = function () { var config = this.config; return typeof(config.data_order) === 'string' && config.data_order.toLowerCase() === 'desc'; }; c3_chart_internal_fn.isOrderAsc = function () { var config = this.config; return typeof(config.data_order) === 'string' && config.data_order.toLowerCase() === 'asc'; }; c3_chart_internal_fn.orderTargets = function (targets) { var $$ = this, config = $$.config, orderAsc = $$.isOrderAsc(), orderDesc = $$.isOrderDesc(); if (orderAsc || orderDesc) { targets.sort(function (t1, t2) { var reducer = function (p, c) { return p + Math.abs(c.value); }; var t1Sum = t1.values.reduce(reducer, 0), t2Sum = t2.values.reduce(reducer, 0); return orderAsc ? t2Sum - t1Sum : t1Sum - t2Sum; }); } else if (isFunction(config.data_order)) { targets.sort(config.data_order); } // TODO: accept name array for order return targets; }; c3_chart_internal_fn.filterByX = function (targets, x) { return this.d3.merge(targets.map(function (t) { return t.values; })).filter(function (v) { return v.x - x === 0; }); }; c3_chart_internal_fn.filterRemoveNull = function (data) { return data.filter(function (d) { return isValue(d.value); }); }; c3_chart_internal_fn.filterByXDomain = function (targets, xDomain) { return targets.map(function (t) { return { id: t.id, id_org: t.id_org, values: t.values.filter(function (v) { return xDomain[0] <= v.x && v.x <= xDomain[1]; }) }; }); }; c3_chart_internal_fn.hasDataLabel = function () { var config = this.config; if (typeof config.data_labels === 'boolean' && config.data_labels) { return true; } else if (typeof config.data_labels === 'object' && notEmpty(config.data_labels)) { return true; } return false; }; c3_chart_internal_fn.getDataLabelLength = function (min, max, key) { var $$ = this, lengths = [0, 0], paddingCoef = 1.3; $$.selectChart.select('svg').selectAll('.dummy') .data([min, max]) .enter().append('text') .text(function (d) { return $$.dataLabelFormat(d.id)(d); }) .each(function (d, i) { lengths[i] = this.getBoundingClientRect()[key] * paddingCoef; }) .remove(); return lengths; }; c3_chart_internal_fn.isNoneArc = function (d) { return this.hasTarget(this.data.targets, d.id); }, c3_chart_internal_fn.isArc = function (d) { return 'data' in d && this.hasTarget(this.data.targets, d.data.id); }; c3_chart_internal_fn.findSameXOfValues = function (values, index) { var i, targetX = values[index].x, sames = []; for (i = index - 1; i >= 0; i--) { if (targetX !== values[i].x) { break; } sames.push(values[i]); } for (i = index; i < values.length; i++) { if (targetX !== values[i].x) { break; } sames.push(values[i]); } return sames; }; c3_chart_internal_fn.findClosestFromTargets = function (targets, pos) { var $$ = this, candidates; // map to array of closest points of each target candidates = targets.map(function (target) { return $$.findClosest(target.values, pos); }); // decide closest point and return return $$.findClosest(candidates, pos); }; c3_chart_internal_fn.findClosest = function (values, pos) { var $$ = this, minDist = $$.config.point_sensitivity, closest; // find mouseovering bar values.filter(function (v) { return v && $$.isBarType(v.id); }).forEach(function (v) { var shape = $$.main.select('.' + CLASS.bars + $$.getTargetSelectorSuffix(v.id) + ' .' + CLASS.bar + '-' + v.index).node(); if (!closest && $$.isWithinBar(shape)) { closest = v; } }); // find closest point from non-bar values.filter(function (v) { return v && !$$.isBarType(v.id); }).forEach(function (v) { var d = $$.dist(v, pos); if (d < minDist) { minDist = d; closest = v; } }); return closest; }; c3_chart_internal_fn.dist = function (data, pos) { var $$ = this, config = $$.config, xIndex = config.axis_rotated ? 1 : 0, yIndex = config.axis_rotated ? 0 : 1, y = $$.circleY(data, data.index), x = $$.x(data.x); return Math.sqrt(Math.pow(x - pos[xIndex], 2) + Math.pow(y - pos[yIndex], 2)); }; c3_chart_internal_fn.convertValuesToStep = function (values) { var converted = [].concat(values), i; if (!this.isCategorized()) { return values; } for (i = values.length + 1; 0 < i; i--) { converted[i] = converted[i - 1]; } converted[0] = { x: converted[0].x - 1, value: converted[0].value, id: converted[0].id }; converted[values.length + 1] = { x: converted[values.length].x + 1, value: converted[values.length].value, id: converted[values.length].id }; return converted; }; c3_chart_internal_fn.updateDataAttributes = function (name, attrs) { var $$ = this, config = $$.config, current = config['data_' + name]; if (typeof attrs === 'undefined') { return current; } Object.keys(attrs).forEach(function (id) { current[id] = attrs[id]; }); $$.redraw({withLegend: true}); return current; }; c3_chart_internal_fn.convertUrlToData = function (url, mimeType, headers, keys, done) { var $$ = this, type = mimeType ? mimeType : 'csv'; var req = $$.d3.xhr(url); if (headers) { Object.keys(headers).forEach(function (header) { req.header(header, headers[header]); }); } req.get(function (error, data) { var d; if (!data) { throw new Error(error.responseURL + ' ' + error.status + ' (' + error.statusText + ')'); } if (type === 'json') { d = $$.convertJsonToData(JSON.parse(data.response), keys); } else if (type === 'tsv') { d = $$.convertTsvToData(data.response); } else { d = $$.convertCsvToData(data.response); } done.call($$, d); }); }; c3_chart_internal_fn.convertXsvToData = function (xsv, parser) { var rows = parser.parseRows(xsv), d; if (rows.length === 1) { d = [{}]; rows[0].forEach(function (id) { d[0][id] = null; }); } else { d = parser.parse(xsv); } return d; }; c3_chart_internal_fn.convertCsvToData = function (csv) { return this.convertXsvToData(csv, this.d3.csv); }; c3_chart_internal_fn.convertTsvToData = function (tsv) { return this.convertXsvToData(tsv, this.d3.tsv); }; c3_chart_internal_fn.convertJsonToData = function (json, keys) { var $$ = this, new_rows = [], targetKeys, data; if (keys) { // when keys specified, json would be an array that includes objects if (keys.x) { targetKeys = keys.value.concat(keys.x); $$.config.data_x = keys.x; } else { targetKeys = keys.value; } new_rows.push(targetKeys); json.forEach(function (o) { var new_row = []; targetKeys.forEach(function (key) { // convert undefined to null because undefined data will be removed in convertDataToTargets() var v = $$.findValueInJson(o, key); if (isUndefined(v)) { v = null; } new_row.push(v); }); new_rows.push(new_row); }); data = $$.convertRowsToData(new_rows); } else { Object.keys(json).forEach(function (key) { new_rows.push([key].concat(json[key])); }); data = $$.convertColumnsToData(new_rows); } return data; }; c3_chart_internal_fn.findValueInJson = function (object, path) { path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties (replace [] with .) path = path.replace(/^\./, ''); // strip a leading dot var pathArray = path.split('.'); for (var i = 0; i < pathArray.length; ++i) { var k = pathArray[i]; if (k in object) { object = object[k]; } else { return; } } return object; }; c3_chart_internal_fn.convertRowsToData = function (rows) { var keys = rows[0], new_row = {}, new_rows = [], i, j; for (i = 1; i < rows.length; i++) { new_row = {}; for (j = 0; j < rows[i].length; j++) { if (isUndefined(rows[i][j])) { throw new Error("Source data is missing a component at (" + i + "," + j + ")!"); } new_row[keys[j]] = rows[i][j]; } new_rows.push(new_row); } return new_rows; }; c3_chart_internal_fn.convertColumnsToData = function (columns) { var new_rows = [], i, j, key; for (i = 0; i < columns.length; i++) { key = columns[i][0]; for (j = 1; j < columns[i].length; j++) { if (isUndefined(new_rows[j - 1])) { new_rows[j - 1] = {}; } if (isUndefined(columns[i][j])) { throw new Error("Source data is missing a component at (" + i + "," + j + ")!"); } new_rows[j - 1][key] = columns[i][j]; } } return new_rows; }; c3_chart_internal_fn.convertDataToTargets = function (data, appendXs) { var $$ = this, config = $$.config, ids = $$.d3.keys(data[0]).filter($$.isNotX, $$), xs = $$.d3.keys(data[0]).filter($$.isX, $$), targets; // save x for update data by load when custom x and c3.x API ids.forEach(function (id) { var xKey = $$.getXKey(id); if ($$.isCustomX() || $$.isTimeSeries()) { // if included in input data if (xs.indexOf(xKey) >= 0) { $$.data.xs[id] = (appendXs && $$.data.xs[id] ? $$.data.xs[id] : []).concat( data.map(function (d) { return d[xKey]; }) .filter(isValue) .map(function (rawX, i) { return $$.generateTargetX(rawX, id, i); }) ); } // if not included in input data, find from preloaded data of other id's x else if (config.data_x) { $$.data.xs[id] = $$.getOtherTargetXs(); } // if not included in input data, find from preloaded data else if (notEmpty(config.data_xs)) { $$.data.xs[id] = $$.getXValuesOfXKey(xKey, $$.data.targets); } // MEMO: if no x included, use same x of current will be used } else { $$.data.xs[id] = data.map(function (d, i) { return i; }); } }); // check x is defined ids.forEach(function (id) { if (!$$.data.xs[id]) { throw new Error('x is not defined for id = "' + id + '".'); } }); // convert to target targets = ids.map(function (id, index) { var convertedId = config.data_idConverter(id); return { id: convertedId, id_org: id, values: data.map(function (d, i) { var xKey = $$.getXKey(id), rawX = d[xKey], value = d[id] !== null && !isNaN(d[id]) ? +d[id] : null, x; // use x as categories if custom x and categorized if ($$.isCustomX() && $$.isCategorized() && index === 0 && !isUndefined(rawX)) { if (index === 0 && i === 0) { config.axis_x_categories = []; } x = config.axis_x_categories.indexOf(rawX); if (x === -1) { x = config.axis_x_categories.length; config.axis_x_categories.push(rawX); } } else { x = $$.generateTargetX(rawX, id, i); } // mark as x = undefined if value is undefined and filter to remove after mapped if (isUndefined(d[id]) || $$.data.xs[id].length <= i) { x = undefined; } return {x: x, value: value, id: convertedId}; }).filter(function (v) { return isDefined(v.x); }) }; }); // finish targets targets.forEach(function (t) { var i; // sort values by its x if (config.data_xSort) { t.values = t.values.sort(function (v1, v2) { var x1 = v1.x || v1.x === 0 ? v1.x : Infinity, x2 = v2.x || v2.x === 0 ? v2.x : Infinity; return x1 - x2; }); } // indexing each value i = 0; t.values.forEach(function (v) { v.index = i++; }); // this needs to be sorted because its index and value.index is identical $$.data.xs[t.id].sort(function (v1, v2) { return v1 - v2; }); }); // cache information about values $$.hasNegativeValue = $$.hasNegativeValueInTargets(targets); $$.hasPositiveValue = $$.hasPositiveValueInTargets(targets); // set target types if (config.data_type) { $$.setTargetType($$.mapToIds(targets).filter(function (id) { return ! (id in config.data_types); }), config.data_type); } // cache as original id keyed targets.forEach(function (d) { $$.addCache(d.id_org, d); }); return targets; }; c3_chart_internal_fn.load = function (targets, args) { var $$ = this; if (targets) { // filter loading targets if needed if (args.filter) { targets = targets.filter(args.filter); } // set type if args.types || args.type specified if (args.type || args.types) { targets.forEach(function (t) { var type = args.types && args.types[t.id] ? args.types[t.id] : args.type; $$.setTargetType(t.id, type); }); } // Update/Add data $$.data.targets.forEach(function (d) { for (var i = 0; i < targets.length; i++) { if (d.id === targets[i].id) { d.values = targets[i].values; targets.splice(i, 1); break; } } }); $$.data.targets = $$.data.targets.concat(targets); // add remained } // Set targets $$.updateTargets($$.data.targets); // Redraw with new targets $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true}); if (args.done) { args.done(); } }; c3_chart_internal_fn.loadFromArgs = function (args) { var $$ = this; if (args.data) { $$.load($$.convertDataToTargets(args.data), args); } else if (args.url) { $$.convertUrlToData(args.url, args.mimeType, args.headers, args.keys, function (data) { $$.load($$.convertDataToTargets(data), args); }); } else if (args.json) { $$.load($$.convertDataToTargets($$.convertJsonToData(args.json, args.keys)), args); } else if (args.rows) { $$.load($$.convertDataToTargets($$.convertRowsToData(args.rows)), args); } else if (args.columns) { $$.load($$.convertDataToTargets($$.convertColumnsToData(args.columns)), args); } else { $$.load(null, args); } }; c3_chart_internal_fn.unload = function (targetIds, done) { var $$ = this; if (!done) { done = function () {}; } // filter existing target targetIds = targetIds.filter(function (id) { return $$.hasTarget($$.data.targets, id); }); // If no target, call done and return if (!targetIds || targetIds.length === 0) { done(); return; } $$.svg.selectAll(targetIds.map(function (id) { return $$.selectorTarget(id); })) .transition() .style('opacity', 0) .remove() .call($$.endall, done); targetIds.forEach(function (id) { // Reset fadein for future load $$.withoutFadeIn[id] = false; // Remove target's elements if ($$.legend) { $$.legend.selectAll('.' + CLASS.legendItem + $$.getTargetSelectorSuffix(id)).remove(); } // Remove target $$.data.targets = $$.data.targets.filter(function (t) { return t.id !== id; }); }); }; c3_chart_internal_fn.categoryName = function (i) { var config = this.config; return i < config.axis_x_categories.length ? config.axis_x_categories[i] : i; }; c3_chart_internal_fn.initEventRect = function () { var $$ = this; $$.main.select('.' + CLASS.chart).append("g") .attr("class", CLASS.eventRects) .style('fill-opacity', 0); }; c3_chart_internal_fn.redrawEventRect = function () { var $$ = this, config = $$.config, eventRectUpdate, maxDataCountTarget, isMultipleX = $$.isMultipleX(); // rects for mouseover var eventRects = $$.main.select('.' + CLASS.eventRects) .style('cursor', config.zoom_enabled ? config.axis_rotated ? 'ns-resize' : 'ew-resize' : null) .classed(CLASS.eventRectsMultiple, isMultipleX) .classed(CLASS.eventRectsSingle, !isMultipleX); // clear old rects eventRects.selectAll('.' + CLASS.eventRect).remove(); // open as public variable $$.eventRect = eventRects.selectAll('.' + CLASS.eventRect); if (isMultipleX) { eventRectUpdate = $$.eventRect.data([0]); // enter : only one rect will be added $$.generateEventRectsForMultipleXs(eventRectUpdate.enter()); // update $$.updateEventRect(eventRectUpdate); // exit : not needed because always only one rect exists } else { // Set data and update $$.eventRect maxDataCountTarget = $$.getMaxDataCountTarget($$.data.targets); eventRects.datum(maxDataCountTarget ? maxDataCountTarget.values : []); $$.eventRect = eventRects.selectAll('.' + CLASS.eventRect); eventRectUpdate = $$.eventRect.data(function (d) { return d; }); // enter $$.generateEventRectsForSingleX(eventRectUpdate.enter()); // update $$.updateEventRect(eventRectUpdate); // exit eventRectUpdate.exit().remove(); } }; c3_chart_internal_fn.updateEventRect = function (eventRectUpdate) { var $$ = this, config = $$.config, x, y, w, h, rectW, rectX; // set update selection if null eventRectUpdate = eventRectUpdate || $$.eventRect.data(function (d) { return d; }); if ($$.isMultipleX()) { // TODO: rotated not supported yet x = 0; y = 0; w = $$.width; h = $$.height; } else { if (($$.isCustomX() || $$.isTimeSeries()) && !$$.isCategorized()) { // update index for x that is used by prevX and nextX $$.updateXs(); rectW = function (d) { var prevX = $$.getPrevX(d.index), nextX = $$.getNextX(d.index); // if there this is a single data point make the eventRect full width (or height) if (prevX === null && nextX === null) { return config.axis_rotated ? $$.height : $$.width; } if (prevX === null) { prevX = $$.x.domain()[0]; } if (nextX === null) { nextX = $$.x.domain()[1]; } return Math.max(0, ($$.x(nextX) - $$.x(prevX)) / 2); }; rectX = function (d) { var prevX = $$.getPrevX(d.index), nextX = $$.getNextX(d.index), thisX = $$.data.xs[d.id][d.index]; // if there this is a single data point position the eventRect at 0 if (prevX === null && nextX === null) { return 0; } if (prevX === null) { prevX = $$.x.domain()[0]; } return ($$.x(thisX) + $$.x(prevX)) / 2; }; } else { rectW = $$.getEventRectWidth(); rectX = function (d) { return $$.x(d.x) - (rectW / 2); }; } x = config.axis_rotated ? 0 : rectX; y = config.axis_rotated ? rectX : 0; w = config.axis_rotated ? $$.width : rectW; h = config.axis_rotated ? rectW : $$.height; } eventRectUpdate .attr('class', $$.classEvent.bind($$)) .attr("x", x) .attr("y", y) .attr("width", w) .attr("height", h); }; c3_chart_internal_fn.generateEventRectsForSingleX = function (eventRectEnter) { var $$ = this, d3 = $$.d3, config = $$.config; eventRectEnter.append("rect") .attr("class", $$.classEvent.bind($$)) .style("cursor", config.data_selection_enabled && config.data_selection_grouped ? "pointer" : null) .on('mouseover', function (d) { var index = d.index; if ($$.dragging || $$.flowing) { return; } // do nothing while dragging/flowing if ($$.hasArcType()) { return; } // Expand shapes for selection if (config.point_focus_expand_enabled) { $$.expandCircles(index, null, true); } $$.expandBars(index, null, true); // Call event handler $$.main.selectAll('.' + CLASS.shape + '-' + index).each(function (d) { config.data_onmouseover.call($$.api, d); }); }) .on('mouseout', function (d) { var index = d.index; if (!$$.config) { return; } // chart is destroyed if ($$.hasArcType()) { return; } $$.hideXGridFocus(); $$.hideTooltip(); // Undo expanded shapes $$.unexpandCircles(); $$.unexpandBars(); // Call event handler $$.main.selectAll('.' + CLASS.shape + '-' + index).each(function (d) { config.data_onmouseout.call($$.api, d); }); }) .on('mousemove', function (d) { var selectedData, index = d.index, eventRect = $$.svg.select('.' + CLASS.eventRect + '-' + index); if ($$.dragging || $$.flowing) { return; } // do nothing while dragging/flowing if ($$.hasArcType()) { return; } if ($$.isStepType(d) && $$.config.line_step_type === 'step-after' && d3.mouse(this)[0] < $$.x($$.getXValue(d.id, index))) { index -= 1; } // Show tooltip selectedData = $$.filterTargetsToShow($$.data.targets).map(function (t) { return $$.addName($$.getValueOnIndex(t.values, index)); }); if (config.tooltip_grouped) { $$.showTooltip(selectedData, this); $$.showXGridFocus(selectedData); } if (config.tooltip_grouped && (!config.data_selection_enabled || config.data_selection_grouped)) { return; } $$.main.selectAll('.' + CLASS.shape + '-' + index) .each(function () { d3.select(this).classed(CLASS.EXPANDED, true); if (config.data_selection_enabled) { eventRect.style('cursor', config.data_selection_grouped ? 'pointer' : null); } if (!config.tooltip_grouped) { $$.hideXGridFocus(); $$.hideTooltip(); if (!config.data_selection_grouped) { $$.unexpandCircles(index); $$.unexpandBars(index); } } }) .filter(function (d) { return $$.isWithinShape(this, d); }) .each(function (d) { if (config.data_selection_enabled && (config.data_selection_grouped || config.data_selection_isselectable(d))) { eventRect.style('cursor', 'pointer'); } if (!config.tooltip_grouped) { $$.showTooltip([d], this); $$.showXGridFocus([d]); if (config.point_focus_expand_enabled) { $$.expandCircles(index, d.id, true); } $$.expandBars(index, d.id, true); } }); }) .on('click', function (d) { var index = d.index; if ($$.hasArcType() || !$$.toggleShape) { return; } if ($$.cancelClick) { $$.cancelClick = false; return; } if ($$.isStepType(d) && config.line_step_type === 'step-after' && d3.mouse(this)[0] < $$.x($$.getXValue(d.id, index))) { index -= 1; } $$.main.selectAll('.' + CLASS.shape + '-' + index).each(function (d) { if (config.data_selection_grouped || $$.isWithinShape(this, d)) { $$.toggleShape(this, d, index); $$.config.data_onclick.call($$.api, d, this); } }); }) .call( config.data_selection_draggable && $$.drag ? ( d3.behavior.drag().origin(Object) .on('drag', function () { $$.drag(d3.mouse(this)); }) .on('dragstart', function () { $$.dragstart(d3.mouse(this)); }) .on('dragend', function () { $$.dragend(); }) ) : function () {} ); }; c3_chart_internal_fn.generateEventRectsForMultipleXs = function (eventRectEnter) { var $$ = this, d3 = $$.d3, config = $$.config; function mouseout() { $$.svg.select('.' + CLASS.eventRect).style('cursor', null); $$.hideXGridFocus(); $$.hideTooltip(); $$.unexpandCircles(); $$.unexpandBars(); } eventRectEnter.append('rect') .attr('x', 0) .attr('y', 0) .attr('width', $$.width) .attr('height', $$.height) .attr('class', CLASS.eventRect) .on('mouseout', function () { if (!$$.config) { return; } // chart is destroyed if ($$.hasArcType()) { return; } mouseout(); }) .on('mousemove', function () { var targetsToShow = $$.filterTargetsToShow($$.data.targets); var mouse, closest, sameXData, selectedData; if ($$.dragging) { return; } // do nothing when dragging if ($$.hasArcType(targetsToShow)) { return; } mouse = d3.mouse(this); closest = $$.findClosestFromTargets(targetsToShow, mouse); if ($$.mouseover && (!closest || closest.id !== $$.mouseover.id)) { config.data_onmouseout.call($$.api, $$.mouseover); $$.mouseover = undefined; } if (! closest) { mouseout(); return; } if ($$.isScatterType(closest) || !config.tooltip_grouped) { sameXData = [closest]; } else { sameXData = $$.filterByX(targetsToShow, closest.x); } // show tooltip when cursor is close to some point selectedData = sameXData.map(function (d) { return $$.addName(d); }); $$.showTooltip(selectedData, this); // expand points if (config.point_focus_expand_enabled) { $$.expandCircles(closest.index, closest.id, true); } $$.expandBars(closest.index, closest.id, true); // Show xgrid focus line $$.showXGridFocus(selectedData); // Show cursor as pointer if point is close to mouse position if ($$.isBarType(closest.id) || $$.dist(closest, mouse) < config.point_sensitivity) { $$.svg.select('.' + CLASS.eventRect).style('cursor', 'pointer'); if (!$$.mouseover) { config.data_onmouseover.call($$.api, closest); $$.mouseover = closest; } } }) .on('click', function () { var targetsToShow = $$.filterTargetsToShow($$.data.targets); var mouse, closest; if ($$.hasArcType(targetsToShow)) { return; } mouse = d3.mouse(this); closest = $$.findClosestFromTargets(targetsToShow, mouse); if (! closest) { return; } // select if selection enabled if ($$.isBarType(closest.id) || $$.dist(closest, mouse) < config.point_sensitivity) { $$.main.selectAll('.' + CLASS.shapes + $$.getTargetSelectorSuffix(closest.id)).selectAll('.' + CLASS.shape + '-' + closest.index).each(function () { if (config.data_selection_grouped || $$.isWithinShape(this, closest)) { $$.toggleShape(this, closest, closest.index); $$.config.data_onclick.call($$.api, closest, this); } }); } }) .call( config.data_selection_draggable && $$.drag ? ( d3.behavior.drag().origin(Object) .on('drag', function () { $$.drag(d3.mouse(this)); }) .on('dragstart', function () { $$.dragstart(d3.mouse(this)); }) .on('dragend', function () { $$.dragend(); }) ) : function () {} ); }; c3_chart_internal_fn.dispatchEvent = function (type, index, mouse) { var $$ = this, selector = '.' + CLASS.eventRect + (!$$.isMultipleX() ? '-' + index : ''), eventRect = $$.main.select(selector).node(), box = eventRect.getBoundingClientRect(), x = box.left + (mouse ? mouse[0] : 0), y = box.top + (mouse ? mouse[1] : 0), event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, window, 0, x, y, x, y, false, false, false, false, 0, null); eventRect.dispatchEvent(event); }; c3_chart_internal_fn.getCurrentWidth = function () { var $$ = this, config = $$.config; return config.size_width ? config.size_width : $$.getParentWidth(); }; c3_chart_internal_fn.getCurrentHeight = function () { var $$ = this, config = $$.config, h = config.size_height ? config.size_height : $$.getParentHeight(); return h > 0 ? h : 320 / ($$.hasType('gauge') && !config.gauge_fullCircle ? 2 : 1); }; c3_chart_internal_fn.getCurrentPaddingTop = function () { var $$ = this, config = $$.config, padding = isValue(config.padding_top) ? config.padding_top : 0; if ($$.title && $$.title.node()) { padding += $$.getTitlePadding(); } return padding; }; c3_chart_internal_fn.getCurrentPaddingBottom = function () { var config = this.config; return isValue(config.padding_bottom) ? config.padding_bottom : 0; }; c3_chart_internal_fn.getCurrentPaddingLeft = function (withoutRecompute) { var $$ = this, config = $$.config; if (isValue(config.padding_left)) { return config.padding_left; } else if (config.axis_rotated) { return !config.axis_x_show ? 1 : Math.max(ceil10($$.getAxisWidthByAxisId('x', withoutRecompute)), 40); } else if (!config.axis_y_show || config.axis_y_inner) { // && !config.axis_rotated return $$.axis.getYAxisLabelPosition().isOuter ? 30 : 1; } else { return ceil10($$.getAxisWidthByAxisId('y', withoutRecompute)); } }; c3_chart_internal_fn.getCurrentPaddingRight = function () { var $$ = this, config = $$.config, defaultPadding = 10, legendWidthOnRight = $$.isLegendRight ? $$.getLegendWidth() + 20 : 0; if (isValue(config.padding_right)) { return config.padding_right + 1; // 1 is needed not to hide tick line } else if (config.axis_rotated) { return defaultPadding + legendWidthOnRight; } else if (!config.axis_y2_show || config.axis_y2_inner) { // && !config.axis_rotated return 2 + legendWidthOnRight + ($$.axis.getY2AxisLabelPosition().isOuter ? 20 : 0); } else { return ceil10($$.getAxisWidthByAxisId('y2')) + legendWidthOnRight; } }; c3_chart_internal_fn.getParentRectValue = function (key) { var parent = this.selectChart.node(), v; while (parent && parent.tagName !== 'BODY') { try { v = parent.getBoundingClientRect()[key]; } catch(e) { if (key === 'width') { // In IE in certain cases getBoundingClientRect // will cause an "unspecified error" v = parent.offsetWidth; } } if (v) { break; } parent = parent.parentNode; } return v; }; c3_chart_internal_fn.getParentWidth = function () { return this.getParentRectValue('width'); }; c3_chart_internal_fn.getParentHeight = function () { var h = this.selectChart.style('height'); return h.indexOf('px') > 0 ? +h.replace('px', '') : 0; }; c3_chart_internal_fn.getSvgLeft = function (withoutRecompute) { var $$ = this, config = $$.config, hasLeftAxisRect = config.axis_rotated || (!config.axis_rotated && !config.axis_y_inner), leftAxisClass = config.axis_rotated ? CLASS.axisX : CLASS.axisY, leftAxis = $$.main.select('.' + leftAxisClass).node(), svgRect = leftAxis && hasLeftAxisRect ? leftAxis.getBoundingClientRect() : {right: 0}, chartRect = $$.selectChart.node().getBoundingClientRect(), hasArc = $$.hasArcType(), svgLeft = svgRect.right - chartRect.left - (hasArc ? 0 : $$.getCurrentPaddingLeft(withoutRecompute)); return svgLeft > 0 ? svgLeft : 0; }; c3_chart_internal_fn.getAxisWidthByAxisId = function (id, withoutRecompute) { var $$ = this, position = $$.axis.getLabelPositionById(id); return $$.axis.getMaxTickWidth(id, withoutRecompute) + (position.isInner ? 20 : 40); }; c3_chart_internal_fn.getHorizontalAxisHeight = function (axisId) { var $$ = this, config = $$.config, h = 30; if (axisId === 'x' && !config.axis_x_show) { return 8; } if (axisId === 'x' && config.axis_x_height) { return config.axis_x_height; } if (axisId === 'y' && !config.axis_y_show) { return config.legend_show && !$$.isLegendRight && !$$.isLegendInset ? 10 : 1; } if (axisId === 'y2' && !config.axis_y2_show) { return $$.rotated_padding_top; } // Calculate x axis height when tick rotated if (axisId === 'x' && !config.axis_rotated && config.axis_x_tick_rotate) { h = 30 + $$.axis.getMaxTickWidth(axisId) * Math.cos(Math.PI * (90 - config.axis_x_tick_rotate) / 180); } // Calculate y axis height when tick rotated if (axisId === 'y' && config.axis_rotated && config.axis_y_tick_rotate) { h = 30 + $$.axis.getMaxTickWidth(axisId) * Math.cos(Math.PI * (90 - config.axis_y_tick_rotate) / 180); } return h + ($$.axis.getLabelPositionById(axisId).isInner ? 0 : 10) + (axisId === 'y2' ? -10 : 0); }; c3_chart_internal_fn.getEventRectWidth = function () { return Math.max(0, this.xAxis.tickInterval()); }; c3_chart_internal_fn.getShapeIndices = function (typeFilter) { var $$ = this, config = $$.config, indices = {}, i = 0, j, k; $$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$)).forEach(function (d) { for (j = 0; j < config.data_groups.length; j++) { if (config.data_groups[j].indexOf(d.id) < 0) { continue; } for (k = 0; k < config.data_groups[j].length; k++) { if (config.data_groups[j][k] in indices) { indices[d.id] = indices[config.data_groups[j][k]]; break; } } } if (isUndefined(indices[d.id])) { indices[d.id] = i++; } }); indices.__max__ = i - 1; return indices; }; c3_chart_internal_fn.getShapeX = function (offset, targetsNum, indices, isSub) { var $$ = this, scale = isSub ? $$.subX : $$.x; return function (d) { var index = d.id in indices ? indices[d.id] : 0; return d.x || d.x === 0 ? scale(d.x) - offset * (targetsNum / 2 - index) : 0; }; }; c3_chart_internal_fn.getShapeY = function (isSub) { var $$ = this; return function (d) { var scale = isSub ? $$.getSubYScale(d.id) : $$.getYScale(d.id); return scale(d.value); }; }; c3_chart_internal_fn.getShapeOffset = function (typeFilter, indices, isSub) { var $$ = this, targets = $$.orderTargets($$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$))), targetIds = targets.map(function (t) { return t.id; }); return function (d, i) { var scale = isSub ? $$.getSubYScale(d.id) : $$.getYScale(d.id), y0 = scale(0), offset = y0; targets.forEach(function (t) { var values = $$.isStepType(d) ? $$.convertValuesToStep(t.values) : t.values; if (t.id === d.id || indices[t.id] !== indices[d.id]) { return; } if (targetIds.indexOf(t.id) < targetIds.indexOf(d.id)) { // check if the x values line up if (typeof values[i] === 'undefined' || +values[i].x !== +d.x) { // "+" for timeseries // if not, try to find the value that does line up i = -1; values.forEach(function (v, j) { if (v.x === d.x) { i = j; } }); } if (i in values && values[i].value * d.value >= 0) { offset += scale(values[i].value) - y0; } } }); return offset; }; }; c3_chart_internal_fn.isWithinShape = function (that, d) { var $$ = this, shape = $$.d3.select(that), isWithin; if (!$$.isTargetToShow(d.id)) { isWithin = false; } else if (that.nodeName === 'circle') { isWithin = $$.isStepType(d) ? $$.isWithinStep(that, $$.getYScale(d.id)(d.value)) : $$.isWithinCircle(that, $$.pointSelectR(d) * 1.5); } else if (that.nodeName === 'path') { isWithin = shape.classed(CLASS.bar) ? $$.isWithinBar(that) : true; } return isWithin; }; c3_chart_internal_fn.getInterpolate = function (d) { var $$ = this, interpolation = $$.isInterpolationType($$.config.spline_interpolation_type) ? $$.config.spline_interpolation_type : 'cardinal'; return $$.isSplineType(d) ? interpolation : $$.isStepType(d) ? $$.config.line_step_type : "linear"; }; c3_chart_internal_fn.initLine = function () { var $$ = this; $$.main.select('.' + CLASS.chart).append("g") .attr("class", CLASS.chartLines); }; c3_chart_internal_fn.updateTargetsForLine = function (targets) { var $$ = this, config = $$.config, mainLineUpdate, mainLineEnter, classChartLine = $$.classChartLine.bind($$), classLines = $$.classLines.bind($$), classAreas = $$.classAreas.bind($$), classCircles = $$.classCircles.bind($$), classFocus = $$.classFocus.bind($$); mainLineUpdate = $$.main.select('.' + CLASS.chartLines).selectAll('.' + CLASS.chartLine) .data(targets) .attr('class', function (d) { return classChartLine(d) + classFocus(d); }); mainLineEnter = mainLineUpdate.enter().append('g') .attr('class', classChartLine) .style('opacity', 0) .style("pointer-events", "none"); // Lines for each data mainLineEnter.append('g') .attr("class", classLines); // Areas mainLineEnter.append('g') .attr('class', classAreas); // Circles for each data point on lines mainLineEnter.append('g') .attr("class", function (d) { return $$.generateClass(CLASS.selectedCircles, d.id); }); mainLineEnter.append('g') .attr("class", classCircles) .style("cursor", function (d) { return config.data_selection_isselectable(d) ? "pointer" : null; }); // Update date for selected circles targets.forEach(function (t) { $$.main.selectAll('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(t.id)).selectAll('.' + CLASS.selectedCircle).each(function (d) { d.value = t.values[d.index].value; }); }); // MEMO: can not keep same color... //mainLineUpdate.exit().remove(); }; c3_chart_internal_fn.updateLine = function (durationForExit) { var $$ = this; $$.mainLine = $$.main.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line) .data($$.lineData.bind($$)); $$.mainLine.enter().append('path') .attr('class', $$.classLine.bind($$)) .style("stroke", $$.color); $$.mainLine .style("opacity", $$.initialOpacity.bind($$)) .style('shape-rendering', function (d) { return $$.isStepType(d) ? 'crispEdges' : ''; }) .attr('transform', null); $$.mainLine.exit().transition().duration(durationForExit) .style('opacity', 0) .remove(); }; c3_chart_internal_fn.redrawLine = function (drawLine, withTransition) { return [ (withTransition ? this.mainLine.transition(Math.random().toString()) : this.mainLine) .attr("d", drawLine) .style("stroke", this.color) .style("opacity", 1) ]; }; c3_chart_internal_fn.generateDrawLine = function (lineIndices, isSub) { var $$ = this, config = $$.config, line = $$.d3.svg.line(), getPoints = $$.generateGetLinePoints(lineIndices, isSub), yScaleGetter = isSub ? $$.getSubYScale : $$.getYScale, xValue = function (d) { return (isSub ? $$.subxx : $$.xx).call($$, d); }, yValue = function (d, i) { return config.data_groups.length > 0 ? getPoints(d, i)[0][1] : yScaleGetter.call($$, d.id)(d.value); }; line = config.axis_rotated ? line.x(yValue).y(xValue) : line.x(xValue).y(yValue); if (!config.line_connectNull) { line = line.defined(function (d) { return d.value != null; }); } return function (d) { var values = config.line_connectNull ? $$.filterRemoveNull(d.values) : d.values, x = isSub ? $$.x : $$.subX, y = yScaleGetter.call($$, d.id), x0 = 0, y0 = 0, path; if ($$.isLineType(d)) { if (config.data_regions[d.id]) { path = $$.lineWithRegions(values, x, y, config.data_regions[d.id]); } else { if ($$.isStepType(d)) { values = $$.convertValuesToStep(values); } path = line.interpolate($$.getInterpolate(d))(values); } } else { if (values[0]) { x0 = x(values[0].x); y0 = y(values[0].value); } path = config.axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0; } return path ? path : "M 0 0"; }; }; c3_chart_internal_fn.generateGetLinePoints = function (lineIndices, isSub) { // partial duplication of generateGetBarPoints var $$ = this, config = $$.config, lineTargetsNum = lineIndices.__max__ + 1, x = $$.getShapeX(0, lineTargetsNum, lineIndices, !!isSub), y = $$.getShapeY(!!isSub), lineOffset = $$.getShapeOffset($$.isLineType, lineIndices, !!isSub), yScale = isSub ? $$.getSubYScale : $$.getYScale; return function (d, i) { var y0 = yScale.call($$, d.id)(0), offset = lineOffset(d, i) || y0, // offset is for stacked area chart posX = x(d), posY = y(d); // fix posY not to overflow opposite quadrant if (config.axis_rotated) { if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; } } // 1 point that marks the line position return [ [posX, posY - (y0 - offset)], [posX, posY - (y0 - offset)], // needed for compatibility [posX, posY - (y0 - offset)], // needed for compatibility [posX, posY - (y0 - offset)] // needed for compatibility ]; }; }; c3_chart_internal_fn.lineWithRegions = function (d, x, y, _regions) { var $$ = this, config = $$.config, prev = -1, i, j, s = "M", sWithRegion, xp, yp, dx, dy, dd, diff, diffx2, xOffset = $$.isCategorized() ? 0.5 : 0, xValue, yValue, regions = []; function isWithinRegions(x, regions) { var i; for (i = 0; i < regions.length; i++) { if (regions[i].start < x && x <= regions[i].end) { return true; } } return false; } // Check start/end of regions if (isDefined(_regions)) { for (i = 0; i < _regions.length; i++) { regions[i] = {}; if (isUndefined(_regions[i].start)) { regions[i].start = d[0].x; } else { regions[i].start = $$.isTimeSeries() ? $$.parseDate(_regions[i].start) : _regions[i].start; } if (isUndefined(_regions[i].end)) { regions[i].end = d[d.length - 1].x; } else { regions[i].end = $$.isTimeSeries() ? $$.parseDate(_regions[i].end) : _regions[i].end; } } } // Set scales xValue = config.axis_rotated ? function (d) { return y(d.value); } : function (d) { return x(d.x); }; yValue = config.axis_rotated ? function (d) { return x(d.x); } : function (d) { return y(d.value); }; // Define svg generator function for region function generateM(points) { return 'M' + points[0][0] + ' ' + points[0][1] + ' ' + points[1][0] + ' ' + points[1][1]; } if ($$.isTimeSeries()) { sWithRegion = function (d0, d1, j, diff) { var x0 = d0.x.getTime(), x_diff = d1.x - d0.x, xv0 = new Date(x0 + x_diff * j), xv1 = new Date(x0 + x_diff * (j + diff)), points; if (config.axis_rotated) { points = [[y(yp(j)), x(xv0)], [y(yp(j + diff)), x(xv1)]]; } else { points = [[x(xv0), y(yp(j))], [x(xv1), y(yp(j + diff))]]; } return generateM(points); }; } else { sWithRegion = function (d0, d1, j, diff) { var points; if (config.axis_rotated) { points = [[y(yp(j), true), x(xp(j))], [y(yp(j + diff), true), x(xp(j + diff))]]; } else { points = [[x(xp(j), true), y(yp(j))], [x(xp(j + diff), true), y(yp(j + diff))]]; } return generateM(points); }; } // Generate for (i = 0; i < d.length; i++) { // Draw as normal if (isUndefined(regions) || ! isWithinRegions(d[i].x, regions)) { s += " " + xValue(d[i]) + " " + yValue(d[i]); } // Draw with region // TODO: Fix for horizotal charts else { xp = $$.getScale(d[i - 1].x + xOffset, d[i].x + xOffset, $$.isTimeSeries()); yp = $$.getScale(d[i - 1].value, d[i].value); dx = x(d[i].x) - x(d[i - 1].x); dy = y(d[i].value) - y(d[i - 1].value); dd = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2)); diff = 2 / dd; diffx2 = diff * 2; for (j = diff; j <= 1; j += diffx2) { s += sWithRegion(d[i - 1], d[i], j, diff); } } prev = d[i].x; } return s; }; c3_chart_internal_fn.updateArea = function (durationForExit) { var $$ = this, d3 = $$.d3; $$.mainArea = $$.main.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area) .data($$.lineData.bind($$)); $$.mainArea.enter().append('path') .attr("class", $$.classArea.bind($$)) .style("fill", $$.color) .style("opacity", function () { $$.orgAreaOpacity = +d3.select(this).style('opacity'); return 0; }); $$.mainArea .style("opacity", $$.orgAreaOpacity); $$.mainArea.exit().transition().duration(durationForExit) .style('opacity', 0) .remove(); }; c3_chart_internal_fn.redrawArea = function (drawArea, withTransition) { return [ (withTransition ? this.mainArea.transition(Math.random().toString()) : this.mainArea) .attr("d", drawArea) .style("fill", this.color) .style("opacity", this.orgAreaOpacity) ]; }; c3_chart_internal_fn.generateDrawArea = function (areaIndices, isSub) { var $$ = this, config = $$.config, area = $$.d3.svg.area(), getPoints = $$.generateGetAreaPoints(areaIndices, isSub), yScaleGetter = isSub ? $$.getSubYScale : $$.getYScale, xValue = function (d) { return (isSub ? $$.subxx : $$.xx).call($$, d); }, value0 = function (d, i) { return config.data_groups.length > 0 ? getPoints(d, i)[0][1] : yScaleGetter.call($$, d.id)($$.getAreaBaseValue(d.id)); }, value1 = function (d, i) { return config.data_groups.length > 0 ? getPoints(d, i)[1][1] : yScaleGetter.call($$, d.id)(d.value); }; area = config.axis_rotated ? area.x0(value0).x1(value1).y(xValue) : area.x(xValue).y0(config.area_above ? 0 : value0).y1(value1); if (!config.line_connectNull) { area = area.defined(function (d) { return d.value !== null; }); } return function (d) { var values = config.line_connectNull ? $$.filterRemoveNull(d.values) : d.values, x0 = 0, y0 = 0, path; if ($$.isAreaType(d)) { if ($$.isStepType(d)) { values = $$.convertValuesToStep(values); } path = area.interpolate($$.getInterpolate(d))(values); } else { if (values[0]) { x0 = $$.x(values[0].x); y0 = $$.getYScale(d.id)(values[0].value); } path = config.axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0; } return path ? path : "M 0 0"; }; }; c3_chart_internal_fn.getAreaBaseValue = function () { return 0; }; c3_chart_internal_fn.generateGetAreaPoints = function (areaIndices, isSub) { // partial duplication of generateGetBarPoints var $$ = this, config = $$.config, areaTargetsNum = areaIndices.__max__ + 1, x = $$.getShapeX(0, areaTargetsNum, areaIndices, !!isSub), y = $$.getShapeY(!!isSub), areaOffset = $$.getShapeOffset($$.isAreaType, areaIndices, !!isSub), yScale = isSub ? $$.getSubYScale : $$.getYScale; return function (d, i) { var y0 = yScale.call($$, d.id)(0), offset = areaOffset(d, i) || y0, // offset is for stacked area chart posX = x(d), posY = y(d); // fix posY not to overflow opposite quadrant if (config.axis_rotated) { if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; } } // 1 point that marks the area position return [ [posX, offset], [posX, posY - (y0 - offset)], [posX, posY - (y0 - offset)], // needed for compatibility [posX, offset] // needed for compatibility ]; }; }; c3_chart_internal_fn.updateCircle = function () { var $$ = this; $$.mainCircle = $$.main.selectAll('.' + CLASS.circles).selectAll('.' + CLASS.circle) .data($$.lineOrScatterData.bind($$)); $$.mainCircle.enter().append("circle") .attr("class", $$.classCircle.bind($$)) .attr("r", $$.pointR.bind($$)) .style("fill", $$.color); $$.mainCircle .style("opacity", $$.initialOpacityForCircle.bind($$)); $$.mainCircle.exit().remove(); }; c3_chart_internal_fn.redrawCircle = function (cx, cy, withTransition) { var selectedCircles = this.main.selectAll('.' + CLASS.selectedCircle); return [ (withTransition ? this.mainCircle.transition(Math.random().toString()) : this.mainCircle) .style('opacity', this.opacityForCircle.bind(this)) .style("fill", this.color) .attr("cx", cx) .attr("cy", cy), (withTransition ? selectedCircles.transition(Math.random().toString()) : selectedCircles) .attr("cx", cx) .attr("cy", cy) ]; }; c3_chart_internal_fn.circleX = function (d) { return d.x || d.x === 0 ? this.x(d.x) : null; }; c3_chart_internal_fn.updateCircleY = function () { var $$ = this, lineIndices, getPoints; if ($$.config.data_groups.length > 0) { lineIndices = $$.getShapeIndices($$.isLineType), getPoints = $$.generateGetLinePoints(lineIndices); $$.circleY = function (d, i) { return getPoints(d, i)[0][1]; }; } else { $$.circleY = function (d) { return $$.getYScale(d.id)(d.value); }; } }; c3_chart_internal_fn.getCircles = function (i, id) { var $$ = this; return (id ? $$.main.selectAll('.' + CLASS.circles + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.circle + (isValue(i) ? '-' + i : '')); }; c3_chart_internal_fn.expandCircles = function (i, id, reset) { var $$ = this, r = $$.pointExpandedR.bind($$); if (reset) { $$.unexpandCircles(); } $$.getCircles(i, id) .classed(CLASS.EXPANDED, true) .attr('r', r); }; c3_chart_internal_fn.unexpandCircles = function (i) { var $$ = this, r = $$.pointR.bind($$); $$.getCircles(i) .filter(function () { return $$.d3.select(this).classed(CLASS.EXPANDED); }) .classed(CLASS.EXPANDED, false) .attr('r', r); }; c3_chart_internal_fn.pointR = function (d) { var $$ = this, config = $$.config; return $$.isStepType(d) ? 0 : (isFunction(config.point_r) ? config.point_r(d) : config.point_r); }; c3_chart_internal_fn.pointExpandedR = function (d) { var $$ = this, config = $$.config; return config.point_focus_expand_enabled ? (config.point_focus_expand_r ? config.point_focus_expand_r : $$.pointR(d) * 1.75) : $$.pointR(d); }; c3_chart_internal_fn.pointSelectR = function (d) { var $$ = this, config = $$.config; return isFunction(config.point_select_r) ? config.point_select_r(d) : ((config.point_select_r) ? config.point_select_r : $$.pointR(d) * 4); }; c3_chart_internal_fn.isWithinCircle = function (that, r) { var d3 = this.d3, mouse = d3.mouse(that), d3_this = d3.select(that), cx = +d3_this.attr("cx"), cy = +d3_this.attr("cy"); return Math.sqrt(Math.pow(cx - mouse[0], 2) + Math.pow(cy - mouse[1], 2)) < r; }; c3_chart_internal_fn.isWithinStep = function (that, y) { return Math.abs(y - this.d3.mouse(that)[1]) < 30; }; c3_chart_internal_fn.initBar = function () { var $$ = this; $$.main.select('.' + CLASS.chart).append("g") .attr("class", CLASS.chartBars); }; c3_chart_internal_fn.updateTargetsForBar = function (targets) { var $$ = this, config = $$.config, mainBarUpdate, mainBarEnter, classChartBar = $$.classChartBar.bind($$), classBars = $$.classBars.bind($$), classFocus = $$.classFocus.bind($$); mainBarUpdate = $$.main.select('.' + CLASS.chartBars).selectAll('.' + CLASS.chartBar) .data(targets) .attr('class', function (d) { return classChartBar(d) + classFocus(d); }); mainBarEnter = mainBarUpdate.enter().append('g') .attr('class', classChartBar) .style('opacity', 0) .style("pointer-events", "none"); // Bars for each data mainBarEnter.append('g') .attr("class", classBars) .style("cursor", function (d) { return config.data_selection_isselectable(d) ? "pointer" : null; }); }; c3_chart_internal_fn.updateBar = function (durationForExit) { var $$ = this, barData = $$.barData.bind($$), classBar = $$.classBar.bind($$), initialOpacity = $$.initialOpacity.bind($$), color = function (d) { return $$.color(d.id); }; $$.mainBar = $$.main.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar) .data(barData); $$.mainBar.enter().append('path') .attr("class", classBar) .style("stroke", color) .style("fill", color); $$.mainBar .style("opacity", initialOpacity); $$.mainBar.exit().transition().duration(durationForExit) .style('opacity', 0) .remove(); }; c3_chart_internal_fn.redrawBar = function (drawBar, withTransition) { return [ (withTransition ? this.mainBar.transition(Math.random().toString()) : this.mainBar) .attr('d', drawBar) .style("fill", this.color) .style("opacity", 1) ]; }; c3_chart_internal_fn.getBarW = function (axis, barTargetsNum) { var $$ = this, config = $$.config, w = typeof config.bar_width === 'number' ? config.bar_width : barTargetsNum ? (axis.tickInterval() * config.bar_width_ratio) / barTargetsNum : 0; return config.bar_width_max && w > config.bar_width_max ? config.bar_width_max : w; }; c3_chart_internal_fn.getBars = function (i, id) { var $$ = this; return (id ? $$.main.selectAll('.' + CLASS.bars + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.bar + (isValue(i) ? '-' + i : '')); }; c3_chart_internal_fn.expandBars = function (i, id, reset) { var $$ = this; if (reset) { $$.unexpandBars(); } $$.getBars(i, id).classed(CLASS.EXPANDED, true); }; c3_chart_internal_fn.unexpandBars = function (i) { var $$ = this; $$.getBars(i).classed(CLASS.EXPANDED, false); }; c3_chart_internal_fn.generateDrawBar = function (barIndices, isSub) { var $$ = this, config = $$.config, getPoints = $$.generateGetBarPoints(barIndices, isSub); return function (d, i) { // 4 points that make a bar var points = getPoints(d, i); // switch points if axis is rotated, not applicable for sub chart var indexX = config.axis_rotated ? 1 : 0; var indexY = config.axis_rotated ? 0 : 1; var path = 'M ' + points[0][indexX] + ',' + points[0][indexY] + ' ' + 'L' + points[1][indexX] + ',' + points[1][indexY] + ' ' + 'L' + points[2][indexX] + ',' + points[2][indexY] + ' ' + 'L' + points[3][indexX] + ',' + points[3][indexY] + ' ' + 'z'; return path; }; }; c3_chart_internal_fn.generateGetBarPoints = function (barIndices, isSub) { var $$ = this, axis = isSub ? $$.subXAxis : $$.xAxis, barTargetsNum = barIndices.__max__ + 1, barW = $$.getBarW(axis, barTargetsNum), barX = $$.getShapeX(barW, barTargetsNum, barIndices, !!isSub), barY = $$.getShapeY(!!isSub), barOffset = $$.getShapeOffset($$.isBarType, barIndices, !!isSub), yScale = isSub ? $$.getSubYScale : $$.getYScale; return function (d, i) { var y0 = yScale.call($$, d.id)(0), offset = barOffset(d, i) || y0, // offset is for stacked bar chart posX = barX(d), posY = barY(d); // fix posY not to overflow opposite quadrant if ($$.config.axis_rotated) { if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; } } // 4 points that make a bar return [ [posX, offset], [posX, posY - (y0 - offset)], [posX + barW, posY - (y0 - offset)], [posX + barW, offset] ]; }; }; c3_chart_internal_fn.isWithinBar = function (that) { var mouse = this.d3.mouse(that), box = that.getBoundingClientRect(), seg0 = that.pathSegList.getItem(0), seg1 = that.pathSegList.getItem(1), x = Math.min(seg0.x, seg1.x), y = Math.min(seg0.y, seg1.y), w = box.width, h = box.height, offset = 2, sx = x - offset, ex = x + w + offset, sy = y + h + offset, ey = y - offset; return sx < mouse[0] && mouse[0] < ex && ey < mouse[1] && mouse[1] < sy; }; c3_chart_internal_fn.initText = function () { var $$ = this; $$.main.select('.' + CLASS.chart).append("g") .attr("class", CLASS.chartTexts); $$.mainText = $$.d3.selectAll([]); }; c3_chart_internal_fn.updateTargetsForText = function (targets) { var $$ = this, mainTextUpdate, mainTextEnter, classChartText = $$.classChartText.bind($$), classTexts = $$.classTexts.bind($$), classFocus = $$.classFocus.bind($$); mainTextUpdate = $$.main.select('.' + CLASS.chartTexts).selectAll('.' + CLASS.chartText) .data(targets) .attr('class', function (d) { return classChartText(d) + classFocus(d); }); mainTextEnter = mainTextUpdate.enter().append('g') .attr('class', classChartText) .style('opacity', 0) .style("pointer-events", "none"); mainTextEnter.append('g') .attr('class', classTexts); }; c3_chart_internal_fn.updateText = function (durationForExit) { var $$ = this, config = $$.config, barOrLineData = $$.barOrLineData.bind($$), classText = $$.classText.bind($$); $$.mainText = $$.main.selectAll('.' + CLASS.texts).selectAll('.' + CLASS.text) .data(barOrLineData); $$.mainText.enter().append('text') .attr("class", classText) .attr('text-anchor', function (d) { return config.axis_rotated ? (d.value < 0 ? 'end' : 'start') : 'middle'; }) .style("stroke", 'none') .style("fill", function (d) { return $$.color(d); }) .style("fill-opacity", 0); $$.mainText .text(function (d, i, j) { return $$.dataLabelFormat(d.id)(d.value, d.id, i, j); }); $$.mainText.exit() .transition().duration(durationForExit) .style('fill-opacity', 0) .remove(); }; c3_chart_internal_fn.redrawText = function (xForText, yForText, forFlow, withTransition) { return [ (withTransition ? this.mainText.transition() : this.mainText) .attr('x', xForText) .attr('y', yForText) .style("fill", this.color) .style("fill-opacity", forFlow ? 0 : this.opacityForText.bind(this)) ]; }; c3_chart_internal_fn.getTextRect = function (text, cls, element) { var dummy = this.d3.select('body').append('div').classed('c3', true), svg = dummy.append("svg").style('visibility', 'hidden').style('position', 'fixed').style('top', 0).style('left', 0), font = this.d3.select(element).style('font'), rect; svg.selectAll('.dummy') .data([text]) .enter().append('text') .classed(cls ? cls : "", true) .style('font', font) .text(text) .each(function () { rect = this.getBoundingClientRect(); }); dummy.remove(); return rect; }; c3_chart_internal_fn.generateXYForText = function (areaIndices, barIndices, lineIndices, forX) { var $$ = this, getAreaPoints = $$.generateGetAreaPoints(areaIndices, false), getBarPoints = $$.generateGetBarPoints(barIndices, false), getLinePoints = $$.generateGetLinePoints(lineIndices, false), getter = forX ? $$.getXForText : $$.getYForText; return function (d, i) { var getPoints = $$.isAreaType(d) ? getAreaPoints : $$.isBarType(d) ? getBarPoints : getLinePoints; return getter.call($$, getPoints(d, i), d, this); }; }; c3_chart_internal_fn.getXForText = function (points, d, textElement) { var $$ = this, box = textElement.getBoundingClientRect(), xPos, padding; if ($$.config.axis_rotated) { padding = $$.isBarType(d) ? 4 : 6; xPos = points[2][1] + padding * (d.value < 0 ? -1 : 1); } else { xPos = $$.hasType('bar') ? (points[2][0] + points[0][0]) / 2 : points[0][0]; } // show labels regardless of the domain if value is null if (d.value === null) { if (xPos > $$.width) { xPos = $$.width - box.width; } else if (xPos < 0) { xPos = 4; } } return xPos; }; c3_chart_internal_fn.getYForText = function (points, d, textElement) { var $$ = this, box = textElement.getBoundingClientRect(), yPos; if ($$.config.axis_rotated) { yPos = (points[0][0] + points[2][0] + box.height * 0.6) / 2; } else { yPos = points[2][1]; if (d.value < 0 || (d.value === 0 && !$$.hasPositiveValue)) { yPos += box.height; if ($$.isBarType(d) && $$.isSafari()) { yPos -= 3; } else if (!$$.isBarType(d) && $$.isChrome()) { yPos += 3; } } else { yPos += $$.isBarType(d) ? -3 : -6; } } // show labels regardless of the domain if value is null if (d.value === null && !$$.config.axis_rotated) { if (yPos < box.height) { yPos = box.height; } else if (yPos > this.height) { yPos = this.height - 4; } } return yPos; }; c3_chart_internal_fn.setTargetType = function (targetIds, type) { var $$ = this, config = $$.config; $$.mapToTargetIds(targetIds).forEach(function (id) { $$.withoutFadeIn[id] = (type === config.data_types[id]); config.data_types[id] = type; }); if (!targetIds) { config.data_type = type; } }; c3_chart_internal_fn.hasType = function (type, targets) { var $$ = this, types = $$.config.data_types, has = false; targets = targets || $$.data.targets; if (targets && targets.length) { targets.forEach(function (target) { var t = types[target.id]; if ((t && t.indexOf(type) >= 0) || (!t && type === 'line')) { has = true; } }); } else if (Object.keys(types).length) { Object.keys(types).forEach(function (id) { if (types[id] === type) { has = true; } }); } else { has = $$.config.data_type === type; } return has; }; c3_chart_internal_fn.hasArcType = function (targets) { return this.hasType('pie', targets) || this.hasType('donut', targets) || this.hasType('gauge', targets); }; c3_chart_internal_fn.isLineType = function (d) { var config = this.config, id = isString(d) ? d : d.id; return !config.data_types[id] || ['line', 'spline', 'area', 'area-spline', 'step', 'area-step'].indexOf(config.data_types[id]) >= 0; }; c3_chart_internal_fn.isStepType = function (d) { var id = isString(d) ? d : d.id; return ['step', 'area-step'].indexOf(this.config.data_types[id]) >= 0; }; c3_chart_internal_fn.isSplineType = function (d) { var id = isString(d) ? d : d.id; return ['spline', 'area-spline'].indexOf(this.config.data_types[id]) >= 0; }; c3_chart_internal_fn.isAreaType = function (d) { var id = isString(d) ? d : d.id; return ['area', 'area-spline', 'area-step'].indexOf(this.config.data_types[id]) >= 0; }; c3_chart_internal_fn.isBarType = function (d) { var id = isString(d) ? d : d.id; return this.config.data_types[id] === 'bar'; }; c3_chart_internal_fn.isScatterType = function (d) { var id = isString(d) ? d : d.id; return this.config.data_types[id] === 'scatter'; }; c3_chart_internal_fn.isPieType = function (d) { var id = isString(d) ? d : d.id; return this.config.data_types[id] === 'pie'; }; c3_chart_internal_fn.isGaugeType = function (d) { var id = isString(d) ? d : d.id; return this.config.data_types[id] === 'gauge'; }; c3_chart_internal_fn.isDonutType = function (d) { var id = isString(d) ? d : d.id; return this.config.data_types[id] === 'donut'; }; c3_chart_internal_fn.isArcType = function (d) { return this.isPieType(d) || this.isDonutType(d) || this.isGaugeType(d); }; c3_chart_internal_fn.lineData = function (d) { return this.isLineType(d) ? [d] : []; }; c3_chart_internal_fn.arcData = function (d) { return this.isArcType(d.data) ? [d] : []; }; /* not used function scatterData(d) { return isScatterType(d) ? d.values : []; } */ c3_chart_internal_fn.barData = function (d) { return this.isBarType(d) ? d.values : []; }; c3_chart_internal_fn.lineOrScatterData = function (d) { return this.isLineType(d) || this.isScatterType(d) ? d.values : []; }; c3_chart_internal_fn.barOrLineData = function (d) { return this.isBarType(d) || this.isLineType(d) ? d.values : []; }; c3_chart_internal_fn.isInterpolationType = function (type) { return ['linear', 'linear-closed', 'basis', 'basis-open', 'basis-closed', 'bundle', 'cardinal', 'cardinal-open', 'cardinal-closed', 'monotone'].indexOf(type) >= 0; }; c3_chart_internal_fn.initGrid = function () { var $$ = this, config = $$.config, d3 = $$.d3; $$.grid = $$.main.append('g') .attr("clip-path", $$.clipPathForGrid) .attr('class', CLASS.grid); if (config.grid_x_show) { $$.grid.append("g").attr("class", CLASS.xgrids); } if (config.grid_y_show) { $$.grid.append('g').attr('class', CLASS.ygrids); } if (config.grid_focus_show) { $$.grid.append('g') .attr("class", CLASS.xgridFocus) .append('line') .attr('class', CLASS.xgridFocus); } $$.xgrid = d3.selectAll([]); if (!config.grid_lines_front) { $$.initGridLines(); } }; c3_chart_internal_fn.initGridLines = function () { var $$ = this, d3 = $$.d3; $$.gridLines = $$.main.append('g') .attr("clip-path", $$.clipPathForGrid) .attr('class', CLASS.grid + ' ' + CLASS.gridLines); $$.gridLines.append('g').attr("class", CLASS.xgridLines); $$.gridLines.append('g').attr('class', CLASS.ygridLines); $$.xgridLines = d3.selectAll([]); }; c3_chart_internal_fn.updateXGrid = function (withoutUpdate) { var $$ = this, config = $$.config, d3 = $$.d3, xgridData = $$.generateGridData(config.grid_x_type, $$.x), tickOffset = $$.isCategorized() ? $$.xAxis.tickOffset() : 0; $$.xgridAttr = config.axis_rotated ? { 'x1': 0, 'x2': $$.width, 'y1': function (d) { return $$.x(d) - tickOffset; }, 'y2': function (d) { return $$.x(d) - tickOffset; } } : { 'x1': function (d) { return $$.x(d) + tickOffset; }, 'x2': function (d) { return $$.x(d) + tickOffset; }, 'y1': 0, 'y2': $$.height }; $$.xgrid = $$.main.select('.' + CLASS.xgrids).selectAll('.' + CLASS.xgrid) .data(xgridData); $$.xgrid.enter().append('line').attr("class", CLASS.xgrid); if (!withoutUpdate) { $$.xgrid.attr($$.xgridAttr) .style("opacity", function () { return +d3.select(this).attr(config.axis_rotated ? 'y1' : 'x1') === (config.axis_rotated ? $$.height : 0) ? 0 : 1; }); } $$.xgrid.exit().remove(); }; c3_chart_internal_fn.updateYGrid = function () { var $$ = this, config = $$.config, gridValues = $$.yAxis.tickValues() || $$.y.ticks(config.grid_y_ticks); $$.ygrid = $$.main.select('.' + CLASS.ygrids).selectAll('.' + CLASS.ygrid) .data(gridValues); $$.ygrid.enter().append('line') .attr('class', CLASS.ygrid); $$.ygrid.attr("x1", config.axis_rotated ? $$.y : 0) .attr("x2", config.axis_rotated ? $$.y : $$.width) .attr("y1", config.axis_rotated ? 0 : $$.y) .attr("y2", config.axis_rotated ? $$.height : $$.y); $$.ygrid.exit().remove(); $$.smoothLines($$.ygrid, 'grid'); }; c3_chart_internal_fn.gridTextAnchor = function (d) { return d.position ? d.position : "end"; }; c3_chart_internal_fn.gridTextDx = function (d) { return d.position === 'start' ? 4 : d.position === 'middle' ? 0 : -4; }; c3_chart_internal_fn.xGridTextX = function (d) { return d.position === 'start' ? -this.height : d.position === 'middle' ? -this.height / 2 : 0; }; c3_chart_internal_fn.yGridTextX = function (d) { return d.position === 'start' ? 0 : d.position === 'middle' ? this.width / 2 : this.width; }; c3_chart_internal_fn.updateGrid = function (duration) { var $$ = this, main = $$.main, config = $$.config, xgridLine, ygridLine, yv; // hide if arc type $$.grid.style('visibility', $$.hasArcType() ? 'hidden' : 'visible'); main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden"); if (config.grid_x_show) { $$.updateXGrid(); } $$.xgridLines = main.select('.' + CLASS.xgridLines).selectAll('.' + CLASS.xgridLine) .data(config.grid_x_lines); // enter xgridLine = $$.xgridLines.enter().append('g') .attr("class", function (d) { return CLASS.xgridLine + (d['class'] ? ' ' + d['class'] : ''); }); xgridLine.append('line') .style("opacity", 0); xgridLine.append('text') .attr("text-anchor", $$.gridTextAnchor) .attr("transform", config.axis_rotated ? "" : "rotate(-90)") .attr('dx', $$.gridTextDx) .attr('dy', -5) .style("opacity", 0); // udpate // done in d3.transition() of the end of this function // exit $$.xgridLines.exit().transition().duration(duration) .style("opacity", 0) .remove(); // Y-Grid if (config.grid_y_show) { $$.updateYGrid(); } $$.ygridLines = main.select('.' + CLASS.ygridLines).selectAll('.' + CLASS.ygridLine) .data(config.grid_y_lines); // enter ygridLine = $$.ygridLines.enter().append('g') .attr("class", function (d) { return CLASS.ygridLine + (d['class'] ? ' ' + d['class'] : ''); }); ygridLine.append('line') .style("opacity", 0); ygridLine.append('text') .attr("text-anchor", $$.gridTextAnchor) .attr("transform", config.axis_rotated ? "rotate(-90)" : "") .attr('dx', $$.gridTextDx) .attr('dy', -5) .style("opacity", 0); // update yv = $$.yv.bind($$); $$.ygridLines.select('line') .transition().duration(duration) .attr("x1", config.axis_rotated ? yv : 0) .attr("x2", config.axis_rotated ? yv : $$.width) .attr("y1", config.axis_rotated ? 0 : yv) .attr("y2", config.axis_rotated ? $$.height : yv) .style("opacity", 1); $$.ygridLines.select('text') .transition().duration(duration) .attr("x", config.axis_rotated ? $$.xGridTextX.bind($$) : $$.yGridTextX.bind($$)) .attr("y", yv) .text(function (d) { return d.text; }) .style("opacity", 1); // exit $$.ygridLines.exit().transition().duration(duration) .style("opacity", 0) .remove(); }; c3_chart_internal_fn.redrawGrid = function (withTransition) { var $$ = this, config = $$.config, xv = $$.xv.bind($$), lines = $$.xgridLines.select('line'), texts = $$.xgridLines.select('text'); return [ (withTransition ? lines.transition() : lines) .attr("x1", config.axis_rotated ? 0 : xv) .attr("x2", config.axis_rotated ? $$.width : xv) .attr("y1", config.axis_rotated ? xv : 0) .attr("y2", config.axis_rotated ? xv : $$.height) .style("opacity", 1), (withTransition ? texts.transition() : texts) .attr("x", config.axis_rotated ? $$.yGridTextX.bind($$) : $$.xGridTextX.bind($$)) .attr("y", xv) .text(function (d) { return d.text; }) .style("opacity", 1) ]; }; c3_chart_internal_fn.showXGridFocus = function (selectedData) { var $$ = this, config = $$.config, dataToShow = selectedData.filter(function (d) { return d && isValue(d.value); }), focusEl = $$.main.selectAll('line.' + CLASS.xgridFocus), xx = $$.xx.bind($$); if (! config.tooltip_show) { return; } // Hide when scatter plot exists if ($$.hasType('scatter') || $$.hasArcType()) { return; } focusEl .style("visibility", "visible") .data([dataToShow[0]]) .attr(config.axis_rotated ? 'y1' : 'x1', xx) .attr(config.axis_rotated ? 'y2' : 'x2', xx); $$.smoothLines(focusEl, 'grid'); }; c3_chart_internal_fn.hideXGridFocus = function () { this.main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden"); }; c3_chart_internal_fn.updateXgridFocus = function () { var $$ = this, config = $$.config; $$.main.select('line.' + CLASS.xgridFocus) .attr("x1", config.axis_rotated ? 0 : -10) .attr("x2", config.axis_rotated ? $$.width : -10) .attr("y1", config.axis_rotated ? -10 : 0) .attr("y2", config.axis_rotated ? -10 : $$.height); }; c3_chart_internal_fn.generateGridData = function (type, scale) { var $$ = this, gridData = [], xDomain, firstYear, lastYear, i, tickNum = $$.main.select("." + CLASS.axisX).selectAll('.tick').size(); if (type === 'year') { xDomain = $$.getXDomain(); firstYear = xDomain[0].getFullYear(); lastYear = xDomain[1].getFullYear(); for (i = firstYear; i <= lastYear; i++) { gridData.push(new Date(i + '-01-01 00:00:00')); } } else { gridData = scale.ticks(10); if (gridData.length > tickNum) { // use only int gridData = gridData.filter(function (d) { return ("" + d).indexOf('.') < 0; }); } } return gridData; }; c3_chart_internal_fn.getGridFilterToRemove = function (params) { return params ? function (line) { var found = false; [].concat(params).forEach(function (param) { if ((('value' in param && line.value === param.value) || ('class' in param && line['class'] === param['class']))) { found = true; } }); return found; } : function () { return true; }; }; c3_chart_internal_fn.removeGridLines = function (params, forX) { var $$ = this, config = $$.config, toRemove = $$.getGridFilterToRemove(params), toShow = function (line) { return !toRemove(line); }, classLines = forX ? CLASS.xgridLines : CLASS.ygridLines, classLine = forX ? CLASS.xgridLine : CLASS.ygridLine; $$.main.select('.' + classLines).selectAll('.' + classLine).filter(toRemove) .transition().duration(config.transition_duration) .style('opacity', 0).remove(); if (forX) { config.grid_x_lines = config.grid_x_lines.filter(toShow); } else { config.grid_y_lines = config.grid_y_lines.filter(toShow); } }; c3_chart_internal_fn.initTooltip = function () { var $$ = this, config = $$.config, i; $$.tooltip = $$.selectChart .style("position", "relative") .append("div") .attr('class', CLASS.tooltipContainer) .style("position", "absolute") .style("pointer-events", "none") .style("display", "none"); // Show tooltip if needed if (config.tooltip_init_show) { if ($$.isTimeSeries() && isString(config.tooltip_init_x)) { config.tooltip_init_x = $$.parseDate(config.tooltip_init_x); for (i = 0; i < $$.data.targets[0].values.length; i++) { if (($$.data.targets[0].values[i].x - config.tooltip_init_x) === 0) { break; } } config.tooltip_init_x = i; } $$.tooltip.html(config.tooltip_contents.call($$, $$.data.targets.map(function (d) { return $$.addName(d.values[config.tooltip_init_x]); }), $$.axis.getXAxisTickFormat(), $$.getYFormat($$.hasArcType()), $$.color)); $$.tooltip.style("top", config.tooltip_init_position.top) .style("left", config.tooltip_init_position.left) .style("display", "block"); } }; c3_chart_internal_fn.getTooltipContent = function (d, defaultTitleFormat, defaultValueFormat, color) { var $$ = this, config = $$.config, titleFormat = config.tooltip_format_title || defaultTitleFormat, nameFormat = config.tooltip_format_name || function (name) { return name; }, valueFormat = config.tooltip_format_value || defaultValueFormat, text, i, title, value, name, bgcolor, orderAsc = $$.isOrderAsc(); if (config.data_groups.length === 0) { d.sort(function(a, b){ var v1 = a ? a.value : null, v2 = b ? b.value : null; return orderAsc ? v1 - v2 : v2 - v1; }); } else { var ids = $$.orderTargets($$.data.targets).map(function (i) { return i.id; }); d.sort(function(a, b) { var v1 = a ? a.value : null, v2 = b ? b.value : null; if (v1 > 0 && v2 > 0) { v1 = a ? ids.indexOf(a.id) : null; v2 = b ? ids.indexOf(b.id) : null; } return orderAsc ? v1 - v2 : v2 - v1; }); } for (i = 0; i < d.length; i++) { if (! (d[i] && (d[i].value || d[i].value === 0))) { continue; } if (! text) { title = sanitise(titleFormat ? titleFormat(d[i].x) : d[i].x); text = "<table class='" + $$.CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : ""); } value = sanitise(valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index, d)); if (value !== undefined) { // Skip elements when their name is set to null if (d[i].name === null) { continue; } name = sanitise(nameFormat(d[i].name, d[i].ratio, d[i].id, d[i].index)); bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id); text += "<tr class='" + $$.CLASS.tooltipName + "-" + $$.getTargetSelectorSuffix(d[i].id) + "'>"; text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>"; text += "<td class='value'>" + value + "</td>"; text += "</tr>"; } } return text + "</table>"; }; c3_chart_internal_fn.tooltipPosition = function (dataToShow, tWidth, tHeight, element) { var $$ = this, config = $$.config, d3 = $$.d3; var svgLeft, tooltipLeft, tooltipRight, tooltipTop, chartRight; var forArc = $$.hasArcType(), mouse = d3.mouse(element); // Determin tooltip position if (forArc) { tooltipLeft = (($$.width - ($$.isLegendRight ? $$.getLegendWidth() : 0)) / 2) + mouse[0]; tooltipTop = ($$.height / 2) + mouse[1] + 20; } else { svgLeft = $$.getSvgLeft(true); if (config.axis_rotated) { tooltipLeft = svgLeft + mouse[0] + 100; tooltipRight = tooltipLeft + tWidth; chartRight = $$.currentWidth - $$.getCurrentPaddingRight(); tooltipTop = $$.x(dataToShow[0].x) + 20; } else { tooltipLeft = svgLeft + $$.getCurrentPaddingLeft(true) + $$.x(dataToShow[0].x) + 20; tooltipRight = tooltipLeft + tWidth; chartRight = svgLeft + $$.currentWidth - $$.getCurrentPaddingRight(); tooltipTop = mouse[1] + 15; } if (tooltipRight > chartRight) { // 20 is needed for Firefox to keep tooltip width tooltipLeft -= tooltipRight - chartRight + 20; } if (tooltipTop + tHeight > $$.currentHeight) { tooltipTop -= tHeight + 30; } } if (tooltipTop < 0) { tooltipTop = 0; } return {top: tooltipTop, left: tooltipLeft}; }; c3_chart_internal_fn.showTooltip = function (selectedData, element) { var $$ = this, config = $$.config; var tWidth, tHeight, position; var forArc = $$.hasArcType(), dataToShow = selectedData.filter(function (d) { return d && isValue(d.value); }), positionFunction = config.tooltip_position || c3_chart_internal_fn.tooltipPosition; if (dataToShow.length === 0 || !config.tooltip_show) { return; } $$.tooltip.html(config.tooltip_contents.call($$, selectedData, $$.axis.getXAxisTickFormat(), $$.getYFormat(forArc), $$.color)).style("display", "block"); // Get tooltip dimensions tWidth = $$.tooltip.property('offsetWidth'); tHeight = $$.tooltip.property('offsetHeight'); position = positionFunction.call(this, dataToShow, tWidth, tHeight, element); // Set tooltip $$.tooltip .style("top", position.top + "px") .style("left", position.left + 'px'); }; c3_chart_internal_fn.hideTooltip = function () { this.tooltip.style("display", "none"); }; c3_chart_internal_fn.initLegend = function () { var $$ = this; $$.legendItemTextBox = {}; $$.legendHasRendered = false; $$.legend = $$.svg.append("g").attr("transform", $$.getTranslate('legend')); if (!$$.config.legend_show) { $$.legend.style('visibility', 'hidden'); $$.hiddenLegendIds = $$.mapToIds($$.data.targets); return; } // MEMO: call here to update legend box and tranlate for all // MEMO: translate will be upated by this, so transform not needed in updateLegend() $$.updateLegendWithDefaults(); }; c3_chart_internal_fn.updateLegendWithDefaults = function () { var $$ = this; $$.updateLegend($$.mapToIds($$.data.targets), {withTransform: false, withTransitionForTransform: false, withTransition: false}); }; c3_chart_internal_fn.updateSizeForLegend = function (legendHeight, legendWidth) { var $$ = this, config = $$.config, insetLegendPosition = { top: $$.isLegendTop ? $$.getCurrentPaddingTop() + config.legend_inset_y + 5.5 : $$.currentHeight - legendHeight - $$.getCurrentPaddingBottom() - config.legend_inset_y, left: $$.isLegendLeft ? $$.getCurrentPaddingLeft() + config.legend_inset_x + 0.5 : $$.currentWidth - legendWidth - $$.getCurrentPaddingRight() - config.legend_inset_x + 0.5 }; $$.margin3 = { top: $$.isLegendRight ? 0 : $$.isLegendInset ? insetLegendPosition.top : $$.currentHeight - legendHeight, right: NaN, bottom: 0, left: $$.isLegendRight ? $$.currentWidth - legendWidth : $$.isLegendInset ? insetLegendPosition.left : 0 }; }; c3_chart_internal_fn.transformLegend = function (withTransition) { var $$ = this; (withTransition ? $$.legend.transition() : $$.legend).attr("transform", $$.getTranslate('legend')); }; c3_chart_internal_fn.updateLegendStep = function (step) { this.legendStep = step; }; c3_chart_internal_fn.updateLegendItemWidth = function (w) { this.legendItemWidth = w; }; c3_chart_internal_fn.updateLegendItemHeight = function (h) { this.legendItemHeight = h; }; c3_chart_internal_fn.getLegendWidth = function () { var $$ = this; return $$.config.legend_show ? $$.isLegendRight || $$.isLegendInset ? $$.legendItemWidth * ($$.legendStep + 1) : $$.currentWidth : 0; }; c3_chart_internal_fn.getLegendHeight = function () { var $$ = this, h = 0; if ($$.config.legend_show) { if ($$.isLegendRight) { h = $$.currentHeight; } else { h = Math.max(20, $$.legendItemHeight) * ($$.legendStep + 1); } } return h; }; c3_chart_internal_fn.opacityForLegend = function (legendItem) { return legendItem.classed(CLASS.legendItemHidden) ? null : 1; }; c3_chart_internal_fn.opacityForUnfocusedLegend = function (legendItem) { return legendItem.classed(CLASS.legendItemHidden) ? null : 0.3; }; c3_chart_internal_fn.toggleFocusLegend = function (targetIds, focus) { var $$ = this; targetIds = $$.mapToTargetIds(targetIds); $$.legend.selectAll('.' + CLASS.legendItem) .filter(function (id) { return targetIds.indexOf(id) >= 0; }) .classed(CLASS.legendItemFocused, focus) .transition().duration(100) .style('opacity', function () { var opacity = focus ? $$.opacityForLegend : $$.opacityForUnfocusedLegend; return opacity.call($$, $$.d3.select(this)); }); }; c3_chart_internal_fn.revertLegend = function () { var $$ = this, d3 = $$.d3; $$.legend.selectAll('.' + CLASS.legendItem) .classed(CLASS.legendItemFocused, false) .transition().duration(100) .style('opacity', function () { return $$.opacityForLegend(d3.select(this)); }); }; c3_chart_internal_fn.showLegend = function (targetIds) { var $$ = this, config = $$.config; if (!config.legend_show) { config.legend_show = true; $$.legend.style('visibility', 'visible'); if (!$$.legendHasRendered) { $$.updateLegendWithDefaults(); } } $$.removeHiddenLegendIds(targetIds); $$.legend.selectAll($$.selectorLegends(targetIds)) .style('visibility', 'visible') .transition() .style('opacity', function () { return $$.opacityForLegend($$.d3.select(this)); }); }; c3_chart_internal_fn.hideLegend = function (targetIds) { var $$ = this, config = $$.config; if (config.legend_show && isEmpty(targetIds)) { config.legend_show = false; $$.legend.style('visibility', 'hidden'); } $$.addHiddenLegendIds(targetIds); $$.legend.selectAll($$.selectorLegends(targetIds)) .style('opacity', 0) .style('visibility', 'hidden'); }; c3_chart_internal_fn.clearLegendItemTextBoxCache = function () { this.legendItemTextBox = {}; }; c3_chart_internal_fn.updateLegend = function (targetIds, options, transitions) { var $$ = this, config = $$.config; var xForLegend, xForLegendText, xForLegendRect, yForLegend, yForLegendText, yForLegendRect, x1ForLegendTile, x2ForLegendTile, yForLegendTile; var paddingTop = 4, paddingRight = 10, maxWidth = 0, maxHeight = 0, posMin = 10, tileWidth = config.legend_item_tile_width + 5; var l, totalLength = 0, offsets = {}, widths = {}, heights = {}, margins = [0], steps = {}, step = 0; var withTransition, withTransitionForTransform; var texts, rects, tiles, background; // Skip elements when their name is set to null targetIds = targetIds.filter(function(id) { return !isDefined(config.data_names[id]) || config.data_names[id] !== null; }); options = options || {}; withTransition = getOption(options, "withTransition", true); withTransitionForTransform = getOption(options, "withTransitionForTransform", true); function getTextBox(textElement, id) { if (!$$.legendItemTextBox[id]) { $$.legendItemTextBox[id] = $$.getTextRect(textElement.textContent, CLASS.legendItem, textElement); } return $$.legendItemTextBox[id]; } function updatePositions(textElement, id, index) { var reset = index === 0, isLast = index === targetIds.length - 1, box = getTextBox(textElement, id), itemWidth = box.width + tileWidth + (isLast && !($$.isLegendRight || $$.isLegendInset) ? 0 : paddingRight) + config.legend_padding, itemHeight = box.height + paddingTop, itemLength = $$.isLegendRight || $$.isLegendInset ? itemHeight : itemWidth, areaLength = $$.isLegendRight || $$.isLegendInset ? $$.getLegendHeight() : $$.getLegendWidth(), margin, maxLength; // MEMO: care about condifion of step, totalLength function updateValues(id, withoutStep) { if (!withoutStep) { margin = (areaLength - totalLength - itemLength) / 2; if (margin < posMin) { margin = (areaLength - itemLength) / 2; totalLength = 0; step++; } } steps[id] = step; margins[step] = $$.isLegendInset ? 10 : margin; offsets[id] = totalLength; totalLength += itemLength; } if (reset) { totalLength = 0; step = 0; maxWidth = 0; maxHeight = 0; } if (config.legend_show && !$$.isLegendToShow(id)) { widths[id] = heights[id] = steps[id] = offsets[id] = 0; return; } widths[id] = itemWidth; heights[id] = itemHeight; if (!maxWidth || itemWidth >= maxWidth) { maxWidth = itemWidth; } if (!maxHeight || itemHeight >= maxHeight) { maxHeight = itemHeight; } maxLength = $$.isLegendRight || $$.isLegendInset ? maxHeight : maxWidth; if (config.legend_equally) { Object.keys(widths).forEach(function (id) { widths[id] = maxWidth; }); Object.keys(heights).forEach(function (id) { heights[id] = maxHeight; }); margin = (areaLength - maxLength * targetIds.length) / 2; if (margin < posMin) { totalLength = 0; step = 0; targetIds.forEach(function (id) { updateValues(id); }); } else { updateValues(id, true); } } else { updateValues(id); } } if ($$.isLegendInset) { step = config.legend_inset_step ? config.legend_inset_step : targetIds.length; $$.updateLegendStep(step); } if ($$.isLegendRight) { xForLegend = function (id) { return maxWidth * steps[id]; }; yForLegend = function (id) { return margins[steps[id]] + offsets[id]; }; } else if ($$.isLegendInset) { xForLegend = function (id) { return maxWidth * steps[id] + 10; }; yForLegend = function (id) { return margins[steps[id]] + offsets[id]; }; } else { xForLegend = function (id) { return margins[steps[id]] + offsets[id]; }; yForLegend = function (id) { return maxHeight * steps[id]; }; } xForLegendText = function (id, i) { return xForLegend(id, i) + 4 + config.legend_item_tile_width; }; yForLegendText = function (id, i) { return yForLegend(id, i) + 9; }; xForLegendRect = function (id, i) { return xForLegend(id, i); }; yForLegendRect = function (id, i) { return yForLegend(id, i) - 5; }; x1ForLegendTile = function (id, i) { return xForLegend(id, i) - 2; }; x2ForLegendTile = function (id, i) { return xForLegend(id, i) - 2 + config.legend_item_tile_width; }; yForLegendTile = function (id, i) { return yForLegend(id, i) + 4; }; // Define g for legend area l = $$.legend.selectAll('.' + CLASS.legendItem) .data(targetIds) .enter().append('g') .attr('class', function (id) { return $$.generateClass(CLASS.legendItem, id); }) .style('visibility', function (id) { return $$.isLegendToShow(id) ? 'visible' : 'hidden'; }) .style('cursor', 'pointer') .on('click', function (id) { if (config.legend_item_onclick) { config.legend_item_onclick.call($$, id); } else { if ($$.d3.event.altKey) { $$.api.hide(); $$.api.show(id); } else { $$.api.toggle(id); $$.isTargetToShow(id) ? $$.api.focus(id) : $$.api.revert(); } } }) .on('mouseover', function (id) { if (config.legend_item_onmouseover) { config.legend_item_onmouseover.call($$, id); } else { $$.d3.select(this).classed(CLASS.legendItemFocused, true); if (!$$.transiting && $$.isTargetToShow(id)) { $$.api.focus(id); } } }) .on('mouseout', function (id) { if (config.legend_item_onmouseout) { config.legend_item_onmouseout.call($$, id); } else { $$.d3.select(this).classed(CLASS.legendItemFocused, false); $$.api.revert(); } }); l.append('text') .text(function (id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id; }) .each(function (id, i) { updatePositions(this, id, i); }) .style("pointer-events", "none") .attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendText : -200) .attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendText); l.append('rect') .attr("class", CLASS.legendItemEvent) .style('fill-opacity', 0) .attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendRect : -200) .attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendRect); l.append('line') .attr('class', CLASS.legendItemTile) .style('stroke', $$.color) .style("pointer-events", "none") .attr('x1', $$.isLegendRight || $$.isLegendInset ? x1ForLegendTile : -200) .attr('y1', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendTile) .attr('x2', $$.isLegendRight || $$.isLegendInset ? x2ForLegendTile : -200) .attr('y2', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendTile) .attr('stroke-width', config.legend_item_tile_height); // Set background for inset legend background = $$.legend.select('.' + CLASS.legendBackground + ' rect'); if ($$.isLegendInset && maxWidth > 0 && background.size() === 0) { background = $$.legend.insert('g', '.' + CLASS.legendItem) .attr("class", CLASS.legendBackground) .append('rect'); } texts = $$.legend.selectAll('text') .data(targetIds) .text(function (id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id; }) // MEMO: needed for update .each(function (id, i) { updatePositions(this, id, i); }); (withTransition ? texts.transition() : texts) .attr('x', xForLegendText) .attr('y', yForLegendText); rects = $$.legend.selectAll('rect.' + CLASS.legendItemEvent) .data(targetIds); (withTransition ? rects.transition() : rects) .attr('width', function (id) { return widths[id]; }) .attr('height', function (id) { return heights[id]; }) .attr('x', xForLegendRect) .attr('y', yForLegendRect); tiles = $$.legend.selectAll('line.' + CLASS.legendItemTile) .data(targetIds); (withTransition ? tiles.transition() : tiles) .style('stroke', $$.color) .attr('x1', x1ForLegendTile) .attr('y1', yForLegendTile) .attr('x2', x2ForLegendTile) .attr('y2', yForLegendTile); if (background) { (withTransition ? background.transition() : background) .attr('height', $$.getLegendHeight() - 12) .attr('width', maxWidth * (step + 1) + 10); } // toggle legend state $$.legend.selectAll('.' + CLASS.legendItem) .classed(CLASS.legendItemHidden, function (id) { return !$$.isTargetToShow(id); }); // Update all to reflect change of legend $$.updateLegendItemWidth(maxWidth); $$.updateLegendItemHeight(maxHeight); $$.updateLegendStep(step); // Update size and scale $$.updateSizes(); $$.updateScales(); $$.updateSvgSize(); // Update g positions $$.transformAll(withTransitionForTransform, transitions); $$.legendHasRendered = true; }; c3_chart_internal_fn.initTitle = function () { var $$ = this; $$.title = $$.svg.append("text") .text($$.config.title_text) .attr("class", $$.CLASS.title); }; c3_chart_internal_fn.redrawTitle = function () { var $$ = this; $$.title .attr("x", $$.xForTitle.bind($$)) .attr("y", $$.yForTitle.bind($$)); }; c3_chart_internal_fn.xForTitle = function () { var $$ = this, config = $$.config, position = config.title_position || 'left', x; if (position.indexOf('right') >= 0) { x = $$.currentWidth - $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).width - config.title_padding.right; } else if (position.indexOf('center') >= 0) { x = ($$.currentWidth - $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).width) / 2; } else { // left x = config.title_padding.left; } return x; }; c3_chart_internal_fn.yForTitle = function () { var $$ = this; return $$.config.title_padding.top + $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).height; }; c3_chart_internal_fn.getTitlePadding = function() { var $$ = this; return $$.yForTitle() + $$.config.title_padding.bottom; }; function Axis(owner) { API.call(this, owner); } inherit(API, Axis); Axis.prototype.init = function init() { var $$ = this.owner, config = $$.config, main = $$.main; $$.axes.x = main.append("g") .attr("class", CLASS.axis + ' ' + CLASS.axisX) .attr("clip-path", $$.clipPathForXAxis) .attr("transform", $$.getTranslate('x')) .style("visibility", config.axis_x_show ? 'visible' : 'hidden'); $$.axes.x.append("text") .attr("class", CLASS.axisXLabel) .attr("transform", config.axis_rotated ? "rotate(-90)" : "") .style("text-anchor", this.textAnchorForXAxisLabel.bind(this)); $$.axes.y = main.append("g") .attr("class", CLASS.axis + ' ' + CLASS.axisY) .attr("clip-path", config.axis_y_inner ? "" : $$.clipPathForYAxis) .attr("transform", $$.getTranslate('y')) .style("visibility", config.axis_y_show ? 'visible' : 'hidden'); $$.axes.y.append("text") .attr("class", CLASS.axisYLabel) .attr("transform", config.axis_rotated ? "" : "rotate(-90)") .style("text-anchor", this.textAnchorForYAxisLabel.bind(this)); $$.axes.y2 = main.append("g") .attr("class", CLASS.axis + ' ' + CLASS.axisY2) // clip-path? .attr("transform", $$.getTranslate('y2')) .style("visibility", config.axis_y2_show ? 'visible' : 'hidden'); $$.axes.y2.append("text") .attr("class", CLASS.axisY2Label) .attr("transform", config.axis_rotated ? "" : "rotate(-90)") .style("text-anchor", this.textAnchorForY2AxisLabel.bind(this)); }; Axis.prototype.getXAxis = function getXAxis(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) { var $$ = this.owner, config = $$.config, axisParams = { isCategory: $$.isCategorized(), withOuterTick: withOuterTick, tickMultiline: config.axis_x_tick_multiline, tickWidth: config.axis_x_tick_width, tickTextRotate: withoutRotateTickText ? 0 : config.axis_x_tick_rotate, withoutTransition: withoutTransition, }, axis = c3_axis($$.d3, axisParams).scale(scale).orient(orient); if ($$.isTimeSeries() && tickValues && typeof tickValues !== "function") { tickValues = tickValues.map(function (v) { return $$.parseDate(v); }); } // Set tick axis.tickFormat(tickFormat).tickValues(tickValues); if ($$.isCategorized()) { axis.tickCentered(config.axis_x_tick_centered); if (isEmpty(config.axis_x_tick_culling)) { config.axis_x_tick_culling = false; } } return axis; }; Axis.prototype.updateXAxisTickValues = function updateXAxisTickValues(targets, axis) { var $$ = this.owner, config = $$.config, tickValues; if (config.axis_x_tick_fit || config.axis_x_tick_count) { tickValues = this.generateTickValues($$.mapTargetsToUniqueXs(targets), config.axis_x_tick_count, $$.isTimeSeries()); } if (axis) { axis.tickValues(tickValues); } else { $$.xAxis.tickValues(tickValues); $$.subXAxis.tickValues(tickValues); } return tickValues; }; Axis.prototype.getYAxis = function getYAxis(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) { var $$ = this.owner, config = $$.config, axisParams = { withOuterTick: withOuterTick, withoutTransition: withoutTransition, tickTextRotate: withoutRotateTickText ? 0 : config.axis_y_tick_rotate }, axis = c3_axis($$.d3, axisParams).scale(scale).orient(orient).tickFormat(tickFormat); if ($$.isTimeSeriesY()) { axis.ticks($$.d3.time[config.axis_y_tick_time_value], config.axis_y_tick_time_interval); } else { axis.tickValues(tickValues); } return axis; }; Axis.prototype.getId = function getId(id) { var config = this.owner.config; return id in config.data_axes ? config.data_axes[id] : 'y'; }; Axis.prototype.getXAxisTickFormat = function getXAxisTickFormat() { var $$ = this.owner, config = $$.config, format = $$.isTimeSeries() ? $$.defaultAxisTimeFormat : $$.isCategorized() ? $$.categoryName : function (v) { return v < 0 ? v.toFixed(0) : v; }; if (config.axis_x_tick_format) { if (isFunction(config.axis_x_tick_format)) { format = config.axis_x_tick_format; } else if ($$.isTimeSeries()) { format = function (date) { return date ? $$.axisTimeFormat(config.axis_x_tick_format)(date) : ""; }; } } return isFunction(format) ? function (v) { return format.call($$, v); } : format; }; Axis.prototype.getTickValues = function getTickValues(tickValues, axis) { return tickValues ? tickValues : axis ? axis.tickValues() : undefined; }; Axis.prototype.getXAxisTickValues = function getXAxisTickValues() { return this.getTickValues(this.owner.config.axis_x_tick_values, this.owner.xAxis); }; Axis.prototype.getYAxisTickValues = function getYAxisTickValues() { return this.getTickValues(this.owner.config.axis_y_tick_values, this.owner.yAxis); }; Axis.prototype.getY2AxisTickValues = function getY2AxisTickValues() { return this.getTickValues(this.owner.config.axis_y2_tick_values, this.owner.y2Axis); }; Axis.prototype.getLabelOptionByAxisId = function getLabelOptionByAxisId(axisId) { var $$ = this.owner, config = $$.config, option; if (axisId === 'y') { option = config.axis_y_label; } else if (axisId === 'y2') { option = config.axis_y2_label; } else if (axisId === 'x') { option = config.axis_x_label; } return option; }; Axis.prototype.getLabelText = function getLabelText(axisId) { var option = this.getLabelOptionByAxisId(axisId); return isString(option) ? option : option ? option.text : null; }; Axis.prototype.setLabelText = function setLabelText(axisId, text) { var $$ = this.owner, config = $$.config, option = this.getLabelOptionByAxisId(axisId); if (isString(option)) { if (axisId === 'y') { config.axis_y_label = text; } else if (axisId === 'y2') { config.axis_y2_label = text; } else if (axisId === 'x') { config.axis_x_label = text; } } else if (option) { option.text = text; } }; Axis.prototype.getLabelPosition = function getLabelPosition(axisId, defaultPosition) { var option = this.getLabelOptionByAxisId(axisId), position = (option && typeof option === 'object' && option.position) ? option.position : defaultPosition; return { isInner: position.indexOf('inner') >= 0, isOuter: position.indexOf('outer') >= 0, isLeft: position.indexOf('left') >= 0, isCenter: position.indexOf('center') >= 0, isRight: position.indexOf('right') >= 0, isTop: position.indexOf('top') >= 0, isMiddle: position.indexOf('middle') >= 0, isBottom: position.indexOf('bottom') >= 0 }; }; Axis.prototype.getXAxisLabelPosition = function getXAxisLabelPosition() { return this.getLabelPosition('x', this.owner.config.axis_rotated ? 'inner-top' : 'inner-right'); }; Axis.prototype.getYAxisLabelPosition = function getYAxisLabelPosition() { return this.getLabelPosition('y', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top'); }; Axis.prototype.getY2AxisLabelPosition = function getY2AxisLabelPosition() { return this.getLabelPosition('y2', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top'); }; Axis.prototype.getLabelPositionById = function getLabelPositionById(id) { return id === 'y2' ? this.getY2AxisLabelPosition() : id === 'y' ? this.getYAxisLabelPosition() : this.getXAxisLabelPosition(); }; Axis.prototype.textForXAxisLabel = function textForXAxisLabel() { return this.getLabelText('x'); }; Axis.prototype.textForYAxisLabel = function textForYAxisLabel() { return this.getLabelText('y'); }; Axis.prototype.textForY2AxisLabel = function textForY2AxisLabel() { return this.getLabelText('y2'); }; Axis.prototype.xForAxisLabel = function xForAxisLabel(forHorizontal, position) { var $$ = this.owner; if (forHorizontal) { return position.isLeft ? 0 : position.isCenter ? $$.width / 2 : $$.width; } else { return position.isBottom ? -$$.height : position.isMiddle ? -$$.height / 2 : 0; } }; Axis.prototype.dxForAxisLabel = function dxForAxisLabel(forHorizontal, position) { if (forHorizontal) { return position.isLeft ? "0.5em" : position.isRight ? "-0.5em" : "0"; } else { return position.isTop ? "-0.5em" : position.isBottom ? "0.5em" : "0"; } }; Axis.prototype.textAnchorForAxisLabel = function textAnchorForAxisLabel(forHorizontal, position) { if (forHorizontal) { return position.isLeft ? 'start' : position.isCenter ? 'middle' : 'end'; } else { return position.isBottom ? 'start' : position.isMiddle ? 'middle' : 'end'; } }; Axis.prototype.xForXAxisLabel = function xForXAxisLabel() { return this.xForAxisLabel(!this.owner.config.axis_rotated, this.getXAxisLabelPosition()); }; Axis.prototype.xForYAxisLabel = function xForYAxisLabel() { return this.xForAxisLabel(this.owner.config.axis_rotated, this.getYAxisLabelPosition()); }; Axis.prototype.xForY2AxisLabel = function xForY2AxisLabel() { return this.xForAxisLabel(this.owner.config.axis_rotated, this.getY2AxisLabelPosition()); }; Axis.prototype.dxForXAxisLabel = function dxForXAxisLabel() { return this.dxForAxisLabel(!this.owner.config.axis_rotated, this.getXAxisLabelPosition()); }; Axis.prototype.dxForYAxisLabel = function dxForYAxisLabel() { return this.dxForAxisLabel(this.owner.config.axis_rotated, this.getYAxisLabelPosition()); }; Axis.prototype.dxForY2AxisLabel = function dxForY2AxisLabel() { return this.dxForAxisLabel(this.owner.config.axis_rotated, this.getY2AxisLabelPosition()); }; Axis.prototype.dyForXAxisLabel = function dyForXAxisLabel() { var $$ = this.owner, config = $$.config, position = this.getXAxisLabelPosition(); if (config.axis_rotated) { return position.isInner ? "1.2em" : -25 - this.getMaxTickWidth('x'); } else { return position.isInner ? "-0.5em" : config.axis_x_height ? config.axis_x_height - 10 : "3em"; } }; Axis.prototype.dyForYAxisLabel = function dyForYAxisLabel() { var $$ = this.owner, position = this.getYAxisLabelPosition(); if ($$.config.axis_rotated) { return position.isInner ? "-0.5em" : "3em"; } else { return position.isInner ? "1.2em" : -10 - ($$.config.axis_y_inner ? 0 : (this.getMaxTickWidth('y') + 10)); } }; Axis.prototype.dyForY2AxisLabel = function dyForY2AxisLabel() { var $$ = this.owner, position = this.getY2AxisLabelPosition(); if ($$.config.axis_rotated) { return position.isInner ? "1.2em" : "-2.2em"; } else { return position.isInner ? "-0.5em" : 15 + ($$.config.axis_y2_inner ? 0 : (this.getMaxTickWidth('y2') + 15)); } }; Axis.prototype.textAnchorForXAxisLabel = function textAnchorForXAxisLabel() { var $$ = this.owner; return this.textAnchorForAxisLabel(!$$.config.axis_rotated, this.getXAxisLabelPosition()); }; Axis.prototype.textAnchorForYAxisLabel = function textAnchorForYAxisLabel() { var $$ = this.owner; return this.textAnchorForAxisLabel($$.config.axis_rotated, this.getYAxisLabelPosition()); }; Axis.prototype.textAnchorForY2AxisLabel = function textAnchorForY2AxisLabel() { var $$ = this.owner; return this.textAnchorForAxisLabel($$.config.axis_rotated, this.getY2AxisLabelPosition()); }; Axis.prototype.getMaxTickWidth = function getMaxTickWidth(id, withoutRecompute) { var $$ = this.owner, config = $$.config, maxWidth = 0, targetsToShow, scale, axis, dummy, svg; if (withoutRecompute && $$.currentMaxTickWidths[id]) { return $$.currentMaxTickWidths[id]; } if ($$.svg) { targetsToShow = $$.filterTargetsToShow($$.data.targets); if (id === 'y') { scale = $$.y.copy().domain($$.getYDomain(targetsToShow, 'y')); axis = this.getYAxis(scale, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues, false, true, true); } else if (id === 'y2') { scale = $$.y2.copy().domain($$.getYDomain(targetsToShow, 'y2')); axis = this.getYAxis(scale, $$.y2Orient, config.axis_y2_tick_format, $$.y2AxisTickValues, false, true, true); } else { scale = $$.x.copy().domain($$.getXDomain(targetsToShow)); axis = this.getXAxis(scale, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, false, true, true); this.updateXAxisTickValues(targetsToShow, axis); } dummy = $$.d3.select('body').append('div').classed('c3', true); svg = dummy.append("svg").style('visibility', 'hidden').style('position', 'fixed').style('top', 0).style('left', 0), svg.append('g').call(axis).each(function () { $$.d3.select(this).selectAll('text').each(function () { var box = this.getBoundingClientRect(); if (maxWidth < box.width) { maxWidth = box.width; } }); dummy.remove(); }); } $$.currentMaxTickWidths[id] = maxWidth <= 0 ? $$.currentMaxTickWidths[id] : maxWidth; return $$.currentMaxTickWidths[id]; }; Axis.prototype.updateLabels = function updateLabels(withTransition) { var $$ = this.owner; var axisXLabel = $$.main.select('.' + CLASS.axisX + ' .' + CLASS.axisXLabel), axisYLabel = $$.main.select('.' + CLASS.axisY + ' .' + CLASS.axisYLabel), axisY2Label = $$.main.select('.' + CLASS.axisY2 + ' .' + CLASS.axisY2Label); (withTransition ? axisXLabel.transition() : axisXLabel) .attr("x", this.xForXAxisLabel.bind(this)) .attr("dx", this.dxForXAxisLabel.bind(this)) .attr("dy", this.dyForXAxisLabel.bind(this)) .text(this.textForXAxisLabel.bind(this)); (withTransition ? axisYLabel.transition() : axisYLabel) .attr("x", this.xForYAxisLabel.bind(this)) .attr("dx", this.dxForYAxisLabel.bind(this)) .attr("dy", this.dyForYAxisLabel.bind(this)) .text(this.textForYAxisLabel.bind(this)); (withTransition ? axisY2Label.transition() : axisY2Label) .attr("x", this.xForY2AxisLabel.bind(this)) .attr("dx", this.dxForY2AxisLabel.bind(this)) .attr("dy", this.dyForY2AxisLabel.bind(this)) .text(this.textForY2AxisLabel.bind(this)); }; Axis.prototype.getPadding = function getPadding(padding, key, defaultValue, domainLength) { var p = typeof padding === 'number' ? padding : padding[key]; if (!isValue(p)) { return defaultValue; } if (padding.unit === 'ratio') { return padding[key] * domainLength; } // assume padding is pixels if unit is not specified return this.convertPixelsToAxisPadding(p, domainLength); }; Axis.prototype.convertPixelsToAxisPadding = function convertPixelsToAxisPadding(pixels, domainLength) { var $$ = this.owner, length = $$.config.axis_rotated ? $$.width : $$.height; return domainLength * (pixels / length); }; Axis.prototype.generateTickValues = function generateTickValues(values, tickCount, forTimeSeries) { var tickValues = values, targetCount, start, end, count, interval, i, tickValue; if (tickCount) { targetCount = isFunction(tickCount) ? tickCount() : tickCount; // compute ticks according to tickCount if (targetCount === 1) { tickValues = [values[0]]; } else if (targetCount === 2) { tickValues = [values[0], values[values.length - 1]]; } else if (targetCount > 2) { count = targetCount - 2; start = values[0]; end = values[values.length - 1]; interval = (end - start) / (count + 1); // re-construct unique values tickValues = [start]; for (i = 0; i < count; i++) { tickValue = +start + interval * (i + 1); tickValues.push(forTimeSeries ? new Date(tickValue) : tickValue); } tickValues.push(end); } } if (!forTimeSeries) { tickValues = tickValues.sort(function (a, b) { return a - b; }); } return tickValues; }; Axis.prototype.generateTransitions = function generateTransitions(duration) { var $$ = this.owner, axes = $$.axes; return { axisX: duration ? axes.x.transition().duration(duration) : axes.x, axisY: duration ? axes.y.transition().duration(duration) : axes.y, axisY2: duration ? axes.y2.transition().duration(duration) : axes.y2, axisSubX: duration ? axes.subx.transition().duration(duration) : axes.subx }; }; Axis.prototype.redraw = function redraw(transitions, isHidden) { var $$ = this.owner; $$.axes.x.style("opacity", isHidden ? 0 : 1); $$.axes.y.style("opacity", isHidden ? 0 : 1); $$.axes.y2.style("opacity", isHidden ? 0 : 1); $$.axes.subx.style("opacity", isHidden ? 0 : 1); transitions.axisX.call($$.xAxis); transitions.axisY.call($$.yAxis); transitions.axisY2.call($$.y2Axis); transitions.axisSubX.call($$.subXAxis); }; c3_chart_internal_fn.getClipPath = function (id) { var isIE9 = window.navigator.appVersion.toLowerCase().indexOf("msie 9.") >= 0; return "url(" + (isIE9 ? "" : document.URL.split('#')[0]) + "#" + id + ")"; }; c3_chart_internal_fn.appendClip = function (parent, id) { return parent.append("clipPath").attr("id", id).append("rect"); }; c3_chart_internal_fn.getAxisClipX = function (forHorizontal) { // axis line width + padding for left var left = Math.max(30, this.margin.left); return forHorizontal ? -(1 + left) : -(left - 1); }; c3_chart_internal_fn.getAxisClipY = function (forHorizontal) { return forHorizontal ? -20 : -this.margin.top; }; c3_chart_internal_fn.getXAxisClipX = function () { var $$ = this; return $$.getAxisClipX(!$$.config.axis_rotated); }; c3_chart_internal_fn.getXAxisClipY = function () { var $$ = this; return $$.getAxisClipY(!$$.config.axis_rotated); }; c3_chart_internal_fn.getYAxisClipX = function () { var $$ = this; return $$.config.axis_y_inner ? -1 : $$.getAxisClipX($$.config.axis_rotated); }; c3_chart_internal_fn.getYAxisClipY = function () { var $$ = this; return $$.getAxisClipY($$.config.axis_rotated); }; c3_chart_internal_fn.getAxisClipWidth = function (forHorizontal) { var $$ = this, left = Math.max(30, $$.margin.left), right = Math.max(30, $$.margin.right); // width + axis line width + padding for left/right return forHorizontal ? $$.width + 2 + left + right : $$.margin.left + 20; }; c3_chart_internal_fn.getAxisClipHeight = function (forHorizontal) { // less than 20 is not enough to show the axis label 'outer' without legend return (forHorizontal ? this.margin.bottom : (this.margin.top + this.height)) + 20; }; c3_chart_internal_fn.getXAxisClipWidth = function () { var $$ = this; return $$.getAxisClipWidth(!$$.config.axis_rotated); }; c3_chart_internal_fn.getXAxisClipHeight = function () { var $$ = this; return $$.getAxisClipHeight(!$$.config.axis_rotated); }; c3_chart_internal_fn.getYAxisClipWidth = function () { var $$ = this; return $$.getAxisClipWidth($$.config.axis_rotated) + ($$.config.axis_y_inner ? 20 : 0); }; c3_chart_internal_fn.getYAxisClipHeight = function () { var $$ = this; return $$.getAxisClipHeight($$.config.axis_rotated); }; c3_chart_internal_fn.initPie = function () { var $$ = this, d3 = $$.d3, config = $$.config; $$.pie = d3.layout.pie().value(function (d) { return d.values.reduce(function (a, b) { return a + b.value; }, 0); }); if (!config.data_order) { $$.pie.sort(null); } }; c3_chart_internal_fn.updateRadius = function () { var $$ = this, config = $$.config, w = config.gauge_width || config.donut_width; $$.radiusExpanded = Math.min($$.arcWidth, $$.arcHeight) / 2; $$.radius = $$.radiusExpanded * 0.95; $$.innerRadiusRatio = w ? ($$.radius - w) / $$.radius : 0.6; $$.innerRadius = $$.hasType('donut') || $$.hasType('gauge') ? $$.radius * $$.innerRadiusRatio : 0; }; c3_chart_internal_fn.updateArc = function () { var $$ = this; $$.svgArc = $$.getSvgArc(); $$.svgArcExpanded = $$.getSvgArcExpanded(); $$.svgArcExpandedSub = $$.getSvgArcExpanded(0.98); }; c3_chart_internal_fn.updateAngle = function (d) { var $$ = this, config = $$.config, found = false, index = 0, gMin, gMax, gTic, gValue; if (!config) { return null; } $$.pie($$.filterTargetsToShow($$.data.targets)).forEach(function (t) { if (! found && t.data.id === d.data.id) { found = true; d = t; d.index = index; } index++; }); if (isNaN(d.startAngle)) { d.startAngle = 0; } if (isNaN(d.endAngle)) { d.endAngle = d.startAngle; } if ($$.isGaugeType(d.data)) { gMin = config.gauge_min; gMax = config.gauge_max; gTic = (Math.PI * (config.gauge_fullCircle ? 2 : 1)) / (gMax - gMin); gValue = d.value < gMin ? 0 : d.value < gMax ? d.value - gMin : (gMax - gMin); d.startAngle = config.gauge_startingAngle; d.endAngle = d.startAngle + gTic * gValue; } return found ? d : null; }; c3_chart_internal_fn.getSvgArc = function () { var $$ = this, arc = $$.d3.svg.arc().outerRadius($$.radius).innerRadius($$.innerRadius), newArc = function (d, withoutUpdate) { var updated; if (withoutUpdate) { return arc(d); } // for interpolate updated = $$.updateAngle(d); return updated ? arc(updated) : "M 0 0"; }; // TODO: extends all function newArc.centroid = arc.centroid; return newArc; }; c3_chart_internal_fn.getSvgArcExpanded = function (rate) { var $$ = this, arc = $$.d3.svg.arc().outerRadius($$.radiusExpanded * (rate ? rate : 1)).innerRadius($$.innerRadius); return function (d) { var updated = $$.updateAngle(d); return updated ? arc(updated) : "M 0 0"; }; }; c3_chart_internal_fn.getArc = function (d, withoutUpdate, force) { return force || this.isArcType(d.data) ? this.svgArc(d, withoutUpdate) : "M 0 0"; }; c3_chart_internal_fn.transformForArcLabel = function (d) { var $$ = this, config = $$.config, updated = $$.updateAngle(d), c, x, y, h, ratio, translate = ""; if (updated && !$$.hasType('gauge')) { c = this.svgArc.centroid(updated); x = isNaN(c[0]) ? 0 : c[0]; y = isNaN(c[1]) ? 0 : c[1]; h = Math.sqrt(x * x + y * y); if ($$.hasType('donut') && config.donut_label_ratio) { ratio = isFunction(config.donut_label_ratio) ? config.donut_label_ratio(d, $$.radius, h) : config.donut_label_ratio; } else if ($$.hasType('pie') && config.pie_label_ratio) { ratio = isFunction(config.pie_label_ratio) ? config.pie_label_ratio(d, $$.radius, h) : config.pie_label_ratio; } else { ratio = $$.radius && h ? (36 / $$.radius > 0.375 ? 1.175 - 36 / $$.radius : 0.8) * $$.radius / h : 0; } translate = "translate(" + (x * ratio) + ',' + (y * ratio) + ")"; } return translate; }; c3_chart_internal_fn.getArcRatio = function (d) { var $$ = this, config = $$.config, whole = Math.PI * ($$.hasType('gauge') && !config.gauge_fullCircle ? 1 : 2); return d ? (d.endAngle - d.startAngle) / whole : null; }; c3_chart_internal_fn.convertToArcData = function (d) { return this.addName({ id: d.data.id, value: d.value, ratio: this.getArcRatio(d), index: d.index }); }; c3_chart_internal_fn.textForArcLabel = function (d) { var $$ = this, updated, value, ratio, id, format; if (! $$.shouldShowArcLabel()) { return ""; } updated = $$.updateAngle(d); value = updated ? updated.value : null; ratio = $$.getArcRatio(updated); id = d.data.id; if (! $$.hasType('gauge') && ! $$.meetsArcLabelThreshold(ratio)) { return ""; } format = $$.getArcLabelFormat(); return format ? format(value, ratio, id) : $$.defaultArcValueFormat(value, ratio); }; c3_chart_internal_fn.expandArc = function (targetIds) { var $$ = this, interval; // MEMO: avoid to cancel transition if ($$.transiting) { interval = window.setInterval(function () { if (!$$.transiting) { window.clearInterval(interval); if ($$.legend.selectAll('.c3-legend-item-focused').size() > 0) { $$.expandArc(targetIds); } } }, 10); return; } targetIds = $$.mapToTargetIds(targetIds); $$.svg.selectAll($$.selectorTargets(targetIds, '.' + CLASS.chartArc)).each(function (d) { if (! $$.shouldExpand(d.data.id)) { return; } $$.d3.select(this).selectAll('path') .transition().duration($$.expandDuration(d.data.id)) .attr("d", $$.svgArcExpanded) .transition().duration($$.expandDuration(d.data.id) * 2) .attr("d", $$.svgArcExpandedSub) .each(function (d) { if ($$.isDonutType(d.data)) { // callback here } }); }); }; c3_chart_internal_fn.unexpandArc = function (targetIds) { var $$ = this; if ($$.transiting) { return; } targetIds = $$.mapToTargetIds(targetIds); $$.svg.selectAll($$.selectorTargets(targetIds, '.' + CLASS.chartArc)).selectAll('path') .transition().duration(function(d) { return $$.expandDuration(d.data.id); }) .attr("d", $$.svgArc); $$.svg.selectAll('.' + CLASS.arc) .style("opacity", 1); }; c3_chart_internal_fn.expandDuration = function (id) { var $$ = this, config = $$.config; if ($$.isDonutType(id)) { return config.donut_expand_duration; } else if ($$.isGaugeType(id)) { return config.gauge_expand_duration; } else if ($$.isPieType(id)) { return config.pie_expand_duration; } else { return 50; } }; c3_chart_internal_fn.shouldExpand = function (id) { var $$ = this, config = $$.config; return ($$.isDonutType(id) && config.donut_expand) || ($$.isGaugeType(id) && config.gauge_expand) || ($$.isPieType(id) && config.pie_expand); }; c3_chart_internal_fn.shouldShowArcLabel = function () { var $$ = this, config = $$.config, shouldShow = true; if ($$.hasType('donut')) { shouldShow = config.donut_label_show; } else if ($$.hasType('pie')) { shouldShow = config.pie_label_show; } // when gauge, always true return shouldShow; }; c3_chart_internal_fn.meetsArcLabelThreshold = function (ratio) { var $$ = this, config = $$.config, threshold = $$.hasType('donut') ? config.donut_label_threshold : config.pie_label_threshold; return ratio >= threshold; }; c3_chart_internal_fn.getArcLabelFormat = function () { var $$ = this, config = $$.config, format = config.pie_label_format; if ($$.hasType('gauge')) { format = config.gauge_label_format; } else if ($$.hasType('donut')) { format = config.donut_label_format; } return format; }; c3_chart_internal_fn.getArcTitle = function () { var $$ = this; return $$.hasType('donut') ? $$.config.donut_title : ""; }; c3_chart_internal_fn.updateTargetsForArc = function (targets) { var $$ = this, main = $$.main, mainPieUpdate, mainPieEnter, classChartArc = $$.classChartArc.bind($$), classArcs = $$.classArcs.bind($$), classFocus = $$.classFocus.bind($$); mainPieUpdate = main.select('.' + CLASS.chartArcs).selectAll('.' + CLASS.chartArc) .data($$.pie(targets)) .attr("class", function (d) { return classChartArc(d) + classFocus(d.data); }); mainPieEnter = mainPieUpdate.enter().append("g") .attr("class", classChartArc); mainPieEnter.append('g') .attr('class', classArcs); mainPieEnter.append("text") .attr("dy", $$.hasType('gauge') ? "-.1em" : ".35em") .style("opacity", 0) .style("text-anchor", "middle") .style("pointer-events", "none"); // MEMO: can not keep same color..., but not bad to update color in redraw //mainPieUpdate.exit().remove(); }; c3_chart_internal_fn.initArc = function () { var $$ = this; $$.arcs = $$.main.select('.' + CLASS.chart).append("g") .attr("class", CLASS.chartArcs) .attr("transform", $$.getTranslate('arc')); $$.arcs.append('text') .attr('class', CLASS.chartArcsTitle) .style("text-anchor", "middle") .text($$.getArcTitle()); }; c3_chart_internal_fn.redrawArc = function (duration, durationForExit, withTransform) { var $$ = this, d3 = $$.d3, config = $$.config, main = $$.main, mainArc; mainArc = main.selectAll('.' + CLASS.arcs).selectAll('.' + CLASS.arc) .data($$.arcData.bind($$)); mainArc.enter().append('path') .attr("class", $$.classArc.bind($$)) .style("fill", function (d) { return $$.color(d.data); }) .style("cursor", function (d) { return config.interaction_enabled && config.data_selection_isselectable(d) ? "pointer" : null; }) .style("opacity", 0) .each(function (d) { if ($$.isGaugeType(d.data)) { d.startAngle = d.endAngle = config.gauge_startingAngle; } this._current = d; }); mainArc .attr("transform", function (d) { return !$$.isGaugeType(d.data) && withTransform ? "scale(0)" : ""; }) .style("opacity", function (d) { return d === this._current ? 0 : 1; }) .on('mouseover', config.interaction_enabled ? function (d) { var updated, arcData; if ($$.transiting) { // skip while transiting return; } updated = $$.updateAngle(d); if (updated) { arcData = $$.convertToArcData(updated); // transitions $$.expandArc(updated.data.id); $$.api.focus(updated.data.id); $$.toggleFocusLegend(updated.data.id, true); $$.config.data_onmouseover(arcData, this); } } : null) .on('mousemove', config.interaction_enabled ? function (d) { var updated = $$.updateAngle(d), arcData, selectedData; if (updated) { arcData = $$.convertToArcData(updated), selectedData = [arcData]; $$.showTooltip(selectedData, this); } } : null) .on('mouseout', config.interaction_enabled ? function (d) { var updated, arcData; if ($$.transiting) { // skip while transiting return; } updated = $$.updateAngle(d); if (updated) { arcData = $$.convertToArcData(updated); // transitions $$.unexpandArc(updated.data.id); $$.api.revert(); $$.revertLegend(); $$.hideTooltip(); $$.config.data_onmouseout(arcData, this); } } : null) .on('click', config.interaction_enabled ? function (d, i) { var updated = $$.updateAngle(d), arcData; if (updated) { arcData = $$.convertToArcData(updated); if ($$.toggleShape) { $$.toggleShape(this, arcData, i); } $$.config.data_onclick.call($$.api, arcData, this); } } : null) .each(function () { $$.transiting = true; }) .transition().duration(duration) .attrTween("d", function (d) { var updated = $$.updateAngle(d), interpolate; if (! updated) { return function () { return "M 0 0"; }; } // if (this._current === d) { // this._current = { // startAngle: Math.PI*2, // endAngle: Math.PI*2, // }; // } if (isNaN(this._current.startAngle)) { this._current.startAngle = 0; } if (isNaN(this._current.endAngle)) { this._current.endAngle = this._current.startAngle; } interpolate = d3.interpolate(this._current, updated); this._current = interpolate(0); return function (t) { var interpolated = interpolate(t); interpolated.data = d.data; // data.id will be updated by interporator return $$.getArc(interpolated, true); }; }) .attr("transform", withTransform ? "scale(1)" : "") .style("fill", function (d) { return $$.levelColor ? $$.levelColor(d.data.values[0].value) : $$.color(d.data.id); }) // Where gauge reading color would receive customization. .style("opacity", 1) .call($$.endall, function () { $$.transiting = false; }); mainArc.exit().transition().duration(durationForExit) .style('opacity', 0) .remove(); main.selectAll('.' + CLASS.chartArc).select('text') .style("opacity", 0) .attr('class', function (d) { return $$.isGaugeType(d.data) ? CLASS.gaugeValue : ''; }) .text($$.textForArcLabel.bind($$)) .attr("transform", $$.transformForArcLabel.bind($$)) .style('font-size', function (d) { return $$.isGaugeType(d.data) ? Math.round($$.radius / 5) + 'px' : ''; }) .transition().duration(duration) .style("opacity", function (d) { return $$.isTargetToShow(d.data.id) && $$.isArcType(d.data) ? 1 : 0; }); main.select('.' + CLASS.chartArcsTitle) .style("opacity", $$.hasType('donut') || $$.hasType('gauge') ? 1 : 0); if ($$.hasType('gauge')) { $$.arcs.select('.' + CLASS.chartArcsBackground) .attr("d", function () { var d = { data: [{value: config.gauge_max}], startAngle: config.gauge_startingAngle, endAngle: -1 * config.gauge_startingAngle }; return $$.getArc(d, true, true); }); $$.arcs.select('.' + CLASS.chartArcsGaugeUnit) .attr("dy", ".75em") .text(config.gauge_label_show ? config.gauge_units : ''); $$.arcs.select('.' + CLASS.chartArcsGaugeMin) .attr("dx", -1 * ($$.innerRadius + (($$.radius - $$.innerRadius) / (config.gauge_fullCircle ? 1 : 2))) + "px") .attr("dy", "1.2em") .text(config.gauge_label_show ? config.gauge_min : ''); $$.arcs.select('.' + CLASS.chartArcsGaugeMax) .attr("dx", $$.innerRadius + (($$.radius - $$.innerRadius) / (config.gauge_fullCircle ? 1 : 2)) + "px") .attr("dy", "1.2em") .text(config.gauge_label_show ? config.gauge_max : ''); } }; c3_chart_internal_fn.initGauge = function () { var arcs = this.arcs; if (this.hasType('gauge')) { arcs.append('path') .attr("class", CLASS.chartArcsBackground); arcs.append("text") .attr("class", CLASS.chartArcsGaugeUnit) .style("text-anchor", "middle") .style("pointer-events", "none"); arcs.append("text") .attr("class", CLASS.chartArcsGaugeMin) .style("text-anchor", "middle") .style("pointer-events", "none"); arcs.append("text") .attr("class", CLASS.chartArcsGaugeMax) .style("text-anchor", "middle") .style("pointer-events", "none"); } }; c3_chart_internal_fn.getGaugeLabelHeight = function () { return this.config.gauge_label_show ? 20 : 0; }; c3_chart_internal_fn.initRegion = function () { var $$ = this; $$.region = $$.main.append('g') .attr("clip-path", $$.clipPath) .attr("class", CLASS.regions); }; c3_chart_internal_fn.updateRegion = function (duration) { var $$ = this, config = $$.config; // hide if arc type $$.region.style('visibility', $$.hasArcType() ? 'hidden' : 'visible'); $$.mainRegion = $$.main.select('.' + CLASS.regions).selectAll('.' + CLASS.region) .data(config.regions); $$.mainRegion.enter().append('g') .append('rect') .style("fill-opacity", 0); $$.mainRegion .attr('class', $$.classRegion.bind($$)); $$.mainRegion.exit().transition().duration(duration) .style("opacity", 0) .remove(); }; c3_chart_internal_fn.redrawRegion = function (withTransition) { var $$ = this, regions = $$.mainRegion.selectAll('rect').each(function () { // data is binded to g and it's not transferred to rect (child node) automatically, // then data of each rect has to be updated manually. // TODO: there should be more efficient way to solve this? var parentData = $$.d3.select(this.parentNode).datum(); $$.d3.select(this).datum(parentData); }), x = $$.regionX.bind($$), y = $$.regionY.bind($$), w = $$.regionWidth.bind($$), h = $$.regionHeight.bind($$); return [ (withTransition ? regions.transition() : regions) .attr("x", x) .attr("y", y) .attr("width", w) .attr("height", h) .style("fill-opacity", function (d) { return isValue(d.opacity) ? d.opacity : 0.1; }) ]; }; c3_chart_internal_fn.regionX = function (d) { var $$ = this, config = $$.config, xPos, yScale = d.axis === 'y' ? $$.y : $$.y2; if (d.axis === 'y' || d.axis === 'y2') { xPos = config.axis_rotated ? ('start' in d ? yScale(d.start) : 0) : 0; } else { xPos = config.axis_rotated ? 0 : ('start' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.start) : d.start) : 0); } return xPos; }; c3_chart_internal_fn.regionY = function (d) { var $$ = this, config = $$.config, yPos, yScale = d.axis === 'y' ? $$.y : $$.y2; if (d.axis === 'y' || d.axis === 'y2') { yPos = config.axis_rotated ? 0 : ('end' in d ? yScale(d.end) : 0); } else { yPos = config.axis_rotated ? ('start' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.start) : d.start) : 0) : 0; } return yPos; }; c3_chart_internal_fn.regionWidth = function (d) { var $$ = this, config = $$.config, start = $$.regionX(d), end, yScale = d.axis === 'y' ? $$.y : $$.y2; if (d.axis === 'y' || d.axis === 'y2') { end = config.axis_rotated ? ('end' in d ? yScale(d.end) : $$.width) : $$.width; } else { end = config.axis_rotated ? $$.width : ('end' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.end) : d.end) : $$.width); } return end < start ? 0 : end - start; }; c3_chart_internal_fn.regionHeight = function (d) { var $$ = this, config = $$.config, start = this.regionY(d), end, yScale = d.axis === 'y' ? $$.y : $$.y2; if (d.axis === 'y' || d.axis === 'y2') { end = config.axis_rotated ? $$.height : ('start' in d ? yScale(d.start) : $$.height); } else { end = config.axis_rotated ? ('end' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.end) : d.end) : $$.height) : $$.height; } return end < start ? 0 : end - start; }; c3_chart_internal_fn.isRegionOnX = function (d) { return !d.axis || d.axis === 'x'; }; c3_chart_internal_fn.drag = function (mouse) { var $$ = this, config = $$.config, main = $$.main, d3 = $$.d3; var sx, sy, mx, my, minX, maxX, minY, maxY; if ($$.hasArcType()) { return; } if (! config.data_selection_enabled) { return; } // do nothing if not selectable if (config.zoom_enabled && ! $$.zoom.altDomain) { return; } // skip if zoomable because of conflict drag dehavior if (!config.data_selection_multiple) { return; } // skip when single selection because drag is used for multiple selection sx = $$.dragStart[0]; sy = $$.dragStart[1]; mx = mouse[0]; my = mouse[1]; minX = Math.min(sx, mx); maxX = Math.max(sx, mx); minY = (config.data_selection_grouped) ? $$.margin.top : Math.min(sy, my); maxY = (config.data_selection_grouped) ? $$.height : Math.max(sy, my); main.select('.' + CLASS.dragarea) .attr('x', minX) .attr('y', minY) .attr('width', maxX - minX) .attr('height', maxY - minY); // TODO: binary search when multiple xs main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape) .filter(function (d) { return config.data_selection_isselectable(d); }) .each(function (d, i) { var shape = d3.select(this), isSelected = shape.classed(CLASS.SELECTED), isIncluded = shape.classed(CLASS.INCLUDED), _x, _y, _w, _h, toggle, isWithin = false, box; if (shape.classed(CLASS.circle)) { _x = shape.attr("cx") * 1; _y = shape.attr("cy") * 1; toggle = $$.togglePoint; isWithin = minX < _x && _x < maxX && minY < _y && _y < maxY; } else if (shape.classed(CLASS.bar)) { box = getPathBox(this); _x = box.x; _y = box.y; _w = box.width; _h = box.height; toggle = $$.togglePath; isWithin = !(maxX < _x || _x + _w < minX) && !(maxY < _y || _y + _h < minY); } else { // line/area selection not supported yet return; } if (isWithin ^ isIncluded) { shape.classed(CLASS.INCLUDED, !isIncluded); // TODO: included/unincluded callback here shape.classed(CLASS.SELECTED, !isSelected); toggle.call($$, !isSelected, shape, d, i); } }); }; c3_chart_internal_fn.dragstart = function (mouse) { var $$ = this, config = $$.config; if ($$.hasArcType()) { return; } if (! config.data_selection_enabled) { return; } // do nothing if not selectable $$.dragStart = mouse; $$.main.select('.' + CLASS.chart).append('rect') .attr('class', CLASS.dragarea) .style('opacity', 0.1); $$.dragging = true; }; c3_chart_internal_fn.dragend = function () { var $$ = this, config = $$.config; if ($$.hasArcType()) { return; } if (! config.data_selection_enabled) { return; } // do nothing if not selectable $$.main.select('.' + CLASS.dragarea) .transition().duration(100) .style('opacity', 0) .remove(); $$.main.selectAll('.' + CLASS.shape) .classed(CLASS.INCLUDED, false); $$.dragging = false; }; c3_chart_internal_fn.selectPoint = function (target, d, i) { var $$ = this, config = $$.config, cx = (config.axis_rotated ? $$.circleY : $$.circleX).bind($$), cy = (config.axis_rotated ? $$.circleX : $$.circleY).bind($$), r = $$.pointSelectR.bind($$); config.data_onselected.call($$.api, d, target.node()); // add selected-circle on low layer g $$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i) .data([d]) .enter().append('circle') .attr("class", function () { return $$.generateClass(CLASS.selectedCircle, i); }) .attr("cx", cx) .attr("cy", cy) .attr("stroke", function () { return $$.color(d); }) .attr("r", function (d) { return $$.pointSelectR(d) * 1.4; }) .transition().duration(100) .attr("r", r); }; c3_chart_internal_fn.unselectPoint = function (target, d, i) { var $$ = this; $$.config.data_onunselected.call($$.api, d, target.node()); // remove selected-circle from low layer g $$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i) .transition().duration(100).attr('r', 0) .remove(); }; c3_chart_internal_fn.togglePoint = function (selected, target, d, i) { selected ? this.selectPoint(target, d, i) : this.unselectPoint(target, d, i); }; c3_chart_internal_fn.selectPath = function (target, d) { var $$ = this; $$.config.data_onselected.call($$, d, target.node()); if ($$.config.interaction_brighten) { target.transition().duration(100) .style("fill", function () { return $$.d3.rgb($$.color(d)).brighter(0.75); }); } }; c3_chart_internal_fn.unselectPath = function (target, d) { var $$ = this; $$.config.data_onunselected.call($$, d, target.node()); if ($$.config.interaction_brighten) { target.transition().duration(100) .style("fill", function () { return $$.color(d); }); } }; c3_chart_internal_fn.togglePath = function (selected, target, d, i) { selected ? this.selectPath(target, d, i) : this.unselectPath(target, d, i); }; c3_chart_internal_fn.getToggle = function (that, d) { var $$ = this, toggle; if (that.nodeName === 'circle') { if ($$.isStepType(d)) { // circle is hidden in step chart, so treat as within the click area toggle = function () {}; // TODO: how to select step chart? } else { toggle = $$.togglePoint; } } else if (that.nodeName === 'path') { toggle = $$.togglePath; } return toggle; }; c3_chart_internal_fn.toggleShape = function (that, d, i) { var $$ = this, d3 = $$.d3, config = $$.config, shape = d3.select(that), isSelected = shape.classed(CLASS.SELECTED), toggle = $$.getToggle(that, d).bind($$); if (config.data_selection_enabled && config.data_selection_isselectable(d)) { if (!config.data_selection_multiple) { $$.main.selectAll('.' + CLASS.shapes + (config.data_selection_grouped ? $$.getTargetSelectorSuffix(d.id) : "")).selectAll('.' + CLASS.shape).each(function (d, i) { var shape = d3.select(this); if (shape.classed(CLASS.SELECTED)) { toggle(false, shape.classed(CLASS.SELECTED, false), d, i); } }); } shape.classed(CLASS.SELECTED, !isSelected); toggle(!isSelected, shape, d, i); } }; c3_chart_internal_fn.initBrush = function () { var $$ = this, d3 = $$.d3; $$.brush = d3.svg.brush().on("brush", function () { $$.redrawForBrush(); }); $$.brush.update = function () { if ($$.context) { $$.context.select('.' + CLASS.brush).call(this); } return this; }; $$.brush.scale = function (scale) { return $$.config.axis_rotated ? this.y(scale) : this.x(scale); }; }; c3_chart_internal_fn.initSubchart = function () { var $$ = this, config = $$.config, context = $$.context = $$.svg.append("g").attr("transform", $$.getTranslate('context')), visibility = config.subchart_show ? 'visible' : 'hidden'; context.style('visibility', visibility); // Define g for chart area context.append('g') .attr("clip-path", $$.clipPathForSubchart) .attr('class', CLASS.chart); // Define g for bar chart area context.select('.' + CLASS.chart).append("g") .attr("class", CLASS.chartBars); // Define g for line chart area context.select('.' + CLASS.chart).append("g") .attr("class", CLASS.chartLines); // Add extent rect for Brush context.append("g") .attr("clip-path", $$.clipPath) .attr("class", CLASS.brush) .call($$.brush); // ATTENTION: This must be called AFTER chart added // Add Axis $$.axes.subx = context.append("g") .attr("class", CLASS.axisX) .attr("transform", $$.getTranslate('subx')) .attr("clip-path", config.axis_rotated ? "" : $$.clipPathForXAxis) .style("visibility", config.subchart_axis_x_show ? visibility : 'hidden'); }; c3_chart_internal_fn.updateTargetsForSubchart = function (targets) { var $$ = this, context = $$.context, config = $$.config, contextLineEnter, contextLineUpdate, contextBarEnter, contextBarUpdate, classChartBar = $$.classChartBar.bind($$), classBars = $$.classBars.bind($$), classChartLine = $$.classChartLine.bind($$), classLines = $$.classLines.bind($$), classAreas = $$.classAreas.bind($$); if (config.subchart_show) { //-- Bar --// contextBarUpdate = context.select('.' + CLASS.chartBars).selectAll('.' + CLASS.chartBar) .data(targets) .attr('class', classChartBar); contextBarEnter = contextBarUpdate.enter().append('g') .style('opacity', 0) .attr('class', classChartBar); // Bars for each data contextBarEnter.append('g') .attr("class", classBars); //-- Line --// contextLineUpdate = context.select('.' + CLASS.chartLines).selectAll('.' + CLASS.chartLine) .data(targets) .attr('class', classChartLine); contextLineEnter = contextLineUpdate.enter().append('g') .style('opacity', 0) .attr('class', classChartLine); // Lines for each data contextLineEnter.append("g") .attr("class", classLines); // Area contextLineEnter.append("g") .attr("class", classAreas); //-- Brush --// context.selectAll('.' + CLASS.brush + ' rect') .attr(config.axis_rotated ? "width" : "height", config.axis_rotated ? $$.width2 : $$.height2); } }; c3_chart_internal_fn.updateBarForSubchart = function (durationForExit) { var $$ = this; $$.contextBar = $$.context.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar) .data($$.barData.bind($$)); $$.contextBar.enter().append('path') .attr("class", $$.classBar.bind($$)) .style("stroke", 'none') .style("fill", $$.color); $$.contextBar .style("opacity", $$.initialOpacity.bind($$)); $$.contextBar.exit().transition().duration(durationForExit) .style('opacity', 0) .remove(); }; c3_chart_internal_fn.redrawBarForSubchart = function (drawBarOnSub, withTransition, duration) { (withTransition ? this.contextBar.transition(Math.random().toString()).duration(duration) : this.contextBar) .attr('d', drawBarOnSub) .style('opacity', 1); }; c3_chart_internal_fn.updateLineForSubchart = function (durationForExit) { var $$ = this; $$.contextLine = $$.context.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line) .data($$.lineData.bind($$)); $$.contextLine.enter().append('path') .attr('class', $$.classLine.bind($$)) .style('stroke', $$.color); $$.contextLine .style("opacity", $$.initialOpacity.bind($$)); $$.contextLine.exit().transition().duration(durationForExit) .style('opacity', 0) .remove(); }; c3_chart_internal_fn.redrawLineForSubchart = function (drawLineOnSub, withTransition, duration) { (withTransition ? this.contextLine.transition(Math.random().toString()).duration(duration) : this.contextLine) .attr("d", drawLineOnSub) .style('opacity', 1); }; c3_chart_internal_fn.updateAreaForSubchart = function (durationForExit) { var $$ = this, d3 = $$.d3; $$.contextArea = $$.context.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area) .data($$.lineData.bind($$)); $$.contextArea.enter().append('path') .attr("class", $$.classArea.bind($$)) .style("fill", $$.color) .style("opacity", function () { $$.orgAreaOpacity = +d3.select(this).style('opacity'); return 0; }); $$.contextArea .style("opacity", 0); $$.contextArea.exit().transition().duration(durationForExit) .style('opacity', 0) .remove(); }; c3_chart_internal_fn.redrawAreaForSubchart = function (drawAreaOnSub, withTransition, duration) { (withTransition ? this.contextArea.transition(Math.random().toString()).duration(duration) : this.contextArea) .attr("d", drawAreaOnSub) .style("fill", this.color) .style("opacity", this.orgAreaOpacity); }; c3_chart_internal_fn.redrawSubchart = function (withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices) { var $$ = this, d3 = $$.d3, config = $$.config, drawAreaOnSub, drawBarOnSub, drawLineOnSub; $$.context.style('visibility', config.subchart_show ? 'visible' : 'hidden'); // subchart if (config.subchart_show) { // reflect main chart to extent on subchart if zoomed if (d3.event && d3.event.type === 'zoom') { $$.brush.extent($$.x.orgDomain()).update(); } // update subchart elements if needed if (withSubchart) { // extent rect if (!$$.brush.empty()) { $$.brush.extent($$.x.orgDomain()).update(); } // setup drawer - MEMO: this must be called after axis updated drawAreaOnSub = $$.generateDrawArea(areaIndices, true); drawBarOnSub = $$.generateDrawBar(barIndices, true); drawLineOnSub = $$.generateDrawLine(lineIndices, true); $$.updateBarForSubchart(duration); $$.updateLineForSubchart(duration); $$.updateAreaForSubchart(duration); $$.redrawBarForSubchart(drawBarOnSub, duration, duration); $$.redrawLineForSubchart(drawLineOnSub, duration, duration); $$.redrawAreaForSubchart(drawAreaOnSub, duration, duration); } } }; c3_chart_internal_fn.redrawForBrush = function () { var $$ = this, x = $$.x; $$.redraw({ withTransition: false, withY: $$.config.zoom_rescale, withSubchart: false, withUpdateXDomain: true, withDimension: false }); $$.config.subchart_onbrush.call($$.api, x.orgDomain()); }; c3_chart_internal_fn.transformContext = function (withTransition, transitions) { var $$ = this, subXAxis; if (transitions && transitions.axisSubX) { subXAxis = transitions.axisSubX; } else { subXAxis = $$.context.select('.' + CLASS.axisX); if (withTransition) { subXAxis = subXAxis.transition(); } } $$.context.attr("transform", $$.getTranslate('context')); subXAxis.attr("transform", $$.getTranslate('subx')); }; c3_chart_internal_fn.getDefaultExtent = function () { var $$ = this, config = $$.config, extent = isFunction(config.axis_x_extent) ? config.axis_x_extent($$.getXDomain($$.data.targets)) : config.axis_x_extent; if ($$.isTimeSeries()) { extent = [$$.parseDate(extent[0]), $$.parseDate(extent[1])]; } return extent; }; c3_chart_internal_fn.initZoom = function () { var $$ = this, d3 = $$.d3, config = $$.config, startEvent; $$.zoom = d3.behavior.zoom() .on("zoomstart", function () { startEvent = d3.event.sourceEvent; $$.zoom.altDomain = d3.event.sourceEvent.altKey ? $$.x.orgDomain() : null; config.zoom_onzoomstart.call($$.api, d3.event.sourceEvent); }) .on("zoom", function () { $$.redrawForZoom.call($$); }) .on('zoomend', function () { var event = d3.event.sourceEvent; // if click, do nothing. otherwise, click interaction will be canceled. if (event && startEvent.clientX === event.clientX && startEvent.clientY === event.clientY) { return; } $$.redrawEventRect(); $$.updateZoom(); config.zoom_onzoomend.call($$.api, $$.x.orgDomain()); }); $$.zoom.scale = function (scale) { return config.axis_rotated ? this.y(scale) : this.x(scale); }; $$.zoom.orgScaleExtent = function () { var extent = config.zoom_extent ? config.zoom_extent : [1, 10]; return [extent[0], Math.max($$.getMaxDataCount() / extent[1], extent[1])]; }; $$.zoom.updateScaleExtent = function () { var ratio = diffDomain($$.x.orgDomain()) / diffDomain($$.getZoomDomain()), extent = this.orgScaleExtent(); this.scaleExtent([extent[0] * ratio, extent[1] * ratio]); return this; }; }; c3_chart_internal_fn.getZoomDomain = function () { var $$ = this, config = $$.config, d3 = $$.d3, min = d3.min([$$.orgXDomain[0], config.zoom_x_min]), max = d3.max([$$.orgXDomain[1], config.zoom_x_max]); return [min, max]; }; c3_chart_internal_fn.updateZoom = function () { var $$ = this, z = $$.config.zoom_enabled ? $$.zoom : function () {}; $$.main.select('.' + CLASS.zoomRect).call(z).on("dblclick.zoom", null); $$.main.selectAll('.' + CLASS.eventRect).call(z).on("dblclick.zoom", null); }; c3_chart_internal_fn.redrawForZoom = function () { var $$ = this, d3 = $$.d3, config = $$.config, zoom = $$.zoom, x = $$.x; if (!config.zoom_enabled) { return; } if ($$.filterTargetsToShow($$.data.targets).length === 0) { return; } if (d3.event.sourceEvent.type === 'mousemove' && zoom.altDomain) { x.domain(zoom.altDomain); zoom.scale(x).updateScaleExtent(); return; } if ($$.isCategorized() && x.orgDomain()[0] === $$.orgXDomain[0]) { x.domain([$$.orgXDomain[0] - 1e-10, x.orgDomain()[1]]); } $$.redraw({ withTransition: false, withY: config.zoom_rescale, withSubchart: false, withEventRect: false, withDimension: false }); if (d3.event.sourceEvent.type === 'mousemove') { $$.cancelClick = true; } config.zoom_onzoom.call($$.api, x.orgDomain()); }; c3_chart_internal_fn.generateColor = function () { var $$ = this, config = $$.config, d3 = $$.d3, colors = config.data_colors, pattern = notEmpty(config.color_pattern) ? config.color_pattern : d3.scale.category10().range(), callback = config.data_color, ids = []; return function (d) { var id = d.id || (d.data && d.data.id) || d, color; // if callback function is provided if (colors[id] instanceof Function) { color = colors[id](d); } // if specified, choose that color else if (colors[id]) { color = colors[id]; } // if not specified, choose from pattern else { if (ids.indexOf(id) < 0) { ids.push(id); } color = pattern[ids.indexOf(id) % pattern.length]; colors[id] = color; } return callback instanceof Function ? callback(color, d) : color; }; }; c3_chart_internal_fn.generateLevelColor = function () { var $$ = this, config = $$.config, colors = config.color_pattern, threshold = config.color_threshold, asValue = threshold.unit === 'value', values = threshold.values && threshold.values.length ? threshold.values : [], max = threshold.max || 100; return notEmpty(config.color_threshold) ? function (value) { var i, v, color = colors[colors.length - 1]; for (i = 0; i < values.length; i++) { v = asValue ? value : (value * 100 / max); if (v < values[i]) { color = colors[i]; break; } } return color; } : null; }; c3_chart_internal_fn.getYFormat = function (forArc) { var $$ = this, formatForY = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.yFormat, formatForY2 = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.y2Format; return function (v, ratio, id) { var format = $$.axis.getId(id) === 'y2' ? formatForY2 : formatForY; return format.call($$, v, ratio); }; }; c3_chart_internal_fn.yFormat = function (v) { var $$ = this, config = $$.config, format = config.axis_y_tick_format ? config.axis_y_tick_format : $$.defaultValueFormat; return format(v); }; c3_chart_internal_fn.y2Format = function (v) { var $$ = this, config = $$.config, format = config.axis_y2_tick_format ? config.axis_y2_tick_format : $$.defaultValueFormat; return format(v); }; c3_chart_internal_fn.defaultValueFormat = function (v) { return isValue(v) ? +v : ""; }; c3_chart_internal_fn.defaultArcValueFormat = function (v, ratio) { return (ratio * 100).toFixed(1) + '%'; }; c3_chart_internal_fn.dataLabelFormat = function (targetId) { var $$ = this, data_labels = $$.config.data_labels, format, defaultFormat = function (v) { return isValue(v) ? +v : ""; }; // find format according to axis id if (typeof data_labels.format === 'function') { format = data_labels.format; } else if (typeof data_labels.format === 'object') { if (data_labels.format[targetId]) { format = data_labels.format[targetId] === true ? defaultFormat : data_labels.format[targetId]; } else { format = function () { return ''; }; } } else { format = defaultFormat; } return format; }; c3_chart_internal_fn.hasCaches = function (ids) { for (var i = 0; i < ids.length; i++) { if (! (ids[i] in this.cache)) { return false; } } return true; }; c3_chart_internal_fn.addCache = function (id, target) { this.cache[id] = this.cloneTarget(target); }; c3_chart_internal_fn.getCaches = function (ids) { var targets = [], i; for (i = 0; i < ids.length; i++) { if (ids[i] in this.cache) { targets.push(this.cloneTarget(this.cache[ids[i]])); } } return targets; }; var CLASS = c3_chart_internal_fn.CLASS = { target: 'c3-target', chart: 'c3-chart', chartLine: 'c3-chart-line', chartLines: 'c3-chart-lines', chartBar: 'c3-chart-bar', chartBars: 'c3-chart-bars', chartText: 'c3-chart-text', chartTexts: 'c3-chart-texts', chartArc: 'c3-chart-arc', chartArcs: 'c3-chart-arcs', chartArcsTitle: 'c3-chart-arcs-title', chartArcsBackground: 'c3-chart-arcs-background', chartArcsGaugeUnit: 'c3-chart-arcs-gauge-unit', chartArcsGaugeMax: 'c3-chart-arcs-gauge-max', chartArcsGaugeMin: 'c3-chart-arcs-gauge-min', selectedCircle: 'c3-selected-circle', selectedCircles: 'c3-selected-circles', eventRect: 'c3-event-rect', eventRects: 'c3-event-rects', eventRectsSingle: 'c3-event-rects-single', eventRectsMultiple: 'c3-event-rects-multiple', zoomRect: 'c3-zoom-rect', brush: 'c3-brush', focused: 'c3-focused', defocused: 'c3-defocused', region: 'c3-region', regions: 'c3-regions', title: 'c3-title', tooltipContainer: 'c3-tooltip-container', tooltip: 'c3-tooltip', tooltipName: 'c3-tooltip-name', shape: 'c3-shape', shapes: 'c3-shapes', line: 'c3-line', lines: 'c3-lines', bar: 'c3-bar', bars: 'c3-bars', circle: 'c3-circle', circles: 'c3-circles', arc: 'c3-arc', arcs: 'c3-arcs', area: 'c3-area', areas: 'c3-areas', empty: 'c3-empty', text: 'c3-text', texts: 'c3-texts', gaugeValue: 'c3-gauge-value', grid: 'c3-grid', gridLines: 'c3-grid-lines', xgrid: 'c3-xgrid', xgrids: 'c3-xgrids', xgridLine: 'c3-xgrid-line', xgridLines: 'c3-xgrid-lines', xgridFocus: 'c3-xgrid-focus', ygrid: 'c3-ygrid', ygrids: 'c3-ygrids', ygridLine: 'c3-ygrid-line', ygridLines: 'c3-ygrid-lines', axis: 'c3-axis', axisX: 'c3-axis-x', axisXLabel: 'c3-axis-x-label', axisY: 'c3-axis-y', axisYLabel: 'c3-axis-y-label', axisY2: 'c3-axis-y2', axisY2Label: 'c3-axis-y2-label', legendBackground: 'c3-legend-background', legendItem: 'c3-legend-item', legendItemEvent: 'c3-legend-item-event', legendItemTile: 'c3-legend-item-tile', legendItemHidden: 'c3-legend-item-hidden', legendItemFocused: 'c3-legend-item-focused', dragarea: 'c3-dragarea', EXPANDED: '_expanded_', SELECTED: '_selected_', INCLUDED: '_included_' }; c3_chart_internal_fn.generateClass = function (prefix, targetId) { return " " + prefix + " " + prefix + this.getTargetSelectorSuffix(targetId); }; c3_chart_internal_fn.classText = function (d) { return this.generateClass(CLASS.text, d.index); }; c3_chart_internal_fn.classTexts = function (d) { return this.generateClass(CLASS.texts, d.id); }; c3_chart_internal_fn.classShape = function (d) { return this.generateClass(CLASS.shape, d.index); }; c3_chart_internal_fn.classShapes = function (d) { return this.generateClass(CLASS.shapes, d.id); }; c3_chart_internal_fn.classLine = function (d) { return this.classShape(d) + this.generateClass(CLASS.line, d.id); }; c3_chart_internal_fn.classLines = function (d) { return this.classShapes(d) + this.generateClass(CLASS.lines, d.id); }; c3_chart_internal_fn.classCircle = function (d) { return this.classShape(d) + this.generateClass(CLASS.circle, d.index); }; c3_chart_internal_fn.classCircles = function (d) { return this.classShapes(d) + this.generateClass(CLASS.circles, d.id); }; c3_chart_internal_fn.classBar = function (d) { return this.classShape(d) + this.generateClass(CLASS.bar, d.index); }; c3_chart_internal_fn.classBars = function (d) { return this.classShapes(d) + this.generateClass(CLASS.bars, d.id); }; c3_chart_internal_fn.classArc = function (d) { return this.classShape(d.data) + this.generateClass(CLASS.arc, d.data.id); }; c3_chart_internal_fn.classArcs = function (d) { return this.classShapes(d.data) + this.generateClass(CLASS.arcs, d.data.id); }; c3_chart_internal_fn.classArea = function (d) { return this.classShape(d) + this.generateClass(CLASS.area, d.id); }; c3_chart_internal_fn.classAreas = function (d) { return this.classShapes(d) + this.generateClass(CLASS.areas, d.id); }; c3_chart_internal_fn.classRegion = function (d, i) { return this.generateClass(CLASS.region, i) + ' ' + ('class' in d ? d['class'] : ''); }; c3_chart_internal_fn.classEvent = function (d) { return this.generateClass(CLASS.eventRect, d.index); }; c3_chart_internal_fn.classTarget = function (id) { var $$ = this; var additionalClassSuffix = $$.config.data_classes[id], additionalClass = ''; if (additionalClassSuffix) { additionalClass = ' ' + CLASS.target + '-' + additionalClassSuffix; } return $$.generateClass(CLASS.target, id) + additionalClass; }; c3_chart_internal_fn.classFocus = function (d) { return this.classFocused(d) + this.classDefocused(d); }; c3_chart_internal_fn.classFocused = function (d) { return ' ' + (this.focusedTargetIds.indexOf(d.id) >= 0 ? CLASS.focused : ''); }; c3_chart_internal_fn.classDefocused = function (d) { return ' ' + (this.defocusedTargetIds.indexOf(d.id) >= 0 ? CLASS.defocused : ''); }; c3_chart_internal_fn.classChartText = function (d) { return CLASS.chartText + this.classTarget(d.id); }; c3_chart_internal_fn.classChartLine = function (d) { return CLASS.chartLine + this.classTarget(d.id); }; c3_chart_internal_fn.classChartBar = function (d) { return CLASS.chartBar + this.classTarget(d.id); }; c3_chart_internal_fn.classChartArc = function (d) { return CLASS.chartArc + this.classTarget(d.data.id); }; c3_chart_internal_fn.getTargetSelectorSuffix = function (targetId) { return targetId || targetId === 0 ? ('-' + targetId).replace(/[\s?!@#$%^&*()_=+,.<>'":;\[\]\/|~`{}\\]/g, '-') : ''; }; c3_chart_internal_fn.selectorTarget = function (id, prefix) { return (prefix || '') + '.' + CLASS.target + this.getTargetSelectorSuffix(id); }; c3_chart_internal_fn.selectorTargets = function (ids, prefix) { var $$ = this; ids = ids || []; return ids.length ? ids.map(function (id) { return $$.selectorTarget(id, prefix); }) : null; }; c3_chart_internal_fn.selectorLegend = function (id) { return '.' + CLASS.legendItem + this.getTargetSelectorSuffix(id); }; c3_chart_internal_fn.selectorLegends = function (ids) { var $$ = this; return ids && ids.length ? ids.map(function (id) { return $$.selectorLegend(id); }) : null; }; var isValue = c3_chart_internal_fn.isValue = function (v) { return v || v === 0; }, isFunction = c3_chart_internal_fn.isFunction = function (o) { return typeof o === 'function'; }, isString = c3_chart_internal_fn.isString = function (o) { return typeof o === 'string'; }, isUndefined = c3_chart_internal_fn.isUndefined = function (v) { return typeof v === 'undefined'; }, isDefined = c3_chart_internal_fn.isDefined = function (v) { return typeof v !== 'undefined'; }, ceil10 = c3_chart_internal_fn.ceil10 = function (v) { return Math.ceil(v / 10) * 10; }, asHalfPixel = c3_chart_internal_fn.asHalfPixel = function (n) { return Math.ceil(n) + 0.5; }, diffDomain = c3_chart_internal_fn.diffDomain = function (d) { return d[1] - d[0]; }, isEmpty = c3_chart_internal_fn.isEmpty = function (o) { return typeof o === 'undefined' || o === null || (isString(o) && o.length === 0) || (typeof o === 'object' && Object.keys(o).length === 0); }, notEmpty = c3_chart_internal_fn.notEmpty = function (o) { return !c3_chart_internal_fn.isEmpty(o); }, getOption = c3_chart_internal_fn.getOption = function (options, key, defaultValue) { return isDefined(options[key]) ? options[key] : defaultValue; }, hasValue = c3_chart_internal_fn.hasValue = function (dict, value) { var found = false; Object.keys(dict).forEach(function (key) { if (dict[key] === value) { found = true; } }); return found; }, sanitise = c3_chart_internal_fn.sanitise = function (str) { return typeof str === 'string' ? str.replace(/</g, '&lt;').replace(/>/g, '&gt;') : str; }, getPathBox = c3_chart_internal_fn.getPathBox = function (path) { var box = path.getBoundingClientRect(), items = [path.pathSegList.getItem(0), path.pathSegList.getItem(1)], minX = items[0].x, minY = Math.min(items[0].y, items[1].y); return {x: minX, y: minY, width: box.width, height: box.height}; }; c3_chart_fn.focus = function (targetIds) { var $$ = this.internal, candidates; targetIds = $$.mapToTargetIds(targetIds); candidates = $$.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))), this.revert(); this.defocus(); candidates.classed(CLASS.focused, true).classed(CLASS.defocused, false); if ($$.hasArcType()) { $$.expandArc(targetIds); } $$.toggleFocusLegend(targetIds, true); $$.focusedTargetIds = targetIds; $$.defocusedTargetIds = $$.defocusedTargetIds.filter(function (id) { return targetIds.indexOf(id) < 0; }); }; c3_chart_fn.defocus = function (targetIds) { var $$ = this.internal, candidates; targetIds = $$.mapToTargetIds(targetIds); candidates = $$.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))), candidates.classed(CLASS.focused, false).classed(CLASS.defocused, true); if ($$.hasArcType()) { $$.unexpandArc(targetIds); } $$.toggleFocusLegend(targetIds, false); $$.focusedTargetIds = $$.focusedTargetIds.filter(function (id) { return targetIds.indexOf(id) < 0; }); $$.defocusedTargetIds = targetIds; }; c3_chart_fn.revert = function (targetIds) { var $$ = this.internal, candidates; targetIds = $$.mapToTargetIds(targetIds); candidates = $$.svg.selectAll($$.selectorTargets(targetIds)); // should be for all targets candidates.classed(CLASS.focused, false).classed(CLASS.defocused, false); if ($$.hasArcType()) { $$.unexpandArc(targetIds); } if ($$.config.legend_show) { $$.showLegend(targetIds.filter($$.isLegendToShow.bind($$))); $$.legend.selectAll($$.selectorLegends(targetIds)) .filter(function () { return $$.d3.select(this).classed(CLASS.legendItemFocused); }) .classed(CLASS.legendItemFocused, false); } $$.focusedTargetIds = []; $$.defocusedTargetIds = []; }; c3_chart_fn.show = function (targetIds, options) { var $$ = this.internal, targets; targetIds = $$.mapToTargetIds(targetIds); options = options || {}; $$.removeHiddenTargetIds(targetIds); targets = $$.svg.selectAll($$.selectorTargets(targetIds)); targets.transition() .style('opacity', 1, 'important') .call($$.endall, function () { targets.style('opacity', null).style('opacity', 1); }); if (options.withLegend) { $$.showLegend(targetIds); } $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true}); }; c3_chart_fn.hide = function (targetIds, options) { var $$ = this.internal, targets; targetIds = $$.mapToTargetIds(targetIds); options = options || {}; $$.addHiddenTargetIds(targetIds); targets = $$.svg.selectAll($$.selectorTargets(targetIds)); targets.transition() .style('opacity', 0, 'important') .call($$.endall, function () { targets.style('opacity', null).style('opacity', 0); }); if (options.withLegend) { $$.hideLegend(targetIds); } $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true}); }; c3_chart_fn.toggle = function (targetIds, options) { var that = this, $$ = this.internal; $$.mapToTargetIds(targetIds).forEach(function (targetId) { $$.isTargetToShow(targetId) ? that.hide(targetId, options) : that.show(targetId, options); }); }; c3_chart_fn.zoom = function (domain) { var $$ = this.internal; if (domain) { if ($$.isTimeSeries()) { domain = domain.map(function (x) { return $$.parseDate(x); }); } $$.brush.extent(domain); $$.redraw({withUpdateXDomain: true, withY: $$.config.zoom_rescale}); $$.config.zoom_onzoom.call(this, $$.x.orgDomain()); } return $$.brush.extent(); }; c3_chart_fn.zoom.enable = function (enabled) { var $$ = this.internal; $$.config.zoom_enabled = enabled; $$.updateAndRedraw(); }; c3_chart_fn.unzoom = function () { var $$ = this.internal; $$.brush.clear().update(); $$.redraw({withUpdateXDomain: true}); }; c3_chart_fn.zoom.max = function (max) { var $$ = this.internal, config = $$.config, d3 = $$.d3; if (max === 0 || max) { config.zoom_x_max = d3.max([$$.orgXDomain[1], max]); } else { return config.zoom_x_max; } }; c3_chart_fn.zoom.min = function (min) { var $$ = this.internal, config = $$.config, d3 = $$.d3; if (min === 0 || min) { config.zoom_x_min = d3.min([$$.orgXDomain[0], min]); } else { return config.zoom_x_min; } }; c3_chart_fn.zoom.range = function (range) { if (arguments.length) { if (isDefined(range.max)) { this.domain.max(range.max); } if (isDefined(range.min)) { this.domain.min(range.min); } } else { return { max: this.domain.max(), min: this.domain.min() }; } }; c3_chart_fn.load = function (args) { var $$ = this.internal, config = $$.config; // update xs if specified if (args.xs) { $$.addXs(args.xs); } // update names if exists if ('names' in args) { c3_chart_fn.data.names.bind(this)(args.names); } // update classes if exists if ('classes' in args) { Object.keys(args.classes).forEach(function (id) { config.data_classes[id] = args.classes[id]; }); } // update categories if exists if ('categories' in args && $$.isCategorized()) { config.axis_x_categories = args.categories; } // update axes if exists if ('axes' in args) { Object.keys(args.axes).forEach(function (id) { config.data_axes[id] = args.axes[id]; }); } // update colors if exists if ('colors' in args) { Object.keys(args.colors).forEach(function (id) { config.data_colors[id] = args.colors[id]; }); } // use cache if exists if ('cacheIds' in args && $$.hasCaches(args.cacheIds)) { $$.load($$.getCaches(args.cacheIds), args.done); return; } // unload if needed if ('unload' in args) { // TODO: do not unload if target will load (included in url/rows/columns) $$.unload($$.mapToTargetIds((typeof args.unload === 'boolean' && args.unload) ? null : args.unload), function () { $$.loadFromArgs(args); }); } else { $$.loadFromArgs(args); } }; c3_chart_fn.unload = function (args) { var $$ = this.internal; args = args || {}; if (args instanceof Array) { args = {ids: args}; } else if (typeof args === 'string') { args = {ids: [args]}; } $$.unload($$.mapToTargetIds(args.ids), function () { $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true}); if (args.done) { args.done(); } }); }; c3_chart_fn.flow = function (args) { var $$ = this.internal, targets, data, notfoundIds = [], orgDataCount = $$.getMaxDataCount(), dataCount, domain, baseTarget, baseValue, length = 0, tail = 0, diff, to; if (args.json) { data = $$.convertJsonToData(args.json, args.keys); } else if (args.rows) { data = $$.convertRowsToData(args.rows); } else if (args.columns) { data = $$.convertColumnsToData(args.columns); } else { return; } targets = $$.convertDataToTargets(data, true); // Update/Add data $$.data.targets.forEach(function (t) { var found = false, i, j; for (i = 0; i < targets.length; i++) { if (t.id === targets[i].id) { found = true; if (t.values[t.values.length - 1]) { tail = t.values[t.values.length - 1].index + 1; } length = targets[i].values.length; for (j = 0; j < length; j++) { targets[i].values[j].index = tail + j; if (!$$.isTimeSeries()) { targets[i].values[j].x = tail + j; } } t.values = t.values.concat(targets[i].values); targets.splice(i, 1); break; } } if (!found) { notfoundIds.push(t.id); } }); // Append null for not found targets $$.data.targets.forEach(function (t) { var i, j; for (i = 0; i < notfoundIds.length; i++) { if (t.id === notfoundIds[i]) { tail = t.values[t.values.length - 1].index + 1; for (j = 0; j < length; j++) { t.values.push({ id: t.id, index: tail + j, x: $$.isTimeSeries() ? $$.getOtherTargetX(tail + j) : tail + j, value: null }); } } } }); // Generate null values for new target if ($$.data.targets.length) { targets.forEach(function (t) { var i, missing = []; for (i = $$.data.targets[0].values[0].index; i < tail; i++) { missing.push({ id: t.id, index: i, x: $$.isTimeSeries() ? $$.getOtherTargetX(i) : i, value: null }); } t.values.forEach(function (v) { v.index += tail; if (!$$.isTimeSeries()) { v.x += tail; } }); t.values = missing.concat(t.values); }); } $$.data.targets = $$.data.targets.concat(targets); // add remained // check data count because behavior needs to change when it's only one dataCount = $$.getMaxDataCount(); baseTarget = $$.data.targets[0]; baseValue = baseTarget.values[0]; // Update length to flow if needed if (isDefined(args.to)) { length = 0; to = $$.isTimeSeries() ? $$.parseDate(args.to) : args.to; baseTarget.values.forEach(function (v) { if (v.x < to) { length++; } }); } else if (isDefined(args.length)) { length = args.length; } // If only one data, update the domain to flow from left edge of the chart if (!orgDataCount) { if ($$.isTimeSeries()) { if (baseTarget.values.length > 1) { diff = baseTarget.values[baseTarget.values.length - 1].x - baseValue.x; } else { diff = baseValue.x - $$.getXDomain($$.data.targets)[0]; } } else { diff = 1; } domain = [baseValue.x - diff, baseValue.x]; $$.updateXDomain(null, true, true, false, domain); } else if (orgDataCount === 1) { if ($$.isTimeSeries()) { diff = (baseTarget.values[baseTarget.values.length - 1].x - baseValue.x) / 2; domain = [new Date(+baseValue.x - diff), new Date(+baseValue.x + diff)]; $$.updateXDomain(null, true, true, false, domain); } } // Set targets $$.updateTargets($$.data.targets); // Redraw with new targets $$.redraw({ flow: { index: baseValue.index, length: length, duration: isValue(args.duration) ? args.duration : $$.config.transition_duration, done: args.done, orgDataCount: orgDataCount, }, withLegend: true, withTransition: orgDataCount > 1, withTrimXDomain: false, withUpdateXAxis: true, }); }; c3_chart_internal_fn.generateFlow = function (args) { var $$ = this, config = $$.config, d3 = $$.d3; return function () { var targets = args.targets, flow = args.flow, drawBar = args.drawBar, drawLine = args.drawLine, drawArea = args.drawArea, cx = args.cx, cy = args.cy, xv = args.xv, xForText = args.xForText, yForText = args.yForText, duration = args.duration; var translateX, scaleX = 1, transform, flowIndex = flow.index, flowLength = flow.length, flowStart = $$.getValueOnIndex($$.data.targets[0].values, flowIndex), flowEnd = $$.getValueOnIndex($$.data.targets[0].values, flowIndex + flowLength), orgDomain = $$.x.domain(), domain, durationForFlow = flow.duration || duration, done = flow.done || function () {}, wait = $$.generateWait(); var xgrid = $$.xgrid || d3.selectAll([]), xgridLines = $$.xgridLines || d3.selectAll([]), mainRegion = $$.mainRegion || d3.selectAll([]), mainText = $$.mainText || d3.selectAll([]), mainBar = $$.mainBar || d3.selectAll([]), mainLine = $$.mainLine || d3.selectAll([]), mainArea = $$.mainArea || d3.selectAll([]), mainCircle = $$.mainCircle || d3.selectAll([]); // set flag $$.flowing = true; // remove head data after rendered $$.data.targets.forEach(function (d) { d.values.splice(0, flowLength); }); // update x domain to generate axis elements for flow domain = $$.updateXDomain(targets, true, true); // update elements related to x scale if ($$.updateXGrid) { $$.updateXGrid(true); } // generate transform to flow if (!flow.orgDataCount) { // if empty if ($$.data.targets[0].values.length !== 1) { translateX = $$.x(orgDomain[0]) - $$.x(domain[0]); } else { if ($$.isTimeSeries()) { flowStart = $$.getValueOnIndex($$.data.targets[0].values, 0); flowEnd = $$.getValueOnIndex($$.data.targets[0].values, $$.data.targets[0].values.length - 1); translateX = $$.x(flowStart.x) - $$.x(flowEnd.x); } else { translateX = diffDomain(domain) / 2; } } } else if (flow.orgDataCount === 1 || (flowStart && flowStart.x) === (flowEnd && flowEnd.x)) { translateX = $$.x(orgDomain[0]) - $$.x(domain[0]); } else { if ($$.isTimeSeries()) { translateX = ($$.x(orgDomain[0]) - $$.x(domain[0])); } else { translateX = ($$.x(flowStart.x) - $$.x(flowEnd.x)); } } scaleX = (diffDomain(orgDomain) / diffDomain(domain)); transform = 'translate(' + translateX + ',0) scale(' + scaleX + ',1)'; $$.hideXGridFocus(); d3.transition().ease('linear').duration(durationForFlow).each(function () { wait.add($$.axes.x.transition().call($$.xAxis)); wait.add(mainBar.transition().attr('transform', transform)); wait.add(mainLine.transition().attr('transform', transform)); wait.add(mainArea.transition().attr('transform', transform)); wait.add(mainCircle.transition().attr('transform', transform)); wait.add(mainText.transition().attr('transform', transform)); wait.add(mainRegion.filter($$.isRegionOnX).transition().attr('transform', transform)); wait.add(xgrid.transition().attr('transform', transform)); wait.add(xgridLines.transition().attr('transform', transform)); }) .call(wait, function () { var i, shapes = [], texts = [], eventRects = []; // remove flowed elements if (flowLength) { for (i = 0; i < flowLength; i++) { shapes.push('.' + CLASS.shape + '-' + (flowIndex + i)); texts.push('.' + CLASS.text + '-' + (flowIndex + i)); eventRects.push('.' + CLASS.eventRect + '-' + (flowIndex + i)); } $$.svg.selectAll('.' + CLASS.shapes).selectAll(shapes).remove(); $$.svg.selectAll('.' + CLASS.texts).selectAll(texts).remove(); $$.svg.selectAll('.' + CLASS.eventRects).selectAll(eventRects).remove(); $$.svg.select('.' + CLASS.xgrid).remove(); } // draw again for removing flowed elements and reverting attr xgrid .attr('transform', null) .attr($$.xgridAttr); xgridLines .attr('transform', null); xgridLines.select('line') .attr("x1", config.axis_rotated ? 0 : xv) .attr("x2", config.axis_rotated ? $$.width : xv); xgridLines.select('text') .attr("x", config.axis_rotated ? $$.width : 0) .attr("y", xv); mainBar .attr('transform', null) .attr("d", drawBar); mainLine .attr('transform', null) .attr("d", drawLine); mainArea .attr('transform', null) .attr("d", drawArea); mainCircle .attr('transform', null) .attr("cx", cx) .attr("cy", cy); mainText .attr('transform', null) .attr('x', xForText) .attr('y', yForText) .style('fill-opacity', $$.opacityForText.bind($$)); mainRegion .attr('transform', null); mainRegion.select('rect').filter($$.isRegionOnX) .attr("x", $$.regionX.bind($$)) .attr("width", $$.regionWidth.bind($$)); if (config.interaction_enabled) { $$.redrawEventRect(); } // callback for end of flow done(); $$.flowing = false; }); }; }; c3_chart_fn.selected = function (targetId) { var $$ = this.internal, d3 = $$.d3; return d3.merge( $$.main.selectAll('.' + CLASS.shapes + $$.getTargetSelectorSuffix(targetId)).selectAll('.' + CLASS.shape) .filter(function () { return d3.select(this).classed(CLASS.SELECTED); }) .map(function (d) { return d.map(function (d) { var data = d.__data__; return data.data ? data.data : data; }); }) ); }; c3_chart_fn.select = function (ids, indices, resetOther) { var $$ = this.internal, d3 = $$.d3, config = $$.config; if (! config.data_selection_enabled) { return; } $$.main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) { var shape = d3.select(this), id = d.data ? d.data.id : d.id, toggle = $$.getToggle(this, d).bind($$), isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0, isTargetIndex = !indices || indices.indexOf(i) >= 0, isSelected = shape.classed(CLASS.SELECTED); // line/area selection not supported yet if (shape.classed(CLASS.line) || shape.classed(CLASS.area)) { return; } if (isTargetId && isTargetIndex) { if (config.data_selection_isselectable(d) && !isSelected) { toggle(true, shape.classed(CLASS.SELECTED, true), d, i); } } else if (isDefined(resetOther) && resetOther) { if (isSelected) { toggle(false, shape.classed(CLASS.SELECTED, false), d, i); } } }); }; c3_chart_fn.unselect = function (ids, indices) { var $$ = this.internal, d3 = $$.d3, config = $$.config; if (! config.data_selection_enabled) { return; } $$.main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) { var shape = d3.select(this), id = d.data ? d.data.id : d.id, toggle = $$.getToggle(this, d).bind($$), isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0, isTargetIndex = !indices || indices.indexOf(i) >= 0, isSelected = shape.classed(CLASS.SELECTED); // line/area selection not supported yet if (shape.classed(CLASS.line) || shape.classed(CLASS.area)) { return; } if (isTargetId && isTargetIndex) { if (config.data_selection_isselectable(d)) { if (isSelected) { toggle(false, shape.classed(CLASS.SELECTED, false), d, i); } } } }); }; c3_chart_fn.transform = function (type, targetIds) { var $$ = this.internal, options = ['pie', 'donut'].indexOf(type) >= 0 ? {withTransform: true} : null; $$.transformTo(targetIds, type, options); }; c3_chart_internal_fn.transformTo = function (targetIds, type, optionsForRedraw) { var $$ = this, withTransitionForAxis = !$$.hasArcType(), options = optionsForRedraw || {withTransitionForAxis: withTransitionForAxis}; options.withTransitionForTransform = false; $$.transiting = false; $$.setTargetType(targetIds, type); $$.updateTargets($$.data.targets); // this is needed when transforming to arc $$.updateAndRedraw(options); }; c3_chart_fn.groups = function (groups) { var $$ = this.internal, config = $$.config; if (isUndefined(groups)) { return config.data_groups; } config.data_groups = groups; $$.redraw(); return config.data_groups; }; c3_chart_fn.xgrids = function (grids) { var $$ = this.internal, config = $$.config; if (! grids) { return config.grid_x_lines; } config.grid_x_lines = grids; $$.redrawWithoutRescale(); return config.grid_x_lines; }; c3_chart_fn.xgrids.add = function (grids) { var $$ = this.internal; return this.xgrids($$.config.grid_x_lines.concat(grids ? grids : [])); }; c3_chart_fn.xgrids.remove = function (params) { // TODO: multiple var $$ = this.internal; $$.removeGridLines(params, true); }; c3_chart_fn.ygrids = function (grids) { var $$ = this.internal, config = $$.config; if (! grids) { return config.grid_y_lines; } config.grid_y_lines = grids; $$.redrawWithoutRescale(); return config.grid_y_lines; }; c3_chart_fn.ygrids.add = function (grids) { var $$ = this.internal; return this.ygrids($$.config.grid_y_lines.concat(grids ? grids : [])); }; c3_chart_fn.ygrids.remove = function (params) { // TODO: multiple var $$ = this.internal; $$.removeGridLines(params, false); }; c3_chart_fn.regions = function (regions) { var $$ = this.internal, config = $$.config; if (!regions) { return config.regions; } config.regions = regions; $$.redrawWithoutRescale(); return config.regions; }; c3_chart_fn.regions.add = function (regions) { var $$ = this.internal, config = $$.config; if (!regions) { return config.regions; } config.regions = config.regions.concat(regions); $$.redrawWithoutRescale(); return config.regions; }; c3_chart_fn.regions.remove = function (options) { var $$ = this.internal, config = $$.config, duration, classes, regions; options = options || {}; duration = $$.getOption(options, "duration", config.transition_duration); classes = $$.getOption(options, "classes", [CLASS.region]); regions = $$.main.select('.' + CLASS.regions).selectAll(classes.map(function (c) { return '.' + c; })); (duration ? regions.transition().duration(duration) : regions) .style('opacity', 0) .remove(); config.regions = config.regions.filter(function (region) { var found = false; if (!region['class']) { return true; } region['class'].split(' ').forEach(function (c) { if (classes.indexOf(c) >= 0) { found = true; } }); return !found; }); return config.regions; }; c3_chart_fn.data = function (targetIds) { var targets = this.internal.data.targets; return typeof targetIds === 'undefined' ? targets : targets.filter(function (t) { return [].concat(targetIds).indexOf(t.id) >= 0; }); }; c3_chart_fn.data.shown = function (targetIds) { return this.internal.filterTargetsToShow(this.data(targetIds)); }; c3_chart_fn.data.values = function (targetId) { var targets, values = null; if (targetId) { targets = this.data(targetId); values = targets[0] ? targets[0].values.map(function (d) { return d.value; }) : null; } return values; }; c3_chart_fn.data.names = function (names) { this.internal.clearLegendItemTextBoxCache(); return this.internal.updateDataAttributes('names', names); }; c3_chart_fn.data.colors = function (colors) { return this.internal.updateDataAttributes('colors', colors); }; c3_chart_fn.data.axes = function (axes) { return this.internal.updateDataAttributes('axes', axes); }; c3_chart_fn.category = function (i, category) { var $$ = this.internal, config = $$.config; if (arguments.length > 1) { config.axis_x_categories[i] = category; $$.redraw(); } return config.axis_x_categories[i]; }; c3_chart_fn.categories = function (categories) { var $$ = this.internal, config = $$.config; if (!arguments.length) { return config.axis_x_categories; } config.axis_x_categories = categories; $$.redraw(); return config.axis_x_categories; }; // TODO: fix c3_chart_fn.color = function (id) { var $$ = this.internal; return $$.color(id); // more patterns }; c3_chart_fn.x = function (x) { var $$ = this.internal; if (arguments.length) { $$.updateTargetX($$.data.targets, x); $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true}); } return $$.data.xs; }; c3_chart_fn.xs = function (xs) { var $$ = this.internal; if (arguments.length) { $$.updateTargetXs($$.data.targets, xs); $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true}); } return $$.data.xs; }; c3_chart_fn.axis = function () {}; c3_chart_fn.axis.labels = function (labels) { var $$ = this.internal; if (arguments.length) { Object.keys(labels).forEach(function (axisId) { $$.axis.setLabelText(axisId, labels[axisId]); }); $$.axis.updateLabels(); } // TODO: return some values? }; c3_chart_fn.axis.max = function (max) { var $$ = this.internal, config = $$.config; if (arguments.length) { if (typeof max === 'object') { if (isValue(max.x)) { config.axis_x_max = max.x; } if (isValue(max.y)) { config.axis_y_max = max.y; } if (isValue(max.y2)) { config.axis_y2_max = max.y2; } } else { config.axis_y_max = config.axis_y2_max = max; } $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true}); } else { return { x: config.axis_x_max, y: config.axis_y_max, y2: config.axis_y2_max }; } }; c3_chart_fn.axis.min = function (min) { var $$ = this.internal, config = $$.config; if (arguments.length) { if (typeof min === 'object') { if (isValue(min.x)) { config.axis_x_min = min.x; } if (isValue(min.y)) { config.axis_y_min = min.y; } if (isValue(min.y2)) { config.axis_y2_min = min.y2; } } else { config.axis_y_min = config.axis_y2_min = min; } $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true}); } else { return { x: config.axis_x_min, y: config.axis_y_min, y2: config.axis_y2_min }; } }; c3_chart_fn.axis.range = function (range) { if (arguments.length) { if (isDefined(range.max)) { this.axis.max(range.max); } if (isDefined(range.min)) { this.axis.min(range.min); } } else { return { max: this.axis.max(), min: this.axis.min() }; } }; c3_chart_fn.legend = function () {}; c3_chart_fn.legend.show = function (targetIds) { var $$ = this.internal; $$.showLegend($$.mapToTargetIds(targetIds)); $$.updateAndRedraw({withLegend: true}); }; c3_chart_fn.legend.hide = function (targetIds) { var $$ = this.internal; $$.hideLegend($$.mapToTargetIds(targetIds)); $$.updateAndRedraw({withLegend: true}); }; c3_chart_fn.resize = function (size) { var $$ = this.internal, config = $$.config; config.size_width = size ? size.width : null; config.size_height = size ? size.height : null; this.flush(); }; c3_chart_fn.flush = function () { var $$ = this.internal; $$.updateAndRedraw({withLegend: true, withTransition: false, withTransitionForTransform: false}); }; c3_chart_fn.destroy = function () { var $$ = this.internal; window.clearInterval($$.intervalForObserveInserted); if ($$.resizeTimeout !== undefined) { window.clearTimeout($$.resizeTimeout); } if (window.detachEvent) { window.detachEvent('onresize', $$.resizeFunction); } else if (window.removeEventListener) { window.removeEventListener('resize', $$.resizeFunction); } else { var wrapper = window.onresize; // check if no one else removed our wrapper and remove our resizeFunction from it if (wrapper && wrapper.add && wrapper.remove) { wrapper.remove($$.resizeFunction); } } $$.selectChart.classed('c3', false).html(""); // MEMO: this is needed because the reference of some elements will not be released, then memory leak will happen. Object.keys($$).forEach(function (key) { $$[key] = null; }); return null; }; c3_chart_fn.tooltip = function () {}; c3_chart_fn.tooltip.show = function (args) { var $$ = this.internal, index, mouse; // determine mouse position on the chart if (args.mouse) { mouse = args.mouse; } // determine focus data if (args.data) { if ($$.isMultipleX()) { // if multiple xs, target point will be determined by mouse mouse = [$$.x(args.data.x), $$.getYScale(args.data.id)(args.data.value)]; index = null; } else { // TODO: when tooltip_grouped = false index = isValue(args.data.index) ? args.data.index : $$.getIndexByX(args.data.x); } } else if (typeof args.x !== 'undefined') { index = $$.getIndexByX(args.x); } else if (typeof args.index !== 'undefined') { index = args.index; } // emulate mouse events to show $$.dispatchEvent('mouseover', index, mouse); $$.dispatchEvent('mousemove', index, mouse); $$.config.tooltip_onshow.call($$, args.data); }; c3_chart_fn.tooltip.hide = function () { // TODO: get target data by checking the state of focus this.internal.dispatchEvent('mouseout', 0); this.internal.config.tooltip_onhide.call(this); }; // Features: // 1. category axis // 2. ceil values of translate/x/y to int for half pixel antialiasing // 3. multiline tick text var tickTextCharSize; function c3_axis(d3, params) { var scale = d3.scale.linear(), orient = "bottom", innerTickSize = 6, outerTickSize, tickPadding = 3, tickValues = null, tickFormat, tickArguments; var tickOffset = 0, tickCulling = true, tickCentered; params = params || {}; outerTickSize = params.withOuterTick ? 6 : 0; function axisX(selection, x) { selection.attr("transform", function (d) { return "translate(" + Math.ceil(x(d) + tickOffset) + ", 0)"; }); } function axisY(selection, y) { selection.attr("transform", function (d) { return "translate(0," + Math.ceil(y(d)) + ")"; }); } function scaleExtent(domain) { var start = domain[0], stop = domain[domain.length - 1]; return start < stop ? [ start, stop ] : [ stop, start ]; } function generateTicks(scale) { var i, domain, ticks = []; if (scale.ticks) { return scale.ticks.apply(scale, tickArguments); } domain = scale.domain(); for (i = Math.ceil(domain[0]); i < domain[1]; i++) { ticks.push(i); } if (ticks.length > 0 && ticks[0] > 0) { ticks.unshift(ticks[0] - (ticks[1] - ticks[0])); } return ticks; } function copyScale() { var newScale = scale.copy(), domain; if (params.isCategory) { domain = scale.domain(); newScale.domain([domain[0], domain[1] - 1]); } return newScale; } function textFormatted(v) { var formatted = tickFormat ? tickFormat(v) : v; return typeof formatted !== 'undefined' ? formatted : ''; } function getSizeFor1Char(tick) { if (tickTextCharSize) { return tickTextCharSize; } var size = { h: 11.5, w: 5.5 }; tick.select('text').text(textFormatted).each(function (d) { var box = this.getBoundingClientRect(), text = textFormatted(d), h = box.height, w = text ? (box.width / text.length) : undefined; if (h && w) { size.h = h; size.w = w; } }).text(''); tickTextCharSize = size; return size; } function transitionise(selection) { return params.withoutTransition ? selection : d3.transition(selection); } function axis(g) { g.each(function () { var g = axis.g = d3.select(this); var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = copyScale(); var ticks = tickValues ? tickValues : generateTicks(scale1), tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", 1e-6), // MEMO: No exit transition. The reason is this transition affects max tick width calculation because old tick will be included in the ticks. tickExit = tick.exit().remove(), tickUpdate = transitionise(tick).style("opacity", 1), tickTransform, tickX, tickY; var range = scale.rangeExtent ? scale.rangeExtent() : scaleExtent(scale.range()), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), transitionise(path)); tickEnter.append("line"); tickEnter.append("text"); var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"); if (params.isCategory) { tickOffset = Math.ceil((scale1(1) - scale1(0)) / 2); tickX = tickCentered ? 0 : tickOffset; tickY = tickCentered ? tickOffset : 0; } else { tickOffset = tickX = 0; } var text, tspan, sizeFor1Char = getSizeFor1Char(g.select('.tick')), counts = []; var tickLength = Math.max(innerTickSize, 0) + tickPadding, isVertical = orient === 'left' || orient === 'right'; // this should be called only when category axis function splitTickText(d, maxWidth) { var tickText = textFormatted(d), subtext, spaceIndex, textWidth, splitted = []; if (Object.prototype.toString.call(tickText) === "[object Array]") { return tickText; } if (!maxWidth || maxWidth <= 0) { maxWidth = isVertical ? 95 : params.isCategory ? (Math.ceil(scale1(ticks[1]) - scale1(ticks[0])) - 12) : 110; } function split(splitted, text) { spaceIndex = undefined; for (var i = 1; i < text.length; i++) { if (text.charAt(i) === ' ') { spaceIndex = i; } subtext = text.substr(0, i + 1); textWidth = sizeFor1Char.w * subtext.length; // if text width gets over tick width, split by space index or crrent index if (maxWidth < textWidth) { return split( splitted.concat(text.substr(0, spaceIndex ? spaceIndex : i)), text.slice(spaceIndex ? spaceIndex + 1 : i) ); } } return splitted.concat(text); } return split(splitted, tickText + ""); } function tspanDy(d, i) { var dy = sizeFor1Char.h; if (i === 0) { if (orient === 'left' || orient === 'right') { dy = -((counts[d.index] - 1) * (sizeFor1Char.h / 2) - 3); } else { dy = ".71em"; } } return dy; } function tickSize(d) { var tickPosition = scale(d) + (tickCentered ? 0 : tickOffset); return range[0] < tickPosition && tickPosition < range[1] ? innerTickSize : 0; } text = tick.select("text"); tspan = text.selectAll('tspan') .data(function (d, i) { var splitted = params.tickMultiline ? splitTickText(d, params.tickWidth) : [].concat(textFormatted(d)); counts[i] = splitted.length; return splitted.map(function (s) { return { index: i, splitted: s }; }); }); tspan.enter().append('tspan'); tspan.exit().remove(); tspan.text(function (d) { return d.splitted; }); var rotate = params.tickTextRotate; function textAnchorForText(rotate) { if (!rotate) { return 'middle'; } return rotate > 0 ? "start" : "end"; } function textTransform(rotate) { if (!rotate) { return ''; } return "rotate(" + rotate + ")"; } function dxForText(rotate) { if (!rotate) { return 0; } return 8 * Math.sin(Math.PI * (rotate / 180)); } function yForText(rotate) { if (!rotate) { return tickLength; } return 11.5 - 2.5 * (rotate / 15) * (rotate > 0 ? 1 : -1); } switch (orient) { case "bottom": { tickTransform = axisX; lineEnter.attr("y2", innerTickSize); textEnter.attr("y", tickLength); lineUpdate.attr("x1", tickX).attr("x2", tickX).attr("y2", tickSize); textUpdate.attr("x", 0).attr("y", yForText(rotate)) .style("text-anchor", textAnchorForText(rotate)) .attr("transform", textTransform(rotate)); tspan.attr('x', 0).attr("dy", tspanDy).attr('dx', dxForText(rotate)); pathUpdate.attr("d", "M" + range[0] + "," + outerTickSize + "V0H" + range[1] + "V" + outerTickSize); break; } case "top": { // TODO: rotated tick text tickTransform = axisX; lineEnter.attr("y2", -innerTickSize); textEnter.attr("y", -tickLength); lineUpdate.attr("x2", 0).attr("y2", -innerTickSize); textUpdate.attr("x", 0).attr("y", -tickLength); text.style("text-anchor", "middle"); tspan.attr('x', 0).attr("dy", "0em"); pathUpdate.attr("d", "M" + range[0] + "," + -outerTickSize + "V0H" + range[1] + "V" + -outerTickSize); break; } case "left": { tickTransform = axisY; lineEnter.attr("x2", -innerTickSize); textEnter.attr("x", -tickLength); lineUpdate.attr("x2", -innerTickSize).attr("y1", tickY).attr("y2", tickY); textUpdate.attr("x", -tickLength).attr("y", tickOffset); text.style("text-anchor", "end"); tspan.attr('x', -tickLength).attr("dy", tspanDy); pathUpdate.attr("d", "M" + -outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + -outerTickSize); break; } case "right": { tickTransform = axisY; lineEnter.attr("x2", innerTickSize); textEnter.attr("x", tickLength); lineUpdate.attr("x2", innerTickSize).attr("y2", 0); textUpdate.attr("x", tickLength).attr("y", 0); text.style("text-anchor", "start"); tspan.attr('x', tickLength).attr("dy", tspanDy); pathUpdate.attr("d", "M" + outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + outerTickSize); break; } } if (scale1.rangeBand) { var x = scale1, dx = x.rangeBand() / 2; scale0 = scale1 = function (d) { return x(d) + dx; }; } else if (scale0.rangeBand) { scale0 = scale1; } else { tickExit.call(tickTransform, scale1); } tickEnter.call(tickTransform, scale0); tickUpdate.call(tickTransform, scale1); }); } axis.scale = function (x) { if (!arguments.length) { return scale; } scale = x; return axis; }; axis.orient = function (x) { if (!arguments.length) { return orient; } orient = x in {top: 1, right: 1, bottom: 1, left: 1} ? x + "" : "bottom"; return axis; }; axis.tickFormat = function (format) { if (!arguments.length) { return tickFormat; } tickFormat = format; return axis; }; axis.tickCentered = function (isCentered) { if (!arguments.length) { return tickCentered; } tickCentered = isCentered; return axis; }; axis.tickOffset = function () { return tickOffset; }; axis.tickInterval = function () { var interval, length; if (params.isCategory) { interval = tickOffset * 2; } else { length = axis.g.select('path.domain').node().getTotalLength() - outerTickSize * 2; interval = length / axis.g.selectAll('line').size(); } return interval === Infinity ? 0 : interval; }; axis.ticks = function () { if (!arguments.length) { return tickArguments; } tickArguments = arguments; return axis; }; axis.tickCulling = function (culling) { if (!arguments.length) { return tickCulling; } tickCulling = culling; return axis; }; axis.tickValues = function (x) { if (typeof x === 'function') { tickValues = function () { return x(scale.domain()); }; } else { if (!arguments.length) { return tickValues; } tickValues = x; } return axis; }; return axis; } c3_chart_internal_fn.isSafari = function () { var ua = window.navigator.userAgent; return ua.indexOf('Safari') >= 0 && ua.indexOf('Chrome') < 0; }; c3_chart_internal_fn.isChrome = function () { var ua = window.navigator.userAgent; return ua.indexOf('Chrome') >= 0; }; /* jshint ignore:start */ // PhantomJS doesn't have support for Function.prototype.bind, which has caused confusion. Use // this polyfill to avoid the confusion. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Polyfill if (!Function.prototype.bind) { Function.prototype.bind = function(oThis) { if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function() {}, fBound = function() { return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } //SVGPathSeg API polyfill //https://github.com/progers/pathseg // //This is a drop-in replacement for the SVGPathSeg and SVGPathSegList APIs that were removed from //SVG2 (https://lists.w3.org/Archives/Public/www-svg/2015Jun/0044.html), including the latest spec //changes which were implemented in Firefox 43 and Chrome 46. //Chrome 48 removes these APIs, so this polyfill is required. (function() { "use strict"; if (!("SVGPathSeg" in window)) { // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSeg window.SVGPathSeg = function(type, typeAsLetter, owningPathSegList) { this.pathSegType = type; this.pathSegTypeAsLetter = typeAsLetter; this._owningPathSegList = owningPathSegList; } SVGPathSeg.PATHSEG_UNKNOWN = 0; SVGPathSeg.PATHSEG_CLOSEPATH = 1; SVGPathSeg.PATHSEG_MOVETO_ABS = 2; SVGPathSeg.PATHSEG_MOVETO_REL = 3; SVGPathSeg.PATHSEG_LINETO_ABS = 4; SVGPathSeg.PATHSEG_LINETO_REL = 5; SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS = 6; SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL = 7; SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS = 8; SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL = 9; SVGPathSeg.PATHSEG_ARC_ABS = 10; SVGPathSeg.PATHSEG_ARC_REL = 11; SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS = 12; SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL = 13; SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS = 14; SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL = 15; SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS = 16; SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL = 17; SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS = 18; SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL = 19; // Notify owning PathSegList on any changes so they can be synchronized back to the path element. SVGPathSeg.prototype._segmentChanged = function() { if (this._owningPathSegList) this._owningPathSegList.segmentChanged(this); } window.SVGPathSegClosePath = function(owningPathSegList) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CLOSEPATH, "z", owningPathSegList); } SVGPathSegClosePath.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegClosePath.prototype.toString = function() { return "[object SVGPathSegClosePath]"; } SVGPathSegClosePath.prototype._asPathString = function() { return this.pathSegTypeAsLetter; } SVGPathSegClosePath.prototype.clone = function() { return new SVGPathSegClosePath(undefined); } window.SVGPathSegMovetoAbs = function(owningPathSegList, x, y) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_MOVETO_ABS, "M", owningPathSegList); this._x = x; this._y = y; } SVGPathSegMovetoAbs.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegMovetoAbs.prototype.toString = function() { return "[object SVGPathSegMovetoAbs]"; } SVGPathSegMovetoAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x + " " + this._y; } SVGPathSegMovetoAbs.prototype.clone = function() { return new SVGPathSegMovetoAbs(undefined, this._x, this._y); } Object.defineProperty(SVGPathSegMovetoAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegMovetoAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegMovetoRel = function(owningPathSegList, x, y) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_MOVETO_REL, "m", owningPathSegList); this._x = x; this._y = y; } SVGPathSegMovetoRel.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegMovetoRel.prototype.toString = function() { return "[object SVGPathSegMovetoRel]"; } SVGPathSegMovetoRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x + " " + this._y; } SVGPathSegMovetoRel.prototype.clone = function() { return new SVGPathSegMovetoRel(undefined, this._x, this._y); } Object.defineProperty(SVGPathSegMovetoRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegMovetoRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegLinetoAbs = function(owningPathSegList, x, y) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_LINETO_ABS, "L", owningPathSegList); this._x = x; this._y = y; } SVGPathSegLinetoAbs.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegLinetoAbs.prototype.toString = function() { return "[object SVGPathSegLinetoAbs]"; } SVGPathSegLinetoAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x + " " + this._y; } SVGPathSegLinetoAbs.prototype.clone = function() { return new SVGPathSegLinetoAbs(undefined, this._x, this._y); } Object.defineProperty(SVGPathSegLinetoAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegLinetoAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegLinetoRel = function(owningPathSegList, x, y) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_LINETO_REL, "l", owningPathSegList); this._x = x; this._y = y; } SVGPathSegLinetoRel.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegLinetoRel.prototype.toString = function() { return "[object SVGPathSegLinetoRel]"; } SVGPathSegLinetoRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x + " " + this._y; } SVGPathSegLinetoRel.prototype.clone = function() { return new SVGPathSegLinetoRel(undefined, this._x, this._y); } Object.defineProperty(SVGPathSegLinetoRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegLinetoRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegCurvetoCubicAbs = function(owningPathSegList, x, y, x1, y1, x2, y2) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS, "C", owningPathSegList); this._x = x; this._y = y; this._x1 = x1; this._y1 = y1; this._x2 = x2; this._y2 = y2; } SVGPathSegCurvetoCubicAbs.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegCurvetoCubicAbs.prototype.toString = function() { return "[object SVGPathSegCurvetoCubicAbs]"; } SVGPathSegCurvetoCubicAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y; } SVGPathSegCurvetoCubicAbs.prototype.clone = function() { return new SVGPathSegCurvetoCubicAbs(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); } Object.defineProperty(SVGPathSegCurvetoCubicAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicAbs.prototype, "x1", { get: function() { return this._x1; }, set: function(x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicAbs.prototype, "y1", { get: function() { return this._y1; }, set: function(y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicAbs.prototype, "x2", { get: function() { return this._x2; }, set: function(x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicAbs.prototype, "y2", { get: function() { return this._y2; }, set: function(y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegCurvetoCubicRel = function(owningPathSegList, x, y, x1, y1, x2, y2) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL, "c", owningPathSegList); this._x = x; this._y = y; this._x1 = x1; this._y1 = y1; this._x2 = x2; this._y2 = y2; } SVGPathSegCurvetoCubicRel.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegCurvetoCubicRel.prototype.toString = function() { return "[object SVGPathSegCurvetoCubicRel]"; } SVGPathSegCurvetoCubicRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y; } SVGPathSegCurvetoCubicRel.prototype.clone = function() { return new SVGPathSegCurvetoCubicRel(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); } Object.defineProperty(SVGPathSegCurvetoCubicRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicRel.prototype, "x1", { get: function() { return this._x1; }, set: function(x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicRel.prototype, "y1", { get: function() { return this._y1; }, set: function(y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicRel.prototype, "x2", { get: function() { return this._x2; }, set: function(x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicRel.prototype, "y2", { get: function() { return this._y2; }, set: function(y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegCurvetoQuadraticAbs = function(owningPathSegList, x, y, x1, y1) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS, "Q", owningPathSegList); this._x = x; this._y = y; this._x1 = x1; this._y1 = y1; } SVGPathSegCurvetoQuadraticAbs.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegCurvetoQuadraticAbs.prototype.toString = function() { return "[object SVGPathSegCurvetoQuadraticAbs]"; } SVGPathSegCurvetoQuadraticAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x + " " + this._y; } SVGPathSegCurvetoQuadraticAbs.prototype.clone = function() { return new SVGPathSegCurvetoQuadraticAbs(undefined, this._x, this._y, this._x1, this._y1); } Object.defineProperty(SVGPathSegCurvetoQuadraticAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoQuadraticAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoQuadraticAbs.prototype, "x1", { get: function() { return this._x1; }, set: function(x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoQuadraticAbs.prototype, "y1", { get: function() { return this._y1; }, set: function(y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegCurvetoQuadraticRel = function(owningPathSegList, x, y, x1, y1) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL, "q", owningPathSegList); this._x = x; this._y = y; this._x1 = x1; this._y1 = y1; } SVGPathSegCurvetoQuadraticRel.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegCurvetoQuadraticRel.prototype.toString = function() { return "[object SVGPathSegCurvetoQuadraticRel]"; } SVGPathSegCurvetoQuadraticRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x + " " + this._y; } SVGPathSegCurvetoQuadraticRel.prototype.clone = function() { return new SVGPathSegCurvetoQuadraticRel(undefined, this._x, this._y, this._x1, this._y1); } Object.defineProperty(SVGPathSegCurvetoQuadraticRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoQuadraticRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoQuadraticRel.prototype, "x1", { get: function() { return this._x1; }, set: function(x1) { this._x1 = x1; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoQuadraticRel.prototype, "y1", { get: function() { return this._y1; }, set: function(y1) { this._y1 = y1; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegArcAbs = function(owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_ARC_ABS, "A", owningPathSegList); this._x = x; this._y = y; this._r1 = r1; this._r2 = r2; this._angle = angle; this._largeArcFlag = largeArcFlag; this._sweepFlag = sweepFlag; } SVGPathSegArcAbs.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegArcAbs.prototype.toString = function() { return "[object SVGPathSegArcAbs]"; } SVGPathSegArcAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._r1 + " " + this._r2 + " " + this._angle + " " + (this._largeArcFlag ? "1" : "0") + " " + (this._sweepFlag ? "1" : "0") + " " + this._x + " " + this._y; } SVGPathSegArcAbs.prototype.clone = function() { return new SVGPathSegArcAbs(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); } Object.defineProperty(SVGPathSegArcAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegArcAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegArcAbs.prototype, "r1", { get: function() { return this._r1; }, set: function(r1) { this._r1 = r1; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegArcAbs.prototype, "r2", { get: function() { return this._r2; }, set: function(r2) { this._r2 = r2; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegArcAbs.prototype, "angle", { get: function() { return this._angle; }, set: function(angle) { this._angle = angle; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegArcAbs.prototype, "largeArcFlag", { get: function() { return this._largeArcFlag; }, set: function(largeArcFlag) { this._largeArcFlag = largeArcFlag; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegArcAbs.prototype, "sweepFlag", { get: function() { return this._sweepFlag; }, set: function(sweepFlag) { this._sweepFlag = sweepFlag; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegArcRel = function(owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_ARC_REL, "a", owningPathSegList); this._x = x; this._y = y; this._r1 = r1; this._r2 = r2; this._angle = angle; this._largeArcFlag = largeArcFlag; this._sweepFlag = sweepFlag; } SVGPathSegArcRel.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegArcRel.prototype.toString = function() { return "[object SVGPathSegArcRel]"; } SVGPathSegArcRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._r1 + " " + this._r2 + " " + this._angle + " " + (this._largeArcFlag ? "1" : "0") + " " + (this._sweepFlag ? "1" : "0") + " " + this._x + " " + this._y; } SVGPathSegArcRel.prototype.clone = function() { return new SVGPathSegArcRel(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); } Object.defineProperty(SVGPathSegArcRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegArcRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegArcRel.prototype, "r1", { get: function() { return this._r1; }, set: function(r1) { this._r1 = r1; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegArcRel.prototype, "r2", { get: function() { return this._r2; }, set: function(r2) { this._r2 = r2; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegArcRel.prototype, "angle", { get: function() { return this._angle; }, set: function(angle) { this._angle = angle; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegArcRel.prototype, "largeArcFlag", { get: function() { return this._largeArcFlag; }, set: function(largeArcFlag) { this._largeArcFlag = largeArcFlag; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegArcRel.prototype, "sweepFlag", { get: function() { return this._sweepFlag; }, set: function(sweepFlag) { this._sweepFlag = sweepFlag; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegLinetoHorizontalAbs = function(owningPathSegList, x) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS, "H", owningPathSegList); this._x = x; } SVGPathSegLinetoHorizontalAbs.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegLinetoHorizontalAbs.prototype.toString = function() { return "[object SVGPathSegLinetoHorizontalAbs]"; } SVGPathSegLinetoHorizontalAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x; } SVGPathSegLinetoHorizontalAbs.prototype.clone = function() { return new SVGPathSegLinetoHorizontalAbs(undefined, this._x); } Object.defineProperty(SVGPathSegLinetoHorizontalAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegLinetoHorizontalRel = function(owningPathSegList, x) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL, "h", owningPathSegList); this._x = x; } SVGPathSegLinetoHorizontalRel.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegLinetoHorizontalRel.prototype.toString = function() { return "[object SVGPathSegLinetoHorizontalRel]"; } SVGPathSegLinetoHorizontalRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x; } SVGPathSegLinetoHorizontalRel.prototype.clone = function() { return new SVGPathSegLinetoHorizontalRel(undefined, this._x); } Object.defineProperty(SVGPathSegLinetoHorizontalRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegLinetoVerticalAbs = function(owningPathSegList, y) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS, "V", owningPathSegList); this._y = y; } SVGPathSegLinetoVerticalAbs.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegLinetoVerticalAbs.prototype.toString = function() { return "[object SVGPathSegLinetoVerticalAbs]"; } SVGPathSegLinetoVerticalAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._y; } SVGPathSegLinetoVerticalAbs.prototype.clone = function() { return new SVGPathSegLinetoVerticalAbs(undefined, this._y); } Object.defineProperty(SVGPathSegLinetoVerticalAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegLinetoVerticalRel = function(owningPathSegList, y) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL, "v", owningPathSegList); this._y = y; } SVGPathSegLinetoVerticalRel.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegLinetoVerticalRel.prototype.toString = function() { return "[object SVGPathSegLinetoVerticalRel]"; } SVGPathSegLinetoVerticalRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._y; } SVGPathSegLinetoVerticalRel.prototype.clone = function() { return new SVGPathSegLinetoVerticalRel(undefined, this._y); } Object.defineProperty(SVGPathSegLinetoVerticalRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegCurvetoCubicSmoothAbs = function(owningPathSegList, x, y, x2, y2) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS, "S", owningPathSegList); this._x = x; this._y = y; this._x2 = x2; this._y2 = y2; } SVGPathSegCurvetoCubicSmoothAbs.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegCurvetoCubicSmoothAbs.prototype.toString = function() { return "[object SVGPathSegCurvetoCubicSmoothAbs]"; } SVGPathSegCurvetoCubicSmoothAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y; } SVGPathSegCurvetoCubicSmoothAbs.prototype.clone = function() { return new SVGPathSegCurvetoCubicSmoothAbs(undefined, this._x, this._y, this._x2, this._y2); } Object.defineProperty(SVGPathSegCurvetoCubicSmoothAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicSmoothAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicSmoothAbs.prototype, "x2", { get: function() { return this._x2; }, set: function(x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicSmoothAbs.prototype, "y2", { get: function() { return this._y2; }, set: function(y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegCurvetoCubicSmoothRel = function(owningPathSegList, x, y, x2, y2) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL, "s", owningPathSegList); this._x = x; this._y = y; this._x2 = x2; this._y2 = y2; } SVGPathSegCurvetoCubicSmoothRel.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegCurvetoCubicSmoothRel.prototype.toString = function() { return "[object SVGPathSegCurvetoCubicSmoothRel]"; } SVGPathSegCurvetoCubicSmoothRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y; } SVGPathSegCurvetoCubicSmoothRel.prototype.clone = function() { return new SVGPathSegCurvetoCubicSmoothRel(undefined, this._x, this._y, this._x2, this._y2); } Object.defineProperty(SVGPathSegCurvetoCubicSmoothRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicSmoothRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicSmoothRel.prototype, "x2", { get: function() { return this._x2; }, set: function(x2) { this._x2 = x2; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoCubicSmoothRel.prototype, "y2", { get: function() { return this._y2; }, set: function(y2) { this._y2 = y2; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegCurvetoQuadraticSmoothAbs = function(owningPathSegList, x, y) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS, "T", owningPathSegList); this._x = x; this._y = y; } SVGPathSegCurvetoQuadraticSmoothAbs.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegCurvetoQuadraticSmoothAbs.prototype.toString = function() { return "[object SVGPathSegCurvetoQuadraticSmoothAbs]"; } SVGPathSegCurvetoQuadraticSmoothAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x + " " + this._y; } SVGPathSegCurvetoQuadraticSmoothAbs.prototype.clone = function() { return new SVGPathSegCurvetoQuadraticSmoothAbs(undefined, this._x, this._y); } Object.defineProperty(SVGPathSegCurvetoQuadraticSmoothAbs.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoQuadraticSmoothAbs.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); window.SVGPathSegCurvetoQuadraticSmoothRel = function(owningPathSegList, x, y) { SVGPathSeg.call(this, SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL, "t", owningPathSegList); this._x = x; this._y = y; } SVGPathSegCurvetoQuadraticSmoothRel.prototype = Object.create(SVGPathSeg.prototype); SVGPathSegCurvetoQuadraticSmoothRel.prototype.toString = function() { return "[object SVGPathSegCurvetoQuadraticSmoothRel]"; } SVGPathSegCurvetoQuadraticSmoothRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + " " + this._x + " " + this._y; } SVGPathSegCurvetoQuadraticSmoothRel.prototype.clone = function() { return new SVGPathSegCurvetoQuadraticSmoothRel(undefined, this._x, this._y); } Object.defineProperty(SVGPathSegCurvetoQuadraticSmoothRel.prototype, "x", { get: function() { return this._x; }, set: function(x) { this._x = x; this._segmentChanged(); }, enumerable: true }); Object.defineProperty(SVGPathSegCurvetoQuadraticSmoothRel.prototype, "y", { get: function() { return this._y; }, set: function(y) { this._y = y; this._segmentChanged(); }, enumerable: true }); // Add createSVGPathSeg* functions to SVGPathElement. // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathElement. SVGPathElement.prototype.createSVGPathSegClosePath = function() { return new SVGPathSegClosePath(undefined); } SVGPathElement.prototype.createSVGPathSegMovetoAbs = function(x, y) { return new SVGPathSegMovetoAbs(undefined, x, y); } SVGPathElement.prototype.createSVGPathSegMovetoRel = function(x, y) { return new SVGPathSegMovetoRel(undefined, x, y); } SVGPathElement.prototype.createSVGPathSegLinetoAbs = function(x, y) { return new SVGPathSegLinetoAbs(undefined, x, y); } SVGPathElement.prototype.createSVGPathSegLinetoRel = function(x, y) { return new SVGPathSegLinetoRel(undefined, x, y); } SVGPathElement.prototype.createSVGPathSegCurvetoCubicAbs = function(x, y, x1, y1, x2, y2) { return new SVGPathSegCurvetoCubicAbs(undefined, x, y, x1, y1, x2, y2); } SVGPathElement.prototype.createSVGPathSegCurvetoCubicRel = function(x, y, x1, y1, x2, y2) { return new SVGPathSegCurvetoCubicRel(undefined, x, y, x1, y1, x2, y2); } SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticAbs = function(x, y, x1, y1) { return new SVGPathSegCurvetoQuadraticAbs(undefined, x, y, x1, y1); } SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticRel = function(x, y, x1, y1) { return new SVGPathSegCurvetoQuadraticRel(undefined, x, y, x1, y1); } SVGPathElement.prototype.createSVGPathSegArcAbs = function(x, y, r1, r2, angle, largeArcFlag, sweepFlag) { return new SVGPathSegArcAbs(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag); } SVGPathElement.prototype.createSVGPathSegArcRel = function(x, y, r1, r2, angle, largeArcFlag, sweepFlag) { return new SVGPathSegArcRel(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag); } SVGPathElement.prototype.createSVGPathSegLinetoHorizontalAbs = function(x) { return new SVGPathSegLinetoHorizontalAbs(undefined, x); } SVGPathElement.prototype.createSVGPathSegLinetoHorizontalRel = function(x) { return new SVGPathSegLinetoHorizontalRel(undefined, x); } SVGPathElement.prototype.createSVGPathSegLinetoVerticalAbs = function(y) { return new SVGPathSegLinetoVerticalAbs(undefined, y); } SVGPathElement.prototype.createSVGPathSegLinetoVerticalRel = function(y) { return new SVGPathSegLinetoVerticalRel(undefined, y); } SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothAbs = function(x, y, x2, y2) { return new SVGPathSegCurvetoCubicSmoothAbs(undefined, x, y, x2, y2); } SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothRel = function(x, y, x2, y2) { return new SVGPathSegCurvetoCubicSmoothRel(undefined, x, y, x2, y2); } SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothAbs = function(x, y) { return new SVGPathSegCurvetoQuadraticSmoothAbs(undefined, x, y); } SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothRel = function(x, y) { return new SVGPathSegCurvetoQuadraticSmoothRel(undefined, x, y); } } if (!("SVGPathSegList" in window)) { // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSegList window.SVGPathSegList = function(pathElement) { this._pathElement = pathElement; this._list = this._parsePath(this._pathElement.getAttribute("d")); // Use a MutationObserver to catch changes to the path's "d" attribute. this._mutationObserverConfig = { "attributes": true, "attributeFilter": ["d"] }; this._pathElementMutationObserver = new MutationObserver(this._updateListFromPathMutations.bind(this)); this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig); } Object.defineProperty(SVGPathSegList.prototype, "numberOfItems", { get: function() { this._checkPathSynchronizedToList(); return this._list.length; }, enumerable: true }); // Add the pathSegList accessors to SVGPathElement. // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGAnimatedPathData Object.defineProperty(SVGPathElement.prototype, "pathSegList", { get: function() { if (!this._pathSegList) this._pathSegList = new SVGPathSegList(this); return this._pathSegList; }, enumerable: true }); // FIXME: The following are not implemented and simply return SVGPathElement.pathSegList. Object.defineProperty(SVGPathElement.prototype, "normalizedPathSegList", { get: function() { return this.pathSegList; }, enumerable: true }); Object.defineProperty(SVGPathElement.prototype, "animatedPathSegList", { get: function() { return this.pathSegList; }, enumerable: true }); Object.defineProperty(SVGPathElement.prototype, "animatedNormalizedPathSegList", { get: function() { return this.pathSegList; }, enumerable: true }); // Process any pending mutations to the path element and update the list as needed. // This should be the first call of all public functions and is needed because // MutationObservers are not synchronous so we can have pending asynchronous mutations. SVGPathSegList.prototype._checkPathSynchronizedToList = function() { this._updateListFromPathMutations(this._pathElementMutationObserver.takeRecords()); } SVGPathSegList.prototype._updateListFromPathMutations = function(mutationRecords) { if (!this._pathElement) return; var hasPathMutations = false; mutationRecords.forEach(function(record) { if (record.attributeName == "d") hasPathMutations = true; }); if (hasPathMutations) this._list = this._parsePath(this._pathElement.getAttribute("d")); } // Serialize the list and update the path's 'd' attribute. SVGPathSegList.prototype._writeListToPath = function() { this._pathElementMutationObserver.disconnect(); this._pathElement.setAttribute("d", SVGPathSegList._pathSegArrayAsString(this._list)); this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig); } // When a path segment changes the list needs to be synchronized back to the path element. SVGPathSegList.prototype.segmentChanged = function(pathSeg) { this._writeListToPath(); } SVGPathSegList.prototype.clear = function() { this._checkPathSynchronizedToList(); this._list.forEach(function(pathSeg) { pathSeg._owningPathSegList = null; }); this._list = []; this._writeListToPath(); } SVGPathSegList.prototype.initialize = function(newItem) { this._checkPathSynchronizedToList(); this._list = [newItem]; newItem._owningPathSegList = this; this._writeListToPath(); return newItem; } SVGPathSegList.prototype._checkValidIndex = function(index) { if (isNaN(index) || index < 0 || index >= this.numberOfItems) throw "INDEX_SIZE_ERR"; } SVGPathSegList.prototype.getItem = function(index) { this._checkPathSynchronizedToList(); this._checkValidIndex(index); return this._list[index]; } SVGPathSegList.prototype.insertItemBefore = function(newItem, index) { this._checkPathSynchronizedToList(); // Spec: If the index is greater than or equal to numberOfItems, then the new item is appended to the end of the list. if (index > this.numberOfItems) index = this.numberOfItems; if (newItem._owningPathSegList) { // SVG2 spec says to make a copy. newItem = newItem.clone(); } this._list.splice(index, 0, newItem); newItem._owningPathSegList = this; this._writeListToPath(); return newItem; } SVGPathSegList.prototype.replaceItem = function(newItem, index) { this._checkPathSynchronizedToList(); if (newItem._owningPathSegList) { // SVG2 spec says to make a copy. newItem = newItem.clone(); } this._checkValidIndex(index); this._list[index] = newItem; newItem._owningPathSegList = this; this._writeListToPath(); return newItem; } SVGPathSegList.prototype.removeItem = function(index) { this._checkPathSynchronizedToList(); this._checkValidIndex(index); var item = this._list[index]; this._list.splice(index, 1); this._writeListToPath(); return item; } SVGPathSegList.prototype.appendItem = function(newItem) { this._checkPathSynchronizedToList(); if (newItem._owningPathSegList) { // SVG2 spec says to make a copy. newItem = newItem.clone(); } this._list.push(newItem); newItem._owningPathSegList = this; // TODO: Optimize this to just append to the existing attribute. this._writeListToPath(); return newItem; } SVGPathSegList._pathSegArrayAsString = function(pathSegArray) { var string = ""; var first = true; pathSegArray.forEach(function(pathSeg) { if (first) { first = false; string += pathSeg._asPathString(); } else { string += " " + pathSeg._asPathString(); } }); return string; } // This closely follows SVGPathParser::parsePath from Source/core/svg/SVGPathParser.cpp. SVGPathSegList.prototype._parsePath = function(string) { if (!string || string.length == 0) return []; var owningPathSegList = this; var Builder = function() { this.pathSegList = []; } Builder.prototype.appendSegment = function(pathSeg) { this.pathSegList.push(pathSeg); } var Source = function(string) { this._string = string; this._currentIndex = 0; this._endIndex = this._string.length; this._previousCommand = SVGPathSeg.PATHSEG_UNKNOWN; this._skipOptionalSpaces(); } Source.prototype._isCurrentSpace = function() { var character = this._string[this._currentIndex]; return character <= " " && (character == " " || character == "\n" || character == "\t" || character == "\r" || character == "\f"); } Source.prototype._skipOptionalSpaces = function() { while (this._currentIndex < this._endIndex && this._isCurrentSpace()) this._currentIndex++; return this._currentIndex < this._endIndex; } Source.prototype._skipOptionalSpacesOrDelimiter = function() { if (this._currentIndex < this._endIndex && !this._isCurrentSpace() && this._string.charAt(this._currentIndex) != ",") return false; if (this._skipOptionalSpaces()) { if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == ",") { this._currentIndex++; this._skipOptionalSpaces(); } } return this._currentIndex < this._endIndex; } Source.prototype.hasMoreData = function() { return this._currentIndex < this._endIndex; } Source.prototype.peekSegmentType = function() { var lookahead = this._string[this._currentIndex]; return this._pathSegTypeFromChar(lookahead); } Source.prototype._pathSegTypeFromChar = function(lookahead) { switch (lookahead) { case "Z": case "z": return SVGPathSeg.PATHSEG_CLOSEPATH; case "M": return SVGPathSeg.PATHSEG_MOVETO_ABS; case "m": return SVGPathSeg.PATHSEG_MOVETO_REL; case "L": return SVGPathSeg.PATHSEG_LINETO_ABS; case "l": return SVGPathSeg.PATHSEG_LINETO_REL; case "C": return SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS; case "c": return SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL; case "Q": return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS; case "q": return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL; case "A": return SVGPathSeg.PATHSEG_ARC_ABS; case "a": return SVGPathSeg.PATHSEG_ARC_REL; case "H": return SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS; case "h": return SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL; case "V": return SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS; case "v": return SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL; case "S": return SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS; case "s": return SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL; case "T": return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS; case "t": return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL; default: return SVGPathSeg.PATHSEG_UNKNOWN; } } Source.prototype._nextCommandHelper = function(lookahead, previousCommand) { // Check for remaining coordinates in the current command. if ((lookahead == "+" || lookahead == "-" || lookahead == "." || (lookahead >= "0" && lookahead <= "9")) && previousCommand != SVGPathSeg.PATHSEG_CLOSEPATH) { if (previousCommand == SVGPathSeg.PATHSEG_MOVETO_ABS) return SVGPathSeg.PATHSEG_LINETO_ABS; if (previousCommand == SVGPathSeg.PATHSEG_MOVETO_REL) return SVGPathSeg.PATHSEG_LINETO_REL; return previousCommand; } return SVGPathSeg.PATHSEG_UNKNOWN; } Source.prototype.initialCommandIsMoveTo = function() { // If the path is empty it is still valid, so return true. if (!this.hasMoreData()) return true; var command = this.peekSegmentType(); // Path must start with moveTo. return command == SVGPathSeg.PATHSEG_MOVETO_ABS || command == SVGPathSeg.PATHSEG_MOVETO_REL; } // Parse a number from an SVG path. This very closely follows genericParseNumber(...) from Source/core/svg/SVGParserUtilities.cpp. // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-PathDataBNF Source.prototype._parseNumber = function() { var exponent = 0; var integer = 0; var frac = 1; var decimal = 0; var sign = 1; var expsign = 1; var startIndex = this._currentIndex; this._skipOptionalSpaces(); // Read the sign. if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == "+") this._currentIndex++; else if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == "-") { this._currentIndex++; sign = -1; } if (this._currentIndex == this._endIndex || ((this._string.charAt(this._currentIndex) < "0" || this._string.charAt(this._currentIndex) > "9") && this._string.charAt(this._currentIndex) != ".")) // The first character of a number must be one of [0-9+-.]. return undefined; // Read the integer part, build right-to-left. var startIntPartIndex = this._currentIndex; while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= "0" && this._string.charAt(this._currentIndex) <= "9") this._currentIndex++; // Advance to first non-digit. if (this._currentIndex != startIntPartIndex) { var scanIntPartIndex = this._currentIndex - 1; var multiplier = 1; while (scanIntPartIndex >= startIntPartIndex) { integer += multiplier * (this._string.charAt(scanIntPartIndex--) - "0"); multiplier *= 10; } } // Read the decimals. if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == ".") { this._currentIndex++; // There must be a least one digit following the . if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < "0" || this._string.charAt(this._currentIndex) > "9") return undefined; while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= "0" && this._string.charAt(this._currentIndex) <= "9") decimal += (this._string.charAt(this._currentIndex++) - "0") * (frac *= 0.1); } // Read the exponent part. if (this._currentIndex != startIndex && this._currentIndex + 1 < this._endIndex && (this._string.charAt(this._currentIndex) == "e" || this._string.charAt(this._currentIndex) == "E") && (this._string.charAt(this._currentIndex + 1) != "x" && this._string.charAt(this._currentIndex + 1) != "m")) { this._currentIndex++; // Read the sign of the exponent. if (this._string.charAt(this._currentIndex) == "+") { this._currentIndex++; } else if (this._string.charAt(this._currentIndex) == "-") { this._currentIndex++; expsign = -1; } // There must be an exponent. if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < "0" || this._string.charAt(this._currentIndex) > "9") return undefined; while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= "0" && this._string.charAt(this._currentIndex) <= "9") { exponent *= 10; exponent += (this._string.charAt(this._currentIndex) - "0"); this._currentIndex++; } } var number = integer + decimal; number *= sign; if (exponent) number *= Math.pow(10, expsign * exponent); if (startIndex == this._currentIndex) return undefined; this._skipOptionalSpacesOrDelimiter(); return number; } Source.prototype._parseArcFlag = function() { if (this._currentIndex >= this._endIndex) return undefined; var flag = false; var flagChar = this._string.charAt(this._currentIndex++); if (flagChar == "0") flag = false; else if (flagChar == "1") flag = true; else return undefined; this._skipOptionalSpacesOrDelimiter(); return flag; } Source.prototype.parseSegment = function() { var lookahead = this._string[this._currentIndex]; var command = this._pathSegTypeFromChar(lookahead); if (command == SVGPathSeg.PATHSEG_UNKNOWN) { // Possibly an implicit command. Not allowed if this is the first command. if (this._previousCommand == SVGPathSeg.PATHSEG_UNKNOWN) return null; command = this._nextCommandHelper(lookahead, this._previousCommand); if (command == SVGPathSeg.PATHSEG_UNKNOWN) return null; } else { this._currentIndex++; } this._previousCommand = command; switch (command) { case SVGPathSeg.PATHSEG_MOVETO_REL: return new SVGPathSegMovetoRel(owningPathSegList, this._parseNumber(), this._parseNumber()); case SVGPathSeg.PATHSEG_MOVETO_ABS: return new SVGPathSegMovetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber()); case SVGPathSeg.PATHSEG_LINETO_REL: return new SVGPathSegLinetoRel(owningPathSegList, this._parseNumber(), this._parseNumber()); case SVGPathSeg.PATHSEG_LINETO_ABS: return new SVGPathSegLinetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber()); case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL: return new SVGPathSegLinetoHorizontalRel(owningPathSegList, this._parseNumber()); case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS: return new SVGPathSegLinetoHorizontalAbs(owningPathSegList, this._parseNumber()); case SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL: return new SVGPathSegLinetoVerticalRel(owningPathSegList, this._parseNumber()); case SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS: return new SVGPathSegLinetoVerticalAbs(owningPathSegList, this._parseNumber()); case SVGPathSeg.PATHSEG_CLOSEPATH: this._skipOptionalSpaces(); return new SVGPathSegClosePath(owningPathSegList); case SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL: var points = {x1: this._parseNumber(), y1: this._parseNumber(), x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()}; return new SVGPathSegCurvetoCubicRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2); case SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS: var points = {x1: this._parseNumber(), y1: this._parseNumber(), x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()}; return new SVGPathSegCurvetoCubicAbs(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2); case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL: var points = {x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()}; return new SVGPathSegCurvetoCubicSmoothRel(owningPathSegList, points.x, points.y, points.x2, points.y2); case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: var points = {x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()}; return new SVGPathSegCurvetoCubicSmoothAbs(owningPathSegList, points.x, points.y, points.x2, points.y2); case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL: var points = {x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()}; return new SVGPathSegCurvetoQuadraticRel(owningPathSegList, points.x, points.y, points.x1, points.y1); case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS: var points = {x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber()}; return new SVGPathSegCurvetoQuadraticAbs(owningPathSegList, points.x, points.y, points.x1, points.y1); case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: return new SVGPathSegCurvetoQuadraticSmoothRel(owningPathSegList, this._parseNumber(), this._parseNumber()); case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: return new SVGPathSegCurvetoQuadraticSmoothAbs(owningPathSegList, this._parseNumber(), this._parseNumber()); case SVGPathSeg.PATHSEG_ARC_REL: var points = {x1: this._parseNumber(), y1: this._parseNumber(), arcAngle: this._parseNumber(), arcLarge: this._parseArcFlag(), arcSweep: this._parseArcFlag(), x: this._parseNumber(), y: this._parseNumber()}; return new SVGPathSegArcRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep); case SVGPathSeg.PATHSEG_ARC_ABS: var points = {x1: this._parseNumber(), y1: this._parseNumber(), arcAngle: this._parseNumber(), arcLarge: this._parseArcFlag(), arcSweep: this._parseArcFlag(), x: this._parseNumber(), y: this._parseNumber()}; return new SVGPathSegArcAbs(owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep); default: throw "Unknown path seg type." } } var builder = new Builder(); var source = new Source(string); if (!source.initialCommandIsMoveTo()) return []; while (source.hasMoreData()) { var pathSeg = source.parseSegment(); if (!pathSeg) return []; builder.appendSegment(pathSeg); } return builder.pathSegList; } } }()); /* jshint ignore:end */ if (typeof define === 'function' && define.amd) { define("c3", ["d3"], function () { return c3; }); } else if ('undefined' !== typeof exports && 'undefined' !== typeof module) { module.exports = c3; } else { window.c3 = c3; } })(window);
joshuadeleon/typingclassifier
ML.TypingClassifier/Scripts/c3-0.4.11/c3.js
JavaScript
mit
375,568
/* * Decompiled with CFR 0_110. */ package edu.stanford.crypto.proof.assets; import edu.stanford.crypto.ECConstants; import edu.stanford.crypto.proof.MemoryProof; import org.bouncycastle.math.ec.ECPoint; import java.math.BigInteger; import java.util.Arrays; import java.util.List; public class AddressProof implements MemoryProof { private final ECPoint commitmentBalance; private final ECPoint commitmentXHat; private final BigInteger challengeZero; private final BigInteger challengeOne; private final BigInteger responseS; private final BigInteger responseV; private final BigInteger responseT; private final BigInteger responseXHat; private final BigInteger responseZero; private final BigInteger responseOne; public AddressProof(ECPoint commitmentBalance, ECPoint commitmentXHat, BigInteger challengeZero, BigInteger challengeOne, BigInteger responseS, BigInteger responseV, BigInteger responseT, BigInteger responseXHat, BigInteger responseZero, BigInteger responseOne) { this.commitmentBalance = commitmentBalance; this.commitmentXHat = commitmentXHat; this.challengeZero = challengeZero; this.challengeOne = challengeOne; this.responseS = responseS; this.responseV = responseV; this.responseT = responseT; this.responseXHat = responseXHat; this.responseZero = responseZero; this.responseOne = responseOne; } public AddressProof(byte[] array) { int index = 0; byte statementLength = array[index++]; this.commitmentBalance = ECConstants.BITCOIN_CURVE.decodePoint(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.commitmentXHat = ECConstants.BITCOIN_CURVE.decodePoint(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.challengeZero = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.challengeOne = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.responseS = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.responseT = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.responseV = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.responseXHat = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.responseZero = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.responseOne = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); } @Override public byte[] serialize() { byte[] commitmentBalanceEncoded = this.commitmentBalance.getEncoded(true); byte[] commitmentXHatEncoded = this.commitmentXHat.getEncoded(true); byte[] challengeZeroEncoded = this.challengeZero.toByteArray(); byte[] challengeOneEncoded = this.challengeOne.toByteArray(); byte[] responseSEncoded = this.responseS.toByteArray(); byte[] responseTEncoded = this.responseT.toByteArray(); byte[] responseVEncoded = this.responseV.toByteArray(); byte[] responseXHatEncoded = this.responseXHat.toByteArray(); byte[] responseZeroEncoded = this.responseZero.toByteArray(); byte[] responseOneEncoded = this.responseOne.toByteArray(); List<byte[]> arrList = Arrays.asList(commitmentBalanceEncoded, commitmentXHatEncoded, challengeZeroEncoded, challengeOneEncoded,responseSEncoded, responseTEncoded, responseVEncoded, responseXHatEncoded, responseZeroEncoded, responseOneEncoded); int totalLength = arrList.stream().mapToInt(arr -> arr.length).map(i -> i + 1).sum(); byte[] fullArray = new byte[totalLength]; int currIndex = 0; for (byte[] arr2 : arrList) { fullArray[currIndex++] = (byte) arr2.length; System.arraycopy(arr2, 0, fullArray, currIndex, arr2.length); currIndex += arr2.length; } return fullArray; } public BigInteger getChallengeZero() { return this.challengeZero; } public BigInteger getChallengeOne() { return challengeOne; } public BigInteger getResponseS() { return this.responseS; } public ECPoint getCommitmentBalance() { return this.commitmentBalance; } public ECPoint getCommitmentXHat() { return this.commitmentXHat; } public BigInteger getResponseV() { return this.responseV; } public BigInteger getResponseT() { return this.responseT; } public BigInteger getResponseXHat() { return this.responseXHat; } public BigInteger getResponseZero() { return responseZero; } public BigInteger getResponseOne() { return responseOne; } }
bbuenz/provisions
src/main/java/edu/stanford/crypto/proof/assets/AddressProof.java
Java
mit
5,567
function solve(args) { const module = 1024; let numbers = args.slice(1).map(Number), current, result = 0, i = 0; while (true) { if (i === 0) { current = numbers[i]; if (numbers.length === 1) { result = current; break; } i++; } if (numbers[i] % 2 === 0 || numbers[i] === 0) { current += numbers[i]; current = current % module; i += 2; if (i > numbers.length - 1) { result = current; break; } } else if (numbers[i] % 2 !== 0 || numbers[i] === 1) { current *= numbers[i]; current = current % module; i++; if (i > numbers.length - 1) { result = current; break; } } } console.log(result); } // tests solve([ '10', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' ]); console.log('------------'); solve([ '9', '9', '9', '9', '9', '9', '9', '9', '9', '9' ]); solve(['2', '2', '2', '2', '2', '2', '2', '2', '2']);
zachdimitrov/Learning_2017
JS-Fundamentals/00.ExamPrep/2017-01-19-Variant-2/1.Coki Skoki/cuki.js
JavaScript
mit
1,241
function populate(form) { form.options.length = 0; form.options[0] = new Option("Select a county of Georgia",""); form.options[1] = new Option("Appling County","Appling County"); form.options[2] = new Option("Atkinson County","Atkinson County"); form.options[3] = new Option("Bacon County","Bacon County"); form.options[4] = new Option("Baker County","Baker County"); form.options[5] = new Option("Baldwin County","Baldwin County"); form.options[6] = new Option("Banks County","Banks County"); form.options[7] = new Option("Barrow County","Barrow County"); form.options[8] = new Option("Bartow County","Bartow County"); form.options[9] = new Option("Ben Hill County","Ben Hill County"); form.options[10] = new Option("Berrien County","Berrien County"); form.options[11] = new Option("Bibb County","Bibb County"); form.options[12] = new Option("Bleckley County","Bleckley County"); form.options[13] = new Option("Brantley County","Brantley County"); form.options[14] = new Option("Brooks County","Brooks County"); form.options[15] = new Option("Bryan County","Bryan County"); form.options[16] = new Option("Bulloch County","Bulloch County"); form.options[17] = new Option("Burke County","Burke County"); form.options[18] = new Option("Butts County","Butts County"); form.options[19] = new Option("Calhoun County","Calhoun County"); form.options[20] = new Option("Camden County","Camden County"); form.options[21] = new Option("Candler County","Candler County"); form.options[22] = new Option("Carroll County","Carroll County"); form.options[23] = new Option("Catoosa County","Catoosa County"); form.options[24] = new Option("Charlton County","Charlton County"); form.options[25] = new Option("Chatham County","Chatham County"); form.options[26] = new Option("Chattahoochee County","Chattahoochee County"); form.options[27] = new Option("Chattooga County","Chattooga County"); form.options[28] = new Option("Cherokee County","Cherokee County"); form.options[29] = new Option("Clarke County","Clarke County"); form.options[30] = new Option("Clay County","Clay County"); form.options[31] = new Option("Clayton County","Clayton County"); form.options[32] = new Option("Clinch County","Clinch County"); form.options[33] = new Option("Cobb County","Cobb County"); form.options[34] = new Option("Coffee County","Coffee County"); form.options[35] = new Option("Colquitt County","Colquitt County"); form.options[36] = new Option("Columbia County","Columbia County"); form.options[37] = new Option("Cook County","Cook County"); form.options[38] = new Option("Coweta County","Coweta County"); form.options[39] = new Option("Crawford County","Crawford County"); form.options[40] = new Option("Crisp County","Crisp County"); form.options[41] = new Option("Dade County","Dade County"); form.options[42] = new Option("Dawson County","Dawson County"); form.options[43] = new Option("Decatur County","Decatur County"); form.options[44] = new Option("DeKalb County","DeKalb County"); form.options[45] = new Option("Dodge County","Dodge County"); form.options[46] = new Option("Dooly County","Dooly County"); form.options[47] = new Option("Dougherty County","Dougherty County"); form.options[48] = new Option("Douglas County","Douglas County"); form.options[49] = new Option("Early County","Early County"); form.options[50] = new Option("Echols County","Echols County"); form.options[51] = new Option("Effingham County","Effingham County"); form.options[52] = new Option("Elbert County","Elbert County"); form.options[53] = new Option("Emanuel County","Emanuel County"); form.options[54] = new Option("Evans County","Evans County"); form.options[55] = new Option("Fannin County","Fannin County"); form.options[56] = new Option("Fayette County","Fayette County"); form.options[57] = new Option("Floyd County","Floyd County"); form.options[58] = new Option("Forsyth County","Forsyth County"); form.options[59] = new Option("Franklin County","Franklin County"); form.options[60] = new Option("Fulton County","Fulton County"); form.options[61] = new Option("Gilmer County","Gilmer County"); form.options[62] = new Option("Glascock County","Glascock County"); form.options[63] = new Option("Glynn County","Glynn County"); form.options[64] = new Option("Gordon County","Gordon County"); form.options[65] = new Option("Grady County","Grady County"); form.options[66] = new Option("Greene County","Greene County"); form.options[67] = new Option("Gwinnett County","Gwinnett County"); form.options[68] = new Option("Habersham County","Habersham County"); form.options[69] = new Option("Hall County","Hall County"); form.options[70] = new Option("Hancock County","Hancock County"); form.options[71] = new Option("Haralson County","Haralson County"); form.options[72] = new Option("Harris County","Harris County"); form.options[73] = new Option("Hart County","Hart County"); form.options[74] = new Option("Heard County","Heard County"); form.options[75] = new Option("Henry County","Henry County"); form.options[76] = new Option("Houston County","Houston County"); form.options[77] = new Option("Irwin County","Irwin County"); form.options[78] = new Option("Jackson County","Jackson County"); form.options[79] = new Option("Jasper County","Jasper County"); form.options[80] = new Option("Jeff Davis County","Jeff Davis County"); form.options[81] = new Option("Jefferson County","Jefferson County"); form.options[82] = new Option("Jenkins County","Jenkins County"); form.options[83] = new Option("Johnson County","Johnson County"); form.options[84] = new Option("Jones County","Jones County"); form.options[85] = new Option("Lamar County","Lamar County"); form.options[86] = new Option("Lanier County","Lanier County"); form.options[87] = new Option("Laurens County","Laurens County"); form.options[88] = new Option("Lee County","Lee County"); form.options[89] = new Option("Liberty County","Liberty County"); form.options[90] = new Option("Lincoln County","Lincoln County"); form.options[91] = new Option("Long County","Long County"); form.options[92] = new Option("Lowndes County","Lowndes County"); form.options[93] = new Option("Lumpkin County","Lumpkin County"); form.options[94] = new Option("Macon County","Macon County"); form.options[95] = new Option("Madison County","Madison County"); form.options[96] = new Option("Marion County","Marion County"); form.options[97] = new Option("McDuffie County","McDuffie County"); form.options[98] = new Option("McIntosh County","McIntosh County"); form.options[99] = new Option("Meriwether County","Meriwether County"); form.options[100] = new Option("Miller County","Miller County"); form.options[101] = new Option("Mitchell County","Mitchell County"); form.options[102] = new Option("Monroe County","Monroe County"); form.options[103] = new Option("Montgomery County","Montgomery County"); form.options[104] = new Option("Morgan County","Morgan County"); form.options[105] = new Option("Murray County","Murray County"); form.options[106] = new Option("Muscogee County","Muscogee County"); form.options[107] = new Option("Newton County","Newton County"); form.options[108] = new Option("Oconee County","Oconee County"); form.options[109] = new Option("Oglethorpe County","Oglethorpe County"); form.options[110] = new Option("Paulding County","Paulding County"); form.options[111] = new Option("Peach County","Peach County"); form.options[112] = new Option("Pickens County","Pickens County"); form.options[113] = new Option("Pierce County","Pierce County"); form.options[114] = new Option("Pike County","Pike County"); form.options[115] = new Option("Polk County","Polk County"); form.options[116] = new Option("Pulaski County","Pulaski County"); form.options[117] = new Option("Putnam County","Putnam County"); form.options[118] = new Option("Quitman County","Quitman County"); form.options[119] = new Option("Rabun County","Rabun County"); form.options[120] = new Option("Randolph County","Randolph County"); form.options[121] = new Option("Richmond County","Richmond County"); form.options[122] = new Option("Rockdale County","Rockdale County"); form.options[123] = new Option("Schley County","Schley County"); form.options[124] = new Option("Screven County","Screven County"); form.options[125] = new Option("Seminole County","Seminole County"); form.options[126] = new Option("Spalding County","Spalding County"); form.options[127] = new Option("Stephens County","Stephens County"); form.options[128] = new Option("Stewart County","Stewart County"); form.options[129] = new Option("Sumter County","Sumter County"); form.options[130] = new Option("Talbot County","Talbot County"); form.options[131] = new Option("Taliaferro County","Taliaferro County"); form.options[132] = new Option("Tattnall County","Tattnall County"); form.options[133] = new Option("Taylor County","Taylor County"); form.options[134] = new Option("Telfair County","Telfair County"); form.options[135] = new Option("Terrell County","Terrell County"); form.options[136] = new Option("Thomas County","Thomas County"); form.options[137] = new Option("Tift County","Tift County"); form.options[138] = new Option("Toombs County","Toombs County"); form.options[139] = new Option("Towns County","Towns County"); form.options[140] = new Option("Treutlen County","Treutlen County"); form.options[141] = new Option("Troup County","Troup County"); form.options[142] = new Option("Turner County","Turner County"); form.options[143] = new Option("Twiggs County","Twiggs County"); form.options[144] = new Option("Union County","Union County"); form.options[145] = new Option("Upson County","Upson County"); form.options[146] = new Option("Walker County","Walker County"); form.options[147] = new Option("Walton County","Walton County"); form.options[148] = new Option("Ware County","Ware County"); form.options[149] = new Option("Warren County","Warren County"); form.options[150] = new Option("Washington County","Washington County"); form.options[151] = new Option("Wayne County","Wayne County"); form.options[152] = new Option("Webster County","Webster County"); form.options[153] = new Option("Wheeler County","Wheeler County"); form.options[154] = new Option("White County","White County"); form.options[155] = new Option("Whitfield County","Whitfield County"); form.options[156] = new Option("Wilcox County","Wilcox County"); form.options[157] = new Option("Wilkes County","Wilkes County"); form.options[158] = new Option("Wilkinson County","Wilkinson County"); form.options[159] = new Option("Worth County","Worth County"); }
CMIP5/HUC8Climate
website/ui/assets/js/states/ga.js
JavaScript
mit
10,508
/** * Created by chenqx on 8/5/15. * @hack 添加三角形绘制提交方式 */ /** * 以四边形填充 * @constant * @type {number} */ qc.BATCH_QUAD = 0; /** * 以三角形填充 * @constant * @type {number} */ qc.BATCH_TRIANGLES = 1; var oldWebGLSpriteBatchSetContext = PIXI.WebGLSpriteBatch.prototype.setContext; PIXI.WebGLSpriteBatch.prototype.setContext = function(gl) { oldWebGLSpriteBatchSetContext.call(this, gl); this.quadSize = this.size; this.triangleSize = 300; this.batchIndexNumber = 6; var triangleIndicesNum = this.triangleSize * 3; this.triangleIndices = new PIXI.Uint16Array(triangleIndicesNum); for (var i = 0; i < triangleIndicesNum; ++i) { this.triangleIndices[i] = i; } this._batchType = qc.BATCH_QUAD; this.quadIndexBuffer = this.indexBuffer; this.triangleIndexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.triangleIndexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.triangleIndices, gl.STATIC_DRAW); }; var oldWebGLSpriteBatchDestroy = PIXI.WebGLSpriteBatch.prototype.destroy; PIXI.WebGLSpriteBatch.prototype.destroy = function() { this.triangleIndices = null; this.gl.deleteBuffer(this.triangleIndexBuffer); oldWebGLSpriteBatchDestroy.call(this); } Object.defineProperties(PIXI.WebGLSpriteBatch.prototype,{ batchType : { get : function() { return this._batchType; }, set : function(v) { if (v === this._batchType) { return; } this.stop(); // 切换IndexBuffer,Size if (v === qc.BATCH_TRIANGLES) { this.size = this.triangleSize; this.indexBuffer = this.triangleIndexBuffer; this._batchType = v; this.batchIndexNumber = 3; } else { this.size = this.quadSize; this.indexBuffer = this.quadIndexBuffer; this._batchType = v; this.batchIndexNumber = 6; } this.start(); } } }); /** * @method renderBatch * @param texture {Texture} * @param size {Number} * @param startIndex {Number} */ PIXI.WebGLSpriteBatch.prototype.renderBatch = function(texture, size, startIndex) { if(size === 0)return; var gl = this.gl; // check if a texture is dirty.. if(texture._dirty[gl.id]) { this.renderSession.renderer.updateTexture(texture); } else { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } //gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.batchIndexNumber === 3 ? this.triangleIndexBuffer : this.indexBuffer); // now draw those suckas! gl.drawElements(gl.TRIANGLES, size * this.batchIndexNumber, gl.UNSIGNED_SHORT, startIndex * this.batchIndexNumber * 2); // increment the draw count this.renderSession.drawCount++; };
qiciengine/qiciengine-core
src/hack/pixi/WebGLSpriteBatch.js
JavaScript
mit
2,960
package com.rogoapp; import com.rogoapp.auth.RegisterActivity; import android.app.Activity; import android.accounts.AccountAuthenticatorActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class LoginActivity extends Activity { EditText email; EditText password; Button loginButton; Button cancelButton; TextView registerButton; public static final String PARAM_AUTHTOKEN_TYPE = "auth.token"; public static final String PARAM_CREATE = "create"; public static final int REQ_CODE_CREATE = 1; public static final int REQ_CODE_UPDATE = 2; public static final String EXTRA_REQUEST_CODE = "req.code"; public static final int RESP_CODE_SUCCESS = 0; public static final int RESP_CODE_ERROR = 1; public static final int RESP_CODE_CANCEL = 2; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.login); } public void onClick(View v) { // Switch to main activity Intent i = new Intent(getApplicationContext(),MainScreenActivity.class); startActivity(i); } public void addListenerOnButton1() { registerButton = (Button) findViewById(R.id.link_to_register); registerButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { openRegistrationScreen(arg0); } }); } public void openRegistrationScreen(View v){ final Context context = this; Intent intent = new Intent(context, RegisterActivity.class); startActivity(intent); } public void onCancelClick(View V){ System.exit(0); } public void addListenerOnButtonCancel(){ cancelButton = (Button) findViewById(R.id.on_Cancel_Click); cancelButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0){ openRegistrationScreen(arg0); } }); } }
Nirespire/Rogo
Android/src/com/rogoapp/LoginActivity.java
Java
mit
2,167
import pytest from clustaar.authorize.conditions import TrueCondition @pytest.fixture def condition(): return TrueCondition() class TestCall(object): def test_returns_true(self, condition): assert condition({})
Clustaar/clustaar.authorize
tests/authorize/conditions/test_true_condition.py
Python
mit
231