text
stringlengths 3
1.05M
|
|---|
var searchData=
[
['dealer',['dealer',['../classjp_1_1gr_1_1java__conf_1_1yuta__yoshinaga_1_1java__trumpcards_1_1_black_jack.html#a01acee20012cd234246a1b058cc9d8c0',1,'jp::gr::java_conf::yuta_yoshinaga::java_trumpcards::BlackJack']]],
['dealerhit',['dealerHit',['../classjp_1_1gr_1_1java__conf_1_1yuta__yoshinaga_1_1java__trumpcards_1_1_black_jack.html#a3db7b3231ab583af54941a41517954ea',1,'jp::gr::java_conf::yuta_yoshinaga::java_trumpcards::BlackJack']]],
['dealerstand',['dealerStand',['../classjp_1_1gr_1_1java__conf_1_1yuta__yoshinaga_1_1java__trumpcards_1_1_black_jack.html#a49f2f12998ffa9892f4e8212f85afc7f',1,'jp::gr::java_conf::yuta_yoshinaga::java_trumpcards::BlackJack']]],
['deck',['deck',['../classjp_1_1gr_1_1java__conf_1_1yuta__yoshinaga_1_1java__trumpcards_1_1_trump_cards.html#a313f49864c7810e4fdcd26ecd3e89ec9',1,'jp::gr::java_conf::yuta_yoshinaga::java_trumpcards::TrumpCards']]],
['deckcnt',['deckCnt',['../classjp_1_1gr_1_1java__conf_1_1yuta__yoshinaga_1_1java__trumpcards_1_1_trump_cards.html#af6c55082de7cb0c1a873e97ce45a8597',1,'jp::gr::java_conf::yuta_yoshinaga::java_trumpcards::TrumpCards']]],
['deckdrowcnt',['deckDrowCnt',['../classjp_1_1gr_1_1java__conf_1_1yuta__yoshinaga_1_1java__trumpcards_1_1_trump_cards.html#a07cfdc2af869e26718dcdee36c661c38',1,'jp::gr::java_conf::yuta_yoshinaga::java_trumpcards::TrumpCards']]],
['deckdrowflaginit',['deckDrowFlagInit',['../classjp_1_1gr_1_1java__conf_1_1yuta__yoshinaga_1_1java__trumpcards_1_1_trump_cards.html#aa1db686e11e2c281976505d527eaffbd',1,'jp::gr::java_conf::yuta_yoshinaga::java_trumpcards::TrumpCards']]],
['deckinit',['deckInit',['../classjp_1_1gr_1_1java__conf_1_1yuta__yoshinaga_1_1java__trumpcards_1_1_trump_cards.html#af1a1d8299e1e79a272351c9e4b4026fa',1,'jp::gr::java_conf::yuta_yoshinaga::java_trumpcards::TrumpCards']]],
['drowcard',['drowCard',['../classjp_1_1gr_1_1java__conf_1_1yuta__yoshinaga_1_1java__trumpcards_1_1_trump_cards.html#a762812743e7d271596147b7dbcdd4ada',1,'jp::gr::java_conf::yuta_yoshinaga::java_trumpcards::TrumpCards']]],
['drowflag',['drowFlag',['../classjp_1_1gr_1_1java__conf_1_1yuta__yoshinaga_1_1java__trumpcards_1_1_card.html#a5ea32985f61009d9e2a99733299bc659',1,'jp::gr::java_conf::yuta_yoshinaga::java_trumpcards::Card']]]
];
|
/**
* @fileoverview Implements x86 video hardware
* @author Jeff Parsons <Jeff@pcjs.org>
* @copyright © 2012-2020 Jeff Parsons
* @license MIT <https://www.pcjs.org/LICENSE.txt>
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*/
import Monitor from "../../modules/monitor.js";
/**
* @typedef {MonitorConfig} PCx86VideoConfig
* @property {number} bufferWidth
* @property {number} bufferHeight
* @property {number} bufferAddr
* @property {number} bufferBits
* @property {number} bufferLeft
* @property {number} interruptRate
*/
/**
* @class {PCx86Video}
* @unrestricted
* @property {PCx86VideoConfig} config
*/
export default class PCx86Video extends Monitor {
/**
* PCx86Video(idMachine, idDevice, config)
*
* The PCx86Video component can be configured with the following config properties:
*
* bufferWidth: the width of a single frame buffer row, in pixels (eg, 256)
* bufferHeight: the number of frame buffer rows (eg, 224)
* bufferAddr: the starting address of the frame buffer (eg, 0x2400)
* bufferRAM: true to use existing RAM (default is false)
* bufferBits: the number of bits per column (default is 1)
* bufferLeft: the bit position of the left-most pixel in a byte (default is 0; CGA uses 7)
* bufferRotate: the amount of counter-clockwise buffer rotation required (eg, -90 or 270)
* interruptRate: normally the same as (or some multiple of) refreshRate (eg, 120)
* refreshRate: how many times updateMonitor() should be performed per second (eg, 60)
*
* We record all the above values now, but we defer creation of the frame buffer until initBuffers()
* is called. At that point, we will also compute the extent of the frame buffer, determine the
* appropriate "cell" size (ie, the number of pixels that updateMonitor() will fetch and process at once),
* and then allocate our cell cache.
*
* @this {PCx86Video}
* @param {string} idMachine
* @param {string} idDevice
* @param {ROMConfig} [config]
*/
constructor(idMachine, idDevice, config)
{
super(idMachine, idDevice, config);
let video = this
this.addrBuffer = this.config['bufferAddr'];
this.nColsBuffer = this.config['bufferWidth'];
this.nRowsBuffer = this.config['bufferHeight'];
this.cxCell = this.config['cellWidth'] || 1;
this.cyCell = this.config['cellHeight'] || 1;
this.rateInterrupt = this.config['interruptRate'];
this.rateRefresh = this.config['refreshRate'] || 60;
this.cxMonitorCell = (this.cxMonitor / this.nColsBuffer)|0;
this.cyMonitorCell = (this.cyMonitor / this.nRowsBuffer)|0;
this.busMemory = /** @type {Bus} */ (this.findDevice(this.config['bus']));
// this.initBuffers();
this.cpu = /** @type {CPUx86} */ (this.findDeviceByClass("CPU"));
this.time = /** @type {Time} */ (this.findDeviceByClass("Time"));
this.timerUpdateNext = this.time.addTimer(this.idDevice, this.updateMonitor.bind(this));
this.time.addUpdate(this);
this.time.setTimer(this.timerUpdateNext, this.getRefreshTime());
this.nUpdates = 0;
}
/**
* onUpdate(fTransition)
*
* This is our obligatory update() function, which every device with visual components should have.
*
* For the video device, our sole function is making sure the screen display is up-to-date. However, calling
* updateScreen() is a bad idea if the machine is running, because we already have a timer to take care of
* that. But we can also be called when the machine is NOT running (eg, the Debugger may be stepping through
* some code, or editing the frame buffer directly, or something else). Since we have no way of knowing, we
* must force an update.
*
* @this {PCx86Video}
* @param {boolean} [fTransition]
*/
onUpdate(fTransition)
{
if (!this.time.isRunning()) this.updateScreen();
}
/**
* getRefreshTime()
*
* @this {PCx86Video}
* @returns {number} (number of milliseconds per refresh)
*/
getRefreshTime()
{
return 1000 / Math.max(this.rateRefresh, this.rateInterrupt);
}
/**
* initCache(nCells)
*
* Initializes the contents of our internal cell cache.
*
* @this {PCx86Video}
* @param {number} [nCells]
*/
initCache(nCells)
{
this.fCacheValid = false;
if (nCells) {
this.nCacheCells = nCells;
if (this.aCacheCells === undefined || this.aCacheCells.length != this.nCacheCells) {
this.aCacheCells = new Array(this.nCacheCells);
}
}
}
/**
* updateMonitor(fForced)
*
* Forced updates are generally internal updates triggered by an I/O operation or other state change,
* while non-forced updates are periodic "refresh" updates.
*
* @this {PCx86Video}
* @param {boolean} [fForced]
*/
updateMonitor(fForced)
{
let fUpdate = true;
if (!fForced) {
/*
* Since this is not a forced update, if our cell cache is valid AND we allocated our own buffer AND the buffer
* is clean, then there's nothing to do.
*/
if (fUpdate && this.fCacheValid && this.sizeBuffer) {
if (this.busMemory.cleanBlocks(this.addrBuffer, this.sizeBuffer)) {
fUpdate = false;
}
}
this.time.setTimer(this.timerUpdateNext, this.getRefreshTime());
this.nUpdates++;
if (!fUpdate) return;
}
this.updateScreen();
}
/**
* updateScreen()
*
* Propagates the video buffer to the cell cache and updates the screen with any changes on the monitor.
*
* For every cell in the video buffer, compare it to the cell stored in the cell cache, render if it differs,
* and then update the cell cache to match. Since initCache() sets every cell in the cell cache to an
* invalid value, we're assured that the next call to updateScreen() will redraw the entire (visible) video buffer.
*
* @this {PCx86Video}
*/
updateScreen()
{
}
}
PCx86Video.CLASSES["PCx86Video"] = PCx86Video;
|
/*global define*/
define([
'../ThirdParty/when',
'./defaultValue',
'./defined',
'./DeveloperError',
'./isCrossOriginUrl'
], function(
when,
defaultValue,
defined,
DeveloperError,
isCrossOriginUrl) {
"use strict";
var dataUriRegex = /^data:/;
/**
* Asynchronously loads the given image URL. Returns a promise that will resolve to
* an {@link Image} once loaded, or reject if the image failed to load.
*
* @exports loadImage
*
* @param {String|Promise} url The source of the image, or a promise for the URL.
* @param {Boolean} [allowCrossOrigin=true] Whether to request the image using Cross-Origin
* Resource Sharing (CORS). CORS is only actually used if the image URL is actually cross-origin.
* Data URIs are never requested using CORS.
* @returns {Promise} a promise that will resolve to the requested data when loaded.
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*
* @example
* // load a single image asynchronously
* Cesium.loadImage('some/image/url.png').then(function(image) {
* // use the loaded image
* }).otherwise(function(error) {
* // an error occurred
* });
*
* // load several images in parallel
* when.all([loadImage('image1.png'), loadImage('image2.png')]).then(function(images) {
* // images is an array containing all the loaded images
* });
*/
var loadImage = function(url, allowCrossOrigin) {
//>>includeStart('debug', pragmas.debug);
if (!defined(url)) {
throw new DeveloperError('url is required.');
}
//>>includeEnd('debug');
allowCrossOrigin = defaultValue(allowCrossOrigin, true);
return when(url, function(url) {
var crossOrigin;
// data URIs can't have allowCrossOrigin set.
if (dataUriRegex.test(url) || !allowCrossOrigin) {
crossOrigin = false;
} else {
crossOrigin = isCrossOriginUrl(url);
}
var deferred = when.defer();
loadImage.createImage(url, crossOrigin, deferred);
return deferred.promise;
});
};
// This is broken out into a separate function so that it can be mocked for testing purposes.
loadImage.createImage = function(url, crossOrigin, deferred) {
var image = new Image();
image.onload = function(e) {
deferred.resolve(image);
};
image.onerror = function(e) {
deferred.reject(e);
};
if (crossOrigin) {
image.crossOrigin = '';
}
image.src = url;
};
loadImage.defaultCreateImage = loadImage.createImage;
return loadImage;
});
|
import React, { Component } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faTwitterSquare, faLinkedin, faGithub } from '@fortawesome/free-brands-svg-icons';
//import './social.css';
const iconLinkedin = (
<FontAwesomeIcon icon={faLinkedin} className="fa-fw fa-lg" />
);
const iconGithub = (
<FontAwesomeIcon icon={faGithub} className="fa-fw fa-lg" />
);
const iconTwitter = (
<FontAwesomeIcon icon={faTwitterSquare} className="fa-fw fa-lg" />
);
class Social extends Component {
render() {
return (
<div className="social">
<a href="http://twitter.com/toddaa">{iconTwitter}</a>
<a href="http://github.com/toddaa">{iconGithub}</a>
<a href="http://linkedin.com/in/toddaa">{iconLinkedin}</a>
</div>
)
}
}
export default Social;
|
'use strict';
/**
* Execute Order
* @param {object} headers
* @param {string} accountId
* @param {string} orderId
* @return {object} data
*/
const request = require('superagent');
const endpoints = require('../util/endpoints');
module.exports = (headers, account_id, order_id) => {
const endpoint = endpoints['cancelOrder'](account_id,order_id);
return request
.delete(`${endpoint}`)
.set(headers)
.send()
.then(res => {
const {
body: {
data
}
} = res;
return data;
});
}
|
import streamlit as st
from pages import page_exploration, page_resultados
st.title("Prototipo Pacientes")
play = st.sidebar.checkbox('Exploration mode')
try:
if play:
page_exploration()
else:
page = st.sidebar.selectbox('Pagina',['Serologia Comunitario',
'Resultados Moleculares',
'Resultados de Sintomáticos',
'Encuesta CAP'])
if page =='Resultados de Sintomáticos':
page_resultados()
elif page=='Encuesta CAP':
page_resultados()
except:
st.write("""
Ups!, Prueba cambiar la agrupación de Color.
""")
pass
|
from nlengine import nlengine #for natural language processing
from flask import Flask,request,jsonify
from query import queryrunner #for database access
import json
import sys
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def send_recieve():
if request.method=='POST':
#if there is incoming data from front end
try:
data = json.loads(request.data.decode('utf-8')) #loading json data recieved
log(data)
except (ValueError,TypeError,KeyError):
print("Error caught")
return json.dumps({'label': 'error'})
if data['label']=="text":
#for voice commands
k=nlengine(data["request"])
message=k.getResult()
k=message["bookread"]
if k=="y":
#if need database access
message['barcode']=data['barcode']
k=queryrunner(message)
message=k.getoutput()
log(message)
return json.dumps(message)
else:
#button clicks
k=queryrunner(data)
message=k.getoutput()
message=json.dumps(message)
log(message)
return message
def log(message):
if message:
print(str(message))
sys.stdout.flush()
else:
print("NULL")
sys.stdout.flush()
port_=int(sys.argv[1])
if __name__ == '__main__':
app.debug = True
app.run(host='192.168.43.29',port=port_)
|
import re
import os
import sys
import json
import logging
import platform
import amazon_pay.ap_region as ap_region
import amazon_pay.version as ap_version
from amazon_pay.payment_request import PaymentRequest
from fileinput import filename
class AmazonPayClient:
logger = logging.getLogger('__amazon_pay_sdk__')
logger.addHandler(logging.NullHandler())
"""This client allows you to make all the necessary API calls to
integrate with Amazon Pay.
"""
# pylint: disable=too-many-instance-attributes, too-many-public-methods
# pylint: disable=too-many-arguments, too-many-lines
def __init__(
self,
mws_access_key=None,
mws_secret_key=None,
merchant_id=None,
region=None,
currency_code=None,
sandbox=False,
handle_throttle=True,
application_name=None,
application_version=None,
log_enabled=False,
log_file_name=None,
log_level=None):
"""
Parameters
----------
mws_access_key : string, optional
Your MWS access key. If no value is passed, check environment.
Environment variable: AP_MWS_ACCESS_KEY
(mws_access_key must be passed or specified in environment or this
will result in an error)
mws_secret_key : string, optional
Your MWS secret key. If no value is passed, check environment.
Environment variable: AP_MWS_SECRET_KEY
(mws_secret_key must be passed or specified in environment or this
will result in an error)
merchant_id : string, optional
Your merchant ID. If you are a marketplace enter the seller's merchant
ID. If no value is passed, check environment.
Environment variable: AP_MERCHANT_ID
(merchant_id must be passed or specified in environment or this
will result in an error)
region : string, optional
The region in which you are conducting business. If no value is
passed, check environment.
Environment variable: AP_REGION
(region must be passed or specified in environment or this
will result in an error)
sandbox : string, optional
Toggle sandbox mode. Default: False.
currency_code: string, required
Currency code for your region.
Environment variable: AP_CURRENCY_CODE
handle_throttle: boolean, optional
If requests are throttled, do you want this client to pause and
retry? Default: True
application_name: string, optional
The name of your application. This will get set in the UserAgent.
Default: None
application_version: string, optional
Your application version. This will get set in the UserAgent.
Default: None
log_file_name: string, optional
The name of the file for logging
Default: None
log_level: integer, optional
The level of logging recorded
Default: "None"
Levels: "CRITICAL"; "ERROR"; "WARNING"; "INFO"; "DEBUG"; "NOTSET"
"""
env_param_map = {'mws_access_key': 'AP_MWS_ACCESS_KEY',
'mws_secret_key': 'AP_MWS_SECRET_KEY',
'merchant_id': 'AP_MERCHANT_ID',
'region': 'AP_REGION',
'currency_code': 'AP_CURRENCY_CODE'}
for param in env_param_map:
if eval(param) is None:
try:
setattr(self, param, os.environ[env_param_map[param]])
except:
raise ValueError('Invalid {}.'.format(param))
else:
setattr(self, param, eval(param))
try:
self._region = ap_region.regions[self.region]
# used for Login with Amazon helper
self._region_code = self.region
except KeyError:
raise KeyError('Invalid region code ({})'.format(self.region))
self.mws_access_key = self.mws_access_key
self.mws_secret_key = self.mws_secret_key
self.merchant_id = self.merchant_id
self.currency_code = self.currency_code
self.handle_throttle = handle_throttle
self.application_name = application_name
self.application_version = application_version
self._sandbox = sandbox
self._api_version = ap_version.versions['api_version']
self._application_library_version = ap_version.versions[
'application_version']
self._mws_endpoint = None
self._set_endpoint()
if log_enabled is not False:
numeric_level = getattr(logging, log_level.upper(), None)
if numeric_level is not None:
if log_file_name is not None:
self.logger.setLevel(numeric_level)
fh = logging.FileHandler(log_file_name)
self.logger.addHandler(fh)
fh.setLevel(numeric_level)
else:
self.logger.setLevel(numeric_level)
ch = logging.StreamHandler(sys.stdout)
self.logger.addHandler(ch)
ch.setLevel(numeric_level)
app_name_and_ver = ''
if application_name not in ['', None]:
app_name_and_ver = app_name_and_ver + str(application_name)
if application_version not in ['', None]:
app_name_and_ver = app_name_and_ver + '/' + str(application_version)
elif application_version not in ['', None]:
app_name_and_ver = app_name_and_ver + str(application_version)
if ((application_name not in ['', None]) | (application_version not in ['', None])):
app_name_and_ver = app_name_and_ver + '; '
current_py_ver = ".".join(map(str, sys.version_info[:3]))
self._user_agent = 'amazon-pay-sdk-python/{0} ({1}Python/{2}; {3}/{4})'.format(
str(self._application_library_version),
str(app_name_and_ver),
str(current_py_ver),
str(platform.system()),
str(platform.release())
)
self.logger.debug('user agent: %s', self._user_agent)
self._headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': self._user_agent}
@property
def sandbox(self):
return self._sandbox
@sandbox.setter
def sandbox(self, value):
"""Set Sandbox mode"""
self._sandbox = value
self._set_endpoint()
def _set_endpoint(self):
"""Set endpoint for API calls"""
if self._sandbox:
self._mws_endpoint = \
'https://{}/OffAmazonPayments_Sandbox/{}'.format(
self._region, self._api_version)
else:
self._mws_endpoint = \
'https://{}/OffAmazonPayments/{}'.format(
self._region, self._api_version)
def get_login_profile(self, access_token, client_id):
"""Get profile associated with LWA user. This is a helper method for
Login with Amazon (separate service). Added here for convenience.
"""
from amazon_pay.login_with_amazon import LoginWithAmazon
lwa_client = LoginWithAmazon(
client_id=client_id,
region=self._region_code,
sandbox=self._sandbox)
response = lwa_client.get_login_profile(access_token=access_token)
return response
def get_merchant_account_status(
self,
merchant_id=None,
mws_auth_token=None):
""" Check the account status of the merchant
Parameters
----------
merchant_id : string, optional
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'GetMerchantAccountStatus'
}
optionals = {
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def create_order_reference_for_id(
self,
object_id,
object_id_type,
order_total,
inherit_shipping_address=True,
confirm_now=False,
platform_id=None,
seller_note=None,
seller_order_id=None,
store_name=None,
custom_information=None,
merchant_id=None,
mws_auth_token=None,
supplementary_data=None):
# pylint: disable=too-many-arguments
"""Creates an order reference for the given object.
Parameters
----------
object_id : string, required
The identifier of the object to be used to create an order reference.
object_id_type : string, required
The type of the object represented by the Id request parameter.
order_total : string, required
Specifies the total amount of the order represented by this order
reference.
inherit_shipping_address : boolean, optional
Specifies whether to inherit the shipping address details from the
object represented by the Id request parameter. Default: True
confirm_now : boolean, optional
Indicates whether to directly confirm the requested order reference.
Default: False
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
supplementary_data: string, optional
Only use if instructed to do so by Amazon Pay. JSON string. Default: None
"""
parameters = {
'Action': 'CreateOrderReferenceForId',
'Id': object_id,
'IdType': object_id_type,
'OrderReferenceAttributes.OrderTotal.Amount': order_total,
'OrderReferenceAttributes.OrderTotal.CurrencyCode': self.currency_code}
optionals = {
'InheritShippingAddress': str(inherit_shipping_address).lower(),
'ConfirmNow': str(confirm_now).lower(),
'OrderReferenceAttributes.PlatformId': platform_id,
'OrderReferenceAttributes.SellerNote': seller_note,
'OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId': seller_order_id,
'OrderReferenceAttributes.SellerOrderAttributes.StoreName': store_name,
'OrderReferenceAttributes.SellerOrderAttributes.CustomInformation': custom_information,
'SellerId': merchant_id,
'OrderReferenceAttributes.SupplementaryData': supplementary_data,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def get_billing_agreement_details(
self,
amazon_billing_agreement_id,
address_consent_token=None,
merchant_id=None,
mws_auth_token=None):
"""Returns details about the Billing Agreement object and its current
state.
Parameters
----------
amazon_billing_agreement_id : string, required
The billing agreement identifier.
address_consent_token : string, optional
The buyer address consent token. You must provide a valid
AddressConsentToken if you want to get the full shipping address
before the billing agreement is confirmed. Otherwise you will only
receive the city, state, postal code, and country before you confirm
the billing agreement. Default: None
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'GetBillingAgreementDetails',
'AmazonBillingAgreementId': amazon_billing_agreement_id}
optionals = {
'AddressConsentToken': address_consent_token,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def set_billing_agreement_details(
self,
amazon_billing_agreement_id,
platform_id=None,
seller_note=None,
seller_billing_agreement_id=None,
store_name=None,
custom_information=None,
merchant_id=None,
mws_auth_token=None):
# pylint: disable=too-many-arguments
"""Sets billing agreement details such as a description of the agreement
and other information about the seller.
Parameters
----------
amazon_billing_agreement_id : string, required
The billing agreement identifier.
platform_id : string, optional
Represents the SellerId of the Solution Provider that developed the
platform. This value should only be provided by solution providers.
It should not be provided by sellers creating their own custom
integration.
seller_note : string, optional
Represents a description of the billing agreement that is displayed
in emails to the buyer.
seller_billing_agreement_id : string, optional
The seller-specified identifier of this billing agreement.
store_name : string, optional
The identifier of the store from which the order was placed. This
overrides the default value in Seller Central under Settings >
Account Settings. It is displayed to the buyer in the email they
receive from Amazon and also in their transaction history on the
Amazon Pay website.
custom_information : string, optional
Any additional information you wish to include with this billing
agreement.
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'SetBillingAgreementDetails',
'AmazonBillingAgreementId': amazon_billing_agreement_id}
optionals = {
'BillingAgreementAttributes.PlatformId': platform_id,
'BillingAgreementAttributes.SellerNote': seller_note,
'BillingAgreementAttributes.SellerBillingAgreementAttributes.SellerBillingAgreementId': seller_billing_agreement_id,
'BillingAgreementAttributes.SellerBillingAgreementAttributes.StoreName': store_name,
'BillingAgreementAttributes.SellerBillingAgreementAttributes.CustomInformation': custom_information,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def confirm_billing_agreement(
self,
amazon_billing_agreement_id,
merchant_id=None,
mws_auth_token=None):
"""Confirms that the billing agreement is free of constraints and all
required information has been set on the billing agreement.
Parameters
----------
amazon_billing_agreement_id : string, required
The billing agreement identifier.
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'ConfirmBillingAgreement',
'AmazonBillingAgreementId': amazon_billing_agreement_id}
optionals = {
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def validate_billing_agreement(
self,
amazon_billing_agreement_id,
merchant_id=None,
mws_auth_token=None):
"""Validates the status of the BillingAgreement object and the payment
method associated with it.
Parameters
----------
amazon_billing_agreement_id : string, required
The billing agreement identifier.
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'ValidateBillingAgreement',
'AmazonBillingAgreementId': amazon_billing_agreement_id}
optionals = {
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def authorize_on_billing_agreement(
self,
amazon_billing_agreement_id,
authorization_reference_id,
authorization_amount,
seller_authorization_note=None,
transaction_timeout=1440,
capture_now=False,
soft_descriptor=None,
seller_note=None,
platform_id=None,
seller_order_id=None,
store_name=None,
custom_information=None,
inherit_shipping_address=True,
merchant_id=None,
mws_auth_token=None,
supplementary_data=None):
# pylint: disable=too-many-arguments
"""Reserves a specified amount against the payment method(s) stored in
the billing agreement.
Parameters
----------
amazon_billing_agreement_id : string, required
The billing agreement identifier.
authorization_reference_id : string, required
The identifier for this authorization transaction that you specify.
This identifier must be unique for all your transactions
(authorization, capture, refund, etc.).
authorization_amount : string, required
Represents the amount to be authorized.
seller_authorization_note : string, optional
A description for the transaction that is displayed in emails to the
buyer. Default: None
transaction_timeout : unsigned integer, optional
The number of minutes after which the authorization will
automatically be closed and you will not be able to capture funds
against the authorization. Default: 1440
capture_now : boolean, optional
Indicates whether to directly capture the amount specified by the
AuthorizationAmount request parameter against an order reference
(without needing to call Capture and without waiting until the order
ships). The captured amount is disbursed to your account in the next
disbursement cycle. Default: False
seller_note : string, optional
Represents a description of the order that is displayed in emails to
the buyer. Default: None
platform_id : string, optional
Represents the SellerId of the Solution Provider that developed the
platform. This value should only be provided by Solution Providers.
It should not be provided by sellers creating their own custom
integration. Default: None
seller_order_id : string, optional
The seller-specified identifier of this order. This is displayed to
the buyer in the email they receive from Amazon and transaction
history on the Amazon Pay website. Default: None
store_name : string, optional
The identifier of the store from which the order was placed. This
overrides the default value in Seller Central under Settings >
Account Settings. It is displayed to the buyer in the email they
receive from Amazon and also in their transaction history on the
Amazon Pay website. Default: None
custom_information : string, optional
Any additional information you wish to include with this order
reference. Default: None
inherit_shipping_address : boolean, optional
Specifies whether to inherit the shipping address details from the
object represented by the Id request parameter. Default: True
supplementary_data: string, optional
Only use if instructed to do so by Amazon Pay. JSON string. Default: None
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'AuthorizeOnBillingAgreement',
'AmazonBillingAgreementId': amazon_billing_agreement_id,
'TransactionTimeout': transaction_timeout,
'AuthorizationReferenceId': authorization_reference_id,
'AuthorizationAmount.Amount': authorization_amount,
'AuthorizationAmount.CurrencyCode': self.currency_code}
optionals = {
'CaptureNow': str(capture_now).lower(),
'SellerAuthorizationNote': seller_authorization_note,
'SoftDescriptor': soft_descriptor,
'SellerNote': seller_note,
'PlatformId': platform_id,
'InheritShippingAddress': str(inherit_shipping_address).lower(),
'SellerOrderAttributes.SellerOrderId': seller_order_id,
'SellerOrderAttributes.StoreName': store_name,
'SellerOrderAttributes.CustomInformation': custom_information,
'SellerOrderAttributes.SupplementaryData': supplementary_data,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def close_billing_agreement(
self,
amazon_billing_agreement_id,
closure_reason=None,
merchant_id=None,
mws_auth_token=None):
"""Confirms that you want to terminate the billing agreement with the
buyer and that you do not expect to create any new order references or
authorizations on this billing agreement.
Parameters
----------
amazon_billing_agreement_id : string, required
The billing agreement identifier.
closure_reason : string, optional
Describes the reason for closing the billing agreement.
Default: None
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'CloseBillingAgreement',
'AmazonBillingAgreementId': amazon_billing_agreement_id}
optionals = {
'ClosureReason': closure_reason,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def set_order_reference_details(
self,
amazon_order_reference_id,
order_total,
platform_id=None,
seller_note=None,
seller_order_id=None,
store_name=None,
custom_information=None,
merchant_id=None,
mws_auth_token=None,
supplementary_data=None):
"""Sets order reference details such as the order total and a
description for the order.
Parameters
----------
amazon_order_reference_id : string, required
The order reference identifier retrieved from the amazon pay Button
widget.
order_total : string, required
Specifies the total amount of the order represented by this order
reference.
platform_id : string, optional
Represents the SellerId of the Solution Provider that developed the
platform. This value should only be provided by Solution Providers.
It should not be provided by sellers creating their own custom
integration. Default: None
seller_note : string, optional
Represents a description of the order that is displayed in emails
to the buyer. Default: None
seller_order_id : string, optional
The seller-specified identifier of this order. This is displayed to
the buyer in the email they receive from Amazon and also in their
transaction history on the Amazon Pay website. Default: None
store_name : string, optional
The identifier of the store from which the order was placed. This
overrides the default value in Seller Central under Settings >
Account Settings. It is displayed to the buyer in the email they
receive from Amazon and also in their transaction history on the
Amazon Pay website. Default: None
custom_information : string, optional
Any additional information you wish to include with this order
reference. Default: None
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
supplementary_data: string, optional
Only use if instructed to do so by Amazon Pay. JSON string. Default: None
"""
parameters = {
'Action': 'SetOrderReferenceDetails',
'AmazonOrderReferenceId': amazon_order_reference_id,
'OrderReferenceAttributes.OrderTotal.Amount': order_total,
'OrderReferenceAttributes.OrderTotal.CurrencyCode': self.currency_code}
optionals = {
'OrderReferenceAttributes.PlatformId': platform_id,
'OrderReferenceAttributes.SellerNote': seller_note,
'OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId': seller_order_id,
'OrderReferenceAttributes.SellerOrderAttributes.StoreName': store_name,
'OrderReferenceAttributes.SellerOrderAttributes.CustomInformation': custom_information,
'OrderReferenceAttributes.SellerOrderAttributes.SupplementaryData': supplementary_data,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def set_order_attributes(
self,
amazon_order_reference_id,
currency_code=None,
amount=None,
seller_order_id=None,
payment_service_provider_id=None,
payment_service_provider_order_id=None,
platform_id=None,
seller_note=None,
request_payment_authorization=None,
store_name=None,
list_order_item_categories=None,
custom_information=None,
merchant_id=None,
mws_auth_token=None,
supplementary_data=None):
'''
Return and update the information of an order with missing
or updated information
Parameters
----------
amazon_order_reference_id : string, required
The order reference identifier retrieved from the amazon pay Button
widget.
merchant_id : string, optional
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
currency_code : string, optional
The currency you're accepting the order in. A three-digit
currency code, formatted based on the ISO 4217 standard.
Default: None
amount : string, optional
Specifies the total amount of the order represented by this order
reference. Default: None
seller_order_id : string, optional
The seller-specified identifier of this order. This is displayed to
the buyer in the email they receive from Amazon and also in their
transaction history on the Amazon Pay website. Default: None
payment_service_provider_id : string, optional
For use with a Payment Service Provider. This is their specific
ID that is associated with Amazon Pay accounts and services.
Default: None
payment_service_provider_order_id : string, optional
For use with a Payment Service Provider. This is their specific
ID that is linked to your specific Amazon Pay Order Reference ID.
Default: None
platform_id : string, optional
Represents the SellerId of the Solution Provider that developed the
platform. This value should only be provided by Solution Providers.
It should not be provided by sellers creating their own custom
integration. Default: None
seller_note : string, optional
Represents a description of the order that is displayed in
e-mails to the buyer. Default: None
request_payment_authorization : boolean (string), optional
Specifies if the merchants want their buyers to go through
multi-factor authentication. Default: None
store_name : string, optional
The identifier of the store from which the order was placed. This
overrides the default value in Seller Central under Settings >
Account Settings. It is displayed to the buyer in the email they
receive from Amazon and also in their transaction history on the
Amazon Pay website. Default: None
list_order_item_categories : list (string), optional
List the category, or categories, that correlate to the order
in question. You may set more than one item. Default: None
custom_information : string, optional
Any additional information you want your back-end system to
keep record of. Your customers will not see this, and this
will not be visible on Seller Central. This can only be
accessed if your back end system supports calling this variable.
Default: None
supplementary_data: string, optional
Only use if instructed to do so by Amazon Pay. JSON string. Default: None
'''
parameters = {
'Action': 'SetOrderAttributes',
'AmazonOrderReferenceId': amazon_order_reference_id
}
optionals = {
'OrderAttributes.OrderTotal.Amount': amount,
'OrderAttributes.OrderTotal.CurrencyCode': currency_code,
'OrderAttributes.SellerOrderAttributes.CustomInformation': custom_information,
'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderId':
payment_service_provider_id,
'OrderAttributes.PaymentServiceProviderAttributes.PaymentServiceProviderOrderId':
payment_service_provider_order_id,
'OrderAttributes.PlatformId': platform_id,
'OrderAttributes.RequestPaymentAuthorization': request_payment_authorization,
'OrderAttributes.SellerNote': seller_note,
'OrderAttributes.SellerOrderAttributes.SellerOrderId': seller_order_id,
'OrderAttributes.SellerOrderAttributes.StoreName': store_name,
'OrderAttributes.SellerOrderAttributes.SupplementaryData': supplementary_data,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token
}
if list_order_item_categories is not None:
self._enumerate(
'OrderAttributes.SellerOrderAttributes.OrderItemCategories.OrderItemCategory.',
list_order_item_categories, optionals)
return self._operation(params=parameters, options=optionals)
def get_order_reference_details(
self,
amazon_order_reference_id,
access_token=None,
address_consent_token=None,
merchant_id=None,
mws_auth_token=None):
"""Returns details about the order reference object and its current
state.
Parameters
----------
amazon_order_reference_id : string, optional
The order reference identifier. This value is retrieved from the
amazon pay Button widget after the buyer has successfully authenticated
with Amazon.
access_token : string, optional
The access token. This value is retrieved from the
amazon pay Button widget after the buyer has successfully authenticated
with Amazon. (Note: When using this value, you cannot use the
address_consent_token at the same time, or this will cause an error.
The same note applies when using just the address_consent_token)
address_consent_token : string, optional
The buyer address consent token. This value is retrieved from the
amazon pay Button widget after the buyer has successfully authenticated
with Amazon.
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'GetOrderReferenceDetails',
'AmazonOrderReferenceId': amazon_order_reference_id
}
optionals = {
'AddressConsentToken': address_consent_token,
'AccessToken': access_token,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def confirm_order_reference(
self,
amazon_order_reference_id,
merchant_id=None,
mws_auth_token=None,
success_url=None,
failure_url=None,
authorization_amount=None,
currency_code=None,
expect_immediate_authorization=None):
"""Confirms that the order reference is free of constraints and all
required information has been set on the order reference.
Parameters
----------
amazon_order_reference_id : string : required
The order reference identifier.
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
success_url: string, optional
Represents the return URL for SCA success.
failure_url: string, optional
Represents the return URL for SCA failure.
authorization_amount: string, optional
Represents the amount to be authorized. If blank both it and currency_code will be excluded.
currency_code: string, optional
Currency code for your region.
Environment variable: AP_CURRENCY_CODE
expect_immediate_authorization: boolean, optional
If this value is set to true, the ORO will auto-close in case no authorize is triggered within 60 minutes after the confirm. Default: None
"""
parameters = {
'Action': 'ConfirmOrderReference',
'AmazonOrderReferenceId': amazon_order_reference_id}
optionals = {
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token,
'SuccessUrl': success_url,
'FailureUrl': failure_url,
'AuthorizationAmount.Amount': authorization_amount,
'AuthorizationAmount.CurrencyCode': self.currency_code if currency_code is None else currency_code,
'ExpectImmediateAuthorization': str(expect_immediate_authorization).lower() if expect_immediate_authorization is not None else None}
if authorization_amount == "0" or authorization_amount is None:
del optionals['AuthorizationAmount.Amount']
del optionals['AuthorizationAmount.CurrencyCode']
return self._operation(params=parameters, options=optionals)
def cancel_order_reference(
self,
amazon_order_reference_id,
cancelation_reason=None,
merchant_id=None,
mws_auth_token=None):
"""Cancels a previously confirmed order reference.
Parameters
----------
amazon_order_reference_id : string, required
The order reference identifier.
cancelation_reason : string, optional
Describes the reason for the cancelation. Default: None
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'CancelOrderReference',
'AmazonOrderReferenceId': amazon_order_reference_id}
optionals = {
'CancelationReason': cancelation_reason,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def close_order_reference(
self,
amazon_order_reference_id,
closure_reason=None,
merchant_id=None,
mws_auth_token=None):
"""Confirms that an order reference has been fulfilled
(fully or partially) and that you do not expect to create any new
authorizations on this order reference.
Parameters
----------
amazon_order_reference_id : string, required
The ID of the order reference for which the details are being
requested.
closure_reason : string, optional
Describes the reason for closing the order reference. Default: None
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'CloseOrderReference',
'AmazonOrderReferenceId': amazon_order_reference_id}
optionals = {
'ClosureReason': closure_reason,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def list_order_reference(
self,
query_id,
query_id_type,
created_time_range_start=None,
created_time_range_end=None,
sort_order=None,
payment_domain=None,
page_size=None,
order_reference_status_list_filter=None,
merchant_id=None,
mws_auth_token=None):
"""
Allows the search of any Amazon Pay order made using secondary
seller order IDs generated manually, a solution provider, or a custom
order fulfillment service.
Parameters
==========================================
query_id: string, required
The identifier that the merchant wishes to use in relation to the
query id type.
query_id_type: string, required
The type of query the id is referencing.
Note: At this time, you can only use the query type (SellerOrderId).
More options will be available in the future. Default: SellerOrderId
payment_domain: string, optional
The region and currency that will be set to authorize and collect
payments from your customers. You can leave this blank for the
system to automatically assign the default payment domain for
your region.
created_time_range_start: string, optional
This filter will allow a merchant to search for a particular item
within a date range of their choice.
Note: If you wish to use this filter, you MUST fill in an end date,
otherwise you will get an error returned when searching. You must
also use the ISO 8601 time format to return a valid response when
searching in a date range. Either of the two examples will work
when using this filter. Default: None
Example: YYYY-MM-DD or YYYY-MM-DDTHH:MM.
created_time_range_end: string, optional
The end-date for the date range the merchant wishes to search for
any of their orders they're looking for.
Note: You need to only use this option if you are using the
created_time_range_start parameter. Default: None
sort_order: string, optional
Filter can be set for "Ascending", or "Descending" order, and must
be written out as shown above. This will sort the orders via
the respective option. Default: None
page_size: integer, optional
This filter limits how many results will be displayed per
request. Default: None
merchant_id : string, optional
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
order_reference_status_list_filter: list (string), optional
When searching for an order, this filter is related to the status
of the orders on file. You can search for any valid status for orders
on file. Filters MUST be written out in English.
Example: "Open", "Closed", "Suspended", "Canceled"
Default: None
"""
if self.region is not None:
region_code = self.region.lower()
if region_code == 'na':
payment_domain = 'NA_USD'
elif region_code in ('uk', 'gb'):
payment_domain = 'EU_GBP'
elif region_code in ('jp', 'fe'):
payment_domain = 'FE_JPY'
elif region_code in ('eu', 'de', 'fr', 'it', 'es', 'cy'):
payment_domain = 'EU_EUR'
else:
raise ValueError("Error. The current region code does not match our records")
parameters = {
'Action': 'ListOrderReference',
'QueryId': query_id,
'QueryIdType': query_id_type,
'PaymentDomain': payment_domain
}
optionals = {
'CreatedTimeRange.StartTime': created_time_range_start,
'CreatedTimeRange.EndTime': created_time_range_end,
'SortOrder': sort_order,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token,
'PageSize': page_size
}
if order_reference_status_list_filter is not None:
self._enumerate(
'OrderReferenceStatusListFilter.OrderReferenceStatus.',
order_reference_status_list_filter, optionals)
return self._operation(params=parameters, options=optionals)
def list_order_reference_by_next_token(
self,
next_page_token,
merchant_id=None,
mws_auth_token=None):
"""
next_page_token : string, required
Uses the key from a list_order_reference call that provides a
NextPageToken for a merchant to call to review the next page
of items, and if applicable, another NextPageToken for the next
set of items to read through.
merchant_id : string, optional
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'ListOrderReferenceByNextToken',
'NextPageToken': next_page_token}
optionals = {
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def get_payment_details(
self,
amazon_order_reference_id,
merchant_id=None,
mws_auth_token=None):
'''
This is a convenience function that will return every authorization,
charge, and refund call of an Amazon Pay order ID.
Parameters
----------
amazon_order_reference_id: string, required
The ID of the order reference for which the details are being
requested.
merchant_id : string, optional
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
'''
parameters = {
'Action': 'GetOrderReferenceDetails',
'AmazonOrderReferenceId': amazon_order_reference_id
}
optionals = {
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token
}
query = self._operation(params=parameters, options=optionals)
answer = []
answer.append(query)
queryID = json.loads(query.to_json())
memberID = queryID['GetOrderReferenceDetailsResponse']\
['GetOrderReferenceDetailsResult']['OrderReferenceDetails']['IdList']
if memberID is not None:
'''
This check will see if the variable is in a list form or not
if it is not it will covert it into a single item list.
Otherwise, it will process the variable normally as a list.
'''
if type(memberID['member']) is not list:
memberID = [memberID['member']]
else:
memberID = memberID['member']
for id in memberID:
parameters = {
'Action': 'GetAuthorizationDetails',
'AmazonAuthorizationId': id
}
response = self._operation(params=parameters)
answer.append(response)
queryID = json.loads(response.to_json())
chargeID = queryID['GetAuthorizationDetailsResponse']\
['GetAuthorizationDetailsResult']['AuthorizationDetails']['IdList']
if chargeID is not None:
chargeID = chargeID['member']
parameters = {
'Action': 'GetCaptureDetails',
'AmazonCaptureId': chargeID
}
response = self._operation(params=parameters)
queryID = json.loads(response.to_json())
refundID = queryID['GetCaptureDetailsResponse']\
['GetCaptureDetailsResult']['CaptureDetails']['IdList']
answer.append(response)
if refundID is not None:
if type(refundID['member']) is not list:
refundID = [refundID['member']]
else:
refundID = refundID['member']
for id in refundID:
parameters = {
'Action': 'GetRefundDetails',
'AmazonRefundId': id
}
response = self._operation(params=parameters)
answer.append(response)
return answer
def authorize(
self,
amazon_order_reference_id,
authorization_reference_id,
authorization_amount,
seller_authorization_note=None,
transaction_timeout=1440,
capture_now=False,
soft_descriptor=None,
merchant_id=None,
mws_auth_token=None):
# pylint: disable=too-many-arguments
"""Reserves a specified amount against the payment method(s) stored in
the order reference.
Parameters
----------
amazon_order_reference_id : string, required
The order reference identifier.
authorization_reference_id : string, required
The identifier for this authorization transaction that you specify.
This identifier must be unique for all your transactions
(authorization, capture, refund, etc.).
authorization_amount : string, required
Represents the amount to be authorized.
seller_authorization_note : string, optional
A description for the transaction that is displayed in emails to
the buyer. Maximum: 225 characters.
transaction_timeout : unsigned integer, optional
The number of minutes after which the authorization will
automatically be closed and you will not be able to capture funds
against the authorization.
Note: In asynchronous mode, the Authorize operation always returns
the State as Pending. The authorization remains in this state until
it is processed by Amazon. The processing time varies and can be a
minute or more. After processing is complete, Amazon will notify
you of the final processing status. For more information, see
Synchronizing your systems with Amazon Pay in the Amazon Pay
Integration Guide. Default: 1440
capture_now : boolean, optional
Indicates whether to directly capture a specified amount against an
order reference (without needing to call Capture and without waiting
until the order ships). The captured amount is disbursed to your
account in the next disbursement cycle.
Note: The Amazon Pay policy states that you charge your buyer
when you fulfill the items in the order. You should not collect
funds prior to fulfilling the order. Default: False
soft_descriptor : string, optional
The description to be shown on the buyer’s payment instrument
statement if CaptureNow is set to true. The soft descriptor sent to
the payment processor is: “AMZ* <soft descriptor specified here>”.
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'Authorize',
'AmazonOrderReferenceId': amazon_order_reference_id,
'TransactionTimeout': transaction_timeout,
'AuthorizationReferenceId': authorization_reference_id,
'AuthorizationAmount.Amount': authorization_amount,
'AuthorizationAmount.CurrencyCode': self.currency_code}
optionals = {
'SellerAuthorizationNote': seller_authorization_note,
'CaptureNow': str(capture_now).lower(),
'SoftDescriptor': soft_descriptor,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def get_authorization_details(
self,
amazon_authorization_id,
merchant_id=None,
mws_auth_token=None):
"""Returns the status of a particular authorization and the total amount
captured on the authorization.
Parameters
----------
amazon_authorization_id : string, required
The authorization identifier that was generated by Amazon in the
earlier call to Authorize.
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'GetAuthorizationDetails',
'AmazonAuthorizationId': amazon_authorization_id}
optionals = {
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def capture(
self,
amazon_authorization_id,
capture_reference_id,
capture_amount,
seller_capture_note=None,
soft_descriptor=None,
merchant_id=None,
mws_auth_token=None):
# pylint: disable=too-many-arguments
"""Captures funds from an authorized payment instrument.
Parameters
----------
amazon_authorization_id : string, required
The authorization identifier that was generated by Amazon in the
earlier call to Authorize or AuthorizeOnBillingAgreement.
capture_reference_id : string, required
The identifier for this capture transaction that you specify. This
identifier must be unique for all your transactions
(authorization, capture, refund, etc.).
capture_amount : string, required
The amount to capture in this transaction. This amount cannot exceed
the original amount that was authorized less any previously captured
amount on this authorization.
seller_capture_note : string, optional
A description for the capture transaction that is displayed in
emails to the buyer. Maximum: 255 characters, Default: None
soft_descriptor : string, optional
The description to be shown on the buyer’s payment instrument
statement. The soft descriptor sent to the payment processor is:
“AMZ* <soft descriptor specified here>”.
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'Capture',
'AmazonAuthorizationId': amazon_authorization_id,
'CaptureReferenceId': capture_reference_id,
'CaptureAmount.Amount': capture_amount,
'CaptureAmount.CurrencyCode': self.currency_code}
optionals = {
'SellerCaptureNote': seller_capture_note,
'SoftDescriptor': soft_descriptor,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def get_capture_details(
self,
amazon_capture_id,
merchant_id=None,
mws_auth_token=None):
"""Returns the status of a particular capture and the total amount
refunded on the capture.
Parameters
----------
amazon_capture_id : string, required
The capture identifier that was generated by Amazon on the earlier
call to Capture.
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'GetCaptureDetails',
'AmazonCaptureId': amazon_capture_id}
optionals = {
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def close_authorization(
self,
amazon_authorization_id,
closure_reason=None,
merchant_id=None,
mws_auth_token=None):
"""Closes an authorization.
Parameters
----------
amazon_authorization_id : string, required
The authorization identifier that was generated by Amazon in the
earlier call to Authorize.
closure_reason : string, optional
A description for the closure that is displayed in emails to the
buyer.
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'CloseAuthorization',
'AmazonAuthorizationId': amazon_authorization_id}
optionals = {
'ClosureReason': closure_reason,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def refund(
self,
amazon_capture_id,
refund_reference_id,
refund_amount,
seller_refund_note=None,
soft_descriptor=None,
merchant_id=None,
mws_auth_token=None):
# pylint: disable=too-many-arguments
"""Refunds a previously captured amount.
Parameters
----------
amazon_capture_id : string, required
The capture identifier that was generated by Amazon in the earlier
call to Capture.
refund_reference_id : string, required
The identifier for this refund transaction that you specify. This
identifier must be unique for all your transactions
(authorization, capture, refund, etc.).
refund_amount : string, required
The amount to refund. This amount cannot exceed:
In the US: the lesser of 15% or $75 above the captured amount
less the amount already refunded on the capture.
In the UK: the lesser of 15% or £75 above the captured amount
for the Capture object.
In Germany: the lesser of 15% or €75 above the captured amount
for the Capture object.
seller_refund_note : string, optional
A description for the refund that is displayed in emails to the
buyer. Maximum: 255 characters, Default: None
soft_descriptor : string, optional
The description to be shown on the buyer’s payment instrument
statement. The soft descriptor sent to the payment processor is:
“AMZ* <soft descriptor specified here>”.
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'Refund',
'AmazonCaptureId': amazon_capture_id,
'RefundReferenceId': refund_reference_id,
'RefundAmount.Amount': refund_amount,
'RefundAmount.CurrencyCode': self.currency_code}
optionals = {
'SellerRefundNote': seller_refund_note,
'SoftDescriptor': soft_descriptor,
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def get_refund_details(
self,
amazon_refund_id,
merchant_id=None,
mws_auth_token=None):
"""Returns the status of a particular refund.
Parameters
----------
amazon_refund_id : string, required
The Amazon-generated identifier for this refund transaction.
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
"""
parameters = {
'Action': 'GetRefundDetails',
'AmazonRefundId': amazon_refund_id}
optionals = {
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}
return self._operation(params=parameters, options=optionals)
def get_service_status(self):
"""Returns the operational status of the Off-Amazon Payments API section.
"""
parameters = {
'Action': 'GetServiceStatus'}
return self._operation(params=parameters)
def charge(
self,
amazon_reference_id,
charge_amount,
authorize_reference_id,
charge_note,
charge_order_id=None,
store_name=None,
custom_information=None,
platform_id=None,
merchant_id=None,
mws_auth_token=None,
soft_descriptor=None):
"""Combine the set, confirm, authorize, and capture calls into one.
Parameters
----------
amazon_reference_id : string, required
The order reference or billing agreement identifier.
charge_amount : string, required
The amount to capture in this transaction.
authorize_reference_id : string, required
The seller-specified identifier of this charge. This parameter sets
both authorization_reference_id and capture_reference_id.
charge_order_id : string, optional
The seller-specified identifier of this order. This is displayed to
the buyer in the emails they receive from Amazon and also in their
transaction history on the Amazon Pay website.
store_name : string, optional
The identifier of the store from which the order was placed. This
overrides the default value in Seller Central under Settings >
Account Settings. It is displayed to the buyer in the email they
receive from Amazon and also in their transaction history on the
Amazon Pay website.
custom_information : string, optional
Any additional information you wish to include with this billing
agreement.
charge_note : string, optional
A description for the capture transaction that is displayed in
emails to the buyer.
platform_id
Represents the SellerId of the Solution Provider that developed the
platform. This value should only be provided by Solution Providers.
It should not be provided by sellers creating their own custom
integration.
merchant_id : string, required
Your merchant ID. If you are a marketplace enter the seller's merchant
ID.
mws_auth_token: string, optional
Your marketplace web service auth token. Default: None
soft_descriptor : string, optional
The description to be shown on the buyer’s payment instrument
statement if CaptureNow is set to true. The soft descriptor sent to
the payment processor is: “AMZ* <soft descriptor specified here>”.
"""
if self.is_order_reference_id(amazon_reference_id):
# set
ret = self.set_order_reference_details(
amazon_order_reference_id=amazon_reference_id,
order_total=charge_amount,
platform_id=platform_id,
seller_note=charge_note,
seller_order_id=charge_order_id,
store_name=store_name,
custom_information=custom_information,
merchant_id=merchant_id,
mws_auth_token=mws_auth_token)
if ret.success:
# confirm
ret = self.confirm_order_reference(
amazon_order_reference_id=amazon_reference_id,
merchant_id=merchant_id,
mws_auth_token=mws_auth_token)
if ret.success:
# auth
ret = self.authorize(
amazon_order_reference_id=amazon_reference_id,
authorization_reference_id=authorize_reference_id,
authorization_amount=charge_amount,
seller_authorization_note=charge_note,
transaction_timeout=0,
capture_now=True,
soft_descriptor=soft_descriptor,
merchant_id=merchant_id,
mws_auth_token=mws_auth_token)
return ret
else:
return ret
else:
return ret
if self.is_billing_agreement_id(amazon_reference_id):
"""Since this is a billing agreement we need to see if details have
already been set. If so, we just need to authorize.
"""
ret = self.get_billing_agreement_details(
amazon_billing_agreement_id=amazon_reference_id,
address_consent_token=None,
merchant_id=merchant_id,
mws_auth_token=mws_auth_token)
if ret.to_dict().get('GetBillingAgreementDetailsResponse').get(
'GetBillingAgreementDetailsResult').get(
'BillingAgreementDetails').get(
'BillingAgreementStatus').get('State') == 'Draft':
# set
ret = self.set_billing_agreement_details(
amazon_billing_agreement_id=amazon_reference_id,
platform_id=platform_id,
seller_note=charge_note,
seller_billing_agreement_id=charge_order_id,
store_name=store_name,
custom_information=custom_information,
merchant_id=merchant_id,
mws_auth_token=mws_auth_token)
if ret.success:
# confirm
ret = self.confirm_billing_agreement(
amazon_billing_agreement_id=amazon_reference_id,
merchant_id=merchant_id,
mws_auth_token=mws_auth_token)
if not ret.success:
return ret
else:
return ret
# auth
ret = self.authorize_on_billing_agreement(
amazon_billing_agreement_id=amazon_reference_id,
authorization_reference_id=authorize_reference_id,
authorization_amount=charge_amount,
seller_authorization_note=charge_note,
transaction_timeout=0,
capture_now=True,
soft_descriptor=soft_descriptor,
seller_note=charge_note,
platform_id=platform_id,
seller_order_id=charge_order_id,
store_name=store_name,
custom_information=custom_information,
inherit_shipping_address=True,
merchant_id=merchant_id,
mws_auth_token=mws_auth_token)
return ret
def is_order_reference_id(self, amazon_reference_id):
"""Checks if Id is order reference. P or S at the beginning indicate a
order reference ID.
"""
return re.search('^(P|S)', amazon_reference_id)
def is_billing_agreement_id(self, amazon_reference_id):
"""Checks if Id is billing agreement. B or C at the beginning indicate a
billing agreement ID
"""
return re.search('^(B|C)', amazon_reference_id)
def _operation(self, params, options=None):
"""Parses required and optional parameters and passes to the Request
object.
"""
if options is not None:
for opt in options.keys():
if options[opt] is not None:
params[opt] = options[opt]
request = PaymentRequest(
params=params,
config={'mws_access_key': self.mws_access_key,
'mws_secret_key': self.mws_secret_key,
'api_version': self._api_version,
'merchant_id': self.merchant_id,
'mws_endpoint': self._mws_endpoint,
'headers': self._headers,
'handle_throttle': self.handle_throttle})
request.send_post()
return request.response
def _enumerate(
self,
category,
filter_types,
optionals):
def enumerate_param(param, values):
"""
Builds a dictionary of an enumerated parameter from the filter list.
This is currently used for two API calls in the client. Specifically,
set_order_attributes & list_order_reference
Example: (For set_order_attributes)
enumerate_param(
'OrderAttributes.SellerOrderAttributes.OrderItemCategories.OrderItemCategory.',
(["Antiques", "Outdoor"])
returns
{
OrderAttributes.SellerOrderAttributes.OrderItemCategories.OrderItemCategory.1:
Antiques,
OrderAttributes.SellerOrderAttributes.OrderItemCategories.OrderItemCategory.2:
Outdoor
}
"""
params = {}
if values is not None:
if not param.endswith('.'):
param = "%s." % param
for num, value in enumerate(values):
params['%s%d' % (param, (num + 1))] = value
return params
"""This will apply your filters from the list filter parameter"""
if isinstance(filter_types, list):
optionals.update(enumerate_param(category, filter_types))
else:
if ',' in filter_types:
filter_types = filter_types.replace(' ','')
filter_types = filter_types.split(',')
optionals.update(enumerate_param(category, filter_types))
else:
raise Exception("Invalid format for this request.")
|
/**
* @file SDK to connect to Tinode chat server.
* See <a href="https://github.com/tinode/webapp">
* https://github.com/tinode/webapp</a> for real-life usage.
*
* @copyright 2015-2019 Tinode
* @summary Javascript bindings for Tinode.
* @license Apache 2.0
* @version 0.16
*
* @example
* <head>
* <script src=".../tinode.js"></script>
* </head>
*
* <body>
* ...
* <script>
* // Instantiate tinode.
* const tinode = new Tinode(APP_NAME, HOST, API_KEY, null, true);
* tinode.enableLogging(true);
* // Add logic to handle disconnects.
* tinode.onDisconnect = function(err) { ... };
* // Connect to the server.
* tinode.connect().then(() => {
* // Connected. Login now.
* return tinode.loginBasic(login, password);
* }).then((ctrl) => {
* // Logged in fine, attach callbacks, subscribe to 'me'.
* const me = tinode.getMeTopic();
* me.onMetaDesc = function(meta) { ... };
* // Subscribe, fetch topic description and the list of contacts.
* me.subscribe({get: {desc: {}, sub: {}});
* }).catch((err) => {
* // Login or subscription failed, do something.
* ...
* });
* ...
* </script>
* </body>
*/
'use strict';
// NOTE TO DEVELOPERS:
// Localizable strings should be double quoted "строка на другом языке",
// non-localizable strings should be single quoted 'non-localized'.
if (typeof require == 'function') {
if (typeof Drafty == 'undefined') {
var Drafty = require('./drafty.js');
}
var package_version = require('../version.json').version;
}
let WebSocketProvider;
if (typeof WebSocket != 'undefined') {
WebSocketProvider = WebSocket;
}
let XHRProvider;
if (typeof XMLHttpRequest != 'undefined') {
XHRProvider = XMLHttpRequest;
}
initForNonBrowserApp();
// Global constants
const PROTOCOL_VERSION = '0';
const VERSION = package_version || '0.16';
const LIBRARY = 'tinodejs/' + VERSION;
const TOPIC_NEW = 'new';
const TOPIC_NEW_CHAN = 'nch';
const TOPIC_ME = 'me';
const TOPIC_FND = 'fnd';
const TOPIC_SYS = 'sys';
const TOPIC_CHAN = 'chn';
const USER_NEW = 'new';
// Starting value of a locally-generated seqId used for pending messages.
const LOCAL_SEQID = 0xFFFFFFF;
const MESSAGE_STATUS_NONE = 0; // Status not assigned.
const MESSAGE_STATUS_QUEUED = 1; // Local ID assigned, in progress to be sent.
const MESSAGE_STATUS_SENDING = 2; // Transmission started.
const MESSAGE_STATUS_FAILED = 3; // At least one attempt was made to send the message.
const MESSAGE_STATUS_SENT = 4; // Delivered to the server.
const MESSAGE_STATUS_RECEIVED = 5; // Received by the client.
const MESSAGE_STATUS_READ = 6; // Read by the user.
const MESSAGE_STATUS_TO_ME = 7; // Message from another user.
// Error code to return in case of a network problem.
const NETWORK_ERROR = 503;
const NETWORK_ERROR_TEXT = "Connection failed";
// Reject unresolved futures after this many milliseconds.
const EXPIRE_PROMISES_TIMEOUT = 5000;
// Periodicity of garbage collection of unresolved futures.
const EXPIRE_PROMISES_PERIOD = 1000;
// Error code to return when user disconnected from server.
const NETWORK_USER = 418;
const NETWORK_USER_TEXT = "Disconnected by client";
// Utility functions
// Add brower missing function for non browser app, eg nodeJs
function initForNonBrowserApp() {
// Tinode requirement in native mode because react native doesn't provide Base64 method
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
if (typeof btoa == 'undefined') {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
global.btoa = function(input = '') {
let str = input;
let output = '';
for (let block = 0, charCode, i = 0, map = chars; str.charAt(i | 0) || (map = '=', i % 1); output += map.charAt(63 & block >> 8 - i % 1 * 8)) {
charCode = str.charCodeAt(i += 3 / 4);
if (charCode > 0xFF) {
throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
}
block = block << 8 | charCode;
}
return output;
};
}
if (typeof atob == 'undefined') {
global.atob = function(input = '') {
let str = input.replace(/=+$/, '');
let output = '';
if (str.length % 4 == 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (let bc = 0, bs = 0, buffer, i = 0; buffer = str.charAt(i++);
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
buffer = chars.indexOf(buffer);
}
return output;
};
}
if (typeof window == 'undefined') {
global.window = {
WebSocket: WebSocketProvider,
XMLHttpRequest: XHRProvider,
URL: {
createObjectURL: function() {
throw new Error("Unable to use URL.createObjectURL in a non-browser application");
}
}
}
}
}
// RFC3339 formater of Date
function rfc3339DateString(d) {
if (!d || d.getTime() == 0) {
return undefined;
}
function pad(val, sp) {
sp = sp || 2;
return '0'.repeat(sp - ('' + val).length) + val;
}
const millis = d.getUTCMilliseconds();
return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) +
'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) +
(millis ? '.' + pad(millis, 3) : '') + 'Z';
}
// btoa replacement. Stock btoa fails on on non-Latin1 strings.
function b64EncodeUnicode(str) {
// The encodeURIComponent percent-encodes UTF-8 string,
// then the percent encoding is converted into raw bytes which
// can be fed into btoa.
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
// Recursively merge src's own properties to dst.
// Ignore properties where ignore[property] is true.
// Array and Date objects are shallow-copied.
function mergeObj(dst, src, ignore) {
if (typeof src != 'object') {
if (src === Tinode.DEL_CHAR) {
return undefined;
}
if (src === undefined) {
return dst;
}
return src;
}
// JS is crazy: typeof null is 'object'.
if (src === null) {
return src;
}
// Handle Date
if (src instanceof Date) {
return (!dst || !(dst instanceof Date) || dst < src) ? src : dst;
}
// Access mode
if (src instanceof AccessMode) {
return new AccessMode(src);
}
// Handle Array
if (src instanceof Array) {
return src;
}
if (!dst || dst === Tinode.DEL_CHAR) {
dst = src.constructor();
}
for (let prop in src) {
if (src.hasOwnProperty(prop) &&
(!ignore || !ignore[prop]) &&
(prop != '_noForwarding')) {
dst[prop] = mergeObj(dst[prop], src[prop]);
}
}
return dst;
}
// Update object stored in a cache. Returns updated value.
function mergeToCache(cache, key, newval, ignore) {
cache[key] = mergeObj(cache[key], newval, ignore);
return cache[key];
}
function stringToDate(obj) {
if (typeof obj.created == 'string') {
obj.created = new Date(obj.created);
}
if (typeof obj.updated == 'string') {
obj.updated = new Date(obj.updated);
}
if (typeof obj.touched == 'string') {
obj.touched = new Date(obj.touched);
}
}
// JSON stringify helper - pre-processor for JSON.stringify
function jsonBuildHelper(key, val) {
if (val instanceof Date) {
// Convert javascript Date objects to rfc3339 strings
val = rfc3339DateString(val);
} else if (val instanceof AccessMode) {
val = val.jsonHelper();
} else if (val === undefined || val === null || val === false ||
(Array.isArray(val) && val.length == 0) ||
((typeof val == 'object') && (Object.keys(val).length == 0))) {
// strip out empty elements while serializing objects to JSON
return undefined;
}
return val;
};
// Strips all values from an object of they evaluate to false or if their name starts with '_'.
function simplify(obj) {
Object.keys(obj).forEach(function(key) {
if (key[0] == '_') {
// Strip fields like "obj._key".
delete obj[key];
} else if (!obj[key]) {
// Strip fields which evaluate to false.
delete obj[key];
} else if (Array.isArray(obj[key]) && obj[key].length == 0) {
// Strip empty arrays.
delete obj[key];
} else if (!obj[key]) {
// Strip fields which evaluate to false.
delete obj[key];
} else if (typeof obj[key] == 'object' && !(obj[key] instanceof Date)) {
simplify(obj[key]);
// Strip empty objects.
if (Object.getOwnPropertyNames(obj[key]).length == 0) {
delete obj[key];
}
}
});
return obj;
};
// Trim whitespace, strip empty and duplicate elements elements.
// If the result is an empty array, add a single element "\u2421" (Unicode Del character).
function normalizeArray(arr) {
let out = [];
if (Array.isArray(arr)) {
// Trim, throw away very short and empty tags.
for (let i = 0, l = arr.length; i < l; i++) {
let t = arr[i];
if (t) {
t = t.trim().toLowerCase();
if (t.length > 1) {
out.push(t);
}
}
}
out.sort().filter(function(item, pos, ary) {
return !pos || item != ary[pos - 1];
});
}
if (out.length == 0) {
// Add single tag with a Unicode Del character, otherwise an ampty array
// is ambiguos. The Del tag will be stripped by the server.
out.push(Tinode.DEL_CHAR);
}
return out;
}
// Attempt to convert date strings to objects.
function jsonParseHelper(key, val) {
// Convert string timestamps with optional milliseconds to Date
// 2015-09-02T01:45:43[.123]Z
if (key === 'ts' && typeof val === 'string' &&
val.length >= 20 && val.length <= 24) {
let date = new Date(val);
if (date) {
return date;
}
} else if (key === 'acs' && typeof val === 'object') {
return new AccessMode(val);
}
return val;
};
// Trims very long strings (encoded images) to make logged packets more readable.
function jsonLoggerHelper(key, val) {
if (typeof val == 'string' && val.length > 128) {
return '<' + val.length + ', bytes: ' + val.substring(0, 12) + '...' + val.substring(val.length - 12) + '>';
}
return jsonBuildHelper(key, val);
};
// Parse browser user agent to extract browser name and version.
function getBrowserInfo(ua, product) {
ua = ua || '';
let reactnative = '';
// Check if this is a ReactNative app.
if (/reactnative/i.test(product)) {
reactnative = 'ReactNative; ';
}
// Then test for WebKit based browser.
ua = ua.replace(' (KHTML, like Gecko)', '');
let m = ua.match(/(AppleWebKit\/[.\d]+)/i);
let result;
if (m) {
// List of common strings, from more useful to less useful.
let priority = ['chrome', 'safari', 'mobile', 'version'];
let tmp = ua.substr(m.index + m[0].length).split(" ");
let tokens = [];
// Split Name/0.0.0 into Name and version 0.0.0
for (let i = 0; i < tmp.length; i++) {
let m2 = /([\w.]+)[\/]([\.\d]+)/.exec(tmp[i]);
if (m2) {
tokens.push([m2[1], m2[2], priority.findIndex(function(e) {
return (e == m2[1].toLowerCase());
})]);
}
}
// Sort by priority: more interesting is earlier than less interesting.
tokens.sort(function(a, b) {
let diff = a[2] - b[2];
return diff != 0 ? diff : b[0].length - a[0].length;
});
if (tokens.length > 0) {
// Return the least common browser string and version.
result = tokens[0][0] + '/' + tokens[0][1];
} else {
// Failed to ID the browser. Return the webkit version.
result = m[1];
}
// Test for MSIE.
} else if (/trident/i.test(ua)) {
m = /(?:\brv[ :]+([.\d]+))|(?:\bMSIE ([.\d]+))/g.exec(ua);
if (m) {
result = 'MSIE/' + (m[1] || m[2]);
} else {
result = 'MSIE/?';
}
// Test for Firefox.
} else if (/firefox/i.test(ua)) {
m = /Firefox\/([.\d]+)/g.exec(ua);
if (m) {
result = 'Firefox/' + m[1];
} else {
result = 'Firefox/?';
}
// Older Opera.
} else if (/presto/i.test(ua)) {
m = /Opera\/([.\d]+)/g.exec(ua);
if (m) {
result = 'Opera/' + m[1];
} else {
result = 'Opera/?';
}
} else {
// Failed to parse anything meaningfull. Try the last resort.
m = /([\w.]+)\/([.\d]+)/.exec(ua);
if (m) {
result = m[1] + '/' + m[2];
} else {
m = ua.split(' ');
result = m[0];
}
}
// Shorten the version to one dot 'a.bb.ccc.d -> a.bb' at most.
m = result.split('/');
if (m.length > 1) {
let v = m[1].split('.');
result = m[0] + '/' + v[0] + (v[1] ? '.' + v[1] : '');
}
return reactnative + result;
}
/**
* In-memory sorted cache of objects.
*
* @class CBuffer
* @memberof Tinode
* @protected
*
* @param {function} compare custom comparator of objects. Returns -1 if a < b, 0 if a == b, 1 otherwise.
* @param {boolean} unique enforce element uniqueness: replace existing element with a new one on conflict.
*/
var CBuffer = function(compare, unique) {
let buffer = [];
compare = compare || function(a, b) {
return a === b ? 0 : a < b ? -1 : 1;
};
function findNearest(elem, arr, exact) {
let start = 0;
let end = arr.length - 1;
let pivot = 0;
let diff = 0;
let found = false;
while (start <= end) {
pivot = (start + end) / 2 | 0;
diff = compare(arr[pivot], elem);
if (diff < 0) {
start = pivot + 1;
} else if (diff > 0) {
end = pivot - 1;
} else {
found = true;
break;
}
}
if (found) {
return {
idx: pivot,
exact: true
};
}
if (exact) {
return {
idx: -1
};
}
// Not exact - insertion point
return {
idx: diff < 0 ? pivot + 1 : pivot
};
}
// Insert element into a sorted array.
function insertSorted(elem, arr) {
const found = findNearest(elem, arr, false);
const count = (found.exact && unique) ? 1 : 0;
arr.splice(found.idx, count, elem);
return arr;
}
return {
/**
* Get an element at the given position.
* @memberof Tinode.CBuffer#
* @param {number} at - Position to fetch from.
* @returns {Object} Element at the given position or <tt>undefined</tt>
*/
getAt: function(at) {
return buffer[at];
},
/**
* Convenience method for getting the last element of the buffer.
* @memberof Tinode.CBuffer#
* @returns {Object} The last element in the buffer or <tt>undefined</tt> if buffer is empty.
*/
getLast: function() {
return buffer.length > 0 ? buffer[buffer.length - 1] : undefined;
},
/** Add new element(s) to the buffer. Variadic: takes one or more arguments. If an array is passed as a single
* argument, its elements are inserted individually.
* @memberof Tinode.CBuffer#
*
* @param {...Object|Array} - One or more objects to insert.
*/
put: function() {
let insert;
// inspect arguments: if array, insert its elements, if one or more non-array arguments, insert them one by one
if (arguments.length == 1 && Array.isArray(arguments[0])) {
insert = arguments[0];
} else {
insert = arguments;
}
for (let idx in insert) {
insertSorted(insert[idx], buffer);
}
},
/**
* Remove element at the given position.
* @memberof Tinode.CBuffer#
* @param {number} at - Position to delete at.
* @returns {Object} Element at the given position or <tt>undefined</tt>
*/
delAt: function(at) {
let r = buffer.splice(at, 1);
if (r && r.length > 0) {
return r[0];
}
return undefined;
},
/**
* Remove elements between two positions.
* @memberof Tinode.CBuffer#
* @param {number} since - Position to delete from (inclusive).
* @param {number} before - Position to delete to (exclusive).
*
* @returns {Array} array of removed elements (could be zero length).
*/
delRange: function(since, before) {
return buffer.splice(since, before - since);
},
/**
* Return the number of elements the buffer holds.
* @memberof Tinode.CBuffer#
* @return {number} Number of elements in the buffer.
*/
length: function() {
return buffer.length;
},
/**
* Reset the buffer discarding all elements
* @memberof Tinode.CBuffer#
*/
reset: function() {
buffer = [];
},
/**
* Callback for iterating contents of buffer. See {@link Tinode.CBuffer#forEach}.
* @callback ForEachCallbackType
* @memberof Tinode.CBuffer#
* @param {Object} elem - Element of the buffer.
* @param {number} index - Index of the current element.
*/
/**
* Apply given function `callback` to all elements of the buffer.
* @memberof Tinode.CBuffer#
*
* @param {Tinode.ForEachCallbackType} callback - Function to call for each element.
* @param {integer} startIdx - Optional index to start iterating from (inclusive).
* @param {integer} beforeIdx - Optional index to stop iterating before (exclusive).
* @param {Object} context - calling context (i.e. value of 'this' in callback)
*/
forEach: function(callback, startIdx, beforeIdx, context) {
startIdx = startIdx | 0;
beforeIdx = beforeIdx || buffer.length;
for (let i = startIdx; i < beforeIdx; i++) {
callback.call(context, buffer[i], i);
}
},
/**
* Find element in buffer using buffer's comparison function.
* @memberof Tinode.CBuffer#
*
* @param {Object} elem - element to find.
* @param {boolean=} nearest - when true and exact match is not found, return the nearest element (insertion point).
* @returns {number} index of the element in the buffer or -1.
*/
find: function(elem, nearest) {
const {
idx
} = findNearest(elem, buffer, !nearest);
return idx;
}
}
}
// Helper function for creating an endpoint URL
function makeBaseUrl(host, protocol, apiKey) {
let url = null;
if (protocol === 'http' || protocol === 'https' || protocol === 'ws' || protocol === 'wss') {
url = protocol + '://';
url += host;
if (url.charAt(url.length - 1) !== '/') {
url += '/';
}
url += 'v' + PROTOCOL_VERSION + '/channels';
if (protocol === 'http' || protocol === 'https') {
// Long polling endpoint end with "lp", i.e.
// '/v0/channels/lp' vs just '/v0/channels' for ws
url += '/lp';
}
url += '?apikey=' + apiKey;
}
return url;
}
/**
* An abstraction for a websocket or a long polling connection.
*
* @class Connection
* @memberof Tinode
*
* @param {string} host_ - Host name and port number to connect to.
* @param {string} apiKey_ - API key generated by keygen
* @param {string} transport_ - Network transport to use, either `ws`/`wss` for websocket or `lp` for long polling.
* @param {boolean} secure_ - Use secure WebSocket (wss) if true.
* @param {boolean} autoreconnect_ - If connection is lost, try to reconnect automatically.
*/
var Connection = function(host_, apiKey_, transport_, secure_, autoreconnect_) {
let host = host_;
let secure = secure_;
let apiKey = apiKey_;
let autoreconnect = autoreconnect_;
// Settings for exponential backoff
const _BOFF_BASE = 2000; // 2000 milliseconds, minimum delay between reconnects
const _BOFF_MAX_ITER = 10; // Maximum delay between reconnects 2^10 * 2000 ~ 34 minutes
const _BOFF_JITTER = 0.3; // Add random delay
let _boffTimer = null;
let _boffIteration = 0;
let _boffClosed = false; // Indicator if the socket was manually closed - don't autoreconnect if true.
let log = (text, ...args) => {
if (this.logger) {
this.logger(text, ...args);
}
}
// Backoff implementation - reconnect after a timeout.
function boffReconnect() {
// Clear timer
clearTimeout(_boffTimer);
// Calculate when to fire the reconnect attempt
const timeout = _BOFF_BASE * (Math.pow(2, _boffIteration) * (1.0 + _BOFF_JITTER * Math.random()));
// Update iteration counter for future use
_boffIteration = (_boffIteration >= _BOFF_MAX_ITER ? _boffIteration : _boffIteration + 1);
if (this.onAutoreconnectIteration) {
this.onAutoreconnectIteration(timeout);
}
_boffTimer = setTimeout(() => {
log("Reconnecting, iter=" + _boffIteration + ", timeout=" + timeout);
// Maybe the socket was closed while we waited for the timer?
if (!_boffClosed) {
const prom = this.connect();
if (this.onAutoreconnectIteration) {
this.onAutoreconnectIteration(0, prom);
} else {
// Suppress error if it's not used.
prom.catch(() => {
/* do nothing */
});
}
} else if (this.onAutoreconnectIteration) {
this.onAutoreconnectIteration(-1);
}
}, timeout);
}
// Terminate auto-reconnect process.
function boffStop() {
clearTimeout(_boffTimer);
_boffTimer = null;
}
// Reset auto-reconnect iteration counter.
function boffReset() {
_boffIteration = 0;
}
// Initialization for Websocket
function init_ws(instance) {
let _socket = null;
/**
* Initiate a new connection
* @memberof Tinode.Connection#
* @param {string} host_ Host name to connect to; if null the old host name will be used.
* @param {boolean} force Force new connection even if one already exists.
* @return {Promise} Promise resolved/rejected when the connection call completes, resolution is called without parameters, rejection passes the {Error} as parameter.
*/
instance.connect = function(host_, force) {
_boffClosed = false;
if (_socket) {
if (!force && _socket.readyState == _socket.OPEN) {
return Promise.resolve();
}
_socket.close();
_socket = null;
}
if (host_) {
host = host_;
}
return new Promise(function(resolve, reject) {
const url = makeBaseUrl(host, secure ? 'wss' : 'ws', apiKey);
log("Connecting to: ", url);
// It throws when the server is not accessible but the exception cannot be caught:
// https://stackoverflow.com/questions/31002592/javascript-doesnt-catch-error-in-websocket-instantiation/31003057
const conn = new WebSocketProvider(url);
conn.onerror = function(err) {
reject(err);
}
conn.onopen = function(evt) {
if (autoreconnect) {
boffStop();
}
if (instance.onOpen) {
instance.onOpen();
}
resolve();
}
conn.onclose = function(evt) {
_socket = null;
if (instance.onDisconnect) {
const code = _boffClosed ? NETWORK_USER : NETWORK_ERROR;
instance.onDisconnect(new Error(_boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT +
' (' + code + ')'), code);
}
if (!_boffClosed && autoreconnect) {
boffReconnect.call(instance);
}
}
conn.onmessage = function(evt) {
if (instance.onMessage) {
instance.onMessage(evt.data);
}
}
_socket = conn;
});
}
/**
* Try to restore a network connection, also reset backoff.
* @memberof Tinode.Connection#
*
* @param {boolean} force - reconnect even if there is a live connection already.
*/
instance.reconnect = function(force) {
boffStop();
instance.connect(null, force);
}
/**
* Terminate the network connection
* @memberof Tinode.Connection#
*/
instance.disconnect = function() {
_boffClosed = true;
boffStop();
if (!_socket) {
return;
}
_socket.close();
_socket = null;
}
/**
* Send a string to the server.
* @memberof Tinode.Connection#
*
* @param {string} msg - String to send.
* @throws Throws an exception if the underlying connection is not live.
*/
instance.sendText = function(msg) {
if (_socket && (_socket.readyState == _socket.OPEN)) {
_socket.send(msg);
} else {
throw new Error("Websocket is not connected");
}
};
/**
* Check if socket is alive.
* @memberof Tinode.Connection#
* @returns {boolean} true if connection is live, false otherwise
*/
instance.isConnected = function() {
return (_socket && (_socket.readyState == _socket.OPEN));
}
/**
* Get the name of the current network transport.
* @memberof Tinode.Connection#
* @returns {string} name of the transport such as 'ws' or 'lp'.
*/
instance.transport = function() {
return 'ws';
}
/**
* Send network probe to check if connection is indeed live.
* @memberof Tinode.Connection#
*/
instance.probe = function() {
instance.sendText('1');
}
}
// Initialization for long polling.
function init_lp(instance) {
const XDR_UNSENT = 0; // Client has been created. open() not called yet.
const XDR_OPENED = 1; // open() has been called.
const XDR_HEADERS_RECEIVED = 2; // send() has been called, and headers and status are available.
const XDR_LOADING = 3; // Downloading; responseText holds partial data.
const XDR_DONE = 4; // The operation is complete.
// Fully composed endpoint URL, with API key & SID
let _lpURL = null;
let _poller = null;
let _sender = null;
function lp_sender(url_) {
let sender = new XMLHttpRequest();
sender.onreadystatechange = function(evt) {
if (sender.readyState == XDR_DONE && sender.status >= 400) {
// Some sort of error response
throw new Error("LP sender failed, " + sender.status);
}
}
sender.open('POST', url_, true);
return sender;
}
function lp_poller(url_, resolve, reject) {
let poller = new XMLHttpRequest();
let promiseCompleted = false;
poller.onreadystatechange = function(evt) {
if (poller.readyState == XDR_DONE) {
if (poller.status == 201) { // 201 == HTTP.Created, get SID
let pkt = JSON.parse(poller.responseText, jsonParseHelper);
_lpURL = url_ + '&sid=' + pkt.ctrl.params.sid
poller = lp_poller(_lpURL);
poller.send(null)
if (instance.onOpen) {
instance.onOpen();
}
if (resolve) {
promiseCompleted = true;
resolve();
}
if (autoreconnect) {
boffStop();
}
} else if (poller.status < 400) { // 400 = HTTP.BadRequest
if (instance.onMessage) {
instance.onMessage(poller.responseText)
}
poller = lp_poller(_lpURL);
poller.send(null);
} else {
// Don't throw an error here, gracefully handle server errors
if (reject && !promiseCompleted) {
promiseCompleted = true;
reject(poller.responseText);
}
if (instance.onMessage && poller.responseText) {
instance.onMessage(poller.responseText);
}
if (instance.onDisconnect) {
const code = poller.status || (_boffClosed ? NETWORK_USER : NETWORK_ERROR);
const text = poller.responseText || (_boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT);
instance.onDisconnect(new Error(text + ' (' + code + ')'), code);
}
// Polling has stopped. Indicate it by setting poller to null.
poller = null;
if (!_boffClosed && autoreconnect) {
boffReconnect.call(instance);
}
}
}
}
poller.open('GET', url_, true);
return poller;
}
instance.connect = function(host_, force) {
_boffClosed = false;
if (_poller) {
if (!force) {
return Promise.resolve();
}
_poller.onreadystatechange = undefined;
_poller.abort();
_poller = null;
}
if (host_) {
host = host_;
}
return new Promise(function(resolve, reject) {
const url = makeBaseUrl(host, secure ? 'https' : 'http', apiKey);
log("Connecting to: ", url);
_poller = lp_poller(url, resolve, reject);
_poller.send(null)
}).catch((err) => {
console.log("LP connection failed:", err);
});
};
instance.reconnect = function(force) {
boffStop();
instance.connect(null, force);
};
instance.disconnect = function() {
_boffClosed = true;
boffStop();
if (_sender) {
_sender.onreadystatechange = undefined;
_sender.abort();
_sender = null;
}
if (_poller) {
_poller.onreadystatechange = undefined;
_poller.abort();
_poller = null;
}
if (instance.onDisconnect) {
instance.onDisconnect(new Error(NETWORK_USER_TEXT + ' (' + NETWORK_USER + ')'), NETWORK_USER);
}
// Ensure it's reconstructed
_lpURL = null;
}
instance.sendText = function(msg) {
_sender = lp_sender(_lpURL);
if (_sender && (_sender.readyState == 1)) { // 1 == OPENED
_sender.send(msg);
} else {
throw new Error("Long poller failed to connect");
}
};
instance.isConnected = function() {
return (_poller && true);
}
instance.transport = function() {
return 'lp';
}
instance.probe = function() {
instance.sendText('1');
}
}
let initialized = false;
if (transport_ === 'lp') {
// explicit request to use long polling
init_lp(this);
initialized = true;
} else if (transport_ === 'ws') {
// explicit request to use web socket
// if websockets are not available, horrible things will happen
init_ws(this);
initialized = true;
// Default transport selection
} else if (typeof window == 'object') {
if (window['WebSocket']) {
// Using web sockets -- default.
init_ws(this);
initialized = true;
} else if (window['XMLHttpRequest']) {
// The browser has no websockets, using long polling.
init_lp(this);
initialized = true;
}
}
if (!initialized) {
// No transport is avaiilable.
console.log("No network transport is available. Running under Node? Call 'Tinode.setNetworkProviders()'.");
throw new Error("No network transport is available. Running under Node? Call 'Tinode.setNetworkProviders()'.");
}
/**
* Check if the given network transport is available.
* @memberof Tinode.Connection#
* @param {String} trans - either 'ws' (websocket) or 'lp' (long polling).
* @returns true if given transport is available, false otherwise.
*/
this.transportAvailable = function(transp) {
switch (transp) {
case 'ws':
return typeof window == 'object' && window['WebSocket'];
case 'lp':
return typeof window == 'object' && window['XMLHttpRequest'];
default:
console.log("Request for unknown transport", transp);
return false;
}
}
/**
* Reset autoreconnect counter to zero.
* @memberof Tinode.Connection#
*/
this.backoffReset = function() {
boffReset();
}
// Callbacks:
/**
* A callback to pass incoming messages to. See {@link Tinode.Connection#onMessage}.
* @callback Tinode.Connection.OnMessage
* @memberof Tinode.Connection
* @param {string} message - Message to process.
*/
/**
* A callback to pass incoming messages to.
* @type {Tinode.Connection.OnMessage}
* @memberof Tinode.Connection#
*/
this.onMessage = undefined;
/**
* A callback for reporting a dropped connection.
* @type {function}
* @memberof Tinode.Connection#
*/
this.onDisconnect = undefined;
/**
* A callback called when the connection is ready to be used for sending. For websockets it's socket open,
* for long polling it's readyState=1 (OPENED)
* @type {function}
* @memberof Tinode.Connection#
*/
this.onOpen = undefined;
/**
* A callback to notify of reconnection attempts. See {@link Tinode.Connection#onAutoreconnectIteration}.
* @memberof Tinode.Connection
* @callback AutoreconnectIterationType
* @param {string} timeout - time till the next reconnect attempt in milliseconds. -1 means reconnect was skipped.
* @param {Promise} promise resolved or rejected when the reconnect attemp completes.
*
*/
/**
* A callback to inform when the next attampt to reconnect will happen and to receive connection promise.
* @memberof Tinode.Connection#
* @type {Tinode.Connection.AutoreconnectIterationType}
*/
this.onAutoreconnectIteration = undefined;
/**
* A callback to log events from Connection. See {@link Tinode.Connection#logger}.
* @memberof Tinode.Connection
* @callback LoggerCallbackType
* @param {string} event - Event to log.
*/
/**
* A callback to report logging events.
* @memberof Tinode.Connection#
* @type {Tinode.Connection.LoggerCallbackType}
*/
this.logger = undefined;
};
/**
* @class Tinode
*
* @param {string} appname_ - Name of the caliing application to be reported in User Agent.
* @param {string} host_ - Host name and port number to connect to.
* @param {string} apiKey_ - API key generated by keygen
* @param {string} transport_ - See {@link Tinode.Connection#transport}.
* @param {boolean} secure_ - Use Secure WebSocket if true.
* @param {string} platform_ - Optional platform identifier, one of "ios", "web", "android".
*/
var Tinode = function(appname_, host_, apiKey_, transport_, secure_, platform_) {
// Client-provided application name, format <Name>/<version number>
if (appname_) {
this._appName = appname_;
} else {
this._appName = "Undefined";
}
// API Key.
this._apiKey = apiKey_;
// Name and version of the browser.
this._browser = '';
this._platform = platform_;
this._hwos = 'undefined';
this._humanLanguage = 'xx';
// Underlying OS.
if (typeof navigator != 'undefined') {
this._browser = getBrowserInfo(navigator.userAgent, navigator.product);
this._hwos = navigator.platform;
// This is the default language. It could be changed by client.
this._humanLanguage = navigator.language || 'en-US';
}
// Logging to console enabled
this._loggingEnabled = false;
// When logging, trip long strings (base64-encoded images) for readability
this._trimLongStrings = false;
// UID of the currently authenticated user.
this._myUID = null;
// Status of connection: authenticated or not.
this._authenticated = false;
// Login used in the last successful basic authentication
this._login = null;
// Token which can be used for login instead of login/password.
this._authToken = null;
// Counter of received packets
this._inPacketCount = 0;
// Counter for generating unique message IDs
this._messageId = Math.floor((Math.random() * 0xFFFF) + 0xFFFF);
// Information about the server, if connected
this._serverInfo = null;
// Push notification token. Called deviceToken for consistency with the Android SDK.
this._deviceToken = null;
// Cache of pending promises by message id.
this._pendingPromises = {};
// The Timeout object returned by the reject expired promises setInterval
this._expirePromises = null;
/** A connection object, see {@link Tinode.Connection}. */
this._connection = new Connection(host_, apiKey_, transport_, secure_, true);
// Console logger. Babel somehow fails to parse '...rest' parameter.
this.logger = (str, ...args) => {
if (this._loggingEnabled) {
const d = new Date()
const dateString = ('0' + d.getUTCHours()).slice(-2) + ':' +
('0' + d.getUTCMinutes()).slice(-2) + ':' +
('0' + d.getUTCSeconds()).slice(-2) + '.' +
('00' + d.getUTCMilliseconds()).slice(-3);
console.log('[' + dateString + ']', str, args.join(' '));
}
}
this._connection.logger = this.logger;
// Tinode's cache of objects
this._cache = {};
const cachePut = this.cachePut = (type, name, obj) => {
this._cache[type + ':' + name] = obj;
}
const cacheGet = this.cacheGet = (type, name) => {
return this._cache[type + ':' + name];
}
const cacheDel = this.cacheDel = (type, name) => {
delete this._cache[type + ':' + name];
}
// Enumerate all items in cache, call func for each item.
// Enumeration stops if func returns true.
const cacheMap = this.cacheMap = (func, context) => {
for (let idx in this._cache) {
if (func(this._cache[idx], idx, context)) {
break;
}
}
}
// Make limited cache management available to topic.
// Caching user.public only. Everything else is per-topic.
this.attachCacheToTopic = (topic) => {
topic._tinode = this;
topic._cacheGetUser = (uid) => {
const pub = cacheGet('user', uid);
if (pub) {
return {
user: uid,
public: mergeObj({}, pub)
};
}
return undefined;
};
topic._cachePutUser = (uid, user) => {
return cachePut('user', uid, mergeObj({}, user.public));
};
topic._cacheDelUser = (uid) => {
return cacheDel('user', uid);
};
topic._cachePutSelf = () => {
return cachePut('topic', topic.name, topic);
}
topic._cacheDelSelf = () => {
return cacheDel('topic', topic.name);
}
}
// Resolve or reject a pending promise.
// Unresolved promises are stored in _pendingPromises.
const execPromise = (id, code, onOK, errorText) => {
const callbacks = this._pendingPromises[id];
if (callbacks) {
delete this._pendingPromises[id];
if (code >= 200 && code < 400) {
if (callbacks.resolve) {
callbacks.resolve(onOK);
}
} else if (callbacks.reject) {
callbacks.reject(new Error(errorText + " (" + code + ")"));
}
}
}
// Generator of default promises for sent packets.
const makePromise = (id) => {
let promise = null;
if (id) {
promise = new Promise((resolve, reject) => {
// Stored callbacks will be called when the response packet with this Id arrives
this._pendingPromises[id] = {
'resolve': resolve,
'reject': reject,
'ts': new Date()
};
})
}
return promise;
}
// Generates unique message IDs
const getNextUniqueId = this.getNextUniqueId = () => {
return (this._messageId != 0) ? '' + this._messageId++ : undefined;
}
// Get User Agent string
const getUserAgent = () => {
return this._appName + ' (' + (this._browser ? this._browser + '; ' : '') + this._hwos + '); ' + LIBRARY;
}
// Generator of packets stubs
this.initPacket = (type, topic) => {
switch (type) {
case 'hi':
return {
'hi': {
'id': getNextUniqueId(),
'ver': VERSION,
'ua': getUserAgent(),
'dev': this._deviceToken,
'lang': this._humanLanguage,
'platf': this._platform
}
};
case 'acc':
return {
'acc': {
'id': getNextUniqueId(),
'user': null,
'scheme': null,
'secret': null,
'login': false,
'tags': null,
'desc': {},
'cred': {}
}
};
case 'login':
return {
'login': {
'id': getNextUniqueId(),
'scheme': null,
'secret': null
}
};
case 'sub':
return {
'sub': {
'id': getNextUniqueId(),
'topic': topic,
'set': {},
'get': {}
}
};
case 'leave':
return {
'leave': {
'id': getNextUniqueId(),
'topic': topic,
'unsub': false
}
};
case 'pub':
return {
'pub': {
'id': getNextUniqueId(),
'topic': topic,
'noecho': false,
'head': null,
'content': {}
}
};
case 'get':
return {
'get': {
'id': getNextUniqueId(),
'topic': topic,
'what': null, // data, sub, desc, space separated list; unknown strings are ignored
'desc': {},
'sub': {},
'data': {}
}
};
case 'set':
return {
'set': {
'id': getNextUniqueId(),
'topic': topic,
'desc': {},
'sub': {},
'tags': []
}
};
case 'del':
return {
'del': {
'id': getNextUniqueId(),
'topic': topic,
'what': null,
'delseq': null,
'user': null,
'hard': false
}
};
case 'note':
return {
'note': {
// no id by design
'topic': topic,
'what': null, // one of "recv", "read", "kp"
'seq': undefined // the server-side message id aknowledged as received or read
}
};
default:
throw new Error("Unknown packet type requested: " + type);
}
}
// Send a packet. If packet id is provided return a promise.
this.send = (pkt, id) => {
let promise;
if (id) {
promise = makePromise(id);
}
pkt = simplify(pkt);
let msg = JSON.stringify(pkt);
this.logger("out: " + (this._trimLongStrings ? JSON.stringify(pkt, jsonLoggerHelper) : msg));
try {
this._connection.sendText(msg);
} catch (err) {
// If sendText throws, wrap the error in a promise or rethrow.
if (id) {
execPromise(id, NETWORK_ERROR, null, err.message);
} else {
throw err;
}
}
return promise;
}
// On successful login save server-provided data.
this.loginSuccessful = (ctrl) => {
if (!ctrl.params || !ctrl.params.user) {
return;
}
// This is a response to a successful login,
// extract UID and security token, save it in Tinode module
this._myUID = ctrl.params.user;
this._authenticated = (ctrl && ctrl.code >= 200 && ctrl.code < 300);
if (ctrl.params && ctrl.params.token && ctrl.params.expires) {
this._authToken = {
token: ctrl.params.token,
expires: new Date(ctrl.params.expires)
};
} else {
this._authToken = null;
}
if (this.onLogin) {
this.onLogin(ctrl.code, ctrl.text);
}
}
// The main message dispatcher.
this._connection.onMessage = (data) => {
// Skip empty response. This happens when LP times out.
if (!data) return;
this._inPacketCount++;
// Send raw message to listener
if (this.onRawMessage) {
this.onRawMessage(data);
}
if (data === '0') {
// Server response to a network probe.
if (this.onNetworkProbe) {
this.onNetworkProbe();
}
// No processing is necessary.
return;
}
let pkt = JSON.parse(data, jsonParseHelper);
if (!pkt) {
this.logger("in: " + data);
this.logger("ERROR: failed to parse data");
} else {
this.logger("in: " + (this._trimLongStrings ? JSON.stringify(pkt, jsonLoggerHelper) : data));
// Send complete packet to listener
if (this.onMessage) {
this.onMessage(pkt);
}
if (pkt.ctrl) {
// Handling {ctrl} message
if (this.onCtrlMessage) {
this.onCtrlMessage(pkt.ctrl);
}
// Resolve or reject a pending promise, if any
if (pkt.ctrl.id) {
execPromise(pkt.ctrl.id, pkt.ctrl.code, pkt.ctrl, pkt.ctrl.text);
}
setTimeout(() => {
if (pkt.ctrl.code == 205 && pkt.ctrl.text == 'evicted') {
// User evicted from topic.
const topic = cacheGet('topic', pkt.ctrl.topic);
if (topic) {
topic._resetSub();
if (pkt.ctrl.params && pkt.ctrl.params.unsub) {
topic._gone();
}
}
} else if (pkt.ctrl.params && pkt.ctrl.params.what == 'data') {
// All messages received: "params":{"count":11,"what":"data"},
const topic = cacheGet('topic', pkt.ctrl.topic);
if (topic) {
topic._allMessagesReceived(pkt.ctrl.params.count);
}
} else if (pkt.ctrl.params && pkt.ctrl.params.what == 'sub') {
// The topic has no subscriptions.
const topic = cacheGet('topic', pkt.ctrl.topic);
if (topic) {
// Trigger topic.onSubsUpdated.
topic._processMetaSub([]);
}
}
}, 0);
} else {
setTimeout(() => {
if (pkt.meta) {
// Handling a {meta} message.
// Preferred API: Route meta to topic, if one is registered
const topic = cacheGet('topic', pkt.meta.topic);
if (topic) {
topic._routeMeta(pkt.meta);
}
if (pkt.meta.id) {
execPromise(pkt.meta.id, 200, pkt.meta, 'META');
}
// Secondary API: callback
if (this.onMetaMessage) {
this.onMetaMessage(pkt.meta);
}
} else if (pkt.data) {
// Handling {data} message
// Preferred API: Route data to topic, if one is registered
const topic = cacheGet('topic', pkt.data.topic);
if (topic) {
topic._routeData(pkt.data);
}
// Secondary API: Call callback
if (this.onDataMessage) {
this.onDataMessage(pkt.data);
}
} else if (pkt.pres) {
// Handling {pres} message
// Preferred API: Route presence to topic, if one is registered
const topic = cacheGet('topic', pkt.pres.topic);
if (topic) {
topic._routePres(pkt.pres);
}
// Secondary API - callback
if (this.onPresMessage) {
this.onPresMessage(pkt.pres);
}
} else if (pkt.info) {
// {info} message - read/received notifications and key presses
// Preferred API: Route {info}} to topic, if one is registered
const topic = cacheGet('topic', pkt.info.topic);
if (topic) {
topic._routeInfo(pkt.info);
}
// Secondary API - callback
if (this.onInfoMessage) {
this.onInfoMessage(pkt.info);
}
} else {
this.logger("ERROR: Unknown packet received.");
}
}, 0);
}
}
}
// Ready to start sending.
this._connection.onOpen = () => {
if (!this._expirePromises) {
// Reject promises which have not been resolved for too long.
this._expirePromises = setInterval(() => {
const err = new Error("Timeout (504)");
const expires = new Date(new Date().getTime() - EXPIRE_PROMISES_TIMEOUT);
for (let id in this._pendingPromises) {
let callbacks = this._pendingPromises[id];
if (callbacks && callbacks.ts < expires) {
this.logger("Promise expired", id);
delete this._pendingPromises[id];
if (callbacks.reject) {
callbacks.reject(err);
}
}
}
}, EXPIRE_PROMISES_PERIOD);
}
this.hello();
}
// Wrapper for the reconnect iterator callback.
this._connection.onAutoreconnectIteration = (timeout, promise) => {
if (this.onAutoreconnectIteration) {
this.onAutoreconnectIteration(timeout, promise);
}
}
this._connection.onDisconnect = (err, code) => {
this._inPacketCount = 0;
this._serverInfo = null;
this._authenticated = false;
if (this._expirePromises) {
clearInterval(this._expirePromises);
this._expirePromises = null;
}
// Mark all topics as unsubscribed
cacheMap((obj, key) => {
if (key.lastIndexOf('topic:', 0) === 0) {
obj._resetSub();
}
});
// Reject all pending promises
for (let key in this._pendingPromises) {
let callbacks = this._pendingPromises[key];
if (callbacks && callbacks.reject) {
callbacks.reject(err);
}
}
this._pendingPromises = {};
if (this.onDisconnect) {
this.onDisconnect(err);
}
}
};
// Static methods.
/**
* Helper method to package account credential.
* @memberof Tinode
* @static
*
* @param {String|Object} meth - validation method or object with validation data.
* @param {String=} val - validation value (e.g. email or phone number).
* @param {Object=} params - validation parameters.
* @param {String=} resp - validation response.
*
* @returns {Array} array with a single credentail or null if no valid credentials were given.
*/
Tinode.credential = function(meth, val, params, resp) {
if (typeof meth == 'object') {
({
val,
params,
resp,
meth
} = meth);
}
if (meth && (val || resp)) {
return [{
'meth': meth,
'val': val,
'resp': resp,
'params': params
}];
}
return null;
};
/**
* Determine topic type from topic's name: grp, p2p, me, fnd.
* @memberof Tinode
* @static
*
* @param {string} name - Name of the topic to test.
* @returns {string} One of <tt>'me'</tt>, <tt>'grp'</tt>, <tt>'p2p'</tt> or <tt>undefined</tt>.
*/
Tinode.topicType = function(name) {
const types = {
'me': 'me',
'fnd': 'fnd',
'grp': 'grp',
'new': 'grp',
'nch': 'grp',
'chn': 'grp',
'usr': 'p2p',
'sys': 'sys'
};
return types[(typeof name == 'string') ? name.substring(0, 3) : 'xxx'];
};
/**
* Check if the given topic name is a name of a group topic.
* @memberof Tinode
* @static
*
* @param {string} name - Name of the topic to test.
* @returns {boolean} true if the name is a name of a group topic, false otherwise.
*/
Tinode.isGroupTopicName = function(name) {
return Tinode.topicType(name) === 'grp';
};
/**
* Check if the given topic name is a name of a p2p topic.
* @memberof Tinode
* @static
*
* @param {string} name - Name of the topic to test.
* @returns {boolean} true if the name is a name of a p2p topic, false otherwise.
*/
Tinode.isP2PTopicName = function(name) {
return Tinode.topicType(name) === 'p2p';
};
/**
* Check if the topic name is a name of a new topic.
* @memberof Tinode
* @static
*
* @param {string} name - topic name to check.
* @returns {boolean} true if the name is a name of a new topic.
*/
Tinode.isNewGroupTopicName = function(name) {
return (typeof name == 'string') &&
(name.substring(0, 3) == TOPIC_NEW || name.substring(0, 3) == TOPIC_NEW_CHAN);
};
/**
* Check if the topic name is a name of a channel.
* @memberof Tinode
* @static
*
* @param {string} name - topic name to check.
* @returns {boolean} true if the name is a name of a channel.
*/
Tinode.isChannelTopicName = function(name) {
return (typeof name == 'string') &&
(name.substring(0, 3) == TOPIC_CHAN || name.substring(0, 3) == TOPIC_NEW_CHAN);
};
/**
* Return information about the current version of this Tinode client library.
* @memberof Tinode
* @static
*
* @returns {string} semantic version of the library, e.g. '0.15.5-rc1'.
*/
Tinode.getVersion = function() {
return VERSION;
};
/**
* To use Tinode in a non browser context, supply WebSocket and XMLHttpRequest providers.
* @static
* @memberof Tinode
* @param wsProvider WebSocket provider, e.g. for nodeJS require('ws').
* @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').
*/
Tinode.setNetworkProviders = function(wsProvider, xhrProvider) {
WebSocketProvider = wsProvider;
XHRProvider = xhrProvider;
};
/**
* Return information about the current name and version of this Tinode library.
* @memberof Tinode
* @static
*
* @returns {string} the name of the library and it's version.
*/
Tinode.getLibrary = function() {
return LIBRARY;
};
// Exported constants
Tinode.MESSAGE_STATUS_NONE = MESSAGE_STATUS_NONE;
Tinode.MESSAGE_STATUS_QUEUED = MESSAGE_STATUS_QUEUED;
Tinode.MESSAGE_STATUS_SENDING = MESSAGE_STATUS_SENDING;
Tinode.MESSAGE_STATUS_FAILED = MESSAGE_STATUS_FAILED;
Tinode.MESSAGE_STATUS_SENT = MESSAGE_STATUS_SENT;
Tinode.MESSAGE_STATUS_RECEIVED = MESSAGE_STATUS_RECEIVED;
Tinode.MESSAGE_STATUS_READ = MESSAGE_STATUS_READ;
Tinode.MESSAGE_STATUS_TO_ME = MESSAGE_STATUS_TO_ME;
// Unicode [del] symbol.
Tinode.DEL_CHAR = '\u2421';
/**
* Check if the given string represents NULL value as defined by Tinode ('\u2421').
* @memberof Tinode
* @static
*
* @param {String} str - string to check for null value.
*
* @returns {boolean} true if string represents NULL value, false otherwise.
*/
Tinode.isNullValue = function(str) {
return str === Tinode.DEL_CHAR;
};
/**
* Check if the given URL string is a relative URL.
* Check for cases like:
* 'http://example.com'
* ' http://example.com'
* '//example.com/'
* 'http:example.com'
* 'http:/example.com'
* @memberof Tinode
* @static
*
* @param {String} url - URL string to check.
*
* @returns {boolean} true if the URL is relative, false otherwise.
*/
Tinode.isRelativeURL = function(url) {
return !/^\s*([a-z][a-z0-9+.-]*:|\/\/)/im.test(url);
};
// Names of keys to server-provided configuration limits.
Tinode.MAX_MESSAGE_SIZE = 'maxMessageSize';
Tinode.MAX_SUBSCRIBER_COUNT = 'maxSubscriberCount';
Tinode.MAX_TAG_COUNT = 'maxTagCount';
Tinode.MAX_FILE_UPLOAD_SIZE = 'maxFileUploadSize';
// Public methods;
Tinode.prototype = {
/**
* Connect to the server.
* @memberof Tinode#
*
* @param {String} host_ - name of the host to connect to.
*
* @return {Promise} Promise resolved/rejected when the connection call completes:
* <tt>resolve()</tt> is called without parameters, <tt>reject()</tt> receives the <tt>Error</tt> as a single parameter.
*/
connect: function(host_) {
return this._connection.connect(host_);
},
/**
* Attempt to reconnect to the server immediately.
* @memberof Tinode#
*
* @param {String} force - reconnect even if there is a connection already.
*/
reconnect: function(force) {
this._connection.reconnect(force);
},
/**
* Disconnect from the server.
* @memberof Tinode#
*/
disconnect: function() {
this._connection.disconnect();
},
/**
* Send a network probe message to make sure the connection is alive.
* @memberof Tinode#
*/
networkProbe: function() {
this._connection.probe();
},
/**
* Check for live connection to server.
* @memberof Tinode#
*
* @returns {Boolean} true if there is a live connection, false otherwise.
*/
isConnected: function() {
return this._connection.isConnected();
},
/**
* Check if connection is authenticated (last login was successful).
* @memberof Tinode#
* @returns {boolean} true if authenticated, false otherwise.
*/
isAuthenticated: function() {
return this._authenticated;
},
/**
* Add API key and auth token to the relative URL making it usable for getting data
* from the server in a simple GET request.
* @memberof Tinode#
*
* @param {String} URL to wrap.
* @returns {string} URL with appended API key and token, if valid token is present.
*/
authorizeURL: function(url) {
if (!url) {
return url;
}
if (Tinode.isRelativeURL(url)) {
// Fake base to make the relative URL parseable.
const base = 'scheme://host/';
const parsed = new URL(url, base);
if (this._apiKey) {
parsed.searchParams.append('apikey', this._apiKey);
}
if (this._authToken.token) {
parsed.searchParams.append('auth', 'token');
parsed.searchParams.append('secret', this._authToken.token);
}
// Convert back to string and strip fake base URL except for the root slash.
url = parsed.toString().substring(base.length - 1);
}
return url;
},
/**
* @typedef AccountParams
* @memberof Tinode
* @type Object
* @property {Tinode.DefAcs=} defacs - Default access parameters for user's <tt>me</tt> topic.
* @property {Object=} public - Public application-defined data exposed on <tt>me</tt> topic.
* @property {Object=} private - Private application-defined data accessible on <tt>me</tt> topic.
* @property {Array} tags - array of string tags for user discovery.
* @property {string=} token - authentication token to use.
*/
/**
* @typedef DefAcs
* @memberof Tinode
* @type Object
* @property {string=} auth - Access mode for <tt>me</tt> for authenticated users.
* @property {string=} anon - Access mode for <tt>me</tt> anonymous users.
*/
/**
* Create or update an account.
* @memberof Tinode#
*
* @param {String} uid - User id to update
* @param {String} scheme - Authentication scheme; <tt>"basic"</tt> and <tt>"anonymous"</tt> are the currently supported schemes.
* @param {String} secret - Authentication secret, assumed to be already base64 encoded.
* @param {Boolean=} login - Use new account to authenticate current session
* @param {Tinode.AccountParams=} params - User data to pass to the server.
*/
account: function(uid, scheme, secret, login, params) {
const pkt = this.initPacket('acc');
pkt.acc.user = uid;
pkt.acc.scheme = scheme;
pkt.acc.secret = secret;
// Log in to the new account using selected scheme
pkt.acc.login = login;
if (params) {
pkt.acc.desc.defacs = params.defacs;
pkt.acc.desc.public = params.public;
pkt.acc.desc.private = params.private;
pkt.acc.tags = params.tags;
pkt.acc.cred = params.cred;
pkt.acc.token = params.token;
}
return this.send(pkt, pkt.acc.id);
},
/**
* Create a new user. Wrapper for {@link Tinode#account}.
* @memberof Tinode#
*
* @param {String} scheme - Authentication scheme; <tt>"basic"</tt> is the only currently supported scheme.
* @param {String} secret - Authentication.
* @param {Boolean=} login - Use new account to authenticate current session
* @param {Tinode.AccountParams=} params - User data to pass to the server.
*
* @returns {Promise} Promise which will be resolved/rejected when server reply is received.
*/
createAccount: function(scheme, secret, login, params) {
let promise = this.account(USER_NEW, scheme, secret, login, params);
if (login) {
promise = promise.then((ctrl) => {
this.loginSuccessful(ctrl);
return ctrl;
});
}
return promise;
},
/**
* Create user with 'basic' authentication scheme and immediately
* use it for authentication. Wrapper for {@link Tinode#account}.
* @memberof Tinode#
*
* @param {string} username - Login to use for the new account.
* @param {string} password - User's password.
* @param {Tinode.AccountParams=} params - User data to pass to the server.
*
* @returns {Promise} Promise which will be resolved/rejected when server reply is received.
*/
createAccountBasic: function(username, password, params) {
// Make sure we are not using 'null' or 'undefined';
username = username || '';
password = password || '';
return this.createAccount('basic',
b64EncodeUnicode(username + ':' + password), true, params);
},
/**
* Update user's credentials for 'basic' authentication scheme. Wrapper for {@link Tinode#account}.
* @memberof Tinode#
*
* @param {string} uid - User ID to update.
* @param {string} username - Login to use for the new account.
* @param {string} password - User's password.
* @param {Tinode.AccountParams=} params - data to pass to the server.
*
* @returns {Promise} Promise which will be resolved/rejected when server reply is received.
*/
updateAccountBasic: function(uid, username, password, params) {
// Make sure we are not using 'null' or 'undefined';
username = username || '';
password = password || '';
return this.account(uid, 'basic',
b64EncodeUnicode(username + ':' + password), false, params);
},
/**
* Send handshake to the server.
* @memberof Tinode#
*
* @returns {Promise} Promise which will be resolved/rejected when server reply is received.
*/
hello: function() {
const pkt = this.initPacket('hi');
return this.send(pkt, pkt.hi.id)
.then((ctrl) => {
// Reset backoff counter on successful connection.
this._connection.backoffReset();
// Server response contains server protocol version, build, constraints,
// session ID for long polling. Save them.
if (ctrl.params) {
this._serverInfo = ctrl.params;
}
if (this.onConnect) {
this.onConnect();
}
return ctrl;
}).catch((err) => {
this._connection.reconnect(true);
if (this.onDisconnect) {
this.onDisconnect(err);
}
});
},
/**
* Set or refresh the push notifications/device token. If the client is connected,
* the deviceToken can be sent to the server.
*
* @memberof Tinode#
* @param {string} dt - token obtained from the provider.
* @param {boolean} sendToServer - if true, send dt to server immediately.
*
* @returns true if attempt was made to send the token to the server.
*/
setDeviceToken: function(dt, sendToServer) {
let sent = false;
if (dt && dt != this._deviceToken) {
this._deviceToken = dt;
if (sendToServer && this.isConnected() && this.isAuthenticated()) {
this.send({
'hi': {
'dev': dt
}
});
sent = true;
}
}
return sent;
},
/**
* Authenticate current session.
* @memberof Tinode#
*
* @param {String} scheme - Authentication scheme; <tt>"basic"</tt> is the only currently supported scheme.
* @param {String} secret - Authentication secret, assumed to be already base64 encoded.
*
* @returns {Promise} Promise which will be resolved/rejected when server reply is received.
*/
login: function(scheme, secret, cred) {
const pkt = this.initPacket('login');
pkt.login.scheme = scheme;
pkt.login.secret = secret;
pkt.login.cred = cred;
return this.send(pkt, pkt.login.id)
.then((ctrl) => {
this.loginSuccessful(ctrl);
return ctrl;
});
},
/**
* Wrapper for {@link Tinode#login} with basic authentication
* @memberof Tinode#
*
* @param {String} uname - User name.
* @param {String} password - Password.
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
loginBasic: function(uname, password, cred) {
return this.login('basic', b64EncodeUnicode(uname + ':' + password), cred)
.then((ctrl) => {
this._login = uname;
return ctrl;
});
},
/**
* Wrapper for {@link Tinode#login} with token authentication
* @memberof Tinode#
*
* @param {String} token - Token received in response to earlier login.
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
loginToken: function(token, cred) {
return this.login('token', token, cred);
},
/**
* Send a request for resetting an authentication secret.
* @memberof Tinode#
*
* @param {String} scheme - authentication scheme to reset.
* @param {String} method - method to use for resetting the secret, such as "email" or "tel".
* @param {String} value - value of the credential to use, a specific email address or a phone number.
*
* @returns {Promise} Promise which will be resolved/rejected on receiving the server reply.
*/
requestResetAuthSecret: function(scheme, method, value) {
return this.login('reset', b64EncodeUnicode(scheme + ':' + method + ':' + value));
},
/**
* @typedef AuthToken
* @memberof Tinode
* @type Object
* @property {String} token - Token value.
* @property {Date} expires - Token expiration time.
*/
/**
* Get stored authentication token.
* @memberof Tinode#
*
* @returns {Tinode.AuthToken} authentication token.
*/
getAuthToken: function() {
if (this._authToken && (this._authToken.expires.getTime() > Date.now())) {
return this._authToken;
} else {
this._authToken = null;
}
return null;
},
/**
* Application may provide a saved authentication token.
* @memberof Tinode#
*
* @param {Tinode.AuthToken} token - authentication token.
*/
setAuthToken: function(token) {
this._authToken = token;
},
/**
* @typedef SetParams
* @memberof Tinode
* @property {Tinode.SetDesc=} desc - Topic initialization parameters when creating a new topic or a new subscription.
* @property {Tinode.SetSub=} sub - Subscription initialization parameters.
*/
/**
* @typedef SetDesc
* @memberof Tinode
* @property {Tinode.DefAcs=} defacs - Default access mode.
* @property {Object=} public - Free-form topic description, publically accessible.
* @property {Object=} private - Free-form topic descriptionaccessible only to the owner.
*/
/**
* @typedef SetSub
* @memberof Tinode
* @property {String=} user - UID of the user affected by the request. Default (empty) - current user.
* @property {String=} mode - User access mode, either requested or assigned dependent on context.
* @property {Object=} info - Free-form payload to pass to the invited user or topic manager.
*/
/**
* Parameters passed to {@link Tinode#subscribe}.
*
* @typedef SubscriptionParams
* @memberof Tinode
* @property {Tinode.SetParams=} set - Parameters used to initialize topic
* @property {Tinode.GetQuery=} get - Query for fetching data from topic.
*/
/**
* Send a topic subscription request.
* @memberof Tinode#
*
* @param {String} topic - Name of the topic to subscribe to.
* @param {Tinode.GetQuery=} getParams - Optional subscription metadata query
* @param {Tinode.SetParams=} setParams - Optional initialization parameters
*
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
subscribe: function(topicName, getParams, setParams) {
const pkt = this.initPacket('sub', topicName)
if (!topicName) {
topicName = TOPIC_NEW;
}
pkt.sub.get = getParams;
if (setParams) {
if (setParams.sub) {
pkt.sub.set.sub = setParams.sub;
}
if (setParams.desc) {
if (Tinode.isNewGroupTopicName(topicName)) {
// Full set.desc params are used for new topics only
pkt.sub.set.desc = setParams.desc;
} else if (Tinode.isP2PTopicName(topicName) && setParams.desc.defacs) {
// Use optional default permissions only.
pkt.sub.set.desc = {
defacs: setParams.desc.defacs
};
}
}
if (setParams.tags) {
pkt.sub.set.tags = setParams.tags;
}
}
return this.send(pkt, pkt.sub.id);
},
/**
* Detach and optionally unsubscribe from the topic
* @memberof Tinode#
*
* @param {String} topic - Topic to detach from.
* @param {Boolean} unsub - If <tt>true</tt>, detach and unsubscribe, otherwise just detach.
*
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
leave: function(topic, unsub) {
const pkt = this.initPacket('leave', topic);
pkt.leave.unsub = unsub;
return this.send(pkt, pkt.leave.id);
},
/**
* Create message draft without sending it to the server.
* @memberof Tinode#
*
* @param {String} topic - Name of the topic to publish to.
* @param {Object} data - Payload to publish.
* @param {Boolean=} noEcho - If <tt>true</tt>, tell the server not to echo the message to the original session.
*
* @returns {Object} new message which can be sent to the server or otherwise used.
*/
createMessage: function(topic, data, noEcho) {
const pkt = this.initPacket('pub', topic);
let dft = typeof data == 'string' ? Drafty.parse(data) : data;
if (dft && !Drafty.isPlainText(dft)) {
pkt.pub.head = {
mime: Drafty.getContentType()
};
data = dft;
}
pkt.pub.noecho = noEcho;
pkt.pub.content = data;
return pkt.pub;
},
/**
* Publish {data} message to topic.
* @memberof Tinode#
*
* @param {String} topic - Name of the topic to publish to.
* @param {Object} data - Payload to publish.
* @param {Boolean=} noEcho - If <tt>true</tt>, tell the server not to echo the message to the original session.
*
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
publish: function(topic, data, noEcho) {
return this.publishMessage(
this.createMessage(topic, data, noEcho)
);
},
/**
* Publish message to topic. The message should be created by {@link Tinode#createMessage}.
* @memberof Tinode#
*
* @param {Object} pub - Message to publish.
*
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
publishMessage: function(pub) {
// Make a shallow copy. Needed in order to clear locally-assigned temp values;
pub = Object.assign({}, pub);
pub.seq = undefined;
pub.from = undefined;
pub.ts = undefined;
return this.send({
pub: pub
}, pub.id);
},
/**
* @typedef GetQuery
* @type Object
* @memberof Tinode
* @property {Tinode.GetOptsType=} desc - If provided (even if empty), fetch topic description.
* @property {Tinode.GetOptsType=} sub - If provided (even if empty), fetch topic subscriptions.
* @property {Tinode.GetDataType=} data - If provided (even if empty), get messages.
*/
/**
* @typedef GetOptsType
* @type Object
* @memberof Tinode
* @property {Date=} ims - "If modified since", fetch data only it was was modified since stated date.
* @property {Number=} limit - Maximum number of results to return. Ignored when querying topic description.
*/
/**
* @typedef GetDataType
* @type Object
* @memberof Tinode
* @property {Number=} since - Load messages with seq id equal or greater than this value.
* @property {Number=} before - Load messages with seq id lower than this number.
* @property {Number=} limit - Maximum number of results to return.
*/
/**
* Request topic metadata
* @memberof Tinode#
*
* @param {String} topic - Name of the topic to query.
* @param {Tinode.GetQuery} params - Parameters of the query. Use {Tinode.MetaGetBuilder} to generate.
*
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
getMeta: function(topic, params) {
const pkt = this.initPacket('get', topic);
pkt.get = mergeObj(pkt.get, params);
return this.send(pkt, pkt.get.id);
},
/**
* Update topic's metadata: description, subscribtions.
* @memberof Tinode#
*
* @param {String} topic - Topic to update.
* @param {Tinode.SetParams} params - topic metadata to update.
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
setMeta: function(topic, params) {
const pkt = this.initPacket('set', topic);
const what = [];
if (params) {
['desc', 'sub', 'tags', 'cred'].map(function(key) {
if (params.hasOwnProperty(key)) {
what.push(key);
pkt.set[key] = params[key];
}
});
}
if (what.length == 0) {
return Promise.reject(new Error("Invalid {set} parameters"));
}
return this.send(pkt, pkt.set.id);
},
/**
* Range of message IDs to delete.
*
* @typedef DelRange
* @type Object
* @memberof Tinode
* @property {Number} low - low end of the range, inclusive (closed).
* @property {Number=} hi - high end of the range, exclusive (open).
*/
/**
* Delete some or all messages in a topic.
* @memberof Tinode#
*
* @param {String} topic - Topic name to delete messages from.
* @param {Tinode.DelRange[]} list - Ranges of message IDs to delete.
* @param {Boolean=} hard - Hard or soft delete
*
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
delMessages: function(topic, ranges, hard) {
const pkt = this.initPacket('del', topic);
pkt.del.what = 'msg';
pkt.del.delseq = ranges;
pkt.del.hard = hard;
return this.send(pkt, pkt.del.id);
},
/**
* Delete the topic alltogether. Requires Owner permission.
* @memberof Tinode#
*
* @param {String} topic - Name of the topic to delete
* @param {Boolean} hard - hard-delete topic.
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
delTopic: function(topic, hard) {
const pkt = this.initPacket('del', topic);
pkt.del.what = 'topic';
pkt.del.hard = hard;
return this.send(pkt, pkt.del.id).then((ctrl) => {
this.cacheDel('topic', topic);
return this.ctrl;
});
},
/**
* Delete subscription. Requires Share permission.
* @memberof Tinode#
*
* @param {String} topic - Name of the topic to delete
* @param {String} user - User ID to remove.
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
delSubscription: function(topic, user) {
const pkt = this.initPacket('del', topic);
pkt.del.what = 'sub';
pkt.del.user = user;
return this.send(pkt, pkt.del.id);
},
/**
* Delete credential. Always sent on 'me' topic.
* @memberof Tinode#
*
* @param {String} method - validation method such as 'email' or 'tel'.
* @param {String} value - validation value, i.e. 'alice@example.com'.
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
delCredential: function(method, value) {
const pkt = this.initPacket('del', TOPIC_ME);
pkt.del.what = 'cred';
pkt.del.cred = {
meth: method,
val: value
};
return this.send(pkt, pkt.del.id);
},
/**
* Request to delete account of the current user.
* @memberof Tinode#
*
* @param {Boolean} hard - hard-delete user.
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
delCurrentUser: function(hard) {
const pkt = this.initPacket('del', null);
pkt.del.what = 'user';
pkt.del.hard = hard;
return this.send(pkt, pkt.del.id).then((ctrl) => {
this._myUID = null;
});
},
/**
* Notify server that a message or messages were read or received. Does NOT return promise.
* @memberof Tinode#
*
* @param {String} topic - Name of the topic where the mesage is being aknowledged.
* @param {String} what - Action being aknowledged, either "read" or "recv".
* @param {Number} seq - Maximum id of the message being acknowledged.
*/
note: function(topic, what, seq) {
if (seq <= 0 || seq >= LOCAL_SEQID) {
throw new Error("Invalid message id " + seq);
}
const pkt = this.initPacket('note', topic);
pkt.note.what = what;
pkt.note.seq = seq;
this.send(pkt);
},
/**
* Broadcast a key-press notification to topic subscribers. Used to show
* typing notifications "user X is typing...".
* @memberof Tinode#
*
* @param {String} topic - Name of the topic to broadcast to.
*/
noteKeyPress: function(topic) {
const pkt = this.initPacket('note', topic);
pkt.note.what = 'kp';
this.send(pkt);
},
/**
* Get a named topic, either pull it from cache or create a new instance.
* There is a single instance of topic for each name.
* @memberof Tinode#
*
* @param {String} name - Name of the topic to get.
* @returns {Tinode.Topic} Requested or newly created topic or <tt>undefined</tt> if topic name is invalid.
*/
getTopic: function(name) {
let topic = this.cacheGet('topic', name);
if (!topic && name) {
if (name == TOPIC_ME) {
topic = new TopicMe();
} else if (name == TOPIC_FND) {
topic = new TopicFnd();
} else {
topic = new Topic(name);
}
// topic._new = false;
this.cachePut('topic', name, topic);
this.attachCacheToTopic(topic);
}
return topic;
},
/**
* Check if named topic is already present in cache.
* @memberof Tinode#
*
* @param {String} name - Name of the topic to check.
* @returns {Boolean} true if topic is found in cache, false oterwise.
*/
isTopicCached: function(name) {
return !!this.cacheGet('topic', name);
},
/**
* Instantiate a new group topic. An actual name will be assigned by the server
* on {@link Tinode.Topic.subscribe}.
* @memberof Tinode#
*
* @param {Tinode.Callbacks} callbacks - Object with callbacks for various events.
* @returns {Tinode.Topic} Newly created topic.
*/
newTopic: function(callbacks) {
const topic = new Topic(TOPIC_NEW, callbacks);
this.attachCacheToTopic(topic);
return topic;
},
/**
* Instantiate a new channel-enabled group topic. An actual name will be assigned by the server
* on {@link Tinode.Topic.subscribe}.
* @memberof Tinode#
*
* @param {Tinode.Callbacks} callbacks - Object with callbacks for various events.
* @returns {Tinode.Topic} Newly created topic.
*/
newChannel: function(callbacks) {
const topic = new Topic(TOPIC_NEW_CHAN, callbacks);
this.attachCacheToTopic(topic);
return topic;
},
/**
* Generate unique name like 'new123456' suitable for creating a new group topic.
* @memberof Tinode#
*
* @param {Boolean} isChan - if the topic is channel-enabled.
* @returns {string} name which can be used for creating a new group topic.
*/
newGroupTopicName: function(isChan) {
return (isChan ? TOPIC_NEW_CHAN : TOPIC_NEW) + this.getNextUniqueId();
},
/**
* Instantiate a new P2P topic with a given peer.
* @memberof Tinode#
*
* @param {string} peer - UID of the peer to start topic with.
* @param {Tinode.Callbacks} callbacks - Object with callbacks for various events.
* @returns {Tinode.Topic} Newly created topic.
*/
newTopicWith: function(peer, callbacks) {
const topic = new Topic(peer, callbacks);
this.attachCacheToTopic(topic);
return topic;
},
/**
* Instantiate 'me' topic or get it from cache.
* @memberof Tinode#
*
* @returns {Tinode.TopicMe} Instance of 'me' topic.
*/
getMeTopic: function() {
return this.getTopic(TOPIC_ME);
},
/**
* Instantiate 'fnd' (find) topic or get it from cache.
* @memberof Tinode#
*
* @returns {Tinode.Topic} Instance of 'fnd' topic.
*/
getFndTopic: function() {
return this.getTopic(TOPIC_FND);
},
/**
* Create a new LargeFileHelper instance
* @memberof Tinode#
*
* @returns {Tinode.LargeFileHelper} instance of a LargeFileHelper.
*/
getLargeFileHelper: function() {
return new LargeFileHelper(this);
},
/**
* Get the UID of the the current authenticated user.
* @memberof Tinode#
* @returns {string} UID of the current user or <tt>undefined</tt> if the session is not yet authenticated or if there is no session.
*/
getCurrentUserID: function() {
return this._myUID;
},
/**
* Check if the given user ID is equal to the current user's UID.
* @memberof Tinode#
* @param {string} uid - UID to check.
* @returns {boolean} true if the given UID belongs to the current logged in user.
*/
isMe: function(uid) {
return this._myUID === uid;
},
/**
* Get login used for last successful authentication.
* @memberof Tinode#
* @returns {string} login last used successfully or <tt>undefined</tt>.
*/
getCurrentLogin: function() {
return this._login;
},
/**
* Return information about the server: protocol version and build timestamp.
* @memberof Tinode#
* @returns {Object} build and version of the server or <tt>null</tt> if there is no connection or if the first server response has not been received yet.
*/
getServerInfo: function() {
return this._serverInfo;
},
/**
* Return server-provided configuration value (long integer).
* @memberof Tinode#
* @param {String} name of the value to return
* @param {Object} defaultValue to return in case server limit is not set or not found.
* @returns {integer} named value.
*/
getServerLimit: function(name, defaultValue) {
return (this._serverInfo ? this._serverInfo[name] : null) || defaultValue;
},
/**
* Toggle console logging. Logging is off by default.
* @memberof Tinode#
* @param {boolean} enabled - Set to <tt>true</tt> to enable logging to console.
* @param {boolean} trimLongStrings - Set to <tt>true</tt> to trim long strings.
*/
enableLogging: function(enabled, trimLongStrings) {
this._loggingEnabled = enabled;
this._trimLongStrings = enabled && trimLongStrings;
},
/**
* Set UI language to report to the server. Must be called before 'hi' is sent, otherwise it will not be used.
* @memberof Tinode#
*
* @param {String} hl - human (UI) language, like "en_US" or "zh-Hans".
*/
setHumanLanguage: function(hl) {
if (hl) {
this._humanLanguage = hl;
}
},
/**
* Check if given topic is online.
* @memberof Tinode#
*
* @param {String} name of the topic to test.
* @returns {Boolean} true if topic is online, false otherwise.
*/
isTopicOnline: function(name) {
const me = this.getMeTopic();
const cont = me && me.getContact(name);
return cont && cont.online;
},
/**
* Get access mode for the given contact.
* @memberof Tinode#
*
* @param {String} name of the topic to query.
* @returns {AccessMode} access mode if topic is found, null otherwise.
*/
getTopicAccessMode: function(name) {
const me = this.getMeTopic();
const cont = me && me.getContact(name);
return cont ? cont.acs : null;
},
/**
* Include message ID into all subsequest messages to server instructin it to send aknowledgemens.
* Required for promises to function. Default is "on".
* @memberof Tinode#
*
* @param {Boolean} status - Turn aknowledgemens on or off.
* @deprecated
*/
wantAkn: function(status) {
if (status) {
this._messageId = Math.floor((Math.random() * 0xFFFFFF) + 0xFFFFFF);
} else {
this._messageId = 0;
}
},
// Callbacks:
/**
* Callback to report when the websocket is opened. The callback has no parameters.
* @memberof Tinode#
* @type {Tinode.onWebsocketOpen}
*/
onWebsocketOpen: undefined,
/**
* @typedef Tinode.ServerParams
* @memberof Tinode
* @type Object
* @property {string} ver - Server version
* @property {string} build - Server build
* @property {string=} sid - Session ID, long polling connections only.
*/
/**
* @callback Tinode.onConnect
* @param {number} code - Result code
* @param {string} text - Text epxplaining the completion, i.e "OK" or an error message.
* @param {Tinode.ServerParams} params - Parameters returned by the server.
*/
/**
* Callback to report when connection with Tinode server is established.
* @memberof Tinode#
* @type {Tinode.onConnect}
*/
onConnect: undefined,
/**
* Callback to report when connection is lost. The callback has no parameters.
* @memberof Tinode#
* @type {Tinode.onDisconnect}
*/
onDisconnect: undefined,
/**
* @callback Tinode.onLogin
* @param {number} code - NUmeric completion code, same as HTTP status codes.
* @param {string} text - Explanation of the completion code.
*/
/**
* Callback to report login completion.
* @memberof Tinode#
* @type {Tinode.onLogin}
*/
onLogin: undefined,
/**
* Callback to receive {ctrl} (control) messages.
* @memberof Tinode#
* @type {Tinode.onCtrlMessage}
*/
onCtrlMessage: undefined,
/**
* Callback to recieve {data} (content) messages.
* @memberof Tinode#
* @type {Tinode.onDataMessage}
*/
onDataMessage: undefined,
/**
* Callback to receive {pres} (presence) messages.
* @memberof Tinode#
* @type {Tinode.onPresMessage}
*/
onPresMessage: undefined,
/**
* Callback to receive all messages as objects.
* @memberof Tinode#
* @type {Tinode.onMessage}
*/
onMessage: undefined,
/**
* Callback to receive all messages as unparsed text.
* @memberof Tinode#
* @type {Tinode.onRawMessage}
*/
onRawMessage: undefined,
/**
* Callback to receive server responses to network probes. See {@link Tinode#networkProbe}
* @memberof Tinode#
* @type {Tinode.onNetworkProbe}
*/
onNetworkProbe: undefined,
/**
* Callback to be notified when exponential backoff is iterating.
* @memberof Tinode#
* @type {Tinode.onAutoreconnectIteration}
*/
onAutoreconnectIteration: undefined,
};
/**
* Helper class for constructing {@link Tinode.GetQuery}.
*
* @class MetaGetBuilder
* @memberof Tinode
*
* @param {Tinode.Topic} parent topic which instantiated this builder.
*/
var MetaGetBuilder = function(parent) {
this.topic = parent;
const me = parent._tinode.getMeTopic();
this.contact = me && me.getContact(parent.name);
this.what = {};
}
MetaGetBuilder.prototype = {
// Get latest timestamp
_get_ims: function() {
const cupd = this.contact && this.contact.updated;
const tupd = this.topic._lastDescUpdate || 0;
return cupd > tupd ? cupd : tupd;
},
/**
* Add query parameters to fetch messages within explicit limits.
* @memberof Tinode.MetaGetBuilder#
*
* @param {Number=} since messages newer than this (inclusive);
* @param {Number=} before older than this (exclusive)
* @param {Number=} limit number of messages to fetch
* @returns {Tinode.MetaGetBuilder} <tt>this</tt> object.
*/
withData: function(since, before, limit) {
this.what['data'] = {
since: since,
before: before,
limit: limit
};
return this;
},
/**
* Add query parameters to fetch messages newer than the latest saved message.
* @memberof Tinode.MetaGetBuilder#
*
* @param {Number=} limit number of messages to fetch
*
* @returns {Tinode.MetaGetBuilder} <tt>this</tt> object.
*/
withLaterData: function(limit) {
return this.withData(this.topic._maxSeq > 0 ? this.topic._maxSeq + 1 : undefined, undefined, limit);
},
/**
* Add query parameters to fetch messages older than the earliest saved message.
* @memberof Tinode.MetaGetBuilder#
*
* @param {Number=} limit maximum number of messages to fetch.
*
* @returns {Tinode.MetaGetBuilder} <tt>this</tt> object.
*/
withEarlierData: function(limit) {
return this.withData(undefined, this.topic._minSeq > 0 ? this.topic._minSeq : undefined, limit);
},
/**
* Add query parameters to fetch topic description if it's newer than the given timestamp.
* @memberof Tinode.MetaGetBuilder#
*
* @param {Date=} ims fetch messages newer than this timestamp.
*
* @returns {Tinode.MetaGetBuilder} <tt>this</tt> object.
*/
withDesc: function(ims) {
this.what['desc'] = {
ims: ims
};
return this;
},
/**
* Add query parameters to fetch topic description if it's newer than the last update.
* @memberof Tinode.MetaGetBuilder#
*
* @returns {Tinode.MetaGetBuilder} <tt>this</tt> object.
*/
withLaterDesc: function() {
return this.withDesc(this._get_ims());
},
/**
* Add query parameters to fetch subscriptions.
* @memberof Tinode.MetaGetBuilder#
*
* @param {Date=} ims fetch subscriptions modified more recently than this timestamp
* @param {Number=} limit maximum number of subscriptions to fetch.
* @param {String=} userOrTopic user ID or topic name to fetch for fetching one subscription.
*
* @returns {Tinode.MetaGetBuilder} <tt>this</tt> object.
*/
withSub: function(ims, limit, userOrTopic) {
const opts = {
ims: ims,
limit: limit
};
if (this.topic.getType() == 'me') {
opts.topic = userOrTopic;
} else {
opts.user = userOrTopic;
}
this.what['sub'] = opts;
return this;
},
/**
* Add query parameters to fetch a single subscription.
* @memberof Tinode.MetaGetBuilder#
*
* @param {Date=} ims fetch subscriptions modified more recently than this timestamp
* @param {String=} userOrTopic user ID or topic name to fetch for fetching one subscription.
*
* @returns {Tinode.MetaGetBuilder} <tt>this</tt> object.
*/
withOneSub: function(ims, userOrTopic) {
return this.withSub(ims, undefined, userOrTopic);
},
/**
* Add query parameters to fetch a single subscription if it's been updated since the last update.
* @memberof Tinode.MetaGetBuilder#
*
* @param {String=} userOrTopic user ID or topic name to fetch for fetching one subscription.
*
* @returns {Tinode.MetaGetBuilder} <tt>this</tt> object.
*/
withLaterOneSub: function(userOrTopic) {
return this.withOneSub(this.topic._lastSubsUpdate, userOrTopic);
},
/**
* Add query parameters to fetch subscriptions updated since the last update.
* @memberof Tinode.MetaGetBuilder#
*
* @param {Number=} limit maximum number of subscriptions to fetch.
*
* @returns {Tinode.MetaGetBuilder} <tt>this</tt> object.
*/
withLaterSub: function(limit) {
return this.withSub(this.topic.isP2P() ?
this._get_ims() : this.topic._lastSubsUpdate,
limit);
},
/**
* Add query parameters to fetch topic tags.
* @memberof Tinode.MetaGetBuilder#
*
* @returns {Tinode.MetaGetBuilder} <tt>this</tt> object.
*/
withTags: function() {
this.what['tags'] = true;
return this;
},
/**
* Add query parameters to fetch user's credentials. 'me' topic only.
* @memberof Tinode.MetaGetBuilder#
*
* @returns {Tinode.MetaGetBuilder} <tt>this</tt> object.
*/
withCred: function() {
if (this.topic.getType() == 'me') {
this.what['cred'] = true;
} else {
this.topic._tinode.logger("ERROR: Invalid topic type for MetaGetBuilder:withCreds", this.topic.getType());
}
return this;
},
/**
* Add query parameters to fetch deleted messages within explicit limits. Any/all parameters can be null.
* @memberof Tinode.MetaGetBuilder#
*
* @param {Number=} since ids of messages deleted since this 'del' id (inclusive)
* @param {Number=} limit number of deleted message ids to fetch
*
* @returns {Tinode.MetaGetBuilder} <tt>this</tt> object.
*/
withDel: function(since, limit) {
if (since || limit) {
this.what['del'] = {
since: since,
limit: limit
};
}
return this;
},
/**
* Add query parameters to fetch messages deleted after the saved 'del' id.
* @memberof Tinode.MetaGetBuilder#
*
* @param {Number=} limit number of deleted message ids to fetch
*
* @returns {Tinode.MetaGetBuilder} <tt>this</tt> object.
*/
withLaterDel: function(limit) {
// Specify 'since' only if we have already received some messages. If
// we have no locally cached messages then we don't care if any messages were deleted.
return this.withDel(this.topic._maxSeq > 0 ? this.topic._maxDel + 1 : undefined, limit);
},
/**
* Construct parameters
* @memberof Tinode.MetaGetBuilder#
*
* @returns {Tinode.GetQuery} Get query
*/
build: function() {
const what = [];
const instance = this;
let params = {};
['data', 'sub', 'desc', 'tags', 'cred', 'del'].map(function(key) {
if (instance.what.hasOwnProperty(key)) {
what.push(key);
if (Object.getOwnPropertyNames(instance.what[key]).length > 0) {
params[key] = instance.what[key];
}
}
});
if (what.length > 0) {
params.what = what.join(' ');
} else {
params = undefined;
}
return params;
}
};
/**
* Helper class for handling access mode.
*
* @class AccessMode
* @memberof Tinode
*
* @param {AccessMode|Object=} acs AccessMode to copy or access mode object received from the server.
*/
var AccessMode = function(acs) {
if (acs) {
this.given = typeof acs.given == 'number' ? acs.given : AccessMode.decode(acs.given);
this.want = typeof acs.want == 'number' ? acs.want : AccessMode.decode(acs.want);
this.mode = acs.mode ? (typeof acs.mode == 'number' ? acs.mode : AccessMode.decode(acs.mode)) :
(this.given & this.want);
}
};
AccessMode._NONE = 0x00;
AccessMode._JOIN = 0x01;
AccessMode._READ = 0x02;
AccessMode._WRITE = 0x04;
AccessMode._PRES = 0x08;
AccessMode._APPROVE = 0x10;
AccessMode._SHARE = 0x20;
AccessMode._DELETE = 0x40;
AccessMode._OWNER = 0x80;
AccessMode._BITMASK = AccessMode._JOIN | AccessMode._READ | AccessMode._WRITE | AccessMode._PRES |
AccessMode._APPROVE | AccessMode._SHARE | AccessMode._DELETE | AccessMode._OWNER;
AccessMode._INVALID = 0x100000;
AccessMode._checkFlag = function(val, side, flag) {
side = side || 'mode';
if (['given', 'want', 'mode'].includes(side)) {
return ((val[side] & flag) != 0);
}
throw new Error("Invalid AccessMode component '" + side + "'");
}
/**
* Parse string into an access mode value.
* @memberof Tinode.AccessMode
* @static
*
* @param {string | number} mode - either a String representation of the access mode to parse or a set of bits to assign.
* @returns {number} - Access mode as a numeric value.
*/
AccessMode.decode = function(str) {
if (!str) {
return null;
} else if (typeof str == 'number') {
return str & AccessMode._BITMASK;
} else if (str === 'N' || str === 'n') {
return AccessMode._NONE;
}
const bitmask = {
'J': AccessMode._JOIN,
'R': AccessMode._READ,
'W': AccessMode._WRITE,
'P': AccessMode._PRES,
'A': AccessMode._APPROVE,
'S': AccessMode._SHARE,
'D': AccessMode._DELETE,
'O': AccessMode._OWNER
};
let m0 = AccessMode._NONE;
for (let i = 0; i < str.length; i++) {
const bit = bitmask[str.charAt(i).toUpperCase()];
if (!bit) {
// Unrecognized bit, skip.
continue;
}
m0 |= bit;
}
return m0;
};
/**
* Convert numeric representation of the access mode into a string.
*
* @memberof Tinode.AccessMode
* @static
*
* @param {number} val - access mode value to convert to a string.
* @returns {string} - Access mode as a string.
*/
AccessMode.encode = function(val) {
if (val === null || val === AccessMode._INVALID) {
return null;
} else if (val === AccessMode._NONE) {
return 'N';
}
const bitmask = ['J', 'R', 'W', 'P', 'A', 'S', 'D', 'O'];
let res = '';
for (let i = 0; i < bitmask.length; i++) {
if ((val & (1 << i)) != 0) {
res = res + bitmask[i];
}
}
return res;
};
/**
* Update numeric representation of access mode with the new value. The value
* is one of the following:
* - a string starting with '+' or '-' then the bits to add or remove, e.g. '+R-W' or '-PS'.
* - a new value of access mode
*
* @memberof Tinode.AccessMode
* @static
*
* @param {number} val - access mode value to update.
* @param {string} upd - update to apply to val.
* @returns {number} - updated access mode.
*/
AccessMode.update = function(val, upd) {
if (!upd || typeof upd != 'string') {
return val;
}
let action = upd.charAt(0);
if (action == '+' || action == '-') {
let val0 = val;
// Split delta-string like '+ABC-DEF+Z' into an array of parts including + and -.
const parts = upd.split(/([-+])/);
// Starting iteration from 1 because String.split() creates an array with the first empty element.
// Iterating by 2 because we parse pairs +/- then data.
for (let i = 1; i < parts.length - 1; i += 2) {
action = parts[i];
const m0 = AccessMode.decode(parts[i + 1]);
if (m0 == AccessMode._INVALID) {
return val;
}
if (m0 == null) {
continue;
}
if (action === '+') {
val0 |= m0;
} else if (action === '-') {
val0 &= ~m0;
}
}
val = val0;
} else {
// The string is an explicit new value 'ABC' rather than delta.
const val0 = AccessMode.decode(upd);
if (val0 != AccessMode._INVALID) {
val = val0;
}
}
return val;
};
/**
* Bits present in a1 but missing in a2.
*
* @static
* @memberof Tinode
*
* @param {number | string} a1 - access mode to subtract from.
* @param {number | string} a2 - access mode to subtract.
* @returns {number} access mode with bits present in a1 but missing in a2
*/
AccessMode.diff = function(a1, a2) {
a1 = AccessMode.decode(a1);
a2 = AccessMode.decode(a2);
if (a1 == AccessMode._INVALID || a2 == AccessMode._INVALID) {
return AccessMode._INVALID;
}
return a1 & ~a2;
};
/**
* AccessMode is a class representing topic access mode.
*
* @memberof Tinode
* @class AccessMode
*/
AccessMode.prototype = {
/**
* Custom formatter
*/
toString: function() {
return '{"mode": "' + AccessMode.encode(this.mode) +
'", "given": "' + AccessMode.encode(this.given) +
'", "want": "' + AccessMode.encode(this.want) + '"}';
},
/**
* Convert numeric values to strings.
*/
jsonHelper: function() {
return {
mode: AccessMode.encode(this.mode),
given: AccessMode.encode(this.given),
want: AccessMode.encode(this.want)
};
},
/**
* Assign value to 'mode'.
* @memberof Tinode.AccessMode
*
* @param {string | number} m - either a string representation of the access mode or a set of bits.
* @returns {AccessMode} - <b>this</b> AccessMode.
*/
setMode: function(m) {
this.mode = AccessMode.decode(m);
return this;
},
/**
* Update 'mode' value.
* @memberof Tinode.AccessMode
*
* @param {string} u - string representation of the changes to apply to access mode.
* @returns {AccessMode} - <b>this</b> AccessMode.
*/
updateMode: function(u) {
this.mode = AccessMode.update(this.mode, u);
return this;
},
/**
* Get 'mode' value as a string.
* @memberof Tinode.AccessMode
*
* @returns {string} - <b>mode</b> value.
*/
getMode: function() {
return AccessMode.encode(this.mode);
},
/**
* Assign 'given' value.
* @memberof Tinode.AccessMode
*
* @param {string | number} g - either a string representation of the access mode or a set of bits.
* @returns {AccessMode} - <b>this</b> AccessMode.
*/
setGiven: function(g) {
this.given = AccessMode.decode(g);
return this;
},
/**
* Update 'given' value.
* @memberof Tinode.AccessMode
*
* @param {string} u - string representation of the changes to apply to access mode.
* @returns {AccessMode} - <b>this</b> AccessMode.
*/
updateGiven: function(u) {
this.given = AccessMode.update(this.given, u);
return this;
},
/**
* Get 'given' value as a string.
* @memberof Tinode.AccessMode
*
* @returns {string} - <b>given</b> value.
*/
getGiven: function() {
return AccessMode.encode(this.given);
},
/**
* Assign 'want' value.
* @memberof Tinode.AccessMode
*
* @param {string | number} w - either a string representation of the access mode or a set of bits.
* @returns {AccessMode} - <b>this</b> AccessMode.
*/
setWant: function(w) {
this.want = AccessMode.decode(w);
return this;
},
/**
* Update 'want' value.
* @memberof Tinode.AccessMode
*
* @param {string} u - string representation of the changes to apply to access mode.
* @returns {AccessMode} - <b>this</b> AccessMode.
*/
updateWant: function(u) {
this.want = AccessMode.update(this.want, u);
return this;
},
/**
* Get 'want' value as a string.
* @memberof Tinode.AccessMode
*
* @returns {string} - <b>want</b> value.
*/
getWant: function() {
return AccessMode.encode(this.want);
},
/**
* Get permissions present in 'want' but missing in 'given'.
* Inverse of {@link Tinode.AccessMode#getExcessive}
*
* @memberof Tinode.AccessMode
*
* @returns {string} permissions present in <b>want</b> but missing in <b>given</b>.
*/
getMissing: function() {
return AccessMode.encode(this.want & ~this.given);
},
/**
* Get permissions present in 'given' but missing in 'want'.
* Inverse of {@link Tinode.AccessMode#getMissing}
* @memberof Tinode.AccessMode
*
* @returns {string} permissions present in <b>given</b> but missing in <b>want</b>.
*/
getExcessive: function() {
return AccessMode.encode(this.given & ~this.want);
},
/**
* Update 'want', 'give', and 'mode' values.
* @memberof Tinode.AccessMode
*
* @param {AccessMode} val - new access mode value.
* @returns {AccessMode} - <b>this</b> AccessMode.
*/
updateAll: function(val) {
if (val) {
this.updateGiven(val.given);
this.updateWant(val.want);
this.mode = this.given & this.want;
}
return this;
},
/**
* Check if Owner (O) flag is set.
* @memberof Tinode.AccessMode
* @param {string=} side - which permission to check: given, want, mode; default: mode.
* @returns {boolean} - true if flag is set.
*/
isOwner: function(side) {
return AccessMode._checkFlag(this, side, AccessMode._OWNER);
},
/**
* Check if Presence (P) flag is set.
* @memberof Tinode.AccessMode
* @param {string=} side - which permission to check: given, want, mode; default: mode.
* @returns {boolean} - true if flag is set.
*/
isPresencer: function(side) {
return AccessMode._checkFlag(this, side, AccessMode._PRES);
},
/**
* Check if Presence (P) flag is NOT set.
* @memberof Tinode.AccessMode
* @param {string=} side - which permission to check: given, want, mode; default: mode.
* @returns {boolean} - true if flag is set.
*/
isMuted: function(side) {
return !this.isPresencer(side);
},
/**
* Check if Join (J) flag is set.
* @memberof Tinode.AccessMode
* @param {string=} side - which permission to check: given, want, mode; default: mode.
* @returns {boolean} - true if flag is set.
*/
isJoiner: function(side) {
return AccessMode._checkFlag(this, side, AccessMode._JOIN);
},
/**
* Check if Reader (R) flag is set.
* @memberof Tinode.AccessMode
* @param {string=} side - which permission to check: given, want, mode; default: mode.
* @returns {boolean} - true if flag is set.
*/
isReader: function(side) {
return AccessMode._checkFlag(this, side, AccessMode._READ);
},
/**
* Check if Writer (W) flag is set.
* @memberof Tinode.AccessMode
* @param {string=} side - which permission to check: given, want, mode; default: mode.
* @returns {boolean} - true if flag is set.
*/
isWriter: function(side) {
return AccessMode._checkFlag(this, side, AccessMode._WRITE);
},
/**
* Check if Approver (A) flag is set.
* @memberof Tinode.AccessMode
* @param {string=} side - which permission to check: given, want, mode; default: mode.
* @returns {boolean} - true if flag is set.
*/
isApprover: function(side) {
return AccessMode._checkFlag(this, side, AccessMode._APPROVE);
},
/**
* Check if either one of Owner (O) or Approver (A) flags is set.
* @memberof Tinode.AccessMode
* @param {string=} side - which permission to check: given, want, mode; default: mode.
* @returns {boolean} - true if flag is set.
*/
isAdmin: function(side) {
return this.isOwner(side) || this.isApprover(side);
},
/**
* Check if either one of Owner (O), Approver (A), or Sharer (S) flags is set.
* @memberof Tinode.AccessMode
* @param {string=} side - which permission to check: given, want, mode; default: mode.
* @returns {boolean} - true if flag is set.
*/
isSharer: function(side) {
return this.isAdmin(side) || AccessMode._checkFlag(this, side, AccessMode._SHARE);
},
/**
* Check if Deleter (D) flag is set.
* @memberof Tinode.AccessMode
* @param {string=} side - which permission to check: given, want, mode; default: mode.
* @returns {boolean} - true if flag is set.
*/
isDeleter: function(side) {
return AccessMode._checkFlag(this, side, AccessMode._DELETE);
}
};
/**
* @callback Tinode.Topic.onData
* @param {Data} data - Data packet
*/
/**
* Topic is a class representing a logical communication channel.
* @class Topic
* @memberof Tinode
*
* @param {string} name - Name of the topic to create.
* @param {Object=} callbacks - Object with various event callbacks.
* @param {Tinode.Topic.onData} callbacks.onData - Callback which receives a {data} message.
* @param {callback} callbacks.onMeta - Callback which receives a {meta} message.
* @param {callback} callbacks.onPres - Callback which receives a {pres} message.
* @param {callback} callbacks.onInfo - Callback which receives an {info} message.
* @param {callback} callbacks.onMetaDesc - Callback which receives changes to topic desctioption {@link desc}.
* @param {callback} callbacks.onMetaSub - Called for a single subscription record change.
* @param {callback} callbacks.onSubsUpdated - Called after a batch of subscription changes have been recieved and cached.
* @param {callback} callbacks.onDeleteTopic - Called after the topic is deleted.
* @param {callback} callbacls.onAllMessagesReceived - Called when all requested {data} messages have been recived.
*/
var Topic = function(name, callbacks) {
// Parent Tinode object.
this._tinode = null;
// Server-provided data, locally immutable.
// topic name
this.name = name;
// timestamp when the topic was created
this.created = null;
// timestamp when the topic was last updated
this.updated = null;
// timestamp of the last messages
this.touched = null;
// access mode, see AccessMode
this.acs = new AccessMode(null);
// per-topic private data
this.private = null;
// per-topic public data
this.public = null;
// Locally cached data
// Subscribed users, for tracking read/recv/msg notifications.
this._users = {};
// Current value of locally issued seqId, used for pending messages.
this._queuedSeqId = LOCAL_SEQID;
// The maximum known {data.seq} value.
this._maxSeq = 0;
// The minimum known {data.seq} value.
this._minSeq = 0;
// Indicator that the last request for earlier messages returned 0.
this._noEarlierMsgs = false;
// The maximum known deletion ID.
this._maxDel = 0;
// User discovery tags
this._tags = [];
// Credentials such as email or phone number.
this._credentials = [];
// Message cache, sorted by message seq values, from old to new.
this._messages = CBuffer(function(a, b) {
return a.seq - b.seq;
}, true);
// Boolean, true if the topic is currently live
this._subscribed = false;
// Timestap when topic meta-desc update was recived.
this._lastDescUpdate = null;
// Timestap when topic meta-subs update was recived.
this._lastSubsUpdate = null;
// Topic created but not yet synced with the server. Used only during initialization.
this._new = true;
// Callbacks
if (callbacks) {
this.onData = callbacks.onData;
this.onMeta = callbacks.onMeta;
this.onPres = callbacks.onPres;
this.onInfo = callbacks.onInfo;
// A single desc update;
this.onMetaDesc = callbacks.onMetaDesc;
// A single subscription record;
this.onMetaSub = callbacks.onMetaSub;
// All subscription records received;
this.onSubsUpdated = callbacks.onSubsUpdated;
this.onTagsUpdated = callbacks.onTagsUpdated;
this.onCredsUpdated = callbacks.onCredsUpdated;
this.onDeleteTopic = callbacks.onDeleteTopic;
this.onAllMessagesReceived = callbacks.onAllMessagesReceived;
}
};
Topic.prototype = {
/**
* Check if the topic is subscribed.
* @memberof Tinode.Topic#
* @returns {boolean} True is topic is attached/subscribed, false otherwise.
*/
isSubscribed: function() {
return this._subscribed;
},
/**
* Request topic to subscribe. Wrapper for {@link Tinode#subscribe}.
* @memberof Tinode.Topic#
*
* @param {Tinode.GetQuery=} getParams - get query parameters.
* @param {Tinode.SetParams=} setParams - set parameters.
* @returns {Promise} Promise to be resolved/rejected when the server responds to the request.
*/
subscribe: function(getParams, setParams) {
// If the topic is already subscribed, return resolved promise
if (this._subscribed) {
return Promise.resolve(this);
}
// Send subscribe message, handle async response.
// If topic name is explicitly provided, use it. If no name, then it's a new group topic,
// use "new".
return this._tinode.subscribe(this.name || TOPIC_NEW, getParams, setParams).then((ctrl) => {
if (ctrl.code >= 300) {
// Do nothing if subscription status has not changed.
return ctrl;
}
this._subscribed = true;
this.acs = (ctrl.params && ctrl.params.acs) ? ctrl.params.acs : this.acs;
// Set topic name for new topics and add it to cache.
if (this._new) {
this._new = false;
// Name may change new123456 -> grpAbCdEf
this.name = ctrl.topic;
this.created = ctrl.ts;
this.updated = ctrl.ts;
// Don't assign touched, otherwise topic will be put on top of the list on subscribe.
this._cachePutSelf();
if (this.name != TOPIC_ME && this.name != TOPIC_FND) {
// Add the new topic to the list of contacts maintained by the 'me' topic.
const me = this._tinode.getMeTopic();
if (me) {
me._processMetaSub([{
_noForwarding: true,
topic: this.name,
created: ctrl.ts,
updated: ctrl.ts,
acs: this.acs
}]);
}
}
if (setParams && setParams.desc) {
setParams.desc._noForwarding = true;
this._processMetaDesc(setParams.desc);
}
}
return ctrl;
});
},
/**
* Create a draft of a message without sending it to the server.
* @memberof Tinode.Topic#
*
* @param {string | Object} data - Content to wrap in a draft.
* @param {Boolean=} noEcho - If <tt>true</tt> server will not echo message back to originating
* session. Otherwise the server will send a copy of the message to sender.
*
* @returns {Object} message draft.
*/
createMessage: function(data, noEcho) {
return this._tinode.createMessage(this.name, data, noEcho);
},
/**
* Immediately publish data to topic. Wrapper for {@link Tinode#publish}.
* @memberof Tinode.Topic#
*
* @param {string | Object} data - Data to publish, either plain string or a Drafty object.
* @param {Boolean=} noEcho - If <tt>true</tt> server will not echo message back to originating
* @returns {Promise} Promise to be resolved/rejected when the server responds to the request.
*/
publish: function(data, noEcho) {
return this.publishMessage(this.createMessage(data, noEcho));
},
/**
* Publish message created by {@link Tinode.Topic#createMessage}.
* @memberof Tinode.Topic#
*
* @param {Object} pub - {data} object to publish. Must be created by {@link Tinode.Topic#createMessage}
*
* @returns {Promise} Promise to be resolved/rejected when the server responds to the request.
*/
publishMessage: function(pub) {
if (!this._subscribed) {
return Promise.reject(new Error("Cannot publish on inactive topic"));
}
// Update header with attachment records.
if (Drafty.hasAttachments(pub.content) && !pub.head.attachments) {
let attachments = [];
Drafty.attachments(pub.content, (data) => {
attachments.push(data.ref);
});
pub.head.attachments = attachments;
}
// Send data.
pub._sending = true;
pub._failed = false;
return this._tinode.publishMessage(pub).then((ctrl) => {
pub._sending = false;
pub.ts = ctrl.ts;
this.swapMessageId(pub, ctrl.params.seq);
this._routeData(pub);
return ctrl;
}).catch((err) => {
this._tinode.logger("WARNING: Message rejected by the server", err);
pub._sending = false;
pub._failed = true;
if (this.onData) {
this.onData();
}
});
},
/**
* Add message to local message cache, send to the server when the promise is resolved.
* If promise is null or undefined, the message will be sent immediately.
* The message is sent when the
* The message should be created by {@link Tinode.Topic#createMessage}.
* This is probably not the final API.
* @memberof Tinode.Topic#
*
* @param {Object} pub - Message to use as a draft.
* @param {Promise} prom - Message will be sent when this promise is resolved, discarded if rejected.
*
* @returns {Promise} derived promise.
*/
publishDraft: function(pub, prom) {
if (!prom && !this._subscribed) {
return Promise.reject(new Error("Cannot publish on inactive topic"));
}
const seq = pub.seq || this._getQueuedSeqId();
if (!pub._noForwarding) {
// The 'seq', 'ts', and 'from' are added to mimic {data}. They are removed later
// before the message is sent.
pub._noForwarding = true;
pub.seq = seq;
pub.ts = new Date();
pub.from = this._tinode.getCurrentUserID();
// Don't need an echo message because the message is added to local cache right away.
pub.noecho = true;
// Add to cache.
this._messages.put(pub);
if (this.onData) {
this.onData(pub);
}
}
// If promise is provided, send the queued message when it's resolved.
// If no promise is provided, create a resolved one and send immediately.
prom = (prom || Promise.resolve()).then(
( /* argument ignored */ ) => {
if (pub._cancelled) {
return {
code: 300,
text: "cancelled"
};
}
return this.publishMessage(pub);
},
(err) => {
this._tinode.logger("WARNING: Message draft rejected", err);
pub._sending = false;
pub._failed = true;
this._messages.delAt(this._messages.find(pub));
if (this.onData) {
this.onData();
}
});
return prom;
},
/**
* Leave the topic, optionally unsibscribe. Leaving the topic means the topic will stop
* receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.
* Wrapper for {@link Tinode#leave}.
* @memberof Tinode.Topic#
*
* @param {Boolean=} unsub - If true, unsubscribe, otherwise just leave.
* @returns {Promise} Promise to be resolved/rejected when the server responds to the request.
*/
leave: function(unsub) {
// It's possible to unsubscribe (unsub==true) from inactive topic.
if (!this._subscribed && !unsub) {
return Promise.reject(new Error("Cannot leave inactive topic"));
}
// Send a 'leave' message, handle async response
return this._tinode.leave(this.name, unsub).then((ctrl) => {
this._resetSub();
if (unsub) {
this._tinode.cacheDel('topic', this.name);
this._gone();
}
return ctrl;
});
},
/**
* Request topic metadata from the server.
* @memberof Tinode.Topic#
*
* @param {Tinode.GetQuery} request parameters
*
* @returns {Promise} Promise to be resolved/rejected when the server responds to request.
*/
getMeta: function(params) {
// Send {get} message, return promise.
return this._tinode.getMeta(this.name, params);
},
/**
* Request more messages from the server
* @memberof Tinode.Topic#
*
* @param {integer} limit number of messages to get.
* @param {boolean} forward if true, request newer messages.
*/
getMessagesPage: function(limit, forward) {
const query = this.startMetaQuery();
if (forward) {
query.withLaterData(limit);
} else {
query.withEarlierData(limit);
}
let promise = this.getMeta(query.build());
if (!forward) {
promise = promise.then((ctrl) => {
if (ctrl && ctrl.params && !ctrl.params.count) {
this._noEarlierMsgs = true;
}
});
}
return promise;
},
/**
* Update topic metadata.
* @memberof Tinode.Topic#
*
* @param {Tinode.SetParams} params parameters to update.
* @returns {Promise} Promise to be resolved/rejected when the server responds to request.
*/
setMeta: function(params) {
if (params.tags) {
params.tags = normalizeArray(params.tags);
}
// Send Set message, handle async response.
return this._tinode.setMeta(this.name, params)
.then((ctrl) => {
if (ctrl && ctrl.code >= 300) {
// Not modified
return ctrl;
}
if (params.sub) {
params.sub.topic = this.name;
if (ctrl.params && ctrl.params.acs) {
params.sub.acs = ctrl.params.acs;
params.sub.updated = ctrl.ts;
}
if (!params.sub.user) {
// This is a subscription update of the current user.
// Assign user ID otherwise the update will be ignored by _processMetaSub.
params.sub.user = this._tinode.getCurrentUserID();
if (!params.desc) {
// Force update to topic's asc.
params.desc = {};
}
}
params.sub._noForwarding = true;
this._processMetaSub([params.sub]);
}
if (params.desc) {
if (ctrl.params && ctrl.params.acs) {
params.desc.acs = ctrl.params.acs;
params.desc.updated = ctrl.ts;
}
this._processMetaDesc(params.desc);
}
if (params.tags) {
this._processMetaTags(params.tags);
}
if (params.cred) {
this._processMetaCreds([params.cred], true);
}
return ctrl;
});
},
/**
* Update access mode of the current user or of another topic subsriber.
* @memberof Tinode.Topic#
*
* @param {string} uid - UID of the user to update or null to update current user.
* @param {string} update - the update value, full or delta.
* @returns {Promise} Promise to be resolved/rejected when the server responds to request.
*/
updateMode: function(uid, update) {
const user = uid ? this.subscriber(uid) : null;
const am = user ?
user.acs.updateGiven(update).getGiven() :
this.getAccessMode().updateWant(update).getWant();
return this.setMeta({
sub: {
user: uid,
mode: am
}
});
},
/**
* Create new topic subscription. Wrapper for {@link Tinode#setMeta}.
* @memberof Tinode.Topic#
*
* @param {String} uid - ID of the user to invite
* @param {String=} mode - Access mode. <tt>null</tt> means to use default.
*
* @returns {Promise} Promise to be resolved/rejected when the server responds to request.
*/
invite: function(uid, mode) {
return this.setMeta({
sub: {
user: uid,
mode: mode
}
});
},
/**
* Archive or un-archive the topic. Wrapper for {@link Tinode#setMeta}.
* @memberof Tinode.Topic#
*
* @param {Boolean} arch - true to archive the topic, false otherwise.
*
* @returns {Promise} Promise to be resolved/rejected when the server responds to request.
*/
archive: function(arch) {
if (this.private && this.private.arch == arch) {
return Promise.resolve(arch);
}
return this.setMeta({
desc: {
private: {
arch: arch ? true : Tinode.DEL_CHAR
}
}
});
},
/**
* Delete messages. Hard-deleting messages requires Owner permission.
* Wrapper for {@link Tinode#delMessages}.
* @memberof Tinode.Topic#
*
* @param {Tinode.DelRange[]} ranges - Ranges of message IDs to delete.
* @param {Boolean=} hard - Hard or soft delete
* @returns {Promise} Promise to be resolved/rejected when the server responds to request.
*/
delMessages: function(ranges, hard) {
if (!this._subscribed) {
return Promise.reject(new Error("Cannot delete messages in inactive topic"));
}
// Sort ranges in accending order by low, the descending by hi.
ranges.sort((r1, r2) => {
if (r1.low < r2.low) {
return true;
}
if (r1.low == r2.low) {
return !r2.hi || (r1.hi >= r2.hi);
}
return false;
});
// Remove pending messages from ranges possibly clipping some ranges.
let tosend = ranges.reduce((out, r) => {
if (r.low < LOCAL_SEQID) {
if (!r.hi || r.hi < LOCAL_SEQID) {
out.push(r);
} else {
// Clip hi to max allowed value.
out.push({
low: r.low,
hi: this._maxSeq + 1
});
}
}
return out;
}, []);
// Send {del} message, return promise
let result;
if (tosend.length > 0) {
result = this._tinode.delMessages(this.name, tosend, hard);
} else {
result = Promise.resolve({
params: {
del: 0
}
});
}
// Update local cache.
return result.then((ctrl) => {
if (ctrl.params.del > this._maxDel) {
this._maxDel = ctrl.params.del;
}
ranges.map((r) => {
if (r.hi) {
this.flushMessageRange(r.low, r.hi);
} else {
this.flushMessage(r.low);
}
});
this._updateDeletedRanges();
if (this.onData) {
// Calling with no parameters to indicate the messages were deleted.
this.onData();
}
return ctrl;
});
},
/**
* Delete all messages. Hard-deleting messages requires Owner permission.
* @memberof Tinode.Topic#
*
* @param {boolean} hardDel - true if messages should be hard-deleted.
*
* @returns {Promise} Promise to be resolved/rejected when the server responds to request.
*/
delMessagesAll: function(hardDel) {
if (!this._maxSeq || this._maxSeq <= 0) {
// There are no messages to delete.
return Promise.resolve();
}
return this.delMessages([{
low: 1,
hi: this._maxSeq + 1,
_all: true
}], hardDel);
},
/**
* Delete multiple messages defined by their IDs. Hard-deleting messages requires Owner permission.
* @memberof Tinode.Topic#
*
* @param {Tinode.DelRange[]} list - list of seq IDs to delete
* @param {Boolean=} hardDel - true if messages should be hard-deleted.
*
* @returns {Promise} Promise to be resolved/rejected when the server responds to request.
*/
delMessagesList: function(list, hardDel) {
// Sort the list in ascending order
list.sort((a, b) => a - b);
// Convert the array of IDs to ranges.
let ranges = list.reduce((out, id) => {
if (out.length == 0) {
// First element.
out.push({
low: id
});
} else {
let prev = out[out.length - 1];
if ((!prev.hi && (id != prev.low + 1)) || (id > prev.hi)) {
// New range.
out.push({
low: id
});
} else {
// Expand existing range.
prev.hi = prev.hi ? Math.max(prev.hi, id + 1) : id + 1;
}
}
return out;
}, []);
// Send {del} message, return promise
return this.delMessages(ranges, hardDel)
},
/**
* Delete topic. Requires Owner permission. Wrapper for {@link Tinode#delTopic}.
* @memberof Tinode.Topic#
*
* @param {Boolean} hard - had-delete topic.
* @returns {Promise} Promise to be resolved/rejected when the server responds to the request.
*/
delTopic: function(hard) {
return this._tinode.delTopic(this.name, hard).then((ctrl) => {
this._resetSub();
this._gone();
return ctrl;
});
},
/**
* Delete subscription. Requires Share permission. Wrapper for {@link Tinode#delSubscription}.
* @memberof Tinode.Topic#
*
* @param {String} user - ID of the user to remove subscription for.
* @returns {Promise} Promise to be resolved/rejected when the server responds to request.
*/
delSubscription: function(user) {
if (!this._subscribed) {
return Promise.reject(new Error("Cannot delete subscription in inactive topic"));
}
// Send {del} message, return promise
return this._tinode.delSubscription(this.name, user).then((ctrl) => {
// Remove the object from the subscription cache;
delete this._users[user];
// Notify listeners
if (this.onSubsUpdated) {
this.onSubsUpdated(Object.keys(this._users));
}
return ctrl;
});
},
/**
* Send a read/recv notification
* @memberof Tinode.Topic#
*
* @param {String} what - what notification to send: <tt>recv</tt>, <tt>read</tt>.
* @param {Number} seq - ID or the message read or received.
*/
note: function(what, seq) {
if (!this._subscribed) {
// Cannot sending {note} on an inactive topic".
return;
}
// Update locally cached contact with the new count.
const me = this._tinode.getMeTopic();
const user = this._users[this._tinode.getCurrentUserID()];
let update = false;
if (user) {
// Known topic subscriber.
if (!user[what] || user[what] < seq) {
user[what] = seq;
update = true;
}
} else if (me) {
// Subscriber not found, such as in case of no S permission.
update = (me.getMsgReadRecv(this.name, what) < seq);
}
if (update) {
this._tinode.note(this.name, what, seq);
}
// Update locally cached contact with the new count.
if (me) {
me.setMsgReadRecv(this.name, what, seq);
}
},
/**
* Send a 'recv' receipt. Wrapper for {@link Tinode#noteRecv}.
* @memberof Tinode.Topic#
*
* @param {Number} seq - ID of the message to aknowledge.
*/
noteRecv: function(seq) {
this.note('recv', seq);
},
/**
* Send a 'read' receipt. Wrapper for {@link Tinode#noteRead}.
* @memberof Tinode.Topic#
*
* @param {Number} seq - ID of the message to aknowledge or 0/undefined to acknowledge the latest messages.
*/
noteRead: function(seq) {
seq = seq || this._maxSeq;
if (seq > 0) {
this.note('read', seq);
}
},
/**
* Send a key-press notification. Wrapper for {@link Tinode#noteKeyPress}.
* @memberof Tinode.Topic#
*/
noteKeyPress: function() {
if (this._subscribed) {
this._tinode.noteKeyPress(this.name);
} else {
this._tinode.logger("INFO: Cannot send notification in inactive topic");
}
},
/**
* Get user description from global cache. The user does not need to be a
* subscriber of this topic.
* @memberof Tinode.Topic#
*
* @param {String} uid - ID of the user to fetch.
* @return {Object} user description or undefined.
*/
userDesc: function(uid) {
// TODO(gene): handle asynchronous requests
const user = this._cacheGetUser(uid);
if (user) {
return user; // Promise.resolve(user)
}
},
/**
* Get description of the p2p peer from subscription cache.
* @memberof Tinode.Topic#
*
* @return {Object} peer's description or undefined.
*/
p2pPeerDesc: function() {
if (!this.isP2P()) {
return undefined;
}
return this._users[this.name];
},
/**
* Iterate over cached subscribers. If callback is undefined, use this.onMetaSub.
* @memberof Tinode.Topic#
*
* @param {Function} callback - Callback which will receive subscribers one by one.
* @param {Object=} context - Value of `this` inside the `callback`.
*/
subscribers: function(callback, context) {
const cb = (callback || this.onMetaSub);
if (cb) {
for (let idx in this._users) {
cb.call(context, this._users[idx], idx, this._users);
}
}
},
/**
* Get a copy of cached tags.
* @memberof Tinode.Topic#
* @return a copy of tags
*/
tags: function() {
// Return a copy.
return this._tags.slice(0);
},
/**
* Get cached subscription for the given user ID.
* @memberof Tinode.Topic#
*
* @param {String} uid - id of the user to query for
* @return user description or undefined.
*/
subscriber: function(uid) {
return this._users[uid];
},
/**
* Iterate over cached messages. If callback is undefined, use this.onData.
* @memberof Tinode.Topic#
*
* @param {function} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}
* @param {integer} sinceId - Optional seqId to start iterating from (inclusive).
* @param {integer} beforeId - Optional seqId to stop iterating before (exclusive).
* @param {Object} context - Value of `this` inside the `callback`.
*/
messages: function(callback, sinceId, beforeId, context) {
const cb = (callback || this.onData);
if (cb) {
let startIdx = typeof sinceId == 'number' ? this._messages.find({
seq: sinceId
}, true) : undefined;
let beforeIdx = typeof beforeId == 'number' ? this._messages.find({
seq: beforeId
}, true) : undefined;
if (startIdx != -1 && beforeIdx != -1) {
this._messages.forEach(cb, startIdx, beforeIdx, context);
}
}
},
/**
* Iterate over cached unsent messages. Wraps {@link Tinode.Topic#messages}.
* @memberof Tinode.Topic#
*
* @param {function} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}
* @param {Object} context - Value of `this` inside the `callback`.
*/
queuedMessages: function(callback, context) {
if (!callback) {
throw new Error("Callback must be provided");
}
this.messages(callback, LOCAL_SEQID, undefined, context);
},
/**
* Get the number of topic subscribers who marked this message as either recv or read
* Current user is excluded from the count.
* @memberof Tinode.Topic#
*
* @param {String} what - what notification to send: <tt>recv</tt>, <tt>read</tt>.
* @param {Number} seq - ID or the message read or received.
*/
msgReceiptCount: function(what, seq) {
let count = 0;
if (seq > 0) {
const me = this._tinode.getCurrentUserID();
for (let idx in this._users) {
const user = this._users[idx];
if (user.user !== me && user[what] >= seq) {
count++;
}
}
}
return count;
},
/**
* Get the number of topic subscribers who marked this message (and all older messages) as read.
* The current user is excluded from the count.
* @memberof Tinode.Topic#
*
* @param {Number} seq - Message id to check.
* @returns {Number} Number of subscribers who claim to have received the message.
*/
msgReadCount: function(seq) {
return this.msgReceiptCount('read', seq);
},
/**
* Get the number of topic subscribers who marked this message (and all older messages) as received.
* The current user is excluded from the count.
* @memberof Tinode.Topic#
*
* @param {number} seq - Message id to check.
* @returns {number} Number of subscribers who claim to have received the message.
*/
msgRecvCount: function(seq) {
return this.msgReceiptCount('recv', seq);
},
/**
* Check if cached message IDs indicate that the server may have more messages.
* @memberof Tinode.Topic#
*
* @param {boolean} newer check for newer messages
*/
msgHasMoreMessages: function(newer) {
return newer ? this.seq > this._maxSeq :
// _minSeq cound be more than 1, but earlier messages could have been deleted.
(this._minSeq > 1 && !this._noEarlierMsgs);
},
/**
* Check if the given seq Id is id of the most recent message.
* @memberof Tinode.Topic#
*
* @param {integer} seqId id of the message to check
*/
isNewMessage: function(seqId) {
return this._maxSeq <= seqId;
},
/**
* Remove one message from local cache.
* @memberof Tinode.Topic#
*
* @param {integer} seqId id of the message to remove from cache.
* @returns {Message} removed message or undefined if such message was not found.
*/
flushMessage: function(seqId) {
const idx = this._messages.find({
seq: seqId
});
return idx >= 0 ? this._messages.delAt(idx) : undefined;
},
/**
* Update message's seqId.
* @memberof Tinode.Topic#
*
* @param {Object} pub message object.
* @param {integer} newSeqId new seq id for pub.
*/
swapMessageId: function(pub, newSeqId) {
const idx = this._messages.find({
seq: pub.seq
});
const numMessages = this._messages.length();
pub.seq = newSeqId;
if (0 <= idx && idx < numMessages) {
// this._messages are sorted by `seq`.
// If changing pub.seq to newSeqId breaks the invariant, fix it.
if ((idx > 0 && this._messages.getAt(idx - 1).seq >= newSeqId) ||
(idx + 1 < numMessages && newSeqId < this._messages.getAt(idx + 1).seq <= newSeqId)) {
this._messages.delAt(idx);
this._messages.put(pub);
}
}
},
/**
* Remove a range of messages from the local cache.
* @memberof Tinode.Topic#
*
* @param {integer} fromId seq ID of the first message to remove (inclusive).
* @param {integer} untilId seqID of the last message to remove (exclusive).
*
* @returns {Message[]} array of removed messages (could be empty).
*/
flushMessageRange: function(fromId, untilId) {
// start, end: find insertion points (nearest == true).
const since = this._messages.find({
seq: fromId
}, true);
return since >= 0 ? this._messages.delRange(since, this._messages.find({
seq: untilId
}, true)) : [];
},
/**
* Attempt to stop message from being sent.
* @memberof Tinode.Topic#
*
* @param {integer} seqId id of the message to stop sending and remove from cache.
*
* @returns {boolean} true if message was cancelled, false otherwise.
*/
cancelSend: function(seqId) {
const idx = this._messages.find({
seq: seqId
});
if (idx >= 0) {
const msg = this._messages.getAt(idx);
const status = this.msgStatus(msg);
if (status == MESSAGE_STATUS_QUEUED || status == MESSAGE_STATUS_FAILED) {
msg._cancelled = true;
this._messages.delAt(idx);
if (this.onData) {
// Calling with no parameters to indicate the message was deleted.
this.onData();
}
return true;
}
}
return false;
},
/**
* Get type of the topic: me, p2p, grp, fnd...
* @memberof Tinode.Topic#
*
* @returns {String} One of 'me', 'p2p', 'grp', 'fnd', 'sys' or <tt>undefined</tt>.
*/
getType: function() {
return Tinode.topicType(this.name);
},
/**
* Get user's cumulative access mode of the topic.
* @memberof Tinode.Topic#
*
* @returns {Tinode.AccessMode} - user's access mode
*/
getAccessMode: function() {
return this.acs;
},
/**
* Get topic's default access mode.
* @memberof Tinode.Topic#
*
* @returns {Tinode.DefAcs} - access mode, such as {auth: `RWP`, anon: `N`}.
*/
getDefaultAccess: function() {
return this.defacs;
},
/**
* Initialize new meta {@link Tinode.GetQuery} builder. The query is attched to the current topic.
* It will not work correctly if used with a different topic.
* @memberof Tinode.Topic#
*
* @returns {Tinode.MetaGetBuilder} query attached to the current topic.
*/
startMetaQuery: function() {
return new MetaGetBuilder(this);
},
/**
* Check if topic is archived, i.e. private.arch == true.
* @memberof Tinode.Topic#
*
* @returns {boolean} - true if topic is archived, false otherwise.
*/
isArchived: function() {
return this.private && this.private.arch ? true : false;
},
/**
* Check if topic is a channel.
* @memberof Tinode.Topic#
*
* @returns {boolean} - true if topic is a channel, false otherwise.
*/
isChannel: function() {
return Tinode.isChannelTopicName(this.name);
},
/**
* Check if topic is a group topic.
* @memberof Tinode.Topic#
*
* @returns {boolean} - true if topic is a group, false otherwise.
*/
isGroup: function() {
return Tinode.isGroupTopicName(this.name);
},
/**
* Check if topic is a p2p topic.
* @memberof Tinode.Topic#
*
* @returns {boolean} - true if topic is a p2p topic, false otherwise.
*/
isP2P: function() {
return Tinode.isP2PTopicName(this.name);
},
/**
* Get status (queued, sent, received etc) of a given message in the context
* of this topic.
* @memberof Tinode.Topic#
*
* @param {Message} msg message to check for status.
* @returns message status constant.
*/
msgStatus: function(msg) {
let status = MESSAGE_STATUS_NONE;
if (this._tinode.isMe(msg.from)) {
if (msg._sending) {
status = MESSAGE_STATUS_SENDING;
} else if (msg._failed || msg._cancelled) {
status = MESSAGE_STATUS_FAILED;
} else if (msg.seq >= LOCAL_SEQID) {
status = MESSAGE_STATUS_QUEUED;
} else if (this.msgReadCount(msg.seq) > 0) {
status = MESSAGE_STATUS_READ;
} else if (this.msgRecvCount(msg.seq) > 0) {
status = MESSAGE_STATUS_RECEIVED;
} else if (msg.seq > 0) {
status = MESSAGE_STATUS_SENT;
}
} else {
status = MESSAGE_STATUS_TO_ME;
}
return status;
},
// Process data message
_routeData: function(data) {
if (data.content) {
if (!this.touched || this.touched < data.ts) {
this.touched = data.ts;
}
}
if (data.seq > this._maxSeq) {
this._maxSeq = data.seq;
}
if (data.seq < this._minSeq || this._minSeq == 0) {
this._minSeq = data.seq;
}
if (!data._noForwarding) {
this._messages.put(data);
this._updateDeletedRanges();
}
if (this.onData) {
this.onData(data);
}
// Update locally cached contact with the new message count.
const me = this._tinode.getMeTopic();
if (me) {
// Messages from the current user are considered to be read already.
me.setMsgReadRecv(this.name,
(!data.from || this._tinode.isMe(data.from)) ? 'read' : 'msg', data.seq, data.ts);
}
},
// Process metadata message
_routeMeta: function(meta) {
if (meta.desc) {
this._lastDescUpdate = meta.ts;
this._processMetaDesc(meta.desc);
}
if (meta.sub && meta.sub.length > 0) {
this._lastSubsUpdate = meta.ts;
this._processMetaSub(meta.sub);
}
if (meta.del) {
this._processDelMessages(meta.del.clear, meta.del.delseq);
}
if (meta.tags) {
this._processMetaTags(meta.tags);
}
if (meta.cred) {
this._processMetaCreds(meta.cred);
}
if (this.onMeta) {
this.onMeta(meta);
}
},
// Process presence change message
_routePres: function(pres) {
let user;
switch (pres.what) {
case 'del':
// Delete cached messages.
this._processDelMessages(pres.clear, pres.delseq);
break;
case 'on':
case 'off':
// Update online status of a subscription.
user = this._users[pres.src];
if (user) {
user.online = pres.what == 'on';
} else {
this._tinode.logger("WARNING: Presence update for an unknown user", this.name, pres.src);
}
break;
case 'term':
// Attachment to topic is terminated probably due to cluster rehashing.
this._resetSub();
break;
case 'acs':
const uid = pres.src || this._tinode.getCurrentUserID();
user = this._users[uid];
if (!user) {
// Update for an unknown user: notification of a new subscription.
const acs = new AccessMode().updateAll(pres.dacs);
if (acs && acs.mode != AccessMode._NONE) {
user = this._cacheGetUser(uid);
if (!user) {
user = {
user: uid,
acs: acs
};
this.getMeta(this.startMetaQuery().withOneSub(undefined, uid).build());
} else {
user.acs = acs;
}
user.updated = new Date();
this._processMetaSub([user]);
}
} else {
// Known user
user.acs.updateAll(pres.dacs);
// Update user's access mode.
this._processMetaSub([{
user: uid,
updated: new Date(),
acs: user.acs
}]);
}
break;
default:
this._tinode.logger("INFO: Ignored presence update", pres.what);
}
if (this.onPres) {
this.onPres(pres);
}
},
// Process {info} message
_routeInfo: function(info) {
if (info.what !== 'kp') {
const user = this._users[info.from];
if (user) {
user[info.what] = info.seq;
if (user.recv < user.read) {
user.recv = user.read;
}
}
// If this is an update from the current user, update the contact with the new count too.
if (this._tinode.isMe(info.from)) {
const me = this._tinode.getMeTopic();
if (me) {
me.setMsgReadRecv(info.topic, info.what, info.seq);
}
}
}
if (this.onInfo) {
this.onInfo(info);
}
},
// Called by Tinode when meta.desc packet is received.
// Called by 'me' topic on contact update (desc._noForwarding is true).
_processMetaDesc: function(desc) {
// Synthetic desc may include defacs for p2p topics which is useless.
// Remove it.
if (this.isP2P()) {
delete desc.defacs;
}
// Copy parameters from desc object to this topic.
mergeObj(this, desc);
// Make sure date fields are Date().
stringToDate(this);
// Update relevant contact in the me topic, if available:
if (this.name !== TOPIC_ME && !desc._noForwarding) {
const me = this._tinode.getMeTopic();
if (me) {
// Must use original 'desc' instead of 'this' so not to lose DEL_CHAR.
me._processMetaSub([{
_noForwarding: true,
topic: this.name,
updated: this.updated,
touched: this.touched,
acs: desc.acs,
seq: desc.seq,
read: desc.read,
recv: desc.recv,
public: desc.public,
private: desc.private
}]);
}
}
if (this.onMetaDesc) {
this.onMetaDesc(this);
}
},
// Called by Tinode when meta.sub is recived or in response to received
// {ctrl} after setMeta-sub.
_processMetaSub: function(subs) {
for (let idx in subs) {
const sub = subs[idx];
sub.updated = new Date(sub.updated);
sub.deleted = sub.deleted ? new Date(sub.deleted) : null;
let user = null;
if (!sub.deleted) {
// If this is a change to user's own permissions, update them in topic too.
// Desc will update 'me' topic.
if (this._tinode.isMe(sub.user) && sub.acs) {
this._processMetaDesc({
updated: sub.updated || new Date(),
touched: sub.updated,
acs: sub.acs
});
}
user = this._updateCachedUser(sub.user, sub);
} else {
// Subscription is deleted, remove it from topic (but leave in Users cache)
delete this._users[sub.user];
user = sub;
}
if (this.onMetaSub) {
this.onMetaSub(user);
}
}
if (this.onSubsUpdated) {
this.onSubsUpdated(Object.keys(this._users));
}
},
// Called by Tinode when meta.tags is recived.
_processMetaTags: function(tags) {
if (tags.length == 1 && tags[0] == Tinode.DEL_CHAR) {
tags = [];
}
this._tags = tags;
if (this.onTagsUpdated) {
this.onTagsUpdated(tags);
}
},
// Do nothing for topics other than 'me'
_processMetaCreds: function(creds) {},
// Delete cached messages and update cached transaction IDs
_processDelMessages: function(clear, delseq) {
this._maxDel = Math.max(clear, this._maxDel);
this.clear = Math.max(clear, this.clear);
const topic = this;
let count = 0;
if (Array.isArray(delseq)) {
delseq.map(function(range) {
if (!range.hi) {
count++;
topic.flushMessage(range.low);
} else {
for (let i = range.low; i < range.hi; i++) {
count++;
topic.flushMessage(i);
}
}
});
}
if (count > 0) {
this._updateDeletedRanges();
if (this.onData) {
this.onData();
}
}
},
// Topic is informed that the entire response to {get what=data} has been received.
_allMessagesReceived: function(count) {
this._updateDeletedRanges();
if (this.onAllMessagesReceived) {
this.onAllMessagesReceived(count);
}
},
// Reset subscribed state
_resetSub: function() {
this._subscribed = false;
},
// This topic is either deleted or unsubscribed from.
_gone: function() {
this._messages.reset();
this._users = {};
this.acs = new AccessMode(null);
this.private = null;
this.public = null;
this._maxSeq = 0;
this._minSeq = 0;
this._subscribed = false;
const me = this._tinode.getMeTopic();
if (me) {
me._routePres({
_noForwarding: true,
what: 'gone',
topic: TOPIC_ME,
src: this.name
});
}
if (this.onDeleteTopic) {
this.onDeleteTopic();
}
},
// Update global user cache and local subscribers cache.
// Don't call this method for non-subscribers.
_updateCachedUser: function(uid, obj) {
// Fetch user object from the global cache.
// This is a clone of the stored object
let cached = this._cacheGetUser(uid);
cached = mergeObj(cached || {}, obj);
// Save to global cache
this._cachePutUser(uid, cached);
// Save to the list of topic subsribers.
return mergeToCache(this._users, uid, cached);
},
// Get local seqId for a queued message.
_getQueuedSeqId: function() {
return this._queuedSeqId++;
},
// Calculate ranges of missing messages.
_updateDeletedRanges: function() {
const ranges = [];
let prev = null;
// Check for gap in the beginning, before the first message.
const first = this._messages.getAt(0);
if (first && this._minSeq > 1 && !this._noEarlierMsgs) {
// Some messages are missing in the beginning.
if (first.hi) {
// The first message already represents a gap.
if (first.seq > 1) {
first.seq = 1;
}
if (first.hi < this._minSeq - 1) {
first.hi = this._minSeq - 1;
}
prev = first;
} else {
// Create new gap.
prev = {
seq: 1,
hi: this._minSeq - 1
};
ranges.push(prev);
}
} else {
// No gap in the beginning.
prev = {
seq: 0,
hi: 0
};
}
// Find gaps in the list of received messages. The list contains messages-proper as well
// as placeholers for deleted ranges.
// The messages are iterated by seq ID in ascending order.
this._messages.forEach((data) => {
// Do not create a gap between the last sent message and the first unsent.
if (data.seq >= LOCAL_SEQID) {
return;
}
// New message is reducing the existing gap
if (data.seq == (prev.hi || prev.seq) + 1) {
// No new gap. Replace previous with current.
prev = data;
return;
}
// Found a new gap.
if (prev.hi) {
// Previous is also a gap, alter it.
prev.hi = data.hi || data.seq;
return;
}
// Previous is not a gap. Create a new gap.
prev = {
seq: (prev.hi || prev.seq) + 1,
hi: data.hi || data.seq
};
ranges.push(prev);
});
// Check for missing messages at the end.
// All messages could be missing or it could be a new topic with no messages.
const last = this._messages.getLast();
const maxSeq = Math.max(this.seq, this._maxSeq) || 0;
if ((maxSeq > 0 && !last) || (last && ((last.hi || last.seq) < maxSeq))) {
if (last && last.hi) {
// Extend existing gap
last.hi = maxSeq;
} else {
// Create new gap.
ranges.push({
seq: last ? last.seq + 1 : 1,
hi: maxSeq
});
}
}
// Insert new gaps into cache.
ranges.map((gap) => {
this._messages.put(gap);
});
}
};
/**
* @class TopicMe - special case of {@link Tinode.Topic} for
* managing data of the current user, including contact list.
* @extends Tinode.Topic
* @memberof Tinode
*
* @param {TopicMe.Callbacks} callbacks - Callbacks to receive various events.
*/
var TopicMe = function(callbacks) {
Topic.call(this, TOPIC_ME, callbacks);
// List of contacts (topic_name -> Contact object)
this._contacts = {};
// me-specific callbacks
if (callbacks) {
this.onContactUpdate = callbacks.onContactUpdate;
}
};
// Inherit everyting from the generic Topic
TopicMe.prototype = Object.create(Topic.prototype, {
// Override the original Topic._processMetaDesc.
_processMetaDesc: {
value: function(desc) {
// Check if online contacts need to be turned off because P permission was removed.
const turnOff = (desc.acs && !desc.acs.isPresencer()) && (this.acs && this.acs.isPresencer());
// Copy parameters from desc object to this topic.
mergeObj(this, desc);
// String datetime headers to Date() objects.
stringToDate(this);
// 'P' permission was removed. All topics are offline now.
if (turnOff) {
Object.values(this._contacts).map((cont) => {
if (cont.online) {
cont.online = false;
if (cont.seen) {
cont.seen.when = new Date();
} else {
cont.seen = {
when: new Date()
};
}
if (this.onContactUpdate) {
this.onContactUpdate('off', cont);
}
}
});
}
if (this.onMetaDesc) {
this.onMetaDesc(this);
}
},
enumerable: true,
configurable: true,
writable: false
},
// Override the original Topic._processMetaSub
_processMetaSub: {
value: function(subs) {
let updateCount = 0;
for (let idx in subs) {
const sub = subs[idx];
const topicName = sub.topic;
// Don't show 'me' and 'fnd' topics in the list of contacts.
if (topicName == TOPIC_FND || topicName == TOPIC_ME) {
continue;
}
sub.updated = new Date(sub.updated);
sub.touched = sub.touched ? new Date(sub.touched) : undefined;
sub.deleted = sub.deleted ? new Date(sub.deleted) : null;
let cont = null;
if (sub.deleted) {
cont = sub;
delete this._contacts[topicName];
this._tinode.cacheDel('topic', topicName);
} else {
// Ensure the values are defined and are integers.
if (typeof sub.seq != 'undefined') {
sub.seq = sub.seq | 0;
sub.recv = sub.recv | 0;
sub.read = sub.read | 0;
sub.unread = sub.seq - sub.read;
}
if (sub.seen && sub.seen.when) {
sub.seen.when = new Date(sub.seen.when);
}
cont = mergeToCache(this._contacts, topicName, sub);
if (Tinode.isP2PTopicName(topicName)) {
this._cachePutUser(topicName, cont);
}
// Notify topic of the update if it's an external update.
if (!sub._noForwarding) {
const topic = this._tinode.getTopic(topicName);
if (topic) {
sub._noForwarding = true;
topic._processMetaDesc(sub);
}
}
}
updateCount++;
if (this.onMetaSub) {
this.onMetaSub(cont);
}
}
if (this.onSubsUpdated) {
this.onSubsUpdated(Object.keys(this._contacts), updateCount);
}
},
enumerable: true,
configurable: true,
writable: false
},
// Called by Tinode when meta.sub is recived.
_processMetaCreds: {
value: function(creds, upd) {
if (creds.length == 1 && creds[0] == Tinode.DEL_CHAR) {
creds = [];
}
if (upd) {
creds.map((cr) => {
if (cr.val) {
// Adding a credential.
let idx = this._credentials.findIndex((el) => {
return el.meth == cr.meth && el.val == cr.val;
});
if (idx < 0) {
// Not found.
if (!cr.done) {
// Unconfirmed credential replaces previous unconfirmed credential of the same method.
idx = this._credentials.findIndex((el) => {
return el.meth == cr.meth && !el.done;
});
if (idx >= 0) {
// Remove previous unconfirmed credential.
this._credentials.splice(idx, 1);
}
}
this._credentials.push(cr);
} else {
// Found. Maybe change 'done' status.
this._credentials[idx].done = cr.done;
}
} else if (cr.resp) {
// Handle credential confirmation.
const idx = this._credentials.findIndex((el) => {
return el.meth == cr.meth && !el.done;
});
if (idx >= 0) {
this._credentials[idx].done = true;
}
}
});
} else {
this._credentials = creds;
}
if (this.onCredsUpdated) {
this.onCredsUpdated(this._credentials);
}
},
enumerable: true,
configurable: true,
writable: false
},
// Process presence change message
_routePres: {
value: function(pres) {
if (pres.what == 'term') {
// The 'me' topic itself is detached. Mark as unsubscribed.
this._resetSub();
return;
}
if (pres.what == 'upd' && pres.src == TOPIC_ME) {
// Update to me's description. Request updated value.
this.getMeta(this.startMetaQuery().withDesc().build());
return;
}
const cont = this._contacts[pres.src];
if (cont) {
switch (pres.what) {
case 'on': // topic came online
cont.online = true;
break;
case 'off': // topic went offline
if (cont.online) {
cont.online = false;
if (cont.seen) {
cont.seen.when = new Date();
} else {
cont.seen = {
when: new Date()
};
}
}
break;
case 'msg': // new message received
cont.touched = new Date();
cont.seq = pres.seq | 0;
// Check if message is sent by the current user. If so it's been read already.
if (!pres.act || this._tinode.isMe(pres.act)) {
cont.read = cont.read ? Math.max(cont.read, cont.seq) : cont.seq;
cont.recv = cont.recv ? Math.max(cont.read, cont.recv) : cont.read;
}
cont.unread = cont.seq - (cont.read | 0);
break;
case 'upd': // desc updated
// Request updated subscription.
this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());
break;
case 'acs': // access mode changed
if (cont.acs) {
cont.acs.updateAll(pres.dacs);
} else {
cont.acs = new AccessMode().updateAll(pres.dacs);
}
cont.touched = new Date();
break;
case 'ua': // user agent changed
cont.seen = {
when: new Date(),
ua: pres.ua
};
break;
case 'recv': // user's other session marked some messges as received
pres.seq = pres.seq | 0;
cont.recv = cont.recv ? Math.max(cont.recv, pres.seq) : pres.seq;
break;
case 'read': // user's other session marked some messages as read
pres.seq = pres.seq | 0;
cont.read = cont.read ? Math.max(cont.read, pres.seq) : pres.seq;
cont.recv = cont.recv ? Math.max(cont.read, cont.recv) : cont.recv;
cont.unread = cont.seq - cont.read;
break;
case 'gone': // topic deleted or unsubscribed from
delete this._contacts[pres.src];
this._tinode.cacheDel('topic', pres.src);
break;
case 'del':
// Update topic.del value.
break;
default:
this._tinode.logger("INFO: Unsupported presence update in 'me'", pres.what);
}
if (this.onContactUpdate) {
this.onContactUpdate(pres.what, cont);
}
} else {
if (pres.what == 'acs') {
// New subscriptions and deleted/banned subscriptions have full
// access mode (no + or - in the dacs string). Changes to known subscriptions are sent as
// deltas, but they should not happen here.
const acs = new AccessMode(pres.dacs);
if (!acs || acs.mode == AccessMode._INVALID) {
this._tinode.logger("ERROR: Invalid access mode update", pres.src, pres.dacs);
return;
} else if (acs.mode == AccessMode._NONE) {
this._tinode.logger("WARNING: Removing non-existent subscription", pres.src, pres.dacs);
return;
} else {
// New subscription. Send request for the full description.
// Using .withOneSub (not .withLaterOneSub) to make sure IfModifiedSince is not set.
this.getMeta(this.startMetaQuery().withOneSub(undefined, pres.src).build());
// Create a dummy entry to catch online status update.
this._contacts[pres.src] = {
touched: new Date(),
topic: pres.src,
online: false,
acs: acs
};
}
} else if (pres.what == 'tags') {
this.getMeta(this.startMetaQuery().withTags().build());
}
}
if (this.onPres) {
this.onPres(pres);
}
},
enumerable: true,
configurable: true,
writable: false
},
/**
* Publishing to TopicMe is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.
* @memberof Tinode.TopicMe#
* @throws {Error} Always throws an error.
*/
publish: {
value: function() {
return Promise.reject(new Error("Publishing to 'me' is not supported"));
},
enumerable: true,
configurable: true,
writable: false
},
/**
* Delete validation credential.
* @memberof Tinode.TopicMe#
*
* @param {String} topic - Name of the topic to delete
* @param {String} user - User ID to remove.
* @returns {Promise} Promise which will be resolved/rejected on receiving server reply.
*/
delCredential: {
value: function(method, value) {
if (!this._subscribed) {
return Promise.reject(new Error("Cannot delete credential in inactive 'me' topic"));
}
// Send {del} message, return promise
return this._tinode.delCredential(method, value).then((ctrl) => {
// Remove deleted credential from the cache.
const index = this._credentials.findIndex((el) => {
return el.meth == method && el.val == value;
});
if (index > -1) {
this._credentials.splice(index, 1);
}
// Notify listeners
if (this.onCredsUpdated) {
this.onCredsUpdated(this._credentials);
}
return ctrl;
});
},
enumerable: true,
configurable: true,
writable: false
},
/**
* Iterate over cached contacts.
*
* @function
* @memberof Tinode.TopicMe#
* @param {TopicMe.ContactCallback} callback - Callback to call for each contact.
* @param {function=} filter - Optionally filter contacts; include all if filter is false-ish, otherwise include those for
* which filter returns true-ish.
* @param {Object=} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.
*/
contacts: {
value: function(callback, filter, context) {
for (let idx in this._contacts) {
const c = this._contacts[idx];
if (!filter || filter(c)) {
callback.call(context, c, idx, this._contacts);
}
}
},
enumerable: true,
configurable: true,
writable: true
},
/**
* Update a cached contact with new read/received/message count.
* @function
* @memberof Tinode.TopicMe#
*
* @param {String} contactName - UID of contact to update.
* @param {String} what - Which count to update, one of <tt>"read", "recv", "msg"</tt>
* @param {Number} seq - New value of the count.
* @param {Date} ts - Timestamp of the update.
*/
setMsgReadRecv: {
value: function(contactName, what, seq, ts) {
const cont = this._contacts[contactName];
let oldVal, doUpdate = false;
let mode = null;
if (cont) {
seq = seq | 0;
cont.seq = cont.seq | 0;
cont.read = cont.read | 0;
cont.recv = cont.recv | 0;
switch (what) {
case 'recv':
oldVal = cont.recv;
cont.recv = Math.max(cont.recv, seq);
doUpdate = (oldVal != cont.recv);
break;
case 'read':
oldVal = cont.read;
cont.read = Math.max(cont.read, seq);
doUpdate = (oldVal != cont.read);
break;
case 'msg':
oldVal = cont.seq;
cont.seq = Math.max(cont.seq, seq);
if (!cont.touched || cont.touched < ts) {
cont.touched = ts;
}
doUpdate = (oldVal != cont.seq);
break;
}
// Sanity checks.
if (cont.recv < cont.read) {
cont.recv = cont.read;
doUpdate = true;
}
if (cont.seq < cont.recv) {
cont.seq = cont.recv;
if (!cont.touched || cont.touched < ts) {
cont.touched = ts;
}
doUpdate = true;
}
cont.unread = cont.seq - cont.read;
if (doUpdate && (!cont.acs || !cont.acs.isMuted()) && this.onContactUpdate) {
this.onContactUpdate(what, cont);
}
}
},
enumerable: true,
configurable: true,
writable: true
},
/**
* Get cached read/received/message count for the given contact.
* @function
* @memberof Tinode.TopicMe#
*
* @param {String} contactName - UID of contact to read.
* @param {String} what - Which count to read, one of <tt>"read", "recv", "msg"</tt>
*/
getMsgReadRecv: {
value: function(contactName, what) {
const cont = this._contacts[contactName];
if (cont) {
switch (what) {
case 'recv':
return cont.recv | 0;
case 'read':
return cont.read | 0;
case 'msg':
return cont.seq | 0;
}
}
return 0;
},
enumerable: true,
configurable: true,
writable: true
},
/**
* Get a contact from cache.
* @memberof Tinode.TopicMe#
*
* @param {string} name - Name of the contact to get, either a UID (for p2p topics) or a topic name.
* @returns {Tinode.Contact} - Contact or `undefined`.
*/
getContact: {
value: function(name) {
return this._contacts[name];
},
enumerable: true,
configurable: true,
writable: true
},
/**
* Get access mode of a given contact from cache.
* @memberof Tinode.TopicMe#
*
* @param {String} name - Name of the contact to get access mode for, either a UID (for p2p topics)
* or a topic name; if missing, access mode for the 'me' topic itself.
* @returns {string} - access mode, such as `RWP`.
*/
getAccessMode: {
value: function(name) {
if (name) {
const cont = this._contacts[name];
return cont ? cont.acs : null;
}
return this.acs;
},
enumerable: true,
configurable: true,
writable: true
},
/**
* Check if contact is archived, i.e. contact.private.arch == true.
* @memberof Tinode.TopicMe#
*
* @param {String} name - Name of the contact to check archived status, either a UID (for p2p topics) or a topic name.
* @returns {boolean} - true if contact is archived, false otherwise.
*/
isArchived: {
value: function(name) {
const cont = this._contacts[name];
return cont ? ((cont.private && cont.private.arch) ? true : false) : null;
},
enumerable: true,
configurable: true,
writable: true
},
/**
* @typedef Tinode.Credential
* @memberof Tinode
* @type Object
* @property {string} meth - validation method such as 'email' or 'tel'.
* @property {string} val - credential value, i.e. 'jdoe@example.com' or '+17025551234'
* @property {boolean} done - true if credential is validated.
*/
/**
* Get the user's credentials: email, phone, etc.
* @memberof Tinode.TopicMe#
*
* @returns {Tinode.Credential[]} - array of credentials.
*/
getCredentials: {
value: function() {
return this._credentials;
},
enumerable: true,
configurable: true,
writable: true
}
});
TopicMe.prototype.constructor = TopicMe;
/**
* @class TopicFnd - special case of {@link Tinode.Topic} for searching for
* contacts and group topics.
* @extends Tinode.Topic
* @memberof Tinode
*
* @param {TopicFnd.Callbacks} callbacks - Callbacks to receive various events.
*/
var TopicFnd = function(callbacks) {
Topic.call(this, TOPIC_FND, callbacks);
// List of users and topics uid or topic_name -> Contact object)
this._contacts = {};
};
// Inherit everyting from the generic Topic
TopicFnd.prototype = Object.create(Topic.prototype, {
// Override the original Topic._processMetaSub
_processMetaSub: {
value: function(subs) {
let updateCount = Object.getOwnPropertyNames(this._contacts).length;
// Reset contact list.
this._contacts = {};
for (let idx in subs) {
let sub = subs[idx];
const indexBy = sub.topic ? sub.topic : sub.user;
sub.updated = new Date(sub.updated);
if (sub.seen && sub.seen.when) {
sub.seen.when = new Date(sub.seen.when);
}
sub = mergeToCache(this._contacts, indexBy, sub);
updateCount++;
if (this.onMetaSub) {
this.onMetaSub(sub);
}
}
if (updateCount > 0 && this.onSubsUpdated) {
this.onSubsUpdated(Object.keys(this._contacts));
}
},
enumerable: true,
configurable: true,
writable: false
},
/**
* Publishing to TopicFnd is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.
* @memberof Tinode.TopicFnd#
* @throws {Error} Always throws an error.
*/
publish: {
value: function() {
return Promise.reject(new Error("Publishing to 'fnd' is not supported"));
},
enumerable: true,
configurable: true,
writable: false
},
/**
* setMeta to TopicFnd resets contact list in addition to sending the message.
* @memberof Tinode.TopicFnd#
* @param {Tinode.SetParams} params parameters to update.
* @returns {Promise} Promise to be resolved/rejected when the server responds to request.
*/
setMeta: {
value: function(params) {
const instance = this;
return Object.getPrototypeOf(TopicFnd.prototype).setMeta.call(this, params).then(function() {
if (Object.keys(instance._contacts).length > 0) {
instance._contacts = {};
if (instance.onSubsUpdated) {
instance.onSubsUpdated([]);
}
}
});
},
enumerable: true,
configurable: true,
writable: false
},
/**
* Iterate over found contacts. If callback is undefined, use {@link this.onMetaSub}.
* @function
* @memberof Tinode.TopicFnd#
* @param {TopicFnd.ContactCallback} callback - Callback to call for each contact.
* @param {Object} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.
*/
contacts: {
value: function(callback, context) {
const cb = (callback || this.onMetaSub);
if (cb) {
for (let idx in this._contacts) {
cb.call(context, this._contacts[idx], idx, this._contacts);
}
}
},
enumerable: true,
configurable: true,
writable: true
}
});
TopicFnd.prototype.constructor = TopicFnd;
/**
* @class LargeFileHelper - collection of utilities for uploading and downloading files
* out of band. Don't instantiate this class directly. Use {Tinode.getLargeFileHelper} instead.
* @memberof Tinode
*
* @param {Tinode} tinode - the main Tinode object.
*/
var LargeFileHelper = function(tinode) {
this._tinode = tinode;
this._apiKey = tinode._apiKey;
this._authToken = tinode.getAuthToken();
this._msgId = tinode.getNextUniqueId();
this.xhr = new XMLHttpRequest();
// Promise
this.toResolve = null;
this.toReject = null;
// Callbacks
this.onProgress = null;
this.onSuccess = null;
this.onFailure = null;
}
LargeFileHelper.prototype = {
/**
* Start uploading the file to a non-default endpoint.
*
* @memberof Tinode.LargeFileHelper#
*
* @param {String} baseUrl alternative base URL of upload server.
* @param {File|Blob} data to upload
* @param {Callback} onProgress callback. Takes one {float} parameter 0..1
* @param {Callback} onSuccess callback. Called when the file is successfully uploaded.
* @param {Callback} onFailure callback. Called in case of a failure.
*
* @returns {Promise} resolved/rejected when the upload is completed/failed.
*/
uploadWithBaseUrl: function(baseUrl, data, onProgress, onSuccess, onFailure) {
if (!this._authToken) {
throw new Error("Must authenticate first");
}
const instance = this;
let url = '/v' + PROTOCOL_VERSION + '/file/u/';
if (baseUrl) {
if (baseUrl.indexOf('http://') == 0 || baseUrl.indexOf('https://') == 0) {
url = baseUrl + url;
} else {
throw new Error("Invalid base URL '" + baseUrl + "'");
}
}
this.xhr.open('POST', url, true);
this.xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);
this.xhr.setRequestHeader('X-Tinode-Auth', 'Token ' + this._authToken.token);
const result = new Promise((resolve, reject) => {
this.toResolve = resolve;
this.toReject = reject;
});
this.onProgress = onProgress;
this.onSuccess = onSuccess;
this.onFailure = onFailure;
this.xhr.upload.onprogress = (e) => {
if (e.lengthComputable && instance.onProgress) {
instance.onProgress(e.loaded / e.total);
}
}
this.xhr.onload = function() {
let pkt;
try {
pkt = JSON.parse(this.response, jsonParseHelper);
} catch (err) {
instance._tinode.logger("ERROR: Invalid server response in LargeFileHelper", this.response);
pkt = {
ctrl: {
code: this.status,
text: this.statusText
}
};
}
if (this.status >= 200 && this.status < 300) {
if (instance.toResolve) {
instance.toResolve(pkt.ctrl.params.url);
}
if (instance.onSuccess) {
instance.onSuccess(pkt.ctrl);
}
} else if (this.status >= 400) {
if (instance.toReject) {
instance.toReject(new Error(pkt.ctrl.text + " (" + pkt.ctrl.code + ")"));
}
if (instance.onFailure) {
instance.onFailure(pkt.ctrl)
}
} else {
instance._tinode.logger("ERROR: Unexpected server response status", this.status, this.response);
}
};
this.xhr.onerror = function(e) {
if (instance.toReject) {
instance.toReject(new Error("failed"));
}
if (instance.onFailure) {
instance.onFailure(null);
}
};
this.xhr.onabort = function(e) {
if (instance.toReject) {
instance.toReject(new Error("upload cancelled by user"));
}
if (instance.onFailure) {
instance.onFailure(null);
}
};
try {
const form = new FormData();
form.append('file', data);
form.set('id', this._msgId);
this.xhr.send(form);
} catch (err) {
if (this.toReject) {
this.toReject(err);
}
if (this.onFailure) {
this.onFailure(null);
}
}
return result;
},
/**
* Start uploading the file to default endpoint.
*
* @memberof Tinode.LargeFileHelper#
*
* @param {File|Blob} data to upload
* @param {Callback} onProgress callback. Takes one {float} parameter 0..1
* @param {Callback} onSuccess callback. Called when the file is successfully uploaded.
* @param {Callback} onFailure callback. Called in case of a failure.
*
* @returns {Promise} resolved/rejected when the upload is completed/failed.
*/
upload: function(data, onProgress, onSuccess, onFailure) {
return this.uploadWithBaseUrl(undefined, data, onProgress, onSuccess, onFailure);
},
/**
* Download the file from a given URL using GET request. This method works with the Tinode server only.
*
* @memberof Tinode.LargeFileHelper#
*
* @param {String} relativeUrl - URL to download the file from. Must be relative url, i.e. must not contain the host.
* @param {String=} filename - file name to use for the downloaded file.
*
* @returns {Promise} resolved/rejected when the download is completed/failed.
*/
download: function(relativeUrl, filename, mimetype, onProgress, onError) {
if (!Tinode.isRelativeURL(relativeUrl)) {
// As a security measure refuse to download from an absolute URL.
if (onError) {
onError("The URL '" + relativeUrl + "' must be relative, not absolute");
}
return;
}
if (!this._authToken) {
if (onError) {
onError("Must authenticate first");
}
return;
}
const instance = this;
// Get data as blob (stored by the browser as a temporary file).
this.xhr.open('GET', relativeUrl, true);
this.xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);
this.xhr.setRequestHeader('X-Tinode-Auth', 'Token ' + this._authToken.token);
this.xhr.responseType = 'blob';
this.onProgress = onProgress;
this.xhr.onprogress = function(e) {
if (instance.onProgress) {
// Passing e.loaded instead of e.loaded/e.total because e.total
// is always 0 with gzip compression enabled by the server.
instance.onProgress(e.loaded);
}
};
const result = new Promise((resolve, reject) => {
this.toResolve = resolve;
this.toReject = reject;
});
// The blob needs to be saved as file. There is no known way to
// save the blob as file other than to fake a click on an <a href... download=...>.
this.xhr.onload = function() {
if (this.status == 200) {
const link = document.createElement('a');
// URL.createObjectURL is not available in non-browser environment. This call will fail.
link.href = window.URL.createObjectURL(new Blob([this.response], {
type: mimetype
}));
link.style.display = 'none';
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(link.href);
if (instance.toResolve) {
instance.toResolve();
}
} else if (this.status >= 400 && instance.toReject) {
// The this.responseText is undefined, must use this.response which is a blob.
// Need to convert this.response to JSON. The blob can only be accessed by the
// FileReader.
const reader = new FileReader();
reader.onload = function() {
try {
const pkt = JSON.parse(this.result, jsonParseHelper);
instance.toReject(new Error(pkt.ctrl.text + " (" + pkt.ctrl.code + ")"));
} catch (err) {
instance._tinode.logger("ERROR: Invalid server response in LargeFileHelper", this.result);
instance.toReject(err);
}
};
reader.readAsText(this.response);
}
};
this.xhr.onerror = function(e) {
if (instance.toReject) {
instance.toReject(new Error("failed"));
}
};
this.xhr.onabort = function() {
if (instance.toReject) {
instance.toReject(null);
}
};
try {
this.xhr.send();
} catch (err) {
if (this.toReject) {
this.toReject(err);
}
}
return result;
},
/**
* Try to cancel an ongoing upload or download.
* @memberof Tinode.LargeFileHelper#
*/
cancel: function() {
if (this.xhr && this.xhr.readyState < 4) {
this.xhr.abort();
}
},
/**
* Get unique id of this request.
* @memberof Tinode.LargeFileHelper#
*
* @returns {string} unique id
*/
getId: function() {
return this._msgId;
}
};
/**
* @class Message - definition a communication message.
* Work in progress.
* @memberof Tinode
*
* @param {string} topic_ - name of the topic the message belongs to.
* @param {string | Drafty} content_ - message contant.
*/
var Message = function(topic_, content_) {
this.status = Message.STATUS_NONE;
this.topic = topic_;
this.content = content_;
}
Message.STATUS_NONE = MESSAGE_STATUS_NONE;
Message.STATUS_QUEUED = MESSAGE_STATUS_QUEUED;
Message.STATUS_SENDING = MESSAGE_STATUS_SENDING;
Message.STATUS_FAILED = MESSAGE_STATUS_FAILED;
Message.STATUS_SENT = MESSAGE_STATUS_SENT;
Message.STATUS_RECEIVED = MESSAGE_STATUS_RECEIVED;
Message.STATUS_READ = MESSAGE_STATUS_READ;
Message.STATUS_TO_ME = MESSAGE_STATUS_TO_ME;
Message.prototype = {
/**
* Convert message object to {pub} packet.
*/
toJSON: function() {
},
/**
* Parse JSON into message.
*/
fromJSON: function(json) {
}
}
Message.prototype.constructor = Message;
if (typeof module != 'undefined') {
module.exports = Tinode;
module.exports.Drafty = Drafty;
module.exports.AccessMode = AccessMode;
}
|
# Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import pytest
import itertools
import numpy as np
import copy
# import mil internal ops to add it to the builder
import coremltools as ct
from coremltools.converters.mil.mil import Builder as mb
from coremltools.converters.mil.mil.passes.pass_registry import PASS_REGISTRY
from coremltools.converters.mil import types
from coremltools.converters.mil.mil.types import string_to_builtin, builtin_to_string, promote_types
# Set the testing backend
import coremltools.converters.mil.testing_reqs as testing_reqs
from coremltools.converters.mil.testing_utils import (
get_op_types_in_program,
apply_pass_and_basic_check,
assert_model_is_valid,
)
class TestAdjustToSupportedTypes:
def test_basic(self):
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 1, 1, 1), dtype=types.bool),
mb.TensorSpec(shape=(1, 1, 1, 1), dtype=types.int32),
mb.TensorSpec(shape=(1, 1, 1, 1), dtype=types.fp32)])
def prog(x, y, z):
out = mb.logical_not(x=x)
return (out, y, z)
prog.functions['not_main'] = copy.deepcopy(prog.functions['main'])
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::adjust_io_to_supported_types"
)
"""
Input graph:
func main(bool x, int32 y, fp32 z) {
bool out = logical_not(x)
} -> (out, y, z)
becomes
func main(fp32 x, int32 y, fp32 z) {
bool x_casted = cast(x)
bool out__pre__output__fp32__cast = logical_not(x_casted)
fp32 out = cast(out__pre__output__fp32__cast)
} -> (out, y, z)
"""
assert get_op_types_in_program(prev_prog) == ['logical_not']
assert get_op_types_in_program(prog) == ['cast', 'logical_not', 'cast']
prev_inputs = list(prev_prog.functions['main'].inputs.items())
inputs = list(prog.functions['main'].inputs.items())
assert prev_inputs[0][1].name == inputs[0][1].name
assert inputs[0][1].dtype == types.fp32
for i in range(1, len(inputs)):
assert prev_inputs[i][1].name == inputs[i][1].name
assert prev_inputs[i][1].dtype == inputs[i][1].dtype
prev_outputs = prev_prog.functions['main'].outputs
outputs = prog.functions['main'].outputs
assert prev_outputs[0].name == outputs[0].name
assert outputs[0].dtype == types.fp32
for i in range(1, len(outputs)):
assert prev_outputs[i].name == outputs[i].name
assert prev_outputs[i].dtype == outputs[i].dtype
"""
Input graph:
func not_main(bool x, int32 y, fp32 z) {
bool out = logical_not(x)
} -> (out, y, z)
is identical after the pass.
"""
assert get_op_types_in_program(prev_prog, 'not_main') == ['logical_not']
assert get_op_types_in_program(prog, 'not_main') == ['logical_not']
prev_inputs = list(prev_prog.functions['not_main'].inputs.items())
inputs = list(prog.functions['not_main'].inputs.items())
for i in range(0, len(inputs)):
assert prev_inputs[i][1].name == inputs[i][1].name
assert prev_inputs[i][1].dtype == inputs[i][1].dtype
prev_outputs = prev_prog.functions['not_main'].outputs
outputs = prog.functions['not_main'].outputs
for i in range(0, len(outputs)):
assert prev_outputs[i].name == outputs[i].name
assert prev_outputs[i].dtype == outputs[i].dtype
def test_int64_input(self):
"""
Input graph:
func main(int64 x) {
} -> (x)
becomes
func main(int32 x) {
} -> (x)
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 1, 1, 1), dtype=types.int64)])
def prog(x):
return x
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::adjust_io_to_supported_types"
)
prev_inputs = list(prev_prog.functions['main'].inputs.items())
inputs = list(prog.functions['main'].inputs.items())
assert prev_inputs[0][1].name == inputs[0][1].name
assert inputs[0][1].dtype == types.int32
def test_float64_input(self):
"""
Input graph:
func main(float64 x) {
} -> (x)
becomes
func main(float32 x) {
} -> (x)
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 1, 1, 1), dtype=types.fp64)])
def prog(x):
return x
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::adjust_io_to_supported_types"
)
prev_inputs = list(prev_prog.functions['main'].inputs.items())
inputs = list(prog.functions['main'].inputs.items())
assert prev_inputs[0][1].name == inputs[0][1].name
assert inputs[0][1].dtype == types.fp32
def test_int8_input(self):
"""
Input graph:
func main(int8 x) {
} -> (x)
becomes
func main(int32 x) {
} -> (x)
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 1, 1, 1), dtype=types.int8)])
def prog(x):
return x
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::adjust_io_to_supported_types"
)
prev_inputs = list(prev_prog.functions['main'].inputs.items())
inputs = list(prog.functions['main'].inputs.items())
assert prev_inputs[0][1].name == inputs[0][1].name
assert inputs[0][1].dtype == types.int32
def test_subblock(self):
"""
Input graph:
func main(float64 a, float32 b) {
float64 out_0, float32 out_1 = while_loop(a, b,
(float64 a, float32 b) {
bool cond = less(a, b)
} -> (cond)
(float64 a, float32 b) {
float64 temp = const(1)
float64 out = add(a, b)
} -> (out, b)
);
} -> (out_0, out_1)
becomes
func main(float32 a, float32 b) {
float32 out_0, float32 out_1 = while_loop(a, b,
(float32 a, float32 b) {
bool cond = less(a, b)
} -> (cond)
(float32 a, float32 b) {
float32 temp = const(1)
float32 out = add(a, b)
} -> (out, b)
);
} -> (out_0, out_1)
"""
def body(a, b):
return mb.add(x=a, y=np.float64(1)), b
def cond(a, b):
return mb.less(x=a, y=b)
@mb.program(input_specs=[mb.TensorSpec(shape=(1,), dtype=types.fp64),
mb.TensorSpec(shape=(1,), dtype=types.fp32)])
def prog(a, b):
return mb.while_loop(_cond=cond, _body=body, loop_vars=(a, b))
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::adjust_io_to_supported_types"
)
prev_inputs = list(prev_prog.functions['main'].inputs.items())
inputs = list(prog.functions['main'].inputs.items())
for i in range(0, len(prev_inputs)):
assert prev_inputs[i][1].name == inputs[i][1].name
assert inputs[i][1].dtype == types.fp32
assert get_op_types_in_program(prev_prog) == ['while_loop']
assert get_op_types_in_program(prog) == ['while_loop']
def assert_block_inputs(prev_inputs, inputs):
for i in range(0, len(prev_inputs)):
assert prev_inputs[i].name == inputs[i].name
assert inputs[i].dtype == types.fp32
subblocks = prog.functions['main'].operations[0].blocks
prev_subblocks = prev_prog.functions['main'].operations[0].blocks
for i in range(0, len(subblocks)):
assert_block_inputs(prev_subblocks[i].inputs, subblocks[i].inputs)
def test_adjust_cast(self):
"""
Input graph:
func main(int32 x) {
fp64 y = cast(x=x, dtype="fp64")
} -> (y)
becomes
func main(int32 x) {
fp32 y = cast(x=x, dtype="fp32")
} -> (y)
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 1, 1, 1), dtype=types.int32)])
def prog(x):
y = mb.cast(x=x, dtype="fp64")
return y
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::adjust_io_to_supported_types"
)
assert get_op_types_in_program(prev_prog) == ['cast']
assert get_op_types_in_program(prog) == ['cast']
prev_cast = prev_prog.functions['main'].operations[1]
cast = prog.functions['main'].operations[2]
assert prev_cast.dtype.val == "fp64"
assert prev_cast.outputs[0].dtype == types.fp64
assert cast.dtype.val == "fp32"
assert cast.outputs[0].dtype == types.fp32
def test_adjust_redundant_cast(self):
"""
Input graph:
func main(int32 x) {
int64 y = cast(x=x, dtype="int64")
} -> (y)
becomes
func main(int32 x) {
} -> (x)
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 1, 1, 1), dtype=types.int32)])
def prog(x):
y = mb.cast(x=x, dtype="int64")
return y
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::adjust_io_to_supported_types"
)
assert get_op_types_in_program(prev_prog) == ['cast']
assert get_op_types_in_program(prog) == []
class TestImagePreprocessingPass:
def test_program_grayscale(self):
"""
Input graph:
main(x: ImageType(color_layout="G", channel_first=True)) {
y1 = relu(x)
y2 = relu(x)
output = add(y1, y2)
} [output]
Output graph:
main(x: ImageType(channel_first=True)) {
y1 = relu(x)
y2 = relu(x)
output = add(y1, y2)
} [output]
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 1, 20, 20))])
def prog(x):
y1 = mb.relu(x=x)
y2 = mb.relu(x=x)
z = mb.add(x=y1, y=y2)
return z
prog.main_input_types = (ct.ImageType(name='x',
shape=[1, 1, 20, 20],
color_layout="G",
channel_first=True),)
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::insert_image_preprocessing_ops"
)
assert get_op_types_in_program(prev_prog) == ["relu", "relu", "add"]
assert get_op_types_in_program(prog) == ["relu", "relu", "add"]
def test_program_grayscale_with_scale(self):
"""
Input graph:
main(x: ImageType(scale=2.0, color_layout="G", channel_first=True)) {
y1 = relu(x)
y2 = relu(x)
output = add(y1, y2)
} [output]
Output graph:
main(x: ImageType(channel_first=True)) {
y = mul(x, 2)
y1 = relu(y)
y2 = relu(y)
output = add(y1, y2)
} [output]
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 1, 20, 20))])
def prog(x):
y1 = mb.relu(x=x)
y2 = mb.relu(x=x)
z = mb.add(x=y1, y=y2)
return z
prog.main_input_types = (ct.ImageType(name='x',
shape=[1, 1, 20, 20],
scale=2.0,
color_layout="G",
channel_first=True),)
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::insert_image_preprocessing_ops"
)
assert get_op_types_in_program(prev_prog) == ["relu", "relu", "add"]
assert get_op_types_in_program(prog) == ["mul", "relu", "relu", "add"]
scale_op = prog.find_ops(op_type="mul", exactly_one=True)[0]
assert scale_op.y.val == 2.0
def test_program_grayscale_with_bias(self):
"""
Input graph:
main(x: ImageType(bias=2.0, color_layout="G", channel_first=True)) {
y1 = relu(x)
y2 = relu(x)
output = add(y1, y2)
} [output]
Output graph:
main(x: ImageType(channel_first=True)) {
y = add(x, 2)
y1 = relu(y)
y2 = relu(y)
output = add(y1, y2)
} [output]
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 1, 20, 20))])
def prog(x):
y1 = mb.relu(x=x)
y2 = mb.relu(x=x)
z = mb.add(x=y1, y=y2)
return z
prog.main_input_types = (ct.ImageType(name='x',
shape=[1, 1, 20, 20],
bias=2.0,
color_layout="G",
channel_first=True),)
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::insert_image_preprocessing_ops"
)
assert get_op_types_in_program(prev_prog) == ["relu", "relu", "add"]
assert get_op_types_in_program(prog) == ["add", "relu", "relu", "add"]
add_op = prog.find_ops(op_type="add", exactly_one=False)[0]
assert add_op.y.val == 2.0
def test_program_grayscale_with_scale_bias(self):
"""
Input graph:
main(x: ImageType(scale=2.0, bias=2.0, color_layout="G", channel_first=True)) {
y1 = relu(x)
y2 = relu(x)
output = add(y1, y2)
} [output]
Output graph:
main(x: ImageType(channel_first=True)) {
y_scaled = mul(x, 2)
y = add(y_scaled, 2)
y1 = relu(y)
y2 = relu(y)
output = add(y1, y2)
} [output]
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 1, 20, 20))])
def prog(x):
y1 = mb.relu(x=x)
y2 = mb.relu(x=x)
z = mb.add(x=y1, y=y2)
return z
prog.main_input_types = (ct.ImageType(name='x',
shape=[1, 1, 20, 20],
scale=2.0,
bias=2.0,
color_layout="G",
channel_first=True),)
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::insert_image_preprocessing_ops"
)
assert get_op_types_in_program(prev_prog) == ["relu", "relu", "add"]
assert get_op_types_in_program(prog) == ["mul", "add", "relu", "relu", "add"]
scale_op = prog.find_ops(op_type="mul", exactly_one=True)[0]
assert scale_op.y.val == 2.0
add_op = prog.find_ops(op_type="add", exactly_one=False)[0]
assert add_op.y.val == 2.0
def test_program_rgb(self):
"""
Input graph:
main(x: ImageType(color_layout="RGB", channel_first=True)) {
y1 = relu(x)
y2 = relu(x)
output = add(y1, y2)
} [output]
Output graph:
main(x: ImageType(channel_first=True)) {
y1 = relu(x)
y2 = relu(x)
output = add(y1, y2)
} [output]
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 3, 20, 20))])
def prog(x):
y1 = mb.relu(x=x)
y2 = mb.relu(x=x)
z = mb.add(x=y1, y=y2)
return z
prog.main_input_types = (ct.ImageType(name='x',
shape=[1, 3, 20, 20],
color_layout="RGB",
channel_first=True),)
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::insert_image_preprocessing_ops"
)
assert get_op_types_in_program(prev_prog) == ["relu", "relu", "add"]
assert get_op_types_in_program(prog) == ["relu", "relu", "add"]
def test_program_rgb_scale_bias(self):
"""
Input graph:
main(x: ImageType(color_layout="RGB", scale=2.0, bias=[1.0, 2.0, 3.0], channel_first=True)) {
y1 = relu(x)
y2 = relu(x)
output = add(y1, y2)
} [output]
Output graph:
main(x: ImageType(channel_first=True)) {
y = mul(x, scale)
y_bias = add(y, bias)
y1 = relu(y_bias)
y2 = relu(y_bias)
output = add(y1, y2)
} [output]
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 3, 20, 20))])
def prog(x):
y1 = mb.relu(x=x)
y2 = mb.relu(x=x)
z = mb.add(x=y1, y=y2)
return z
prog.main_input_types = (ct.ImageType(name='x',
shape=[1, 3, 20, 20],
scale=2.0,
bias=[1.0, 2.0, 3.0],
color_layout="RGB",
channel_first=True),)
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::insert_image_preprocessing_ops"
)
assert get_op_types_in_program(prev_prog) == ["relu", "relu", "add"]
assert get_op_types_in_program(prog) == ["mul", "add", "relu", "relu", "add"]
scale_op = prog.find_ops(op_type="mul", exactly_one=True)[0]
assert scale_op.y.val == 2.0
add_op = prog.find_ops(op_type="add", exactly_one=False)[0]
assert np.all(add_op.y.val == np.array([1.0, 2.0, 3.0]).reshape([1, 3, 1, 1]))
def test_program_bgr(self):
"""
Input graph:
main(x: ImageType(color_layout="BGR", channel_first=True)) {
y1 = relu(x)
y2 = relu(x)
output = add(y1, y2)
} [output]
Output graph:
main(x: ImageType(channel_first=True)) {
y1 = relu(x)
y2 = relu(x)
output = add(y1, y2)
} [output]
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 3, 20, 20))])
def prog(x):
y1 = mb.relu(x=x)
y2 = mb.relu(x=x)
z = mb.add(x=y1, y=y2)
return z
prog.main_input_types = (ct.ImageType(name='x',
shape=[1, 3, 20, 20],
color_layout="BGR",
channel_first=True),)
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::insert_image_preprocessing_ops"
)
assert get_op_types_in_program(prev_prog) == ["relu", "relu", "add"]
assert get_op_types_in_program(prog) == ["relu", "relu", "add"]
def test_program_bgr_scale_bias(self):
"""
Input graph:
main(x: ImageType(color_layout="BGR", scale=2.0, bias=[1.0, 2.0, 3.0], channel_first=True)) {
y1 = relu(x)
y2 = relu(x)
output = add(y1, y2)
} [output]
Output graph:
main(x: ImageType(channel_first=True)) {
y = mul(x, scale)
y_bias = add(y, bias)
y1 = relu(y_bias)
y2 = relu(y_bias)
output = add(y1, y2)
} [output]
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 3, 20, 20))])
def prog(x):
y1 = mb.relu(x=x)
y2 = mb.relu(x=x)
z = mb.add(x=y1, y=y2)
return z
prog.main_input_types = (ct.ImageType(name='x',
shape=[1, 3, 20, 20],
scale=2.0,
bias=[1.0, 2.0, 3.0],
color_layout="BGR",
channel_first=True),)
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::insert_image_preprocessing_ops"
)
assert get_op_types_in_program(prev_prog) == ["relu", "relu", "add"]
assert get_op_types_in_program(prog) == ["mul", "add", "relu", "relu", "add"]
scale_op = prog.find_ops(op_type="mul", exactly_one=True)[0]
assert scale_op.y.val == 2.0
add_op = prog.find_ops(op_type="add", exactly_one=False)[0]
assert np.all(add_op.y.val == np.array([1.0, 2.0, 3.0]).reshape([1, 3, 1, 1]))
@pytest.mark.parametrize(
"scale_type, bias_type", itertools.product([np.float, np.int32], [np.float, np.int32])
)
def test_scale_bias_types(self, scale_type, bias_type):
"""
Input graph:
main(x: ImageType(color_layout="RGB", scale=2.0, bias=[1.0, 2.0, 3.0], channel_first=True)) {
y1 = relu(x)
y2 = relu(x)
output = add(y1, y2)
} [output]
Output graph:
main(x: ImageType(channel_first=True)) {
y = mul(x, scale)
y_bias = add(y, bias)
y1 = relu(y_bias)
y2 = relu(y_bias)
output = add(y1, y2)
} [output]
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 3, 20, 20))])
def prog(x):
y1 = mb.relu(x=x)
y2 = mb.relu(x=x)
z = mb.add(x=y1, y=y2)
return z
prog.main_input_types = (ct.ImageType(name='x',
shape=[1, 3, 20, 20],
scale=scale_type(2.0),
bias=np.array([1, 2, 3]).astype(bias_type),
color_layout="RGB",
channel_first=True),)
prev_prog, prev_block, block = apply_pass_and_basic_check(
prog, "mil_backend::insert_image_preprocessing_ops"
)
assert get_op_types_in_program(prev_prog) == ["relu", "relu", "add"]
assert get_op_types_in_program(prog) == ["mul", "add", "relu", "relu", "add"]
scale_op = prog.find_ops(op_type="mul", exactly_one=True)[0]
assert scale_op.y.dtype() == prog.functions["main"].inputs["x"].dtype()
add_op = prog.find_ops(op_type="add", exactly_one=False)[0]
assert add_op.y.dtype() == prog.functions["main"].inputs["x"].dtype()
class TestSanitizerPass:
def test_sanitize_numeric_var_names(self):
"""
Input:
main(%x: (1, 3, 20, fp32)(Tensor)) {
block0() {
%var_1!: (1, 3, 20, fp32)(Tensor) = relu(x=%x, name="var_1!")
%1: (1, 3, 20, fp32)(Tensor) = relu(x=%x, name="1")
%3: (1, 3, 20, fp32)(Tensor) = add(x=%Var_1!, y=%1, name="3")
} -> (%3)
}
Output:
main(%x: (1, 3, 20, fp32)(Tensor)) {
block0() {
%var_1_: (1, 3, 20, fp32)(Tensor) = relu(x=%x, name="var_1_")
%var_1: (1, 3, 20, fp32)(Tensor) = relu(x=%x, name="op_1")
%var_3: (1, 3, 20, fp32)(Tensor) = add(x=%var_1_, y=%var_1, name="op_3")
} -> (%var_3)
}
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 3, 20))])
def prog(x):
y1 = mb.relu(x=x, name = "var_1!")
y2 = mb.relu(x=x, name = "1")
z = mb.add(x=y1, y=y2, name = "3")
return z
PASS_REGISTRY["mil_backend::sanitize_name_strings"](prog)
block = prog.functions["main"]
assert block.find_ops(op_type="relu")[0].outputs[0].name == "var_1_"
assert block.find_ops(op_type="relu")[1].outputs[0].name == "var_1"
assert prog["main"].outputs[0].name == "var_3"
assert block.find_ops(op_type="relu")[0].name == "var_1_"
assert block.find_ops(op_type="relu")[1].name == "op_1"
assert block.find_ops(op_type="add")[0].name == "op_3"
def test_sanitize_var_names_with_two_functions(self):
"""
Input:
main(%x: (1, 3, 20, fp32)(Tensor)) {
block0() {
%var_1!: (1, 3, 20, fp32)(Tensor) = relu(x=%x, name="var_1!")
} -> (%var_1!)
}
main_2(%x: (1, 3, 20, fp32)(Tensor)) {
block0() {
%var_1!: (1, 3, 20, fp32)(Tensor) = relu(x=%x, name="var_1!")
} -> (%var_1!)
}
Output:
main(%x: (1, 3, 20, fp32)(Tensor)) {
block0() {
%var_1!: (1, 3, 20, fp32)(Tensor) = relu(x=%x, name="var_1_")
} -> (%var_1_)
}
main_2(%x: (1, 3, 20, fp32)(Tensor)) {
block0() {
%var_1!: (1, 3, 20, fp32)(Tensor) = relu(x=%x, name="var_1_")
} -> (%var_1_)
}
"""
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 3, 20))])
def prog(x):
z = mb.relu(x=x, name = "var_1!")
return z
@mb.program(input_specs=[mb.TensorSpec(shape=(1, 3, 20))])
def prog_2(x):
z = mb.relu(x=x, name = "var_1!")
return z
prog.add_function("main_2", prog_2.functions["main"])
PASS_REGISTRY["mil_backend::sanitize_name_strings"](prog)
block = prog.functions["main"]
assert block.find_ops(op_type="relu")[0].outputs[0].name == "var_1_"
assert prog["main"].outputs[0].name == "var_1_"
assert block.find_ops(op_type="relu")[0].name == "var_1_"
block = prog.functions["main_2"]
assert block.find_ops(op_type="relu")[0].outputs[0].name == "var_1_"
assert prog["main"].outputs[0].name == "var_1_"
assert block.find_ops(op_type="relu")[0].name == "var_1_"
class TestPassFuseActivationSiLU:
"""
Input graph:
input --> sigmoid --> mul --> output
Output graph:
input --> silu --> output
"""
@pytest.mark.skipif(ct.utils._macos_version() < (12, 0), reason="mlprogram predict available only on macOS12+")
@pytest.mark.parametrize(
"reverse_order", itertools.product([True, False]),
)
def test_0(self, reverse_order):
x_shape = tuple(np.random.randint(low=1, high=4, size=5))
@mb.program(input_specs=[mb.TensorSpec(shape=x_shape)])
def program(x):
sigmoid_x = mb.sigmoid(x=x)
if not reverse_order:
x = mb.mul(x=x, y=sigmoid_x)
else:
x = mb.mul(x=sigmoid_x, y=x)
return x
prev_prog, prev_block, block = apply_pass_and_basic_check(
program, "mil_backend::fuse_activation_silu"
)
assert get_op_types_in_program(prev_prog) == ["sigmoid", "mul"]
assert get_op_types_in_program(program) == ["silu"]
assert_model_is_valid(
program=program,
inputs={"x": x_shape},
backend=("mlprogram", "fp32"),
expected_output_shapes={block.outputs[0].name: tuple(x_shape)},
)
class TestHomogenizeInputDtypes:
@pytest.mark.parametrize(
["op", "x_dtype", "y_dtype"],
[
["add", "int32", "fp32"],
["mul", "fp32", "int32"],
["minimum", "int64", "int32"],
["add", "int32", "fp16"],
["add", "fp16", "int32"],
["equal", "bool", "int32"],
["mod", "int64", "fp16"],
["not_equal", "fp32", "bool"],
["pow", "fp16", "fp32"],
["greater", "fp16", "fp32"],
["matmul", "fp16", "int32"],
]
)
def test_mixed_input_dtypes(self, op, x_dtype, y_dtype):
@mb.program(input_specs=[mb.TensorSpec(shape=(10, 10), dtype=string_to_builtin(x_dtype)),
mb.TensorSpec(shape=(10, 10), dtype=string_to_builtin(y_dtype))])
def prog(x, y):
x = getattr(mb, op)(x=x, y=y)
return x
assert get_op_types_in_program(prog) == [op]
_, _, block = apply_pass_and_basic_check(prog, "mil_backend::homogenize_input_dtypes")
assert get_op_types_in_program(prog) == ["cast", op]
promoted_dtype = promote_types(string_to_builtin(x_dtype), string_to_builtin(y_dtype))
# Asserting cast configuration
cast = block.find_ops(op_type="cast")[0]
assert cast.dtype.val == builtin_to_string(promoted_dtype)
assert len(cast.outputs) == 1
assert len(cast.outputs[0].child_ops) == 1
assert cast.outputs[0].child_ops[0].op_type == op
|
import React from "react";
import styled from "styled-components";
import FooterLink from "./FooterLink";
import colours from "../styles/Colours";
import devices from "../styles/Devices";
import Instagram from "../assets/images/Instagram.svg";
import Facebook from "../assets/images/Facebook.svg";
import Twitter from "../assets/images/Twitter.svg";
var platform = require("platform");
const Footer = () => {
return (
<StyledSection>
<CardWrapper>
<FooterLink
title="Lebanon Relief Network"
links={[
{ title: "Terms of Use", href: "/terms" },
{ title: "Privacy policy", href: "/privacy" },
{
title: "Code Contribution",
href:
"https://github.com/lebanon-relief-project/LRP-web-app/blob/master/CONTRIBUTING.md",
},
]}
/>
<RightHandWrapper>
<CircularLinkWrapper>
<StyledAnchor
href="https://www.instagram.com/lebanonreliefnetwork"
target="_blank"
rel="noopener noreferrer"
>
<StyledImage src={Instagram} alt="Instagram" />
</StyledAnchor>
<FBAnchor />
<StyledAnchor
href="https://twitter.com/LebReliefNet"
target="_blank"
rel="noopener noreferrer"
>
<StyledImage src={Twitter} alt="Twitter" />
</StyledAnchor>
</CircularLinkWrapper>
<Email href="mailto:contact@lebanonreliefnetwork.org" target="_blank">
contact@lebanonreliefnetwork.org
</Email>
</RightHandWrapper>
</CardWrapper>
</StyledSection>
);
};
const FBAnchor = () => {
const os = platform.os.toString();
const isAndroid = os.match(/android/i);
const isIOS = os.match(/iOS/i);
if (isIOS) {
return (
<StyledAnchor
href="fb://page/?id=100368885336321"
target="_blank"
rel="noopener noreferrer"
>
<StyledImage src={Facebook} alt="Facebook" />
</StyledAnchor>
);
} else if (isAndroid) {
return (
<StyledAnchor
href="intent://page/100368885336321?referrer=app_link#Intent;package=com.facebook.katana;scheme=fb;end"
target="_blank"
rel="noopener noreferrer"
>
<StyledImage src={Facebook} alt="Facebook" />
</StyledAnchor>
);
} else {
return (
<StyledAnchor
href="https://www.facebook.com/Lebanonreliefnetwork"
target="_blank"
rel="noopener noreferrer"
>
<StyledImage src={Facebook} alt="Facebook" />
</StyledAnchor>
);
}
};
const Email = styled.a`
color: ${colours.black};
`;
const StyledAnchor = styled.a`
margin: 5%;
`;
const StyledImage = styled.img`
width: 100%;
height: auto;
`;
const RightHandWrapper = styled.div`
padding: 1rem 0;
margin: 2rem 0rem;
`
const CircularLinkWrapper = styled.div`
display: flex;
justify-content: space-between;
@media (max-width: ${devices.mobile}) {
padding: 0;
margin: 0;
order: 1;
}
`;
const CardWrapper = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
width:60%;
margin-left:20%;
@media (max-width: ${devices.ipad}) {
width: 75%;
margin: 0% 12.5%;
}
@media (max-width: ${devices.mobile}) {
flex-direction: column;
align-items: center;
}
`;
const StyledSection = styled.section`
background: ${colours.grey};
margin: 0;
min-height: 5%;
`;
export default Footer;
|
import matplotlib.pyplot as plt
import numpy as np
import astropy.units as u
from astropy.table import Table
from cta_tools.utils import get_value
def compare_rates(counts1, counts2, bins, l1=None, l2=None):
"""
should be able to use it to plot rates against time as well with manual bins
"""
fig = plt.figure()
gs = fig.add_gridspec(3,1)
ax_hist = fig.add_subplot(gs[:-1, :])
ax_hist.set_xscale('log')
ax_hist.set_yscale('log')
ax_ratio = fig.add_subplot(gs[-1, :], sharex=ax_hist)
n1, bins1, patches1 = ax_hist.hist(bins[:-1], weights=counts1, bins=bins, histtype='step', label=l1)
n2, bins2, patches2 = ax_hist.hist(bins[:-1], weights=counts2, bins=bins, histtype='step', label=l2)
c = 0.5 * (bins[:-1] + bins[1:])
r = n1 / n2
xerr = np.diff(bins)
if isinstance(c, u.Quantity):
c = c.to_value()
xerr = xerr.to_value()
ax_ratio.errorbar(c, r, xerr=xerr, linestyle="", color="black")
ax_ratio.axhline(y=1, color="black", linestyle="--", alpha=.3, linewidth=1)
ax_hist.legend()
return fig
def hist_feature(data, column, ax=None, bins=None, logx=True, logy=True, label=None):
if not ax:
fig, ax = plt.subplots()
values = data[column]
if isinstance(data, Table):
if values.unit:
values = values.value
else:
values = values.data
values = get_value(data, column)
if logx:
if bins is None:
bins = np.logspace(np.log10(np.nanmin(values)), np.log10(np.nanmax(values)), 30)
ax.set_xscale("log")
else:
if bins is None:
bins = np.logspace(np.nanmin(values), np.nanmax(values), 30)
ax.hist(
values,
bins,
histtype="step",
weights=data["weights"] if "weights" in data.keys() else None,
label=label
)
ax.set_title(column)
if logy:
ax.set_yscale("log")
ax.legend()
return ax
def plot_binned_time_evolution(binned, ax=None):
"""
delta t is wrt the first event of the df.
This can be tricky when comparing different runs! find a better solution!
index obs id maybe
also seperate tels?
"""
ax.errorbar(
binned["center"],
binned["mean"],
xerr=0.5 * binned["width"],
yerr=binned["std"],
# label=label,
linestyle="",
)
ax.set_xlabel("time w.r.t. the first event [s]")
return ax
|
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// VARIABLES GLOBALES
var punto_venta = getParameterByName('punto_venta');
var id_receta = getParameterByName('id_receta');
var arreglo_insumo_pintar=[];
var arreglo_cantidad_pintar = [];
var insumosFormatos = 0;
var opcion;
//comprobamos si vamos a editar o registrar datos
if (isNaN(parseFloat(id_receta))) {
//REGISTRAR DATOS
insumosFormatos = 1;
pintarInsumos(insumosFormatos);
opcion = 0;
}else{
//ACTUALIZAR DATOS
obtenerReceta();
opcion = 1;
}
//Funciones para pintar y hacer cosas aca cool ya sabes :b
function agregarIngrediente(){
arreglo_insumo_pintar=[];
arreglo_cantidad_pintar = [];
for (var i = 1; i <= insumosFormatos; i++) {
var id_insumo_pintar = `select_insumo${i}`;
var id_cantidad_pintar = `cantidad_insumo${i}`;
var x = parseInt(document.getElementById(id_insumo_pintar).value);
var y = parseFloat(document.getElementById(id_cantidad_pintar).value);
arreglo_insumo_pintar.push(x);
arreglo_cantidad_pintar.push(y);
}
insumosFormatos ++;
pintarInsumos(insumosFormatos);
}
function eliminarIngrediente(){
if(insumosFormatos <= 1){
}else{
insumosFormatos --;
pintarInsumos(insumosFormatos);
}
}
function pintarInsumos(insumosFormatos){
document.getElementById('insumo_formato').innerHTML = '';
for (var i = 1; i <= insumosFormatos; i++) {
document.getElementById('insumo_formato').innerHTML += `
<div class="row">
<div class="form-group col-md-6 col-sm-12">
<label for="exampleSelect2" class="form-label mt-4">Ingrediente</label>
<select class="form-select" id="select_insumo${i}">
</select>
</div>
<div class="row col-md-6 col-sm-12">
<div class="form-group col-md-8">
<label for="exampleInputEmail1" class="form-label mt-4">Cantidad</label>
<input type="number" step="0.1" class="form-control" value="${arreglo_cantidad_pintar[i - 1]}" id="cantidad_insumo${i}" aria-describedby="emailHelp" placeholder="Cantidad">
</div>
<div class="form-group col-md-4">
<label for="exampleInputEmail1" class="form-label mt-4">Eliminar ingrediente</label>
<button onclick="eliminarIngrediente()" class="form-control btn btn-dark btn-sm" type="button"><i class="fa-solid fa-xmark fa-2x"></i></button>
</div>
</div>
</div>
`;
}
obtenerInsumos(insumosFormatos);
}
function obtenerInsumos(insumosFormatos){
$.ajax({
"url" : base_url() + "Recetas/getInsumos",
"type" : "post",
"dataType" : "json",
"success" : function( json ) {
var datos = json.respuesta;
dibujarSelectReceta();
function dibujarSelectReceta(){
for (var i = 1; i <= insumosFormatos; i++) {
var id_select_insumo = "select_insumo"+i;
datos.map((dato,index)=>{
if(dato.idInsumo == arreglo_insumo_pintar[i - 1]){
document.getElementById(id_select_insumo).innerHTML += `<option selected value="${dato.idInsumo}">${dato.nombre} ${dato.unidadMedida}</option>`;
}else{
document.getElementById(id_select_insumo).innerHTML += `<option value="${dato.idInsumo}">${dato.nombre} ${dato.unidadMedida}</option>`;
}
});
}
}
},
error: function (ts) {
console.log(ts.responseText);
alert('Ocurrió un error, por favor vuelva a intentarlo');
}
});
}
function obtenerReceta(){
$.ajax({
"url" : base_url() + "Recetas/obtenerReceta",
"type" : "post",
"data": {
id_receta: id_receta,
},
"dataType" : "json",
"success" : function( json ) {
var datos = json.respuesta;
insumosFormatos = datos.length;
document.getElementById('nombre_receta').value = datos[0].nombre;
document.getElementById('select_presentacion').value = datos[0].presentacion;
document.getElementById('precio_venta').value = datos[0].precioVenta;
arreglo_insumo_pintar=[];
arreglo_cantidad_pintar = [];
for (var i = 1; i <= datos.length; i++) {
var id_insumo_pintar = `select_insumo${i}`;
var id_cantidad_pintar = `cantidad_insumo${i}`;
var x = parseInt(datos[i - 1].idInsumo);
var y = parseFloat(datos[i - 1].cantidad);
arreglo_insumo_pintar.push(x);
arreglo_cantidad_pintar.push(y);
}
pintarInsumos(insumosFormatos);
},
error: function (ts) {
console.log(ts.responseText);
alert('Ocurrió un error, por favor vuelva a intentarlo');
}
});
}
function actualizarRegistrarReceta(){
var url = "";
var nombre_receta = document.getElementById('nombre_receta').value;
var precio_venta = parseFloat(document.getElementById('precio_venta').value);
//console.log( parseFloat(document.getElementById('precio_venta').value));
//console.log(insumosFormatos);
var arreglo_insumo = [];
var arreglo_cantidad_insumo = [];
for (var i = 1; i <= insumosFormatos; i++) {
let id_select_insumo_arreglo = `select_insumo${i}`;
let id_cantidad_insumo = `cantidad_insumo${i}`;
arreglo_insumo.push( parseInt(document.getElementById(id_select_insumo_arreglo).value));
arreglo_cantidad_insumo.push( parseFloat(document.getElementById(id_cantidad_insumo).value));
console.log(nombre_receta );
console.log(precio_venta);
console.log(document.getElementById('select_presentacion').value);
console.log(arreglo_insumo);
console.log(arreglo_cantidad_insumo);
}
if(opcion == 0){
url = "Recetas/insertReceta";
console.log("DAtos ingresados");
}else{
url = "Recetas/actualizarReceta";
console.log("Datos actualziados");
}
$.ajax({
"url" : base_url() + url,
"type" : "post",
"data": {
id_receta : id_receta,
nombre: nombre_receta ,
precio_venta: precio_venta,
arreglo_insumo: arreglo_insumo,
arreglo_cantidad: arreglo_cantidad_insumo,
presentacion: document.getElementById('select_presentacion').value,
},
"dataType" : "json",
"success" : function( json ) {
alert('Registro exitoso jaja saludos');
window.location.href = "http://localhost/inventario/controlador/recetas";
},
error: function (ts) {
console.log(ts.responseText);
alert('mm que interesante');
}
});
}
|
from pathlib import Path
SRC_DIR = Path(__file__).parent / 'docker-src'
ROOT_DIR = Path.home() / '.xnat4tests'
ROOT_DIR.mkdir(exist_ok=True)
BUILD_DIR = ROOT_DIR / 'build'
XNAT_ROOT_DIR = ROOT_DIR / 'xnat_root'
XNAT_MNT_DIRS = [
'home/logs', 'home/work', 'build', 'archive', 'prearchive']
DOCKER_IMAGE = 'xnat4tests'
DOCKER_CONTAINER = 'xnat4tests'
DOCKER_HOST = 'localhost'
XNAT_PORT = '8080' # This shouldn't be changed as it needs to be the same as the internal for the container service to work
DOCKER_REGISTRY_IMAGE = 'registry'
DOCKER_REGISTRY_CONTAINER = 'xnat4tests-docker-registry'
DOCKER_NETWORK_NAME = 'xnat4tests'
REGISTRY_PORT = '80' # Must be 80 to avoid bug in XNAT CS config
XNAT_URI = f'http://{DOCKER_HOST}:{XNAT_PORT}'
REGISTRY_URI = f'{DOCKER_HOST}' # :{REGISTRY_PORT}'
XNAT_USER = 'admin'
XNAT_PASSWORD = 'admin'
CONNECTION_ATTEMPTS = 20
CONNECTION_ATTEMPT_SLEEP = 5
|
/* Copyright 2018-present Samsung Electronics Co., Ltd. and other contributors
*
* 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.
*/
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var net, tls;
var PacketTypeEnum = {
PUBACK: 4,
PUBREC: 5,
PUBREL: 6,
PUBCOMP: 7,
};
// In seconds (should be divisible by 8)
var MQTTTimeout = 64;
function MQTTHandle(client, keepalive) {
this.client = client;
this.isConnected = false;
this.nextPacketId = 0;
this.keepalive = keepalive;
this.keepaliveCounter = 0;
this.pingrespCounter = 0;
this.storage = { };
this.storageCount = 0;
native.MqttInit(this);
}
MQTTHandle.prototype = {};
MQTTHandle.prototype.write = function(buf) {
this.socket.write(buf);
this.keepaliveCounter = 0;
};
MQTTHandle.prototype.sendAck = function(type, packet_id) {
this.write(native.sendAck(type, packet_id));
};
MQTTHandle.prototype.onconnection = function() {
this.isConnected = true;
this.timer = setInterval(storageTimerHit.bind(this), 1000);
this.client.emit('connect');
};
MQTTHandle.prototype.onEnd = function() {
this.isConnected = false;
// Abort outgoing messages.
clearInterval(this.timer);
this.storage = null;
this.storageCount = 0;
this.client.emit('end');
};
MQTTHandle.prototype.onmessage = function(message, topic, qos, packet_id) {
var data = {
message: message,
topic: topic,
qos: qos,
packet_id: packet_id,
};
if (qos >= 1) {
var type = (qos == 1) ? PacketTypeEnum.PUBACK : PacketTypeEnum.PUBREC;
this.sendAck(type, packet_id);
}
this.client.emit('message', data);
};
MQTTHandle.prototype.getPacketId = function() {
while (true) {
var packet_id = this.nextPacketId;
this.nextPacketId = (this.nextPacketId + 1) & 0xffff;
if (!(packet_id in this.storage)) {
this.storage[packet_id] = { remainingTime: MQTTTimeout };
this.storageCount++;
return packet_id;
}
}
};
MQTTHandle.prototype.releasePacket = function(packet_id, error) {
// callback will be invalid after delete
var callback = this.storage[packet_id].callback;
delete this.storage[packet_id];
this.storageCount--;
// This function should never fail.
try {
if (typeof callback == 'function') {
callback(error);
} else if (error) {
this.client.emit('error', error);
}
} catch (e) {
// Do nothing.
}
};
MQTTHandle.prototype.onpingresp = function() {
this.pingrespCounter = 0;
};
MQTTHandle.prototype.onack = function(packet_id, error) {
this.releasePacket(packet_id, error);
};
MQTTHandle.prototype.onpubrec = function(packet_id) {
/*
* Qos level 2
* Handle PUBREC package. If this package is arrived, we have to send back
* a PUBREL package to the server.
*/
var buffer = native.sendAck(PacketTypeEnum.PUBREL, packet_id);
this.write(buffer);
// Upodate packet rather than create a new one
var packet = this.storage[packet_id];
packet.remainingTime = MQTTTimeout;
packet.packet = buffer;
};
MQTTHandle.prototype.onpubrel = function(data) {
/*
* Qos level 2
* Handle PUBREL package. If this package is arrived, we have to send back
* a PUBCOMP package to the server.
*/
this.sendAck(PacketTypeEnum.PUBCOMP, data);
};
function MQTTClient(url, options, callback) {
if (!(this instanceof MQTTClient)) {
return new MQTTClient(url, options, callback);
}
EventEmitter.call(this);
var socket;
if (typeof url == 'string') {
if (typeof options == 'function') {
callback = options;
options = {};
}
} else {
if (typeof url == 'function') {
callback = url;
options = {};
} else if (typeof options == 'function') {
callback = options;
options = url;
} else {
options = url;
}
if (options.socket) {
socket = options.socket;
} else {
url = options.host || '127.0.0.1';
}
}
if (typeof callback == 'function') {
this.on('connect', callback);
}
if (options.will) {
if (typeof options.topic == 'undefined' ||
typeof options.message == 'undefined' ||
options.qos < 0 || options.qos > 2) {
throw new Error('Incorrect mqtt will options');
}
}
var host = '';
var create_tls = false;
if (!socket) {
if (url.substring(0, 8) == 'mqtts://') {
create_tls = true;
host = url.substring(8);
} else if (url.substring(0, 7) == 'mqtt://') {
host = url.substring(7);
} else {
host = url;
}
}
var keepalive = (options.keepalive || 60) | 0;
if (keepalive < 30) {
keepalive = 30;
}
if (keepalive > 65535) {
keepalive = 65535;
}
options = Object.create(options, {
clientId: { value: options.clientId || defaultClientId() },
host: { value: host },
port: { value: options.port || 8883 },
qos: { value: options.qos || 0 },
keepalive: { value: keepalive },
});
// Since network transmission takes time, the
// actual keepalive message is sent a bit earlier
this._handle = new MQTTHandle(this, keepalive - 5);
var connectionMessage = native.connect(options);
var onconnect = function() {
// Currently the connect message is tried only once.
// Multiple tries can be implemented later.
this.write(connectionMessage);
};
if (socket) {
onconnect.call(socket);
} else {
if (create_tls) {
if (!tls) {
tls = require('tls');
}
socket = tls.connect(options, onconnect);
} else {
if (!net) {
net = require('net');
}
socket = net.connect(options, onconnect);
}
}
this._handle.socket = socket;
socket._mqttSocket = this;
socket.on('error', onerror);
socket.on('data', ondata);
socket.on('finish', onfinish);
}
util.inherits(MQTTClient, EventEmitter);
MQTTClient.prototype.end = function(force) {
var handle = this._handle;
handle.isConnected = false;
if (force || handle.storageCount == 0) {
handle.socket.end(native.disconnect());
// Abort ongoing messages.
clearInterval(this.timer);
this.storage = null;
this.storageCount = 0;
}
};
MQTTClient.prototype.checkConnection = function() {
if (!this._handle.isConnected) {
throw new Error('MQTT client is not connected');
}
};
MQTTClient.prototype.publish = function(topic, message, options, callback) {
this.checkConnection();
var handle = this._handle;
// header bits: | 16 bit packet id | 4 bit PUBLISH header |
var header = 0;
var qos = 0;
if (options) {
if (options.retain) {
header = 0x1;
}
qos = options.qos;
if (qos !== 1 && qos !== 2) {
qos = 0;
}
header |= (qos << 1);
}
if (qos > 0) {
var packet_id = handle.getPacketId();
header |= (packet_id << 4);
var buffer = native.publish(topic, message, header);
handle.write(buffer);
// Set dup flag.
buffer.writeUInt8(buffer.readUInt8(0) | 0x08, 0);
var packet = handle.storage[packet_id];
packet.packet = buffer;
packet.callback = callback;
return;
}
handle.write(native.publish(topic, message, header));
if (typeof callback == 'function') {
process.nextTick(callback);
}
};
MQTTClient.prototype.subscribe = function(topic, options, callback) {
this.checkConnection();
var handle = this._handle;
var packet_id = handle.getPacketId();
// header bits: | 2 bit qos | 16 bit packet id |
var header = packet_id;
var qos = 0;
if (options) {
qos = options.qos;
if (qos !== 1 || qos !== 2) {
qos = 0;
}
header |= (qos << 16);
}
var buffer = native.subscribe(topic, header);
handle.write(buffer);
var packet = handle.storage[packet_id];
packet.packet = buffer;
packet.callback = callback;
};
MQTTClient.prototype.unsubscribe = function(topic, callback) {
this.checkConnection();
var handle = this._handle;
var packet_id = handle.getPacketId();
// header bits: | 16 bit packet id |
var header = packet_id;
var buffer = native.unsubscribe(topic, header);
handle.write(buffer);
var packet = handle.storage[packet_id];
packet.packet = buffer;
packet.callback = callback;
};
function onerror(error) {
this._mqttSocket.emit('error', error);
}
function ondata(data) {
native.MqttReceive(this._mqttSocket._handle, data);
}
function onfinish() {
this._mqttSocket._handle.onEnd();
}
function storageTimerHit() {
// this: MQTTHandle
// eslint-disable-next-line guard-for-in
for (var packet_id in this.storage) {
var packet = this.storage[packet_id];
packet.remainingTime--;
if (packet.remainingTime <= 0) {
this.releasePacket(packet_id, new Error('Undelivered message'));
continue;
}
// Every 8 seconds, the message is retransmitted.
if (!(packet.remainingTime & 0x7)) {
this.write(packet.packet);
}
}
if (this.storageCount == 0 && !this.isConnected) {
// Graceful disconnect after all messages transmitted.
this.socket.end(native.disconnect());
clearInterval(this.timer);
this.storage = null;
return;
}
if (this.pingrespCounter > 0) {
this.pingrespCounter--;
if (this.pingrespCounter <= 0) {
this.onEnd();
}
}
this.keepaliveCounter++;
if (this.keepaliveCounter >= this.keepalive) {
this.write(native.ping());
if (this.pingrespCounter == 0) {
this.pingrespCounter = (this.keepalive + 5) * 3 >> 1;
}
}
}
/*
* Returns an unique client ID based on current time.
*/
function defaultClientId() {
return 'iotjs_mqtt_client_' + Date.now();
}
function connect(url, options, callback) {
return new MQTTClient(url, options, callback);
}
exports.connect = connect;
|
import BuyMe from "./BuyMe";
const ThanksForPlaying = () => (
<>
<div className="card">
<div className="text">
Thanks for playing Spyfall!
<br />
If you had fun, try my other game:
</div>
<a
href="https://drawphone.tannerkrewson.com/"
target="_blank"
rel="noopener noreferrer"
>
<button className="btn-small">Play Drawphone</button>
</a>
<div className="text">or, if you're feeling hungry:</div>
<div style={{ width: "148px", margin: "0 auto" }}>
<BuyMe />
</div>
</div>
<style jsx>{`
.card {
margin: 2em auto 0;
border: 2px solid #ddd;
padding: 1em;
max-width: 18em;
font-size: 0.9em;
}
.text {
font-size: 0.9em;
}
button {
margin: 0.8em 0 1.1em;
}
`}</style>
</>
);
export default ThanksForPlaying;
|
from src.algorithm import ID3
class Classifier:
def __init__(self, algorithm):
self.algorithm = algorithm
self.model = None
def train(self):
self.model = self.algorithm.train()
def classify(self, element, vote=False):
if vote:
clazz, prob = self.algorithm.specific_class_probability()
return (
self.model.classify(element),
{ clazz: prob }
)
else:
return self.model.classify(element)
|
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from __future__ import division
import re
import time
from copy import deepcopy
from distutils.version import LooseVersion
import pymongo
from six import PY3, iteritems, itervalues
from six.moves.urllib.parse import unquote_plus, urlsplit
from datadog_checks.base import AgentCheck, ConfigurationError, is_affirmative
from datadog_checks.base.utils.common import round_value
from . import metrics
if PY3:
long = int
DEFAULT_TIMEOUT = 30
ALLOWED_CUSTOM_METRICS_TYPES = ['gauge', 'rate', 'count', 'monotonic_count']
ALLOWED_CUSTOM_QUERIES_COMMANDS = ['aggregate', 'count', 'find']
class MongoDb(AgentCheck):
"""
MongoDB agent check.
# Metrics
Metric available for collection are listed by topic as `MongoDb` class variables.
Various metric topics are collected by default. Others require the
corresponding option enabled in the check configuration file.
## Format
Metrics are listed with the following format:
```
metric_name -> metric_type
```
or
```
metric_name -> (metric_type, alias)*
```
* `alias` parameter is optional, if unspecified, MongoDB metrics are reported
with their original metric names.
# Service checks
Available service checks:
* `mongodb.can_connect`
Connectivity health to the instance.
* `mongodb.replica_set_member_state`
Disposition of the member replica set state.
"""
# Source
SOURCE_TYPE_NAME = 'mongodb'
# Service check
SERVICE_CHECK_NAME = 'mongodb.can_connect'
# Replication states
"""
MongoDB replica set states, as documented at
https://docs.mongodb.org/manual/reference/replica-states/
"""
REPLSET_MEMBER_STATES = {
0: ('STARTUP', 'Starting Up'),
1: ('PRIMARY', 'Primary'),
2: ('SECONDARY', 'Secondary'),
3: ('RECOVERING', 'Recovering'),
4: ('Fatal', 'Fatal'), # MongoDB docs don't list this state
5: ('STARTUP2', 'Starting up (forking threads)'),
6: ('UNKNOWN', 'Unknown to this replset member'),
7: ('ARBITER', 'Arbiter'),
8: ('DOWN', 'Down'),
9: ('ROLLBACK', 'Rollback'),
10: ('REMOVED', 'Removed'),
}
def __init__(self, name, init_config, instances=None):
super(MongoDb, self).__init__(name, init_config, instances)
# Members' last replica set states
self._last_state_by_server = {}
self.collection_metrics_names = (key.split('.')[1] for key in metrics.COLLECTION_METRICS)
if 'server' not in self.instance:
raise ConfigurationError("Missing 'server' in mongo config")
# x.509 authentication
ssl_params = {
'ssl': self.instance.get('ssl', None),
'ssl_keyfile': self.instance.get('ssl_keyfile', None),
'ssl_certfile': self.instance.get('ssl_certfile', None),
'ssl_cert_reqs': self.instance.get('ssl_cert_reqs', None),
'ssl_ca_certs': self.instance.get('ssl_ca_certs', None),
}
self.ssl_params = {key: value for key, value in iteritems(ssl_params) if value is not None}
self.server = self.instance['server']
(
self.username,
self.password,
self.db_name,
self.nodelist,
self.clean_server_name,
self.auth_source,
) = self._parse_uri(self.server, sanitize_username=bool(self.ssl_params))
self.additional_metrics = self.instance.get('additional_metrics', [])
# Get the list of metrics to collect
self.collect_tcmalloc_metrics = 'tcmalloc' in self.additional_metrics
self.metrics_to_collect = self._build_metric_list_to_collect()
if not self.db_name:
self.log.info('No MongoDB database found in URI. Defaulting to admin.')
self.db_name = 'admin'
# Tagging
custom_tags = list(set(self.instance.get('tags', [])))
self.service_check_tags = ["db:%s" % self.db_name] + custom_tags
# ...add the `server` tag to the metrics' tags only
# (it's added in the backend for service checks)
self.tags = custom_tags + ['server:%s' % self.clean_server_name]
if self.nodelist:
host = self.nodelist[0][0]
port = self.nodelist[0][1]
self.service_check_tags = self.service_check_tags + ["host:%s" % host, "port:%s" % port]
self.timeout = float(self.instance.get('timeout', DEFAULT_TIMEOUT)) * 1000
# Authenticate
self.do_auth = True
self.use_x509 = self.ssl_params and not self.password
if not self.username:
self.log.debug(u"A username is required to authenticate to `%s`", self.server)
self.do_auth = False
self.replica_check = is_affirmative(self.instance.get('replica_check', True))
self.collections_indexes_stats = is_affirmative(self.instance.get('collections_indexes_stats'))
self.coll_names = self.instance.get('collections', [])
self.custom_queries = self.instance.get("custom_queries", [])
@classmethod
def get_library_versions(cls):
return {'pymongo': pymongo.version}
def get_state_description(self, state):
if state in self.REPLSET_MEMBER_STATES:
return self.REPLSET_MEMBER_STATES[state][1]
else:
return 'Replset state %d is unknown to the Datadog agent' % state
def get_state_name(self, state):
if state in self.REPLSET_MEMBER_STATES:
return self.REPLSET_MEMBER_STATES[state][0]
else:
return 'UNKNOWN'
def _report_replica_set_state(self, state, replset_name):
"""
Report the member's replica set state
* Submit a service check.
* Create an event on state change.
"""
last_state = self._last_state_by_server.get(self.clean_server_name, -1)
self._last_state_by_server[self.clean_server_name] = state
if last_state != state and last_state != -1:
return self.create_event(last_state, state, replset_name)
def hostname_for_event(self, clean_server_name):
"""Return a reasonable hostname for a replset membership event to mention."""
uri = urlsplit(clean_server_name)
if '@' in uri.netloc:
hostname = uri.netloc.split('@')[1].split(':')[0]
else:
hostname = uri.netloc.split(':')[0]
if hostname == 'localhost':
hostname = self.hostname
return hostname
def create_event(self, last_state, state, replset_name):
"""Create an event with a message describing the replication
state of a mongo node"""
status = self.get_state_description(state)
short_status = self.get_state_name(state)
last_short_status = self.get_state_name(last_state)
hostname = self.hostname_for_event(self.clean_server_name)
msg_title = "%s is %s for %s" % (hostname, short_status, replset_name)
msg = "MongoDB %s (%s) just reported as %s (%s) for %s; it was %s before."
msg = msg % (hostname, self.clean_server_name, status, short_status, replset_name, last_short_status)
self.event(
{
'timestamp': int(time.time()),
'source_type_name': self.SOURCE_TYPE_NAME,
'msg_title': msg_title,
'msg_text': msg,
'host': hostname,
'tags': [
'action:mongo_replset_member_status_change',
'member_status:' + short_status,
'previous_member_status:' + last_short_status,
'replset:' + replset_name,
],
}
)
def _build_metric_list_to_collect(self):
"""
Build the metric list to collect based on the instance preferences.
"""
metrics_to_collect = {}
# Defaut metrics
for default_metrics in itervalues(metrics.DEFAULT_METRICS):
metrics_to_collect.update(default_metrics)
# Additional metrics metrics
for option in self.additional_metrics:
additional_metrics = metrics.AVAILABLE_METRICS.get(option)
if not additional_metrics:
if option in metrics.DEFAULT_METRICS:
self.log.warning(
u"`%s` option is deprecated. The corresponding metrics are collected by default.", option
)
else:
self.log.warning(
u"Failed to extend the list of metrics to collect: unrecognized `%s` option", option
)
continue
self.log.debug(u"Adding `%s` corresponding metrics to the list of metrics to collect.", option)
metrics_to_collect.update(additional_metrics)
return metrics_to_collect
def _resolve_metric(self, original_metric_name, metrics_to_collect, prefix=""):
"""
Return the submit method and the metric name to use.
The metric name is defined as follow:
* If available, the normalized metric name alias
* (Or) the normalized original metric name
"""
submit_method = (
metrics_to_collect[original_metric_name][0]
if isinstance(metrics_to_collect[original_metric_name], tuple)
else metrics_to_collect[original_metric_name]
)
metric_name = (
metrics_to_collect[original_metric_name][1]
if isinstance(metrics_to_collect[original_metric_name], tuple)
else original_metric_name
)
return submit_method, self._normalize(metric_name, submit_method, prefix)
def _normalize(self, metric_name, submit_method, prefix):
"""
Replace case-sensitive metric name characters, normalize the metric name,
prefix and suffix according to its type.
"""
metric_prefix = "mongodb." if not prefix else "mongodb.{0}.".format(prefix)
metric_suffix = "ps" if submit_method == metrics.RATE else ""
# Replace case-sensitive metric name characters
for pattern, repl in iteritems(metrics.CASE_SENSITIVE_METRIC_NAME_SUFFIXES):
metric_name = re.compile(pattern).sub(repl, metric_name)
# Normalize, and wrap
return u"{metric_prefix}{normalized_metric_name}{metric_suffix}".format(
normalized_metric_name=self.normalize(metric_name.lower()),
metric_prefix=metric_prefix,
metric_suffix=metric_suffix,
)
def _authenticate(self, database):
"""
Authenticate to the database.
Available mechanisms:
* Username & password
* X.509
More information:
https://api.mongodb.com/python/current/examples/authentication.html
"""
authenticated = False
try:
# X.509
if self.use_x509:
self.log.debug(u"Authenticate `%s` to `%s` using `MONGODB-X509` mechanism", self.username, database)
authenticated = database.authenticate(self.username, mechanism='MONGODB-X509')
# Username & password
else:
authenticated = database.authenticate(self.username, self.password)
except pymongo.errors.PyMongoError as e:
self.log.error(u"Authentication failed due to invalid credentials or configuration issues. %s", e)
if not authenticated:
message = "Mongo: cannot connect with config %s" % self.clean_server_name
self.service_check(
self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=self.service_check_tags, message=message
)
raise Exception(message)
return authenticated
@classmethod
def _parse_uri(cls, server, sanitize_username=False):
"""
Parses a MongoDB-formatted URI (e.g. mongodb://user:pass@server/db) and returns parsed elements
and a sanitized URI.
"""
parsed = pymongo.uri_parser.parse_uri(server)
username = parsed.get('username')
password = parsed.get('password')
db_name = parsed.get('database')
nodelist = parsed.get('nodelist')
auth_source = parsed.get('options', {}).get('authsource')
# Remove password (and optionally username) from sanitized server URI.
# To ensure that the `replace` works well, we first need to url-decode the raw server string
# since the password parsed by pymongo is url-decoded
decoded_server = unquote_plus(server)
clean_server_name = decoded_server.replace(password, "*" * 5) if password else decoded_server
if sanitize_username and username:
username_pattern = u"{}[@:]".format(re.escape(username))
clean_server_name = re.sub(username_pattern, "", clean_server_name)
return username, password, db_name, nodelist, clean_server_name, auth_source
def _collect_indexes_stats(self, db, tags):
"""
Collect indexes statistics for all collections in the configuration.
This use the "$indexStats" command.
"""
for coll_name in self.coll_names:
try:
for stats in db[coll_name].aggregate([{"$indexStats": {}}], cursor={}):
idx_tags = tags + [
"name:{0}".format(stats.get('name', 'unknown')),
"collection:{0}".format(coll_name),
]
val = int(stats.get('accesses', {}).get('ops', 0))
self.gauge('mongodb.collection.indexes.accesses.ops', val, idx_tags)
except Exception as e:
self.log.error("Could not fetch indexes stats for collection %s: %s", coll_name, e)
def _get_submission_method(self, method_name):
if method_name not in ALLOWED_CUSTOM_METRICS_TYPES:
raise ValueError('Metric type {} is not one of {}.'.format(method_name, ALLOWED_CUSTOM_METRICS_TYPES))
return getattr(self, method_name)
@staticmethod
def _extract_command_from_mongo_query(mongo_query):
"""Extract the command (find, count or aggregate) from the query. Even though mongo and pymongo are supposed
to work with the query as a single document, pymongo expects the command to be the `first` element of the
query dict.
Because python 2 dicts are not ordered, the command is extracted to be later run as the first argument
of pymongo `runcommand`
"""
for command in ALLOWED_CUSTOM_QUERIES_COMMANDS:
if command in mongo_query:
return command
raise ValueError("Custom query command must be of type {}".format(ALLOWED_CUSTOM_QUERIES_COMMANDS))
def _collect_custom_metrics_for_query(self, db, raw_query, tags):
"""Validates the raw_query object, executes the mongo query then submits the metrics to datadog"""
metric_prefix = raw_query.get('metric_prefix')
if not metric_prefix: # no cov
raise ValueError("Custom query field `metric_prefix` is required")
metric_prefix = metric_prefix.rstrip('.')
mongo_query = deepcopy(raw_query.get('query'))
if not mongo_query: # no cov
raise ValueError("Custom query field `query` is required")
mongo_command = self._extract_command_from_mongo_query(mongo_query)
collection_name = mongo_query[mongo_command]
del mongo_query[mongo_command]
if mongo_command not in ALLOWED_CUSTOM_QUERIES_COMMANDS:
raise ValueError("Custom query command must be of type {}".format(ALLOWED_CUSTOM_QUERIES_COMMANDS))
submit_method = self.gauge
fields = []
if mongo_command == 'count':
count_type = raw_query.get('count_type')
if not count_type: # no cov
raise ValueError('Custom query field `count_type` is required with a `count` query')
submit_method = self._get_submission_method(count_type)
else:
fields = raw_query.get('fields')
if not fields: # no cov
raise ValueError('Custom query field `fields` is required')
for field in fields:
field_name = field.get('field_name')
if not field_name: # no cov
raise ValueError('Field `field_name` is required for metric_prefix `{}`'.format(metric_prefix))
name = field.get('name')
if not name: # no cov
raise ValueError('Field `name` is required for metric_prefix `{}`'.format(metric_prefix))
field_type = field.get('type')
if not field_type: # no cov
raise ValueError('Field `type` is required for metric_prefix `{}`'.format(metric_prefix))
if field_type not in ALLOWED_CUSTOM_METRICS_TYPES + ['tag']:
raise ValueError('Field `type` must be one of {}'.format(ALLOWED_CUSTOM_METRICS_TYPES + ['tag']))
tags = list(tags)
tags.extend(raw_query.get('tags', []))
tags.append('collection:{}'.format(collection_name))
try:
# This is where it is necessary to extract the command and its argument from the query to pass it as the
# first two params.
result = db.command(mongo_command, collection_name, **mongo_query)
if result['ok'] == 0:
raise pymongo.errors.PyMongoError(result['errmsg'])
except pymongo.errors.PyMongoError:
self.log.error("Failed to run custom query for metric %s", metric_prefix)
raise
if mongo_command == 'count':
# A count query simply returns a number, no need to iterate through it.
submit_method(metric_prefix, result['n'], tags)
return
cursor = pymongo.command_cursor.CommandCursor(
pymongo.collection.Collection(db, collection_name), result['cursor'], None
)
for row in cursor:
metric_info = []
query_tags = list(tags)
for field in fields:
field_name = field['field_name']
if field_name not in row:
# Each row can have different fields, do not fail here.
continue
field_type = field['type']
if field_type == 'tag':
tag_name = field['name']
query_tags.append('{}:{}'.format(tag_name, row[field_name]))
else:
metric_suffix = field['name']
submit_method = self._get_submission_method(field_type)
metric_name = '{}.{}'.format(metric_prefix, metric_suffix)
try:
metric_info.append((metric_name, float(row[field_name]), submit_method))
except (TypeError, ValueError):
continue
for metric_name, metric_value, submit_method in metric_info:
submit_method(metric_name, metric_value, tags=query_tags)
def check(self, _):
"""
Returns a dictionary that looks a lot like what's sent back by
db.serverStatus()
"""
def total_seconds(td):
"""
Returns total seconds of a timedelta in a way that's safe for
Python < 2.7
"""
if hasattr(td, 'total_seconds'):
return td.total_seconds()
else:
return (lag.microseconds + (lag.seconds + lag.days * 24 * 3600) * 10 ** 6) / 10.0 ** 6
try:
cli = pymongo.mongo_client.MongoClient(
self.server,
socketTimeoutMS=self.timeout,
connectTimeoutMS=self.timeout,
serverSelectionTimeoutMS=self.timeout,
read_preference=pymongo.ReadPreference.PRIMARY_PREFERRED,
**self.ssl_params
)
# some commands can only go against the admin DB
admindb = cli['admin']
db = cli[self.db_name]
except Exception:
self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=self.service_check_tags)
raise
if self.do_auth:
if self.auth_source:
msg = "authSource was specified in the the server URL: using '%s' as the authentication database"
self.log.info(msg, self.auth_source)
self._authenticate(cli[self.auth_source])
else:
self._authenticate(db)
try:
status = db.command('serverStatus', tcmalloc=self.collect_tcmalloc_metrics)
except Exception:
self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=self.service_check_tags)
raise
else:
self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.OK, tags=self.service_check_tags)
if status['ok'] == 0:
raise Exception(status['errmsg'].__str__())
ops = db.current_op()
status['fsyncLocked'] = 1 if ops.get('fsyncLock') else 0
status['stats'] = db.command('dbstats')
dbstats = {self.db_name: {'stats': status['stats']}}
try:
mongo_version = cli.server_info().get('version', '0.0')
self.set_metadata('version', mongo_version)
except Exception:
self.log.exception("Error when collecting the version from the mongo server.")
mongo_version = '0.0'
tags = deepcopy(self.tags)
# Handle replica data, if any
# See
# http://www.mongodb.org/display/DOCS/Replica+Set+Commands#ReplicaSetCommands-replSetGetStatus # noqa
if self.replica_check:
try:
data = {}
replSet = admindb.command('replSetGetStatus')
if replSet:
primary = None
current = None
# need a new connection to deal with replica sets
setname = replSet.get('set')
cli_rs = pymongo.mongo_client.MongoClient(
self.server,
socketTimeoutMS=self.timeout,
connectTimeoutMS=self.timeout,
serverSelectionTimeoutMS=self.timeout,
replicaset=setname,
read_preference=pymongo.ReadPreference.NEAREST,
**self.ssl_params
)
if self.do_auth:
if self.auth_source:
self._authenticate(cli_rs[self.auth_source])
else:
self._authenticate(cli_rs[self.db_name])
# Replication set information
replset_name = replSet['set']
replset_state = self.get_state_name(replSet['myState']).lower()
tags.extend([u"replset_name:{0}".format(replset_name), u"replset_state:{0}".format(replset_state)])
# Find nodes: master and current node (ourself)
for member in replSet.get('members'):
if member.get('self'):
current = member
if int(member.get('state')) == 1:
primary = member
# Compute a lag time
if current is not None and primary is not None:
if 'optimeDate' in primary and 'optimeDate' in current:
lag = primary['optimeDate'] - current['optimeDate']
data['replicationLag'] = total_seconds(lag)
if current is not None:
data['health'] = current['health']
data['state'] = replSet['myState']
if current is not None:
total = 0.0
cfg = cli_rs['local']['system.replset'].find_one()
for member in cfg.get('members'):
total += member.get('votes', 1)
if member['_id'] == current['_id']:
data['votes'] = member.get('votes', 1)
data['voteFraction'] = data['votes'] / total
status['replSet'] = data
# Submit events
self._report_replica_set_state(data['state'], replset_name)
except Exception as e:
if "OperationFailure" in repr(e) and (
"not running with --replSet" in str(e) or "replSetGetStatus" in str(e)
):
pass
else:
raise e
# If these keys exist, remove them for now as they cannot be serialized
try:
status['backgroundFlushing'].pop('last_finished')
except KeyError:
pass
try:
status.pop('localTime')
except KeyError:
pass
dbnames = cli.list_database_names()
self.gauge('mongodb.dbs', len(dbnames), tags=tags)
for db_n in dbnames:
db_aux = cli[db_n]
dbstats[db_n] = {'stats': db_aux.command('dbstats')}
# Go through the metrics and save the values
for metric_name in self.metrics_to_collect:
# each metric is of the form: x.y.z with z optional
# and can be found at status[x][y][z]
value = status
if metric_name.startswith('stats'):
continue
else:
try:
for c in metric_name.split("."):
value = value[c]
except KeyError:
continue
# value is now status[x][y][z]
if not isinstance(value, (int, long, float)):
raise TypeError(
u"{0} value is a {1}, it should be an int, a float or a long instead.".format(
metric_name, type(value)
)
)
# Submit the metric
submit_method, metric_name_alias = self._resolve_metric(metric_name, self.metrics_to_collect)
submit_method(self, metric_name_alias, value, tags=tags)
for st, value in iteritems(dbstats):
for metric_name in self.metrics_to_collect:
if not metric_name.startswith('stats.'):
continue
try:
val = value['stats'][metric_name.split('.')[1]]
except KeyError:
continue
# value is now status[x][y][z]
if not isinstance(val, (int, long, float)):
raise TypeError(
u"{0} value is a {1}, it should be an int, a float or a long instead.".format(
metric_name, type(val)
)
)
# Submit the metric
metrics_tags = tags + [
u"cluster:db:{0}".format(st), # FIXME 6.0 - keep for backward compatibility
u"db:{0}".format(st),
]
submit_method, metric_name_alias = self._resolve_metric(metric_name, self.metrics_to_collect)
submit_method(self, metric_name_alias, val, tags=metrics_tags)
if self.collections_indexes_stats:
if LooseVersion(mongo_version) >= LooseVersion("3.2"):
self._collect_indexes_stats(db, tags)
else:
msg = "'collections_indexes_stats' is only available starting from mongo 3.2: your mongo version is %s"
self.log.error(msg, mongo_version)
# Report the usage metrics for dbs/collections
if 'top' in self.additional_metrics:
try:
dbtop = admindb.command('top')
for ns, ns_metrics in iteritems(dbtop['totals']):
if "." not in ns:
continue
# configure tags for db name and collection name
dbname, collname = ns.split(".", 1)
ns_tags = tags + ["db:%s" % dbname, "collection:%s" % collname]
# iterate over DBTOP metrics
for m in metrics.TOP_METRICS:
# each metric is of the form: x.y.z with z optional
# and can be found at ns_metrics[x][y][z]
value = ns_metrics
try:
for c in m.split("."):
value = value[c]
except Exception:
continue
# value is now status[x][y][z]
if not isinstance(value, (int, long, float)):
raise TypeError(
u"{0} value is a {1}, it should be an int, a float or a long instead.".format(
m, type(value)
)
)
# Submit the metric
submit_method, metric_name_alias = self._resolve_metric(
m, self.metrics_to_collect, prefix="usage"
)
submit_method(self, metric_name_alias, value, tags=ns_tags)
# Keep old incorrect metric
if metric_name_alias.endswith('countps'):
self.gauge(metric_name_alias[:-2], value, tags=ns_tags)
except Exception as e:
self.log.warning('Failed to record `top` metrics %s', e)
if 'local' in dbnames: # it might not be if we are connectiing through mongos
# Fetch information analogous to Mongo's db.getReplicationInfo()
localdb = cli['local']
oplog_data = {}
for ol_collection_name in ("oplog.rs", "oplog.$main"):
ol_options = localdb[ol_collection_name].options()
if ol_options:
break
if ol_options:
try:
oplog_data['logSizeMB'] = round_value(ol_options['size'] / 2.0 ** 20, 2)
oplog = localdb[ol_collection_name]
oplog_data['usedSizeMB'] = round_value(
localdb.command("collstats", ol_collection_name)['size'] / 2.0 ** 20, 2
)
op_asc_cursor = oplog.find({"ts": {"$exists": 1}}).sort("$natural", pymongo.ASCENDING).limit(1)
op_dsc_cursor = oplog.find({"ts": {"$exists": 1}}).sort("$natural", pymongo.DESCENDING).limit(1)
try:
first_timestamp = op_asc_cursor[0]['ts'].as_datetime()
last_timestamp = op_dsc_cursor[0]['ts'].as_datetime()
oplog_data['timeDiff'] = total_seconds(last_timestamp - first_timestamp)
except (IndexError, KeyError):
# if the oplog collection doesn't have any entries
# if an object in the collection doesn't have a ts value, we ignore it
pass
except KeyError:
# encountered an error trying to access options.size for the oplog collection
self.log.warning(u"Failed to record `ReplicationInfo` metrics.")
for m, value in iteritems(oplog_data):
submit_method, metric_name_alias = self._resolve_metric('oplog.%s' % m, self.metrics_to_collect)
submit_method(self, metric_name_alias, value, tags=tags)
else:
self.log.debug('"local" database not in dbnames. Not collecting ReplicationInfo metrics')
# get collection level stats
try:
# Ensure that you're on the right db
db = cli[self.db_name]
# loop through the collections
for coll_name in self.coll_names:
# grab the stats from the collection
stats = db.command("collstats", coll_name)
# loop through the metrics
for m in self.collection_metrics_names:
coll_tags = tags + ["db:%s" % self.db_name, "collection:%s" % coll_name]
value = stats.get(m, None)
if not value:
continue
# if it's the index sizes, then it's a dict.
if m == 'indexSizes':
submit_method, metric_name_alias = self._resolve_metric(
'collection.%s' % m, metrics.COLLECTION_METRICS
)
# loop through the indexes
for idx, val in iteritems(value):
# we tag the index
idx_tags = coll_tags + ["index:%s" % idx]
submit_method(self, metric_name_alias, val, tags=idx_tags)
else:
submit_method, metric_name_alias = self._resolve_metric(
'collection.%s' % m, metrics.COLLECTION_METRICS
)
submit_method(self, metric_name_alias, value, tags=coll_tags)
except Exception as e:
self.log.warning(u"Failed to record `collection` metrics.")
self.log.exception(e)
custom_query_tags = tags + ["db:{}".format(self.db_name)]
for raw_query in self.custom_queries:
try:
self._collect_custom_metrics_for_query(db, raw_query, custom_query_tags)
except Exception as e:
metric_prefix = raw_query.get('metric_prefix')
self.log.warning("Errors while collecting custom metrics with prefix %s", metric_prefix, exc_info=e)
|
import { shallowMount, mount } from "@vue/test-utils";
import PrefectureList from "@/components/PrefectureList.vue";
import BaseCheckbox from "@/components/Base/BaseCheckbox.vue";
import flushPromises from "flush-promises";
jest.mock("axios");
import { setPattern } from "axios";
setPattern(0);
describe("PrefectureList.vue", () => {
test("コンポーネントを描画時に非同期処理が行われデータを取得できているか", async () => {
const wrapper = shallowMount(PrefectureList, {
propsData: {
value: []
}
});
await flushPromises();
const prefectures = wrapper.vm.prefectures;
const data = [{ prefName: "大阪", prefCode: 20 }];
expect(prefectures).toEqual(data);
});
test("非同期処理で取得した分のデータをリストで描画できているか", async () => {
const wrapper = mount(PrefectureList, {
propsData: {
value: []
}
});
await flushPromises();
expect(wrapper.contains("li")).toBe(true);
});
test("Baseコンポーネントからのemitを受け取れているか", async () => {
const wrapper = shallowMount(PrefectureList, {
propsData: {
value: []
}
});
await flushPromises();
const emittestdata = { prefName: "大阪", prefCode: 20 };
wrapper.find(BaseCheckbox).vm.$emit("input", emittestdata);
expect(wrapper.emitted().input[0][0]).toEqual(emittestdata);
});
});
|
import moment from "moment";
import React, { useEffect } from "react";
import { Editor, EditorState,convertToRaw, convertFromRaw } from 'draft-js';
import 'draft-js/dist/Draft.css';
import { useState } from "react";
const Relatorio = ({ retorna, values, putRelatorio }) => {
const [editorState, setEditorState] = useState(() => !values.relatorio_medico ? EditorState.createEmpty() : EditorState.createWithContent(convertFromRaw(JSON.parse(values.relatorio_medico))))
const editor = React.useRef(null)
const focusEditor=()=>{
editor.current.focus()
}
const convertRelatorioToString = ()=>{
const content = convertToRaw(editorState.getCurrentContent())
return JSON.stringify(content)
}
return (
<div>
<div className="header">
<span className="flex">
<i className="pe-7s-angle-left-circle return" onClick={retorna}>
</i>
<p className="btn-voltar">voltar</p>
</span>
<h4>Relatório de Consulta</h4>
</div>
<div className="content">
<label className="control-label">Nome do Paciente</label>
<h5>{values.nome_paciente}</h5>
<label className="control-label">Data da Consulta</label>
<h5>{moment(values.data).format('DD/MM/YYYY')}</h5>
<label className="control-label">Hora da Consulta</label>
<h5>{values.hora_inicio}</h5>
<label className="control-label">Relatório</label>
<div className="editor" onClick={()=>focusEditor} >
<Editor
className="editor"
editorState={editorState}
onChange={setEditorState}
ref={editor}
placeholder="Digite o relatório aqui!" />
</div>
</div>
<br />
<div className="btn btn-success btn-fill btn-wd" onClick={()=>putRelatorio(values.id,convertRelatorioToString())} >Enviar</div>
</div>
)
}
export default Relatorio
|
"""Send Slack message to gather information.
"""
import os
from typing import Dict, Any
import slack
DEFAULT_DOG_NAME = 'Rudi'
SLACK_TOKEN = os.environ['SLACK_API_TOKEN']
SLACK_CLIENT = slack.WebClient(
token=SLACK_TOKEN,
timeout=10,
)
USER_ID_TO_GATHER_INFORMATION_FROM = os.environ['USER_ID']
DOG_NAME = os.environ.get('DOG_NAME', DEFAULT_DOG_NAME)
def gather_information(event: Dict[str, Any], context: Dict[str, Any]) -> None:
"""Triggered from a message on a Cloud Pub/Sub topic."""
del event, context # unused arguments
print('Gathering information...')
SLACK_CLIENT.chat_postMessage(
channel=USER_ID_TO_GATHER_INFORMATION_FROM,
blocks=[
{
'type': 'section',
'text': {
'type': 'mrkdwn',
'text': f'Good Morning! :sunny:\nWill you bring {DOG_NAME} to work today?'
}
},
{
'type': 'actions',
'elements': [
{
'type': 'button',
'text': {
'type': 'plain_text',
'text': ':dog: Yes',
'emoji': True
},
'value': 'response_yes'
},
{
'type': 'button',
'text': {
'type': 'plain_text',
'text': ':no_entry_sign: No',
'emoji': True
},
'value': 'response_no'
}
]
}
]
)
print('Done!')
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.0.4
*/
(function( window, angular, undefined ){
"use strict";
/**
* Initialization function that validates environment
* requirements.
*/
angular
.module('material.core', [
'ngAnimate',
'material.core.animate',
'material.core.layout',
'material.core.gestures',
'material.core.theming'
])
.config(MdCoreConfigure)
.run(DetectNgTouch);
/**
* Detect if the ng-Touch module is also being used.
* Warn if detected.
*/
function DetectNgTouch($log, $injector) {
if ( $injector.has('$swipe') ) {
var msg = "" +
"You are using the ngTouch module. \n" +
"Angular Material already has mobile click, tap, and swipe support... \n" +
"ngTouch is not supported with Angular Material!";
$log.warn(msg);
}
}
DetectNgTouch.$inject = ["$log", "$injector"];
function MdCoreConfigure($provide, $mdThemingProvider) {
$provide.decorator('$$rAF', ["$delegate", rAFDecorator]);
$mdThemingProvider.theme('default')
.primaryPalette('indigo')
.accentPalette('pink')
.warnPalette('deep-orange')
.backgroundPalette('grey');
}
MdCoreConfigure.$inject = ["$provide", "$mdThemingProvider"];
function rAFDecorator($delegate) {
/**
* Use this to throttle events that come in often.
* The throttled function will always use the *last* invocation before the
* coming frame.
*
* For example, window resize events that fire many times a second:
* If we set to use an raf-throttled callback on window resize, then
* our callback will only be fired once per frame, with the last resize
* event that happened before that frame.
*
* @param {function} callback function to debounce
*/
$delegate.throttle = function(cb) {
var queuedArgs, alreadyQueued, queueCb, context;
return function debounced() {
queuedArgs = arguments;
context = this;
queueCb = cb;
if (!alreadyQueued) {
alreadyQueued = true;
$delegate(function() {
queueCb.apply(context, Array.prototype.slice.call(queuedArgs));
alreadyQueued = false;
});
}
};
};
return $delegate;
}
angular.module('material.core')
.directive('mdAutofocus', MdAutofocusDirective)
// Support the deprecated md-auto-focus and md-sidenav-focus as well
.directive('mdAutoFocus', MdAutofocusDirective)
.directive('mdSidenavFocus', MdAutofocusDirective);
/**
* @ngdoc directive
* @name mdAutofocus
* @module material.core.util
*
* @description
*
* `[md-autofocus]` provides an optional way to identify the focused element when a `$mdDialog`,
* `$mdBottomSheet`, or `$mdSidenav` opens or upon page load for input-like elements.
*
* When one of these opens, it will find the first nested element with the `[md-autofocus]`
* attribute directive and optional expression. An expression may be specified as the directive
* value to enable conditional activation of the autofocus.
*
* @usage
*
* ### Dialog
* <hljs lang="html">
* <md-dialog>
* <form>
* <md-input-container>
* <label for="testInput">Label</label>
* <input id="testInput" type="text" md-autofocus>
* </md-input-container>
* </form>
* </md-dialog>
* </hljs>
*
* ### Bottomsheet
* <hljs lang="html">
* <md-bottom-sheet class="md-list md-has-header">
* <md-subheader>Comment Actions</md-subheader>
* <md-list>
* <md-list-item ng-repeat="item in items">
*
* <md-button md-autofocus="$index == 2">
* <md-icon md-svg-src="{{item.icon}}"></md-icon>
* <span class="md-inline-list-icon-label">{{ item.name }}</span>
* </md-button>
*
* </md-list-item>
* </md-list>
* </md-bottom-sheet>
* </hljs>
*
* ### Autocomplete
* <hljs lang="html">
* <md-autocomplete
* md-autofocus
* md-selected-item="selectedItem"
* md-search-text="searchText"
* md-items="item in getMatches(searchText)"
* md-item-text="item.display">
* <span md-highlight-text="searchText">{{item.display}}</span>
* </md-autocomplete>
* </hljs>
*
* ### Sidenav
* <hljs lang="html">
* <div layout="row" ng-controller="MyController">
* <md-sidenav md-component-id="left" class="md-sidenav-left">
* Left Nav!
* </md-sidenav>
*
* <md-content>
* Center Content
* <md-button ng-click="openLeftMenu()">
* Open Left Menu
* </md-button>
* </md-content>
*
* <md-sidenav md-component-id="right"
* md-is-locked-open="$mdMedia('min-width: 333px')"
* class="md-sidenav-right">
* <form>
* <md-input-container>
* <label for="testInput">Test input</label>
* <input id="testInput" type="text"
* ng-model="data" md-autofocus>
* </md-input-container>
* </form>
* </md-sidenav>
* </div>
* </hljs>
**/
function MdAutofocusDirective() {
return {
restrict: 'A',
link: postLink
}
}
function postLink(scope, element, attrs) {
var attr = attrs.mdAutoFocus || attrs.mdAutofocus || attrs.mdSidenavFocus;
// Setup a watcher on the proper attribute to update a class we can check for in $mdUtil
scope.$watch(attr, function(canAutofocus) {
element.toggleClass('_md-autofocus', canAutofocus);
});
}
angular.module('material.core')
.factory('$mdConstant', MdConstantFactory);
/**
* Factory function that creates the grab-bag $mdConstant service.
* ngInject
*/
function MdConstantFactory($sniffer) {
var webkit = /webkit/i.test($sniffer.vendorPrefix);
function vendorProperty(name) {
return webkit ? ('webkit' + name.charAt(0).toUpperCase() + name.substring(1)) : name;
}
return {
KEY_CODE: {
COMMA: 188,
ENTER: 13,
ESCAPE: 27,
SPACE: 32,
PAGE_UP: 33,
PAGE_DOWN: 34,
END: 35,
HOME: 36,
LEFT_ARROW : 37,
UP_ARROW : 38,
RIGHT_ARROW : 39,
DOWN_ARROW : 40,
TAB : 9,
BACKSPACE: 8,
DELETE: 46
},
CSS: {
/* Constants */
TRANSITIONEND: 'transitionend' + (webkit ? ' webkitTransitionEnd' : ''),
ANIMATIONEND: 'animationend' + (webkit ? ' webkitAnimationEnd' : ''),
TRANSFORM: vendorProperty('transform'),
TRANSFORM_ORIGIN: vendorProperty('transformOrigin'),
TRANSITION: vendorProperty('transition'),
TRANSITION_DURATION: vendorProperty('transitionDuration'),
ANIMATION_PLAY_STATE: vendorProperty('animationPlayState'),
ANIMATION_DURATION: vendorProperty('animationDuration'),
ANIMATION_NAME: vendorProperty('animationName'),
ANIMATION_TIMING: vendorProperty('animationTimingFunction'),
ANIMATION_DIRECTION: vendorProperty('animationDirection')
},
/**
* As defined in core/style/variables.scss
*
* $layout-breakpoint-xs: 600px !default;
* $layout-breakpoint-sm: 960px !default;
* $layout-breakpoint-md: 1280px !default;
* $layout-breakpoint-lg: 1920px !default;
*
*/
MEDIA: {
'xs' : '(max-width: 599px)' ,
'gt-xs' : '(min-width: 600px)' ,
'sm' : '(min-width: 600px) and (max-width: 959px)' ,
'gt-sm' : '(min-width: 960px)' ,
'md' : '(min-width: 960px) and (max-width: 1279px)' ,
'gt-md' : '(min-width: 1280px)' ,
'lg' : '(min-width: 1280px) and (max-width: 1919px)',
'gt-lg' : '(min-width: 1920px)' ,
'xl' : '(min-width: 1920px)'
},
MEDIA_PRIORITY: [
'xl',
'gt-lg',
'lg',
'gt-md',
'md',
'gt-sm',
'sm',
'gt-xs',
'xs'
]
};
}
MdConstantFactory.$inject = ["$sniffer"];
angular
.module('material.core')
.config( ["$provide", function($provide){
$provide.decorator('$mdUtil', ['$delegate', function ($delegate){
/**
* Inject the iterator facade to easily support iteration and accessors
* @see iterator below
*/
$delegate.iterator = MdIterator;
return $delegate;
}
]);
}]);
/**
* iterator is a list facade to easily support iteration and accessors
*
* @param items Array list which this iterator will enumerate
* @param reloop Boolean enables iterator to consider the list as an endless reloop
*/
function MdIterator(items, reloop) {
var trueFn = function() { return true; };
if (items && !angular.isArray(items)) {
items = Array.prototype.slice.call(items);
}
reloop = !!reloop;
var _items = items || [ ];
// Published API
return {
items: getItems,
count: count,
inRange: inRange,
contains: contains,
indexOf: indexOf,
itemAt: itemAt,
findBy: findBy,
add: add,
remove: remove,
first: first,
last: last,
next: angular.bind(null, findSubsequentItem, false),
previous: angular.bind(null, findSubsequentItem, true),
hasPrevious: hasPrevious,
hasNext: hasNext
};
/**
* Publish copy of the enumerable set
* @returns {Array|*}
*/
function getItems() {
return [].concat(_items);
}
/**
* Determine length of the list
* @returns {Array.length|*|number}
*/
function count() {
return _items.length;
}
/**
* Is the index specified valid
* @param index
* @returns {Array.length|*|number|boolean}
*/
function inRange(index) {
return _items.length && ( index > -1 ) && (index < _items.length );
}
/**
* Can the iterator proceed to the next item in the list; relative to
* the specified item.
*
* @param item
* @returns {Array.length|*|number|boolean}
*/
function hasNext(item) {
return item ? inRange(indexOf(item) + 1) : false;
}
/**
* Can the iterator proceed to the previous item in the list; relative to
* the specified item.
*
* @param item
* @returns {Array.length|*|number|boolean}
*/
function hasPrevious(item) {
return item ? inRange(indexOf(item) - 1) : false;
}
/**
* Get item at specified index/position
* @param index
* @returns {*}
*/
function itemAt(index) {
return inRange(index) ? _items[index] : null;
}
/**
* Find all elements matching the key/value pair
* otherwise return null
*
* @param val
* @param key
*
* @return array
*/
function findBy(key, val) {
return _items.filter(function(item) {
return item[key] === val;
});
}
/**
* Add item to list
* @param item
* @param index
* @returns {*}
*/
function add(item, index) {
if ( !item ) return -1;
if (!angular.isNumber(index)) {
index = _items.length;
}
_items.splice(index, 0, item);
return indexOf(item);
}
/**
* Remove item from list...
* @param item
*/
function remove(item) {
if ( contains(item) ){
_items.splice(indexOf(item), 1);
}
}
/**
* Get the zero-based index of the target item
* @param item
* @returns {*}
*/
function indexOf(item) {
return _items.indexOf(item);
}
/**
* Boolean existence check
* @param item
* @returns {boolean}
*/
function contains(item) {
return item && (indexOf(item) > -1);
}
/**
* Return first item in the list
* @returns {*}
*/
function first() {
return _items.length ? _items[0] : null;
}
/**
* Return last item in the list...
* @returns {*}
*/
function last() {
return _items.length ? _items[_items.length - 1] : null;
}
/**
* Find the next item. If reloop is true and at the end of the list, it will go back to the
* first item. If given, the `validate` callback will be used to determine whether the next item
* is valid. If not valid, it will try to find the next item again.
*
* @param {boolean} backwards Specifies the direction of searching (forwards/backwards)
* @param {*} item The item whose subsequent item we are looking for
* @param {Function=} validate The `validate` function
* @param {integer=} limit The recursion limit
*
* @returns {*} The subsequent item or null
*/
function findSubsequentItem(backwards, item, validate, limit) {
validate = validate || trueFn;
var curIndex = indexOf(item);
while (true) {
if (!inRange(curIndex)) return null;
var nextIndex = curIndex + (backwards ? -1 : 1);
var foundItem = null;
if (inRange(nextIndex)) {
foundItem = _items[nextIndex];
} else if (reloop) {
foundItem = backwards ? last() : first();
nextIndex = indexOf(foundItem);
}
if ((foundItem === null) || (nextIndex === limit)) return null;
if (validate(foundItem)) return foundItem;
if (angular.isUndefined(limit)) limit = nextIndex;
curIndex = nextIndex;
}
}
}
angular.module('material.core')
.factory('$mdMedia', mdMediaFactory);
/**
* @ngdoc service
* @name $mdMedia
* @module material.core
*
* @description
* `$mdMedia` is used to evaluate whether a given media query is true or false given the
* current device's screen / window size. The media query will be re-evaluated on resize, allowing
* you to register a watch.
*
* `$mdMedia` also has pre-programmed support for media queries that match the layout breakpoints:
*
* <table class="md-api-table">
* <thead>
* <tr>
* <th>Breakpoint</th>
* <th>mediaQuery</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>xs</td>
* <td>(max-width: 599px)</td>
* </tr>
* <tr>
* <td>gt-xs</td>
* <td>(min-width: 600px)</td>
* </tr>
* <tr>
* <td>sm</td>
* <td>(min-width: 600px) and (max-width: 959px)</td>
* </tr>
* <tr>
* <td>gt-sm</td>
* <td>(min-width: 960px)</td>
* </tr>
* <tr>
* <td>md</td>
* <td>(min-width: 960px) and (max-width: 1279px)</td>
* </tr>
* <tr>
* <td>gt-md</td>
* <td>(min-width: 1280px)</td>
* </tr>
* <tr>
* <td>lg</td>
* <td>(min-width: 1280px) and (max-width: 1919px)</td>
* </tr>
* <tr>
* <td>gt-lg</td>
* <td>(min-width: 1920px)</td>
* </tr>
* <tr>
* <td>xl</td>
* <td>(min-width: 1920px)</td>
* </tr>
* </tbody>
* </table>
*
* See Material Design's <a href="https://www.google.com/design/spec/layout/adaptive-ui.html">Layout - Adaptive UI</a> for more details.
*
* <a href="https://www.google.com/design/spec/layout/adaptive-ui.html">
* <img src="https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0B8olV15J7abPSGFxemFiQVRtb1k/layout_adaptive_breakpoints_01.png" width="100%" height="100%"></img>
* </a>
*
* @returns {boolean} a boolean representing whether or not the given media query is true or false.
*
* @usage
* <hljs lang="js">
* app.controller('MyController', function($mdMedia, $scope) {
* $scope.$watch(function() { return $mdMedia('lg'); }, function(big) {
* $scope.bigScreen = big;
* });
*
* $scope.screenIsSmall = $mdMedia('sm');
* $scope.customQuery = $mdMedia('(min-width: 1234px)');
* $scope.anotherCustom = $mdMedia('max-width: 300px');
* });
* </hljs>
*/
function mdMediaFactory($mdConstant, $rootScope, $window) {
var queries = {};
var mqls = {};
var results = {};
var normalizeCache = {};
$mdMedia.getResponsiveAttribute = getResponsiveAttribute;
$mdMedia.getQuery = getQuery;
$mdMedia.watchResponsiveAttributes = watchResponsiveAttributes;
return $mdMedia;
function $mdMedia(query) {
var validated = queries[query];
if (angular.isUndefined(validated)) {
validated = queries[query] = validate(query);
}
var result = results[validated];
if (angular.isUndefined(result)) {
result = add(validated);
}
return result;
}
function validate(query) {
return $mdConstant.MEDIA[query] ||
((query.charAt(0) !== '(') ? ('(' + query + ')') : query);
}
function add(query) {
var result = mqls[query];
if ( !result ) {
result = mqls[query] = $window.matchMedia(query);
}
result.addListener(onQueryChange);
return (results[result.media] = !!result.matches);
}
function onQueryChange(query) {
$rootScope.$evalAsync(function() {
results[query.media] = !!query.matches;
});
}
function getQuery(name) {
return mqls[name];
}
function getResponsiveAttribute(attrs, attrName) {
for (var i = 0; i < $mdConstant.MEDIA_PRIORITY.length; i++) {
var mediaName = $mdConstant.MEDIA_PRIORITY[i];
if (!mqls[queries[mediaName]].matches) {
continue;
}
var normalizedName = getNormalizedName(attrs, attrName + '-' + mediaName);
if (attrs[normalizedName]) {
return attrs[normalizedName];
}
}
// fallback on unprefixed
return attrs[getNormalizedName(attrs, attrName)];
}
function watchResponsiveAttributes(attrNames, attrs, watchFn) {
var unwatchFns = [];
attrNames.forEach(function(attrName) {
var normalizedName = getNormalizedName(attrs, attrName);
if (angular.isDefined(attrs[normalizedName])) {
unwatchFns.push(
attrs.$observe(normalizedName, angular.bind(void 0, watchFn, null)));
}
for (var mediaName in $mdConstant.MEDIA) {
normalizedName = getNormalizedName(attrs, attrName + '-' + mediaName);
if (angular.isDefined(attrs[normalizedName])) {
unwatchFns.push(
attrs.$observe(normalizedName, angular.bind(void 0, watchFn, mediaName)));
}
}
});
return function unwatch() {
unwatchFns.forEach(function(fn) { fn(); })
};
}
// Improves performance dramatically
function getNormalizedName(attrs, attrName) {
return normalizeCache[attrName] ||
(normalizeCache[attrName] = attrs.$normalize(attrName));
}
}
mdMediaFactory.$inject = ["$mdConstant", "$rootScope", "$window"];
/*
* This var has to be outside the angular factory, otherwise when
* there are multiple material apps on the same page, each app
* will create its own instance of this array and the app's IDs
* will not be unique.
*/
var nextUniqueId = 0;
/**
* @ngdoc module
* @name material.core.util
* @description
* Util
*/
angular
.module('material.core')
.factory('$mdUtil', UtilFactory);
function UtilFactory($document, $timeout, $compile, $rootScope, $$mdAnimate, $interpolate, $log, $rootElement, $window) {
// Setup some core variables for the processTemplate method
var startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
usesStandardSymbols = ((startSymbol === '{{') && (endSymbol === '}}'));
/**
* Checks if the target element has the requested style by key
* @param {DOMElement|JQLite} target Target element
* @param {string} key Style key
* @param {string=} expectedVal Optional expected value
* @returns {boolean} Whether the target element has the style or not
*/
var hasComputedStyle = function (target, key, expectedVal) {
var hasValue = false;
if ( target && target.length ) {
var computedStyles = $window.getComputedStyle(target[0]);
hasValue = angular.isDefined(computedStyles[key]) && (expectedVal ? computedStyles[key] == expectedVal : true);
}
return hasValue;
};
var $mdUtil = {
dom: {},
now: window.performance ?
angular.bind(window.performance, window.performance.now) : Date.now || function() {
return new Date().getTime();
},
clientRect: function(element, offsetParent, isOffsetRect) {
var node = getNode(element);
offsetParent = getNode(offsetParent || node.offsetParent || document.body);
var nodeRect = node.getBoundingClientRect();
// The user can ask for an offsetRect: a rect relative to the offsetParent,
// or a clientRect: a rect relative to the page
var offsetRect = isOffsetRect ?
offsetParent.getBoundingClientRect() :
{left: 0, top: 0, width: 0, height: 0};
return {
left: nodeRect.left - offsetRect.left,
top: nodeRect.top - offsetRect.top,
width: nodeRect.width,
height: nodeRect.height
};
},
offsetRect: function(element, offsetParent) {
return $mdUtil.clientRect(element, offsetParent, true);
},
// Annoying method to copy nodes to an array, thanks to IE
nodesToArray: function(nodes) {
nodes = nodes || [];
var results = [];
for (var i = 0; i < nodes.length; ++i) {
results.push(nodes.item(i));
}
return results;
},
/**
* Calculate the positive scroll offset
* TODO: Check with pinch-zoom in IE/Chrome;
* https://code.google.com/p/chromium/issues/detail?id=496285
*/
scrollTop: function(element) {
element = angular.element(element || $document[0].body);
var body = (element[0] == $document[0].body) ? $document[0].body : undefined;
var scrollTop = body ? body.scrollTop + body.parentElement.scrollTop : 0;
// Calculate the positive scroll offset
return scrollTop || Math.abs(element[0].getBoundingClientRect().top);
},
/**
* Finds the proper focus target by searching the DOM.
*
* @param containerEl
* @param attributeVal
* @returns {*}
*/
findFocusTarget: function(containerEl, attributeVal) {
var AUTO_FOCUS = '[md-autofocus]';
var elToFocus;
elToFocus = scanForFocusable(containerEl, attributeVal || AUTO_FOCUS);
if ( !elToFocus && attributeVal != AUTO_FOCUS) {
// Scan for deprecated attribute
elToFocus = scanForFocusable(containerEl, '[md-auto-focus]');
if ( !elToFocus ) {
// Scan for fallback to 'universal' API
elToFocus = scanForFocusable(containerEl, AUTO_FOCUS);
}
}
return elToFocus;
/**
* Can target and nested children for specified Selector (attribute)
* whose value may be an expression that evaluates to True/False.
*/
function scanForFocusable(target, selector) {
var elFound, items = target[0].querySelectorAll(selector);
// Find the last child element with the focus attribute
if ( items && items.length ){
items.length && angular.forEach(items, function(it) {
it = angular.element(it);
// Check the element for the _md-autofocus class to ensure any associated expression
// evaluated to true.
var isFocusable = it.hasClass('_md-autofocus');
if (isFocusable) elFound = it;
});
}
return elFound;
}
},
// Disables scroll around the passed element.
disableScrollAround: function(element, parent) {
$mdUtil.disableScrollAround._count = $mdUtil.disableScrollAround._count || 0;
++$mdUtil.disableScrollAround._count;
if ($mdUtil.disableScrollAround._enableScrolling) return $mdUtil.disableScrollAround._enableScrolling;
element = angular.element(element);
var body = $document[0].body,
restoreBody = disableBodyScroll(),
restoreElement = disableElementScroll(parent);
return $mdUtil.disableScrollAround._enableScrolling = function() {
if (!--$mdUtil.disableScrollAround._count) {
restoreBody();
restoreElement();
delete $mdUtil.disableScrollAround._enableScrolling;
}
};
// Creates a virtual scrolling mask to absorb touchmove, keyboard, scrollbar clicking, and wheel events
function disableElementScroll(element) {
element = angular.element(element || body)[0];
var zIndex = 50;
var scrollMask = angular.element(
'<div class="md-scroll-mask">' +
' <div class="md-scroll-mask-bar"></div>' +
'</div>').css('z-index', zIndex);
element.appendChild(scrollMask[0]);
scrollMask.on('wheel', preventDefault);
scrollMask.on('touchmove', preventDefault);
$document.on('keydown', disableKeyNav);
return function restoreScroll() {
scrollMask.off('wheel');
scrollMask.off('touchmove');
scrollMask[0].parentNode.removeChild(scrollMask[0]);
$document.off('keydown', disableKeyNav);
delete $mdUtil.disableScrollAround._enableScrolling;
};
// Prevent keypresses from elements inside the body
// used to stop the keypresses that could cause the page to scroll
// (arrow keys, spacebar, tab, etc).
function disableKeyNav(e) {
//-- temporarily removed this logic, will possibly re-add at a later date
//if (!element[0].contains(e.target)) {
// e.preventDefault();
// e.stopImmediatePropagation();
//}
}
function preventDefault(e) {
e.preventDefault();
}
}
// Converts the body to a position fixed block and translate it to the proper scroll
// position
function disableBodyScroll() {
var htmlNode = body.parentNode;
var restoreHtmlStyle = htmlNode.style.cssText || '';
var restoreBodyStyle = body.style.cssText || '';
var scrollOffset = $mdUtil.scrollTop(body);
var clientWidth = body.clientWidth;
if (body.scrollHeight > body.clientHeight + 1) {
applyStyles(body, {
position: 'fixed',
width: '100%',
top: -scrollOffset + 'px'
});
applyStyles(htmlNode, {
overflowY: 'scroll'
});
}
if (body.clientWidth < clientWidth) applyStyles(body, {overflow: 'hidden'});
return function restoreScroll() {
body.style.cssText = restoreBodyStyle;
htmlNode.style.cssText = restoreHtmlStyle;
body.scrollTop = scrollOffset;
htmlNode.scrollTop = scrollOffset;
};
}
function applyStyles(el, styles) {
for (var key in styles) {
el.style[key] = styles[key];
}
}
},
enableScrolling: function() {
var method = this.disableScrollAround._enableScrolling;
method && method();
},
floatingScrollbars: function() {
if (this.floatingScrollbars.cached === undefined) {
var tempNode = angular.element('<div><div></div></div>').css({
width: '100%',
'z-index': -1,
position: 'absolute',
height: '35px',
'overflow-y': 'scroll'
});
tempNode.children().css('height', '60px');
$document[0].body.appendChild(tempNode[0]);
this.floatingScrollbars.cached = (tempNode[0].offsetWidth == tempNode[0].childNodes[0].offsetWidth);
tempNode.remove();
}
return this.floatingScrollbars.cached;
},
// Mobile safari only allows you to set focus in click event listeners...
forceFocus: function(element) {
var node = element[0] || element;
document.addEventListener('click', function focusOnClick(ev) {
if (ev.target === node && ev.$focus) {
node.focus();
ev.stopImmediatePropagation();
ev.preventDefault();
node.removeEventListener('click', focusOnClick);
}
}, true);
var newEvent = document.createEvent('MouseEvents');
newEvent.initMouseEvent('click', false, true, window, {}, 0, 0, 0, 0,
false, false, false, false, 0, null);
newEvent.$material = true;
newEvent.$focus = true;
node.dispatchEvent(newEvent);
},
/**
* facade to build md-backdrop element with desired styles
* NOTE: Use $compile to trigger backdrop postLink function
*/
createBackdrop: function(scope, addClass) {
return $compile($mdUtil.supplant('<md-backdrop class="{0}">', [addClass]))(scope);
},
/**
* supplant() method from Crockford's `Remedial Javascript`
* Equivalent to use of $interpolate; without dependency on
* interpolation symbols and scope. Note: the '{<token>}' can
* be property names, property chains, or array indices.
*/
supplant: function(template, values, pattern) {
pattern = pattern || /\{([^\{\}]*)\}/g;
return template.replace(pattern, function(a, b) {
var p = b.split('.'),
r = values;
try {
for (var s in p) {
if (p.hasOwnProperty(s) ) {
r = r[p[s]];
}
}
} catch (e) {
r = a;
}
return (typeof r === 'string' || typeof r === 'number') ? r : a;
});
},
fakeNgModel: function() {
return {
$fake: true,
$setTouched: angular.noop,
$setViewValue: function(value) {
this.$viewValue = value;
this.$render(value);
this.$viewChangeListeners.forEach(function(cb) {
cb();
});
},
$isEmpty: function(value) {
return ('' + value).length === 0;
},
$parsers: [],
$formatters: [],
$viewChangeListeners: [],
$render: angular.noop
};
},
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds.
// @param wait Integer value of msecs to delay (since last debounce reset); default value 10 msecs
// @param invokeApply should the $timeout trigger $digest() dirty checking
debounce: function(func, wait, scope, invokeApply) {
var timer;
return function debounced() {
var context = scope,
args = Array.prototype.slice.call(arguments);
$timeout.cancel(timer);
timer = $timeout(function() {
timer = undefined;
func.apply(context, args);
}, wait || 10, invokeApply);
};
},
// Returns a function that can only be triggered every `delay` milliseconds.
// In other words, the function will not be called unless it has been more
// than `delay` milliseconds since the last call.
throttle: function throttle(func, delay) {
var recent;
return function throttled() {
var context = this;
var args = arguments;
var now = $mdUtil.now();
if (!recent || (now - recent > delay)) {
func.apply(context, args);
recent = now;
}
};
},
/**
* Measures the number of milliseconds taken to run the provided callback
* function. Uses a high-precision timer if available.
*/
time: function time(cb) {
var start = $mdUtil.now();
cb();
return $mdUtil.now() - start;
},
/**
* Create an implicit getter that caches its `getter()`
* lookup value
*/
valueOnUse : function (scope, key, getter) {
var value = null, args = Array.prototype.slice.call(arguments);
var params = (args.length > 3) ? args.slice(3) : [ ];
Object.defineProperty(scope, key, {
get: function () {
if (value === null) value = getter.apply(scope, params);
return value;
}
});
},
/**
* Get a unique ID.
*
* @returns {string} an unique numeric string
*/
nextUid: function() {
return '' + nextUniqueId++;
},
// Stop watchers and events from firing on a scope without destroying it,
// by disconnecting it from its parent and its siblings' linked lists.
disconnectScope: function disconnectScope(scope) {
if (!scope) return;
// we can't destroy the root scope or a scope that has been already destroyed
if (scope.$root === scope) return;
if (scope.$$destroyed) return;
var parent = scope.$parent;
scope.$$disconnected = true;
// See Scope.$destroy
if (parent.$$childHead === scope) parent.$$childHead = scope.$$nextSibling;
if (parent.$$childTail === scope) parent.$$childTail = scope.$$prevSibling;
if (scope.$$prevSibling) scope.$$prevSibling.$$nextSibling = scope.$$nextSibling;
if (scope.$$nextSibling) scope.$$nextSibling.$$prevSibling = scope.$$prevSibling;
scope.$$nextSibling = scope.$$prevSibling = null;
},
// Undo the effects of disconnectScope above.
reconnectScope: function reconnectScope(scope) {
if (!scope) return;
// we can't disconnect the root node or scope already disconnected
if (scope.$root === scope) return;
if (!scope.$$disconnected) return;
var child = scope;
var parent = child.$parent;
child.$$disconnected = false;
// See Scope.$new for this logic...
child.$$prevSibling = parent.$$childTail;
if (parent.$$childHead) {
parent.$$childTail.$$nextSibling = child;
parent.$$childTail = child;
} else {
parent.$$childHead = parent.$$childTail = child;
}
},
/*
* getClosest replicates jQuery.closest() to walk up the DOM tree until it finds a matching nodeName
*
* @param el Element to start walking the DOM from
* @param tagName Tag name to find closest to el, such as 'form'
* @param onlyParent Only start checking from the parent element, not `el`.
*/
getClosest: function getClosest(el, tagName, onlyParent) {
if (el instanceof angular.element) el = el[0];
tagName = tagName.toUpperCase();
if (onlyParent) el = el.parentNode;
if (!el) return null;
do {
if (el.nodeName === tagName) {
return el;
}
} while (el = el.parentNode);
return null;
},
/**
* Build polyfill for the Node.contains feature (if needed)
*/
elementContains: function(node, child) {
var hasContains = (window.Node && window.Node.prototype && Node.prototype.contains);
var findFn = hasContains ? angular.bind(node, node.contains) : angular.bind(node, function(arg) {
// compares the positions of two nodes and returns a bitmask
return (node === child) || !!(this.compareDocumentPosition(arg) & 16)
});
return findFn(child);
},
/**
* Functional equivalent for $element.filter(‘md-bottom-sheet’)
* useful with interimElements where the element and its container are important...
*
* @param {[]} elements to scan
* @param {string} name of node to find (e.g. 'md-dialog')
* @param {boolean=} optional flag to allow deep scans; defaults to 'false'.
* @param {boolean=} optional flag to enable log warnings; defaults to false
*/
extractElementByName: function(element, nodeName, scanDeep, warnNotFound) {
var found = scanTree(element);
if (!found && !!warnNotFound) {
$log.warn( $mdUtil.supplant("Unable to find node '{0}' in element '{1}'.",[nodeName, element[0].outerHTML]) );
}
return angular.element(found || element);
/**
* Breadth-First tree scan for element with matching `nodeName`
*/
function scanTree(element) {
return scanLevel(element) || (!!scanDeep ? scanChildren(element) : null);
}
/**
* Case-insensitive scan of current elements only (do not descend).
*/
function scanLevel(element) {
if ( element ) {
for (var i = 0, len = element.length; i < len; i++) {
if (element[i].nodeName.toLowerCase() === nodeName) {
return element[i];
}
}
}
return null;
}
/**
* Scan children of specified node
*/
function scanChildren(element) {
var found;
if ( element ) {
for (var i = 0, len = element.length; i < len; i++) {
var target = element[i];
if ( !found ) {
for (var j = 0, numChild = target.childNodes.length; j < numChild; j++) {
found = found || scanTree([target.childNodes[j]]);
}
}
}
}
return found;
}
},
/**
* Give optional properties with no value a boolean true if attr provided or false otherwise
*/
initOptionalProperties: function(scope, attr, defaults) {
defaults = defaults || {};
angular.forEach(scope.$$isolateBindings, function(binding, key) {
if (binding.optional && angular.isUndefined(scope[key])) {
var attrIsDefined = angular.isDefined(attr[binding.attrName]);
scope[key] = angular.isDefined(defaults[key]) ? defaults[key] : attrIsDefined;
}
});
},
/**
* Alternative to $timeout calls with 0 delay.
* nextTick() coalesces all calls within a single frame
* to minimize $digest thrashing
*
* @param callback
* @param digest
* @returns {*}
*/
nextTick: function(callback, digest, scope) {
//-- grab function reference for storing state details
var nextTick = $mdUtil.nextTick;
var timeout = nextTick.timeout;
var queue = nextTick.queue || [];
//-- add callback to the queue
queue.push(callback);
//-- set default value for digest
if (digest == null) digest = true;
//-- store updated digest/queue values
nextTick.digest = nextTick.digest || digest;
nextTick.queue = queue;
//-- either return existing timeout or create a new one
return timeout || (nextTick.timeout = $timeout(processQueue, 0, false));
/**
* Grab a copy of the current queue
* Clear the queue for future use
* Process the existing queue
* Trigger digest if necessary
*/
function processQueue() {
var skip = scope && scope.$$destroyed;
var queue = !skip ? nextTick.queue : [];
var digest = !skip ? nextTick.digest : null;
nextTick.queue = [];
nextTick.timeout = null;
nextTick.digest = false;
queue.forEach(function(callback) {
callback();
});
if (digest) $rootScope.$digest();
}
},
/**
* Processes a template and replaces the start/end symbols if the application has
* overriden them.
*
* @param template The template to process whose start/end tags may be replaced.
* @returns {*}
*/
processTemplate: function(template) {
if (usesStandardSymbols) {
return template;
} else {
if (!template || !angular.isString(template)) return template;
return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
}
},
/**
* Scan up dom hierarchy for enabled parent;
*/
getParentWithPointerEvents: function (element) {
var parent = element.parent();
// jqLite might return a non-null, but still empty, parent; so check for parent and length
while (hasComputedStyle(parent, 'pointer-events', 'none')) {
parent = parent.parent();
}
return parent;
},
getNearestContentElement: function (element) {
var current = element.parent()[0];
// Look for the nearest parent md-content, stopping at the rootElement.
while (current && current !== $rootElement[0] && current !== document.body && current.nodeName.toUpperCase() !== 'MD-CONTENT') {
current = current.parentNode;
}
return current;
},
hasComputedStyle: hasComputedStyle
};
// Instantiate other namespace utility methods
$mdUtil.dom.animator = $$mdAnimate($mdUtil);
return $mdUtil;
function getNode(el) {
return el[0] || el;
}
}
UtilFactory.$inject = ["$document", "$timeout", "$compile", "$rootScope", "$$mdAnimate", "$interpolate", "$log", "$rootElement", "$window"];
/*
* Since removing jQuery from the demos, some code that uses `element.focus()` is broken.
* We need to add `element.focus()`, because it's testable unlike `element[0].focus`.
*/
angular.element.prototype.focus = angular.element.prototype.focus || function() {
if (this.length) {
this[0].focus();
}
return this;
};
angular.element.prototype.blur = angular.element.prototype.blur || function() {
if (this.length) {
this[0].blur();
}
return this;
};
angular.module('material.core')
.service('$mdAria', AriaService);
/*
* ngInject
*/
function AriaService($$rAF, $log, $window, $interpolate) {
return {
expect: expect,
expectAsync: expectAsync,
expectWithText: expectWithText
};
/**
* Check if expected attribute has been specified on the target element or child
* @param element
* @param attrName
* @param {optional} defaultValue What to set the attr to if no value is found
*/
function expect(element, attrName, defaultValue) {
var node = angular.element(element)[0] || element;
// if node exists and neither it nor its children have the attribute
if (node &&
((!node.hasAttribute(attrName) ||
node.getAttribute(attrName).length === 0) &&
!childHasAttribute(node, attrName))) {
defaultValue = angular.isString(defaultValue) ? defaultValue.trim() : '';
if (defaultValue.length) {
element.attr(attrName, defaultValue);
} else {
$log.warn('ARIA: Attribute "', attrName, '", required for accessibility, is missing on node:', node);
}
}
}
function expectAsync(element, attrName, defaultValueGetter) {
// Problem: when retrieving the element's contents synchronously to find the label,
// the text may not be defined yet in the case of a binding.
// There is a higher chance that a binding will be defined if we wait one frame.
$$rAF(function() {
expect(element, attrName, defaultValueGetter());
});
}
function expectWithText(element, attrName) {
var content = getText(element) || "";
var hasBinding = content.indexOf($interpolate.startSymbol())>-1;
if ( hasBinding ) {
expectAsync(element, attrName, function() {
return getText(element);
});
} else {
expect(element, attrName, content);
}
}
function getText(element) {
return (element.text() || "").trim();
}
function childHasAttribute(node, attrName) {
var hasChildren = node.hasChildNodes(),
hasAttr = false;
function isHidden(el) {
var style = el.currentStyle ? el.currentStyle : $window.getComputedStyle(el);
return (style.display === 'none');
}
if(hasChildren) {
var children = node.childNodes;
for(var i=0; i<children.length; i++){
var child = children[i];
if(child.nodeType === 1 && child.hasAttribute(attrName)) {
if(!isHidden(child)){
hasAttr = true;
}
}
}
}
return hasAttr;
}
}
AriaService.$inject = ["$$rAF", "$log", "$window", "$interpolate"];
angular
.module('material.core')
.service('$mdCompiler', mdCompilerService);
function mdCompilerService($q, $http, $injector, $compile, $controller, $templateCache) {
/* jshint validthis: true */
/*
* @ngdoc service
* @name $mdCompiler
* @module material.core
* @description
* The $mdCompiler service is an abstraction of angular's compiler, that allows the developer
* to easily compile an element with a templateUrl, controller, and locals.
*
* @usage
* <hljs lang="js">
* $mdCompiler.compile({
* templateUrl: 'modal.html',
* controller: 'ModalCtrl',
* locals: {
* modal: myModalInstance;
* }
* }).then(function(compileData) {
* compileData.element; // modal.html's template in an element
* compileData.link(myScope); //attach controller & scope to element
* });
* </hljs>
*/
/*
* @ngdoc method
* @name $mdCompiler#compile
* @description A helper to compile an HTML template/templateUrl with a given controller,
* locals, and scope.
* @param {object} options An options object, with the following properties:
*
* - `controller` - `{(string=|function()=}` Controller fn that should be associated with
* newly created scope or the name of a registered controller if passed as a string.
* - `controllerAs` - `{string=}` A controller alias name. If present the controller will be
* published to scope under the `controllerAs` name.
* - `template` - `{string=}` An html template as a string.
* - `templateUrl` - `{string=}` A path to an html template.
* - `transformTemplate` - `{function(template)=}` A function which transforms the template after
* it is loaded. It will be given the template string as a parameter, and should
* return a a new string representing the transformed template.
* - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
* be injected into the controller. If any of these dependencies are promises, the compiler
* will wait for them all to be resolved, or if one is rejected before the controller is
* instantiated `compile()` will fail..
* * `key` - `{string}`: a name of a dependency to be injected into the controller.
* * `factory` - `{string|function}`: If `string` then it is an alias for a service.
* Otherwise if function, then it is injected and the return value is treated as the
* dependency. If the result is a promise, it is resolved before its value is
* injected into the controller.
*
* @returns {object=} promise A promise, which will be resolved with a `compileData` object.
* `compileData` has the following properties:
*
* - `element` - `{element}`: an uncompiled element matching the provided template.
* - `link` - `{function(scope)}`: A link function, which, when called, will compile
* the element and instantiate the provided controller (if given).
* - `locals` - `{object}`: The locals which will be passed into the controller once `link` is
* called. If `bindToController` is true, they will be coppied to the ctrl instead
* - `bindToController` - `bool`: bind the locals to the controller, instead of passing them in.
*/
this.compile = function(options) {
var templateUrl = options.templateUrl;
var template = options.template || '';
var controller = options.controller;
var controllerAs = options.controllerAs;
var resolve = angular.extend({}, options.resolve || {});
var locals = angular.extend({}, options.locals || {});
var transformTemplate = options.transformTemplate || angular.identity;
var bindToController = options.bindToController;
// Take resolve values and invoke them.
// Resolves can either be a string (value: 'MyRegisteredAngularConst'),
// or an invokable 'factory' of sorts: (value: function ValueGetter($dependency) {})
angular.forEach(resolve, function(value, key) {
if (angular.isString(value)) {
resolve[key] = $injector.get(value);
} else {
resolve[key] = $injector.invoke(value);
}
});
//Add the locals, which are just straight values to inject
//eg locals: { three: 3 }, will inject three into the controller
angular.extend(resolve, locals);
if (templateUrl) {
resolve.$template = $http.get(templateUrl, {cache: $templateCache})
.then(function(response) {
return response.data;
});
} else {
resolve.$template = $q.when(template);
}
// Wait for all the resolves to finish if they are promises
return $q.all(resolve).then(function(locals) {
var compiledData;
var template = transformTemplate(locals.$template, options);
var element = options.element || angular.element('<div>').html(template.trim()).contents();
var linkFn = $compile(element);
// Return a linking function that can be used later when the element is ready
return compiledData = {
locals: locals,
element: element,
link: function link(scope) {
locals.$scope = scope;
//Instantiate controller if it exists, because we have scope
if (controller) {
var invokeCtrl = $controller(controller, locals, true);
if (bindToController) {
angular.extend(invokeCtrl.instance, locals);
}
var ctrl = invokeCtrl();
//See angular-route source for this logic
element.data('$ngControllerController', ctrl);
element.children().data('$ngControllerController', ctrl);
if (controllerAs) {
scope[controllerAs] = ctrl;
}
// Publish reference to this controller
compiledData.controller = ctrl;
}
return linkFn(scope);
}
};
});
};
}
mdCompilerService.$inject = ["$q", "$http", "$injector", "$compile", "$controller", "$templateCache"];
var HANDLERS = {};
/* The state of the current 'pointer'
* The pointer represents the state of the current touch.
* It contains normalized x and y coordinates from DOM events,
* as well as other information abstracted from the DOM.
*/
var pointer, lastPointer, forceSkipClickHijack = false;
/**
* The position of the most recent click if that click was on a label element.
* @type {{x: number, y: number}?}
*/
var lastLabelClickPos = null;
// Used to attach event listeners once when multiple ng-apps are running.
var isInitialized = false;
angular
.module('material.core.gestures', [ ])
.provider('$mdGesture', MdGestureProvider)
.factory('$$MdGestureHandler', MdGestureHandler)
.run( attachToDocument );
/**
* @ngdoc service
* @name $mdGestureProvider
* @module material.core.gestures
*
* @description
* In some scenarios on Mobile devices (without jQuery), the click events should NOT be hijacked.
* `$mdGestureProvider` is used to configure the Gesture module to ignore or skip click hijacking on mobile
* devices.
*
* <hljs lang="js">
* app.config(function($mdGestureProvider) {
*
* // For mobile devices without jQuery loaded, do not
* // intercept click events during the capture phase.
* $mdGestureProvider.skipClickHijack();
*
* });
* </hljs>
*
*/
function MdGestureProvider() { }
MdGestureProvider.prototype = {
// Publish access to setter to configure a variable BEFORE the
// $mdGesture service is instantiated...
skipClickHijack: function() {
return forceSkipClickHijack = true;
},
/**
* $get is used to build an instance of $mdGesture
* ngInject
*/
$get : ["$$MdGestureHandler", "$$rAF", "$timeout", function($$MdGestureHandler, $$rAF, $timeout) {
return new MdGesture($$MdGestureHandler, $$rAF, $timeout);
}]
};
/**
* MdGesture factory construction function
* ngInject
*/
function MdGesture($$MdGestureHandler, $$rAF, $timeout) {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
var isIos = userAgent.match(/ipad|iphone|ipod/i);
var isAndroid = userAgent.match(/android/i);
var hasJQuery = (typeof window.jQuery !== 'undefined') && (angular.element === window.jQuery);
var self = {
handler: addHandler,
register: register,
// On mobile w/out jQuery, we normally intercept clicks. Should we skip that?
isHijackingClicks: (isIos || isAndroid) && !hasJQuery && !forceSkipClickHijack
};
if (self.isHijackingClicks) {
var maxClickDistance = 6;
self.handler('click', {
options: {
maxDistance: maxClickDistance
},
onEnd: checkDistanceAndEmit('click')
});
self.handler('focus', {
options: {
maxDistance: maxClickDistance
},
onEnd: function(ev, pointer) {
if (pointer.distance < this.state.options.maxDistance) {
if (canFocus(ev.target)) {
this.dispatchEvent(ev, 'focus', pointer);
ev.target.focus();
}
}
function canFocus(element) {
var focusableElements = ['INPUT', 'SELECT', 'BUTTON', 'TEXTAREA', 'VIDEO', 'AUDIO'];
return (element.getAttribute('tabindex') != '-1') &&
!element.hasAttribute('DISABLED') &&
(element.hasAttribute('tabindex') || element.hasAttribute('href') ||
(focusableElements.indexOf(element.nodeName) != -1));
}
}
});
self.handler('mouseup', {
options: {
maxDistance: maxClickDistance
},
onEnd: checkDistanceAndEmit('mouseup')
});
self.handler('mousedown', {
onStart: function(ev) {
this.dispatchEvent(ev, 'mousedown');
}
});
}
function checkDistanceAndEmit(eventName) {
return function(ev, pointer) {
if (pointer.distance < this.state.options.maxDistance) {
this.dispatchEvent(ev, eventName, pointer);
}
};
}
/*
* Register an element to listen for a handler.
* This allows an element to override the default options for a handler.
* Additionally, some handlers like drag and hold only dispatch events if
* the domEvent happens inside an element that's registered to listen for these events.
*
* @see GestureHandler for how overriding of default options works.
* @example $mdGesture.register(myElement, 'drag', { minDistance: 20, horziontal: false })
*/
function register(element, handlerName, options) {
var handler = HANDLERS[handlerName.replace(/^\$md./, '')];
if (!handler) {
throw new Error('Failed to register element with handler ' + handlerName + '. ' +
'Available handlers: ' + Object.keys(HANDLERS).join(', '));
}
return handler.registerElement(element, options);
}
/*
* add a handler to $mdGesture. see below.
*/
function addHandler(name, definition) {
var handler = new $$MdGestureHandler(name);
angular.extend(handler, definition);
HANDLERS[name] = handler;
return self;
}
/*
* Register handlers. These listen to touch/start/move events, interpret them,
* and dispatch gesture events depending on options & conditions. These are all
* instances of GestureHandler.
* @see GestureHandler
*/
return self
/*
* The press handler dispatches an event on touchdown/touchend.
* It's a simple abstraction of touch/mouse/pointer start and end.
*/
.handler('press', {
onStart: function (ev, pointer) {
this.dispatchEvent(ev, '$md.pressdown');
},
onEnd: function (ev, pointer) {
this.dispatchEvent(ev, '$md.pressup');
}
})
/*
* The hold handler dispatches an event if the user keeps their finger within
* the same <maxDistance> area for <delay> ms.
* The hold handler will only run if a parent of the touch target is registered
* to listen for hold events through $mdGesture.register()
*/
.handler('hold', {
options: {
maxDistance: 6,
delay: 500
},
onCancel: function () {
$timeout.cancel(this.state.timeout);
},
onStart: function (ev, pointer) {
// For hold, require a parent to be registered with $mdGesture.register()
// Because we prevent scroll events, this is necessary.
if (!this.state.registeredParent) return this.cancel();
this.state.pos = {x: pointer.x, y: pointer.y};
this.state.timeout = $timeout(angular.bind(this, function holdDelayFn() {
this.dispatchEvent(ev, '$md.hold');
this.cancel(); //we're done!
}), this.state.options.delay, false);
},
onMove: function (ev, pointer) {
// Don't scroll while waiting for hold.
// If we don't preventDefault touchmove events here, Android will assume we don't
// want to listen to anymore touch events. It will start scrolling and stop sending
// touchmove events.
ev.preventDefault();
// If the user moves greater than <maxDistance> pixels, stop the hold timer
// set in onStart
var dx = this.state.pos.x - pointer.x;
var dy = this.state.pos.y - pointer.y;
if (Math.sqrt(dx * dx + dy * dy) > this.options.maxDistance) {
this.cancel();
}
},
onEnd: function () {
this.onCancel();
}
})
/*
* The drag handler dispatches a drag event if the user holds and moves his finger greater than
* <minDistance> px in the x or y direction, depending on options.horizontal.
* The drag will be cancelled if the user moves his finger greater than <minDistance>*<cancelMultiplier> in
* the perpindicular direction. Eg if the drag is horizontal and the user moves his finger <minDistance>*<cancelMultiplier>
* pixels vertically, this handler won't consider the move part of a drag.
*/
.handler('drag', {
options: {
minDistance: 6,
horizontal: true,
cancelMultiplier: 1.5
},
onStart: function (ev) {
// For drag, require a parent to be registered with $mdGesture.register()
if (!this.state.registeredParent) this.cancel();
},
onMove: function (ev, pointer) {
var shouldStartDrag, shouldCancel;
// Don't scroll while deciding if this touchmove qualifies as a drag event.
// If we don't preventDefault touchmove events here, Android will assume we don't
// want to listen to anymore touch events. It will start scrolling and stop sending
// touchmove events.
ev.preventDefault();
if (!this.state.dragPointer) {
if (this.state.options.horizontal) {
shouldStartDrag = Math.abs(pointer.distanceX) > this.state.options.minDistance;
shouldCancel = Math.abs(pointer.distanceY) > this.state.options.minDistance * this.state.options.cancelMultiplier;
} else {
shouldStartDrag = Math.abs(pointer.distanceY) > this.state.options.minDistance;
shouldCancel = Math.abs(pointer.distanceX) > this.state.options.minDistance * this.state.options.cancelMultiplier;
}
if (shouldStartDrag) {
// Create a new pointer representing this drag, starting at this point where the drag started.
this.state.dragPointer = makeStartPointer(ev);
updatePointerState(ev, this.state.dragPointer);
this.dispatchEvent(ev, '$md.dragstart', this.state.dragPointer);
} else if (shouldCancel) {
this.cancel();
}
} else {
this.dispatchDragMove(ev);
}
},
// Only dispatch dragmove events every frame; any more is unnecessray
dispatchDragMove: $$rAF.throttle(function (ev) {
// Make sure the drag didn't stop while waiting for the next frame
if (this.state.isRunning) {
updatePointerState(ev, this.state.dragPointer);
this.dispatchEvent(ev, '$md.drag', this.state.dragPointer);
}
}),
onEnd: function (ev, pointer) {
if (this.state.dragPointer) {
updatePointerState(ev, this.state.dragPointer);
this.dispatchEvent(ev, '$md.dragend', this.state.dragPointer);
}
}
})
/*
* The swipe handler will dispatch a swipe event if, on the end of a touch,
* the velocity and distance were high enough.
*/
.handler('swipe', {
options: {
minVelocity: 0.65,
minDistance: 10
},
onEnd: function (ev, pointer) {
var eventType;
if (Math.abs(pointer.velocityX) > this.state.options.minVelocity &&
Math.abs(pointer.distanceX) > this.state.options.minDistance) {
eventType = pointer.directionX == 'left' ? '$md.swipeleft' : '$md.swiperight';
this.dispatchEvent(ev, eventType);
}
else if (Math.abs(pointer.velocityY) > this.state.options.minVelocity &&
Math.abs(pointer.distanceY) > this.state.options.minDistance) {
eventType = pointer.directionY == 'up' ? '$md.swipeup' : '$md.swipedown';
this.dispatchEvent(ev, eventType);
}
}
});
}
MdGesture.$inject = ["$$MdGestureHandler", "$$rAF", "$timeout"];
/**
* MdGestureHandler
* A GestureHandler is an object which is able to dispatch custom dom events
* based on native dom {touch,pointer,mouse}{start,move,end} events.
*
* A gesture will manage its lifecycle through the start,move,end, and cancel
* functions, which are called by native dom events.
*
* A gesture has the concept of 'options' (eg a swipe's required velocity), which can be
* overridden by elements registering through $mdGesture.register()
*/
function GestureHandler (name) {
this.name = name;
this.state = {};
}
function MdGestureHandler() {
var hasJQuery = (typeof window.jQuery !== 'undefined') && (angular.element === window.jQuery);
GestureHandler.prototype = {
options: {},
// jQuery listeners don't work with custom DOMEvents, so we have to dispatch events
// differently when jQuery is loaded
dispatchEvent: hasJQuery ? jQueryDispatchEvent : nativeDispatchEvent,
// These are overridden by the registered handler
onStart: angular.noop,
onMove: angular.noop,
onEnd: angular.noop,
onCancel: angular.noop,
// onStart sets up a new state for the handler, which includes options from the
// nearest registered parent element of ev.target.
start: function (ev, pointer) {
if (this.state.isRunning) return;
var parentTarget = this.getNearestParent(ev.target);
// Get the options from the nearest registered parent
var parentTargetOptions = parentTarget && parentTarget.$mdGesture[this.name] || {};
this.state = {
isRunning: true,
// Override the default options with the nearest registered parent's options
options: angular.extend({}, this.options, parentTargetOptions),
// Pass in the registered parent node to the state so the onStart listener can use
registeredParent: parentTarget
};
this.onStart(ev, pointer);
},
move: function (ev, pointer) {
if (!this.state.isRunning) return;
this.onMove(ev, pointer);
},
end: function (ev, pointer) {
if (!this.state.isRunning) return;
this.onEnd(ev, pointer);
this.state.isRunning = false;
},
cancel: function (ev, pointer) {
this.onCancel(ev, pointer);
this.state = {};
},
// Find and return the nearest parent element that has been registered to
// listen for this handler via $mdGesture.register(element, 'handlerName').
getNearestParent: function (node) {
var current = node;
while (current) {
if ((current.$mdGesture || {})[this.name]) {
return current;
}
current = current.parentNode;
}
return null;
},
// Called from $mdGesture.register when an element reigsters itself with a handler.
// Store the options the user gave on the DOMElement itself. These options will
// be retrieved with getNearestParent when the handler starts.
registerElement: function (element, options) {
var self = this;
element[0].$mdGesture = element[0].$mdGesture || {};
element[0].$mdGesture[this.name] = options || {};
element.on('$destroy', onDestroy);
return onDestroy;
function onDestroy() {
delete element[0].$mdGesture[self.name];
element.off('$destroy', onDestroy);
}
}
};
return GestureHandler;
/*
* Dispatch an event with jQuery
* TODO: Make sure this sends bubbling events
*
* @param srcEvent the original DOM touch event that started this.
* @param eventType the name of the custom event to send (eg 'click' or '$md.drag')
* @param eventPointer the pointer object that matches this event.
*/
function jQueryDispatchEvent(srcEvent, eventType, eventPointer) {
eventPointer = eventPointer || pointer;
var eventObj = new angular.element.Event(eventType);
eventObj.$material = true;
eventObj.pointer = eventPointer;
eventObj.srcEvent = srcEvent;
angular.extend(eventObj, {
clientX: eventPointer.x,
clientY: eventPointer.y,
screenX: eventPointer.x,
screenY: eventPointer.y,
pageX: eventPointer.x,
pageY: eventPointer.y,
ctrlKey: srcEvent.ctrlKey,
altKey: srcEvent.altKey,
shiftKey: srcEvent.shiftKey,
metaKey: srcEvent.metaKey
});
angular.element(eventPointer.target).trigger(eventObj);
}
/*
* NOTE: nativeDispatchEvent is very performance sensitive.
* @param srcEvent the original DOM touch event that started this.
* @param eventType the name of the custom event to send (eg 'click' or '$md.drag')
* @param eventPointer the pointer object that matches this event.
*/
function nativeDispatchEvent(srcEvent, eventType, eventPointer) {
eventPointer = eventPointer || pointer;
var eventObj;
if (eventType === 'click' || eventType == 'mouseup' || eventType == 'mousedown' ) {
eventObj = document.createEvent('MouseEvents');
eventObj.initMouseEvent(
eventType, true, true, window, srcEvent.detail,
eventPointer.x, eventPointer.y, eventPointer.x, eventPointer.y,
srcEvent.ctrlKey, srcEvent.altKey, srcEvent.shiftKey, srcEvent.metaKey,
srcEvent.button, srcEvent.relatedTarget || null
);
} else {
eventObj = document.createEvent('CustomEvent');
eventObj.initCustomEvent(eventType, true, true, {});
}
eventObj.$material = true;
eventObj.pointer = eventPointer;
eventObj.srcEvent = srcEvent;
eventPointer.target.dispatchEvent(eventObj);
}
}
/**
* Attach Gestures: hook document and check shouldHijack clicks
* ngInject
*/
function attachToDocument( $mdGesture, $$MdGestureHandler ) {
// Polyfill document.contains for IE11.
// TODO: move to util
document.contains || (document.contains = function (node) {
return document.body.contains(node);
});
if (!isInitialized && $mdGesture.isHijackingClicks ) {
/*
* If hijack clicks is true, we preventDefault any click that wasn't
* sent by ngMaterial. This is because on older Android & iOS, a false, or 'ghost',
* click event will be sent ~400ms after a touchend event happens.
* The only way to know if this click is real is to prevent any normal
* click events, and add a flag to events sent by material so we know not to prevent those.
*
* Two exceptions to click events that should be prevented are:
* - click events sent by the keyboard (eg form submit)
* - events that originate from an Ionic app
*/
document.addEventListener('click' , clickHijacker , true);
document.addEventListener('mouseup' , mouseInputHijacker, true);
document.addEventListener('mousedown', mouseInputHijacker, true);
document.addEventListener('focus' , mouseInputHijacker, true);
isInitialized = true;
}
function mouseInputHijacker(ev) {
var isKeyClick = !ev.clientX && !ev.clientY;
if (!isKeyClick && !ev.$material && !ev.isIonicTap
&& !isInputEventFromLabelClick(ev)) {
ev.preventDefault();
ev.stopPropagation();
}
}
function clickHijacker(ev) {
var isKeyClick = ev.clientX === 0 && ev.clientY === 0;
if (!isKeyClick && !ev.$material && !ev.isIonicTap
&& !isInputEventFromLabelClick(ev)) {
ev.preventDefault();
ev.stopPropagation();
lastLabelClickPos = null;
} else {
lastLabelClickPos = null;
if (ev.target.tagName.toLowerCase() == 'label') {
lastLabelClickPos = {x: ev.x, y: ev.y};
}
}
}
// Listen to all events to cover all platforms.
var START_EVENTS = 'mousedown touchstart pointerdown';
var MOVE_EVENTS = 'mousemove touchmove pointermove';
var END_EVENTS = 'mouseup mouseleave touchend touchcancel pointerup pointercancel';
angular.element(document)
.on(START_EVENTS, gestureStart)
.on(MOVE_EVENTS, gestureMove)
.on(END_EVENTS, gestureEnd)
// For testing
.on('$$mdGestureReset', function gestureClearCache () {
lastPointer = pointer = null;
});
/*
* When a DOM event happens, run all registered gesture handlers' lifecycle
* methods which match the DOM event.
* Eg when a 'touchstart' event happens, runHandlers('start') will call and
* run `handler.cancel()` and `handler.start()` on all registered handlers.
*/
function runHandlers(handlerEvent, event) {
var handler;
for (var name in HANDLERS) {
handler = HANDLERS[name];
if( handler instanceof $$MdGestureHandler ) {
if (handlerEvent === 'start') {
// Run cancel to reset any handlers' state
handler.cancel();
}
handler[handlerEvent](event, pointer);
}
}
}
/*
* gestureStart vets if a start event is legitimate (and not part of a 'ghost click' from iOS/Android)
* If it is legitimate, we initiate the pointer state and mark the current pointer's type
* For example, for a touchstart event, mark the current pointer as a 'touch' pointer, so mouse events
* won't effect it.
*/
function gestureStart(ev) {
// If we're already touched down, abort
if (pointer) return;
var now = +Date.now();
// iOS & old android bug: after a touch event, a click event is sent 350 ms later.
// If <400ms have passed, don't allow an event of a different type than the previous event
if (lastPointer && !typesMatch(ev, lastPointer) && (now - lastPointer.endTime < 1500)) {
return;
}
pointer = makeStartPointer(ev);
runHandlers('start', ev);
}
/*
* If a move event happens of the right type, update the pointer and run all the move handlers.
* "of the right type": if a mousemove happens but our pointer started with a touch event, do nothing.
*/
function gestureMove(ev) {
if (!pointer || !typesMatch(ev, pointer)) return;
updatePointerState(ev, pointer);
runHandlers('move', ev);
}
/*
* If an end event happens of the right type, update the pointer, run endHandlers, and save the pointer as 'lastPointer'
*/
function gestureEnd(ev) {
if (!pointer || !typesMatch(ev, pointer)) return;
updatePointerState(ev, pointer);
pointer.endTime = +Date.now();
runHandlers('end', ev);
lastPointer = pointer;
pointer = null;
}
}
attachToDocument.$inject = ["$mdGesture", "$$MdGestureHandler"];
// ********************
// Module Functions
// ********************
/*
* Initiate the pointer. x, y, and the pointer's type.
*/
function makeStartPointer(ev) {
var point = getEventPoint(ev);
var startPointer = {
startTime: +Date.now(),
target: ev.target,
// 'p' for pointer events, 'm' for mouse, 't' for touch
type: ev.type.charAt(0)
};
startPointer.startX = startPointer.x = point.pageX;
startPointer.startY = startPointer.y = point.pageY;
return startPointer;
}
/*
* return whether the pointer's type matches the event's type.
* Eg if a touch event happens but the pointer has a mouse type, return false.
*/
function typesMatch(ev, pointer) {
return ev && pointer && ev.type.charAt(0) === pointer.type;
}
/**
* Gets whether the given event is an input event that was caused by clicking on an
* associated label element.
*
* This is necessary because the browser will, upon clicking on a label element, fire an
* *extra* click event on its associated input (if any). mdGesture is able to flag the label
* click as with `$material` correctly, but not the second input click.
*
* In order to determine whether an input event is from a label click, we compare the (x, y) for
* the event to the (x, y) for the most recent label click (which is cleared whenever a non-label
* click occurs). Unfortunately, there are no event properties that tie the input and the label
* together (such as relatedTarget).
*
* @param {MouseEvent} event
* @returns {boolean}
*/
function isInputEventFromLabelClick(event) {
return lastLabelClickPos
&& lastLabelClickPos.x == event.x
&& lastLabelClickPos.y == event.y;
}
/*
* Update the given pointer based upon the given DOMEvent.
* Distance, velocity, direction, duration, etc
*/
function updatePointerState(ev, pointer) {
var point = getEventPoint(ev);
var x = pointer.x = point.pageX;
var y = pointer.y = point.pageY;
pointer.distanceX = x - pointer.startX;
pointer.distanceY = y - pointer.startY;
pointer.distance = Math.sqrt(
pointer.distanceX * pointer.distanceX + pointer.distanceY * pointer.distanceY
);
pointer.directionX = pointer.distanceX > 0 ? 'right' : pointer.distanceX < 0 ? 'left' : '';
pointer.directionY = pointer.distanceY > 0 ? 'down' : pointer.distanceY < 0 ? 'up' : '';
pointer.duration = +Date.now() - pointer.startTime;
pointer.velocityX = pointer.distanceX / pointer.duration;
pointer.velocityY = pointer.distanceY / pointer.duration;
}
/*
* Normalize the point where the DOM event happened whether it's touch or mouse.
* @returns point event obj with pageX and pageY on it.
*/
function getEventPoint(ev) {
ev = ev.originalEvent || ev; // support jQuery events
return (ev.touches && ev.touches[0]) ||
(ev.changedTouches && ev.changedTouches[0]) ||
ev;
}
angular.module('material.core')
.provider('$$interimElement', InterimElementProvider);
/*
* @ngdoc service
* @name $$interimElement
* @module material.core
*
* @description
*
* Factory that contructs `$$interimElement.$service` services.
* Used internally in material design for elements that appear on screen temporarily.
* The service provides a promise-like API for interacting with the temporary
* elements.
*
* ```js
* app.service('$mdToast', function($$interimElement) {
* var $mdToast = $$interimElement(toastDefaultOptions);
* return $mdToast;
* });
* ```
* @param {object=} defaultOptions Options used by default for the `show` method on the service.
*
* @returns {$$interimElement.$service}
*
*/
function InterimElementProvider() {
createInterimElementProvider.$get = InterimElementFactory;
InterimElementFactory.$inject = ["$document", "$q", "$$q", "$rootScope", "$timeout", "$rootElement", "$animate", "$mdUtil", "$mdCompiler", "$mdTheming", "$injector"];
return createInterimElementProvider;
/**
* Returns a new provider which allows configuration of a new interimElement
* service. Allows configuration of default options & methods for options,
* as well as configuration of 'preset' methods (eg dialog.basic(): basic is a preset method)
*/
function createInterimElementProvider(interimFactoryName) {
var EXPOSED_METHODS = ['onHide', 'onShow', 'onRemove'];
var customMethods = {};
var providerConfig = {
presets: {}
};
var provider = {
setDefaults: setDefaults,
addPreset: addPreset,
addMethod: addMethod,
$get: factory
};
/**
* all interim elements will come with the 'build' preset
*/
provider.addPreset('build', {
methods: ['controller', 'controllerAs', 'resolve',
'template', 'templateUrl', 'themable', 'transformTemplate', 'parent']
});
factory.$inject = ["$$interimElement", "$injector"];
return provider;
/**
* Save the configured defaults to be used when the factory is instantiated
*/
function setDefaults(definition) {
providerConfig.optionsFactory = definition.options;
providerConfig.methods = (definition.methods || []).concat(EXPOSED_METHODS);
return provider;
}
/**
* Add a method to the factory that isn't specific to any interim element operations
*/
function addMethod(name, fn) {
customMethods[name] = fn;
return provider;
}
/**
* Save the configured preset to be used when the factory is instantiated
*/
function addPreset(name, definition) {
definition = definition || {};
definition.methods = definition.methods || [];
definition.options = definition.options || function() { return {}; };
if (/^cancel|hide|show$/.test(name)) {
throw new Error("Preset '" + name + "' in " + interimFactoryName + " is reserved!");
}
if (definition.methods.indexOf('_options') > -1) {
throw new Error("Method '_options' in " + interimFactoryName + " is reserved!");
}
providerConfig.presets[name] = {
methods: definition.methods.concat(EXPOSED_METHODS),
optionsFactory: definition.options,
argOption: definition.argOption
};
return provider;
}
function addPresetMethod(presetName, methodName, method) {
providerConfig.presets[presetName][methodName] = method;
}
/**
* Create a factory that has the given methods & defaults implementing interimElement
*/
/* ngInject */
function factory($$interimElement, $injector) {
var defaultMethods;
var defaultOptions;
var interimElementService = $$interimElement();
/*
* publicService is what the developer will be using.
* It has methods hide(), cancel(), show(), build(), and any other
* presets which were set during the config phase.
*/
var publicService = {
hide: interimElementService.hide,
cancel: interimElementService.cancel,
show: showInterimElement,
// Special internal method to destroy an interim element without animations
// used when navigation changes causes a $scope.$destroy() action
destroy : destroyInterimElement
};
defaultMethods = providerConfig.methods || [];
// This must be invoked after the publicService is initialized
defaultOptions = invokeFactory(providerConfig.optionsFactory, {});
// Copy over the simple custom methods
angular.forEach(customMethods, function(fn, name) {
publicService[name] = fn;
});
angular.forEach(providerConfig.presets, function(definition, name) {
var presetDefaults = invokeFactory(definition.optionsFactory, {});
var presetMethods = (definition.methods || []).concat(defaultMethods);
// Every interimElement built with a preset has a field called `$type`,
// which matches the name of the preset.
// Eg in preset 'confirm', options.$type === 'confirm'
angular.extend(presetDefaults, { $type: name });
// This creates a preset class which has setter methods for every
// method given in the `.addPreset()` function, as well as every
// method given in the `.setDefaults()` function.
//
// @example
// .setDefaults({
// methods: ['hasBackdrop', 'clickOutsideToClose', 'escapeToClose', 'targetEvent'],
// options: dialogDefaultOptions
// })
// .addPreset('alert', {
// methods: ['title', 'ok'],
// options: alertDialogOptions
// })
//
// Set values will be passed to the options when interimElement.show() is called.
function Preset(opts) {
this._options = angular.extend({}, presetDefaults, opts);
}
angular.forEach(presetMethods, function(name) {
Preset.prototype[name] = function(value) {
this._options[name] = value;
return this;
};
});
// Create shortcut method for one-linear methods
if (definition.argOption) {
var methodName = 'show' + name.charAt(0).toUpperCase() + name.slice(1);
publicService[methodName] = function(arg) {
var config = publicService[name](arg);
return publicService.show(config);
};
}
// eg $mdDialog.alert() will return a new alert preset
publicService[name] = function(arg) {
// If argOption is supplied, eg `argOption: 'content'`, then we assume
// if the argument is not an options object then it is the `argOption` option.
//
// @example `$mdToast.simple('hello')` // sets options.content to hello
// // because argOption === 'content'
if (arguments.length && definition.argOption &&
!angular.isObject(arg) && !angular.isArray(arg)) {
return (new Preset())[definition.argOption](arg);
} else {
return new Preset(arg);
}
};
});
return publicService;
/**
*
*/
function showInterimElement(opts) {
// opts is either a preset which stores its options on an _options field,
// or just an object made up of options
opts = opts || { };
if (opts._options) opts = opts._options;
return interimElementService.show(
angular.extend({}, defaultOptions, opts)
);
}
/**
* Special method to hide and destroy an interimElement WITHOUT
* any 'leave` or hide animations ( an immediate force hide/remove )
*
* NOTE: This calls the onRemove() subclass method for each component...
* which must have code to respond to `options.$destroy == true`
*/
function destroyInterimElement(opts) {
return interimElementService.destroy(opts);
}
/**
* Helper to call $injector.invoke with a local of the factory name for
* this provider.
* If an $mdDialog is providing options for a dialog and tries to inject
* $mdDialog, a circular dependency error will happen.
* We get around that by manually injecting $mdDialog as a local.
*/
function invokeFactory(factory, defaultVal) {
var locals = {};
locals[interimFactoryName] = publicService;
return $injector.invoke(factory || function() { return defaultVal; }, {}, locals);
}
}
}
/* ngInject */
function InterimElementFactory($document, $q, $$q, $rootScope, $timeout, $rootElement, $animate,
$mdUtil, $mdCompiler, $mdTheming, $injector ) {
return function createInterimElementService() {
var SHOW_CANCELLED = false;
/*
* @ngdoc service
* @name $$interimElement.$service
*
* @description
* A service used to control inserting and removing an element into the DOM.
*
*/
var service, stack = [];
// Publish instance $$interimElement service;
// ... used as $mdDialog, $mdToast, $mdMenu, and $mdSelect
return service = {
show: show,
hide: hide,
cancel: cancel,
destroy : destroy,
$injector_: $injector
};
/*
* @ngdoc method
* @name $$interimElement.$service#show
* @kind function
*
* @description
* Adds the `$interimElement` to the DOM and returns a special promise that will be resolved or rejected
* with hide or cancel, respectively. To external cancel/hide, developers should use the
*
* @param {*} options is hashMap of settings
* @returns a Promise
*
*/
function show(options) {
options = options || {};
var interimElement = new InterimElement(options || {});
var hideExisting = !options.skipHide && stack.length ? service.hide() : $q.when(true);
// This hide()s only the current interim element before showing the next, new one
// NOTE: this is not reversible (e.g. interim elements are not stackable)
hideExisting.finally(function() {
stack.push(interimElement);
interimElement
.show()
.catch(function( reason ) {
//$log.error("InterimElement.show() error: " + reason );
return reason;
});
});
// Return a promise that will be resolved when the interim
// element is hidden or cancelled...
return interimElement.deferred.promise;
}
/*
* @ngdoc method
* @name $$interimElement.$service#hide
* @kind function
*
* @description
* Removes the `$interimElement` from the DOM and resolves the promise returned from `show`
*
* @param {*} resolveParam Data to resolve the promise with
* @returns a Promise that will be resolved after the element has been removed.
*
*/
function hide(reason, options) {
if ( !stack.length ) return $q.when(reason);
options = options || {};
if (options.closeAll) {
var promise = $q.all(stack.reverse().map(closeElement));
stack = [];
return promise;
} else if (options.closeTo !== undefined) {
return $q.all(stack.splice(options.closeTo).map(closeElement));
} else {
var interim = stack.pop();
return closeElement(interim);
}
function closeElement(interim) {
interim
.remove(reason, false, options || { })
.catch(function( reason ) {
//$log.error("InterimElement.hide() error: " + reason );
return reason;
});
return interim.deferred.promise;
}
}
/*
* @ngdoc method
* @name $$interimElement.$service#cancel
* @kind function
*
* @description
* Removes the `$interimElement` from the DOM and rejects the promise returned from `show`
*
* @param {*} reason Data to reject the promise with
* @returns Promise that will be resolved after the element has been removed.
*
*/
function cancel(reason, options) {
var interim = stack.shift();
if ( !interim ) return $q.when(reason);
interim
.remove(reason, true, options || { })
.catch(function( reason ) {
//$log.error("InterimElement.cancel() error: " + reason );
return reason;
});
return interim.deferred.promise;
}
/*
* Special method to quick-remove the interim element without animations
* Note: interim elements are in "interim containers"
*/
function destroy(target) {
var interim = !target ? stack.shift() : null;
var cntr = angular.element(target).length ? angular.element(target)[0].parentNode : null;
if (cntr) {
// Try to find the interim element in the stack which corresponds to the supplied DOM element.
var filtered = stack.filter(function(entry) {
var currNode = entry.options.element[0];
return (currNode === cntr);
});
// Note: this function might be called when the element already has been removed, in which
// case we won't find any matches. That's ok.
if (filtered.length > 0) {
interim = filtered[0];
stack.splice(stack.indexOf(interim), 1);
}
}
return interim ? interim.remove(SHOW_CANCELLED, false, {'$destroy':true}) : $q.when(SHOW_CANCELLED);
}
/*
* Internal Interim Element Object
* Used internally to manage the DOM element and related data
*/
function InterimElement(options) {
var self, element, showAction = $q.when(true);
options = configureScopeAndTransitions(options);
return self = {
options : options,
deferred: $q.defer(),
show : createAndTransitionIn,
remove : transitionOutAndRemove
};
/**
* Compile, link, and show this interim element
* Use optional autoHided and transition-in effects
*/
function createAndTransitionIn() {
return $q(function(resolve, reject){
compileElement(options)
.then(function( compiledData ) {
element = linkElement( compiledData, options );
showAction = showElement(element, options, compiledData.controller)
.then(resolve, rejectAll );
}, rejectAll);
function rejectAll(fault) {
// Force the '$md<xxx>.show()' promise to reject
self.deferred.reject(fault);
// Continue rejection propagation
reject(fault);
}
});
}
/**
* After the show process has finished/rejected:
* - announce 'removing',
* - perform the transition-out, and
* - perform optional clean up scope.
*/
function transitionOutAndRemove(response, isCancelled, opts) {
// abort if the show() and compile failed
if ( !element ) return $q.when(false);
options = angular.extend(options || {}, opts || {});
options.cancelAutoHide && options.cancelAutoHide();
options.element.triggerHandler('$mdInterimElementRemove');
if ( options.$destroy === true ) {
return hideElement(options.element, options).then(function(){
(isCancelled && rejectAll(response)) || resolveAll(response);
});
} else {
$q.when(showAction)
.finally(function() {
hideElement(options.element, options).then(function() {
(isCancelled && rejectAll(response)) || resolveAll(response);
}, rejectAll);
});
return self.deferred.promise;
}
/**
* The `show()` returns a promise that will be resolved when the interim
* element is hidden or cancelled...
*/
function resolveAll(response) {
self.deferred.resolve(response);
}
/**
* Force the '$md<xxx>.show()' promise to reject
*/
function rejectAll(fault) {
self.deferred.reject(fault);
}
}
/**
* Prepare optional isolated scope and prepare $animate with default enter and leave
* transitions for the new element instance.
*/
function configureScopeAndTransitions(options) {
options = options || { };
if ( options.template ) {
options.template = $mdUtil.processTemplate(options.template);
}
return angular.extend({
preserveScope: false,
cancelAutoHide : angular.noop,
scope: options.scope || $rootScope.$new(options.isolateScope),
/**
* Default usage to enable $animate to transition-in; can be easily overridden via 'options'
*/
onShow: function transitionIn(scope, element, options) {
return $animate.enter(element, options.parent);
},
/**
* Default usage to enable $animate to transition-out; can be easily overridden via 'options'
*/
onRemove: function transitionOut(scope, element) {
// Element could be undefined if a new element is shown before
// the old one finishes compiling.
return element && $animate.leave(element) || $q.when();
}
}, options );
}
/**
* Compile an element with a templateUrl, controller, and locals
*/
function compileElement(options) {
var compiled = !options.skipCompile ? $mdCompiler.compile(options) : null;
return compiled || $q(function (resolve) {
resolve({
locals: {},
link: function () {
return options.element;
}
});
});
}
/**
* Link an element with compiled configuration
*/
function linkElement(compileData, options){
angular.extend(compileData.locals, options);
var element = compileData.link(options.scope);
// Search for parent at insertion time, if not specified
options.element = element;
options.parent = findParent(element, options);
if (options.themable) $mdTheming(element);
return element;
}
/**
* Search for parent at insertion time, if not specified
*/
function findParent(element, options) {
var parent = options.parent;
// Search for parent at insertion time, if not specified
if (angular.isFunction(parent)) {
parent = parent(options.scope, element, options);
} else if (angular.isString(parent)) {
parent = angular.element($document[0].querySelector(parent));
} else {
parent = angular.element(parent);
}
// If parent querySelector/getter function fails, or it's just null,
// find a default.
if (!(parent || {}).length) {
var el;
if ($rootElement[0] && $rootElement[0].querySelector) {
el = $rootElement[0].querySelector(':not(svg) > body');
}
if (!el) el = $rootElement[0];
if (el.nodeName == '#comment') {
el = $document[0].body;
}
return angular.element(el);
}
return parent;
}
/**
* If auto-hide is enabled, start timer and prepare cancel function
*/
function startAutoHide() {
var autoHideTimer, cancelAutoHide = angular.noop;
if (options.hideDelay) {
autoHideTimer = $timeout(service.hide, options.hideDelay) ;
cancelAutoHide = function() {
$timeout.cancel(autoHideTimer);
}
}
// Cache for subsequent use
options.cancelAutoHide = function() {
cancelAutoHide();
options.cancelAutoHide = undefined;
}
}
/**
* Show the element ( with transitions), notify complete and start
* optional auto-Hide
*/
function showElement(element, options, controller) {
// Trigger onShowing callback before the `show()` starts
var notifyShowing = options.onShowing || angular.noop;
// Trigger onComplete callback when the `show()` finishes
var notifyComplete = options.onComplete || angular.noop;
notifyShowing(options.scope, element, options, controller);
return $q(function (resolve, reject) {
try {
// Start transitionIn
$q.when(options.onShow(options.scope, element, options, controller))
.then(function () {
notifyComplete(options.scope, element, options);
startAutoHide();
resolve(element);
}, reject );
} catch(e) {
reject(e.message);
}
});
}
function hideElement(element, options) {
var announceRemoving = options.onRemoving || angular.noop;
return $$q(function (resolve, reject) {
try {
// Start transitionIn
var action = $$q.when( options.onRemove(options.scope, element, options) || true );
// Trigger callback *before* the remove operation starts
announceRemoving(element, action);
if ( options.$destroy == true ) {
// For $destroy, onRemove should be synchronous
resolve(element);
} else {
// Wait until transition-out is done
action.then(function () {
if (!options.preserveScope && options.scope ) {
options.scope.$destroy();
}
resolve(element);
}, reject );
}
} catch(e) {
reject(e.message);
}
});
}
}
};
}
}
(function() {
'use strict';
var $mdUtil, $interpolate, $log;
var SUFFIXES = /(-gt)?-(sm|md|lg)/g;
var WHITESPACE = /\s+/g;
var FLEX_OPTIONS = ['grow', 'initial', 'auto', 'none', 'noshrink', 'nogrow' ];
var LAYOUT_OPTIONS = ['row', 'column'];
var ALIGNMENT_MAIN_AXIS= [ "", "start", "center", "end", "stretch", "space-around", "space-between" ];
var ALIGNMENT_CROSS_AXIS= [ "", "start", "center", "end", "stretch" ];
var config = {
/**
* Enable directive attribute-to-class conversions
* Developers can use `<body md-layout-css />` to quickly
* disable the Layout directives and prohibit the injection of Layout classNames
*/
enabled: true,
/**
* List of mediaQuery breakpoints and associated suffixes
*
* [
* { suffix: "sm", mediaQuery: "screen and (max-width: 599px)" },
* { suffix: "md", mediaQuery: "screen and (min-width: 600px) and (max-width: 959px)" }
* ]
*/
breakpoints: []
};
registerLayoutAPI( angular.module('material.core.layout', ['ng']) );
/**
* registerLayoutAPI()
*
* The original ngMaterial Layout solution used attribute selectors and CSS.
*
* ```html
* <div layout="column"> My Content </div>
* ```
*
* ```css
* [layout] {
* box-sizing: border-box;
* display:flex;
* }
* [layout=column] {
* flex-direction : column
* }
* ```
*
* Use of attribute selectors creates significant performance impacts in some
* browsers... mainly IE.
*
* This module registers directives that allow the same layout attributes to be
* interpreted and converted to class selectors. The directive will add equivalent classes to each element that
* contains a Layout directive.
*
* ```html
* <div layout="column" class="layout layout-column"> My Content </div>
*```
*
* ```css
* .layout {
* box-sizing: border-box;
* display:flex;
* }
* .layout-column {
* flex-direction : column
* }
* ```
*/
function registerLayoutAPI(module){
var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
// NOTE: these are also defined in constants::MEDIA_PRIORITY and constants::MEDIA
var BREAKPOINTS = [ "", "xs", "gt-xs", "sm", "gt-sm", "md", "gt-md", "lg", "gt-lg", "xl" ];
var API_WITH_VALUES = [ "layout", "flex", "flex-order", "flex-offset", "layout-align" ];
var API_NO_VALUES = [ "show", "hide", "layout-padding", "layout-margin" ];
// Build directive registration functions for the standard Layout API... for all breakpoints.
angular.forEach(BREAKPOINTS, function(mqb) {
// Attribute directives with expected, observable value(s)
angular.forEach( API_WITH_VALUES, function(name){
var fullName = mqb ? name + "-" + mqb : name;
module.directive( directiveNormalize(fullName), attributeWithObserve(fullName));
});
// Attribute directives with no expected value(s)
angular.forEach( API_NO_VALUES, function(name){
var fullName = mqb ? name + "-" + mqb : name;
module.directive( directiveNormalize(fullName), attributeWithoutValue(fullName));
});
});
// Register other, special directive functions for the Layout features:
module
.directive('mdLayoutCss' , disableLayoutDirective )
.directive('ngCloak' , buildCloakInterceptor('ng-cloak'))
.directive('layoutWrap' , attributeWithoutValue('layout-wrap'))
.directive('layoutNoWrap' , attributeWithoutValue('layout-no-wrap'))
.directive('layoutFill' , attributeWithoutValue('layout-fill'))
// !! Deprecated attributes: use the `-lt` (aka less-than) notations
.directive('layoutLtMd' , warnAttrNotSupported('layout-lt-md', true))
.directive('layoutLtLg' , warnAttrNotSupported('layout-lt-lg', true))
.directive('flexLtMd' , warnAttrNotSupported('flex-lt-md', true))
.directive('flexLtLg' , warnAttrNotSupported('flex-lt-lg', true))
.directive('layoutAlignLtMd', warnAttrNotSupported('layout-align-lt-md'))
.directive('layoutAlignLtLg', warnAttrNotSupported('layout-align-lt-lg'))
.directive('flexOrderLtMd' , warnAttrNotSupported('flex-order-lt-md'))
.directive('flexOrderLtLg' , warnAttrNotSupported('flex-order-lt-lg'))
.directive('offsetLtMd' , warnAttrNotSupported('flex-offset-lt-md'))
.directive('offsetLtLg' , warnAttrNotSupported('flex-offset-lt-lg'))
.directive('hideLtMd' , warnAttrNotSupported('hide-lt-md'))
.directive('hideLtLg' , warnAttrNotSupported('hide-lt-lg'))
.directive('showLtMd' , warnAttrNotSupported('show-lt-md'))
.directive('showLtLg' , warnAttrNotSupported('show-lt-lg'));
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return name
.replace(PREFIX_REGEXP, '')
.replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
});
}
}
/**
* Special directive that will disable ALL Layout conversions of layout
* attribute(s) to classname(s).
*
* <link rel="stylesheet" href="angular-material.min.css">
* <link rel="stylesheet" href="angular-material.layout.css">
*
* <body md-layout-css>
* ...
* </body>
*
* Note: Using md-layout-css directive requires the developer to load the Material
* Layout Attribute stylesheet (which only uses attribute selectors):
*
* `angular-material.layout.css`
*
* Another option is to use the LayoutProvider to configure and disable the attribute
* conversions; this would obviate the use of the `md-layout-css` directive
*
*/
function disableLayoutDirective() {
return {
restrict : 'A',
priority : '900',
compile : function(element, attr) {
config.enabled = false;
return angular.noop;
}
};
}
/**
* Tail-hook ngCloak to delay the uncloaking while Layout transformers
* finish processing. Eliminates flicker with Material.Layoouts
*/
function buildCloakInterceptor(className) {
return [ '$timeout', function($timeout){
return {
restrict : 'A',
priority : -10, // run after normal ng-cloak
compile : function( element ) {
if (!config.enabled) return angular.noop;
// Re-add the cloak
element.addClass(className);
return function( scope, element ) {
// Wait while layout injectors configure, then uncloak
// NOTE: $rAF does not delay enough... and this is a 1x-only event,
// $timeout is acceptable.
$timeout( function(){
element.removeClass(className);
}, 10, false);
};
}
};
}];
}
// *********************************************************************************
//
// These functions create registration functions for ngMaterial Layout attribute directives
// This provides easy translation to switch ngMaterial attribute selectors to
// CLASS selectors and directives; which has huge performance implications
// for IE Browsers
//
// *********************************************************************************
/**
* Creates a directive registration function where a possible dynamic attribute
* value will be observed/watched.
* @param {string} className attribute name; eg `layout-gt-md` with value ="row"
*/
function attributeWithObserve(className) {
return ['$mdUtil', '$interpolate', "$log", function(_$mdUtil_, _$interpolate_, _$log_) {
$mdUtil = _$mdUtil_;
$interpolate = _$interpolate_;
$log = _$log_;
return {
restrict: 'A',
compile: function(element, attr) {
var linkFn;
if (config.enabled) {
// immediately replace static (non-interpolated) invalid values...
validateAttributeUsage(className, attr, element, $log);
validateAttributeValue( className,
getNormalizedAttrValue(className, attr, ""),
buildUpdateFn(element, className, attr)
);
linkFn = translateWithValueToCssClass;
}
// Use for postLink to account for transforms after ng-transclude.
return linkFn || angular.noop;
}
};
}];
/**
* Add as transformed class selector(s), then
* remove the deprecated attribute selector
*/
function translateWithValueToCssClass(scope, element, attrs) {
var updateFn = updateClassWithValue(element, className, attrs);
var unwatch = attrs.$observe(attrs.$normalize(className), updateFn);
updateFn(getNormalizedAttrValue(className, attrs, ""));
scope.$on("$destroy", function() { unwatch() });
}
}
/**
* Creates a registration function for ngMaterial Layout attribute directive.
* This is a `simple` transpose of attribute usage to class usage; where we ignore
* any attribute value
*/
function attributeWithoutValue(className) {
return ['$mdUtil', '$interpolate', "$log", function(_$mdUtil_, _$interpolate_, _$log_) {
$mdUtil = _$mdUtil_;
$interpolate = _$interpolate_;
$log = _$log_;
return {
restrict: 'A',
compile: function(element, attr) {
var linkFn;
if (config.enabled) {
// immediately replace static (non-interpolated) invalid values...
validateAttributeValue( className,
getNormalizedAttrValue(className, attr, ""),
buildUpdateFn(element, className, attr)
);
translateToCssClass(null, element);
// Use for postLink to account for transforms after ng-transclude.
linkFn = translateToCssClass;
}
return linkFn || angular.noop;
}
};
}];
/**
* Add as transformed class selector, then
* remove the deprecated attribute selector
*/
function translateToCssClass(scope, element) {
element.addClass(className);
}
}
/**
* After link-phase, do NOT remove deprecated layout attribute selector.
* Instead watch the attribute so interpolated data-bindings to layout
* selectors will continue to be supported.
*
* $observe() the className and update with new class (after removing the last one)
*
* e.g. `layout="{{layoutDemo.direction}}"` will update...
*
* NOTE: The value must match one of the specified styles in the CSS.
* For example `flex-gt-md="{{size}}` where `scope.size == 47` will NOT work since
* only breakpoints for 0, 5, 10, 15... 100, 33, 34, 66, 67 are defined.
*
*/
function updateClassWithValue(element, className) {
var lastClass;
return function updateClassFn(newValue) {
var value = validateAttributeValue(className, newValue || "");
if ( angular.isDefined(value) ) {
if (lastClass) element.removeClass(lastClass);
lastClass = !value ? className : className + "-" + value.replace(WHITESPACE, "-");
element.addClass(lastClass);
}
};
}
/**
* Provide console warning that this layout attribute has been deprecated
*
*/
function warnAttrNotSupported(className) {
var parts = className.split("-");
return ["$log", function($log) {
$log.warn(className + "has been deprecated. Please use a `" + parts[0] + "-gt-<xxx>` variant.");
return angular.noop;
}];
}
/**
* Centralize warnings for known flexbox issues (especially IE-related issues)
*/
function validateAttributeUsage(className, attr, element, $log){
var message, usage, url;
var nodeName = element[0].nodeName.toLowerCase();
switch(className.replace(SUFFIXES,"")) {
case "flex":
if ((nodeName == "md-button") || (nodeName == "fieldset")){
// @see https://github.com/philipwalton/flexbugs#9-some-html-elements-cant-be-flex-containers
// Use <div flex> wrapper inside (preferred) or outside
usage = "<" + nodeName + " " + className + "></" + nodeName + ">";
url = "https://github.com/philipwalton/flexbugs#9-some-html-elements-cant-be-flex-containers";
message = "Markup '{0}' may not work as expected in IE Browsers. Consult '{1}' for details.";
$log.warn( $mdUtil.supplant(message, [usage, url]) );
}
}
}
/**
* For the Layout attribute value, validate or replace with default
* fallback value
*/
function validateAttributeValue(className, value, updateFn) {
var origValue = value;
if (!needsInterpolation(value)) {
switch (className.replace(SUFFIXES,"")) {
case 'layout' :
if ( !findIn(value, LAYOUT_OPTIONS) ) {
value = LAYOUT_OPTIONS[0]; // 'row';
}
break;
case 'flex' :
if (!findIn(value, FLEX_OPTIONS)) {
if (isNaN(value)) {
value = '';
}
}
break;
case 'flex-offset' :
case 'flex-order' :
if (!value || isNaN(+value)) {
value = '0';
}
break;
case 'layout-align' :
var axis = extractAlignAxis(value);
value = $mdUtil.supplant("{main}-{cross}",axis);
break;
case 'layout-padding' :
case 'layout-margin' :
case 'layout-fill' :
case 'layout-wrap' :
case 'layout-no-wrap' :
value = '';
break;
}
if (value != origValue) {
(updateFn || angular.noop)(value);
}
}
return value;
}
/**
* Replace current attribute value with fallback value
*/
function buildUpdateFn(element, className, attrs) {
return function updateAttrValue(fallback) {
if (!needsInterpolation(fallback)) {
// Do not modify the element's attribute value; so
// uses '<ui-layout layout="/api/sidebar.html" />' will not
// be affected. Just update the attrs value.
attrs[attrs.$normalize(className)] = fallback;
}
};
}
/**
* See if the original value has interpolation symbols:
* e.g. flex-gt-md="{{triggerPoint}}"
*/
function needsInterpolation(value) {
return (value || "").indexOf($interpolate.startSymbol()) > -1;
}
function getNormalizedAttrValue(className, attrs, defaultVal) {
var normalizedAttr = attrs.$normalize(className);
return attrs[normalizedAttr] ? attrs[normalizedAttr].replace(WHITESPACE, "-") : defaultVal || null;
}
function findIn(item, list, replaceWith) {
item = replaceWith && item ? item.replace(WHITESPACE, replaceWith) : item;
var found = false;
if (item) {
list.forEach(function(it) {
it = replaceWith ? it.replace(WHITESPACE, replaceWith) : it;
found = found || (it === item);
});
}
return found;
}
function extractAlignAxis(attrValue) {
var axis = {
main : "start",
cross: "stretch"
}, values;
attrValue = (attrValue || "");
if ( attrValue.indexOf("-") == 0 || attrValue.indexOf(" ") == 0) {
// For missing main-axis values
attrValue = "none" + attrValue;
}
values = attrValue.toLowerCase().trim().replace(WHITESPACE, "-").split("-");
if ( values.length && (values[0] === "space") ) {
// for main-axis values of "space-around" or "space-between"
values = [ values[0]+"-"+values[1],values[2] ];
}
if ( values.length > 0 ) axis.main = values[0] || axis.main;
if ( values.length > 1 ) axis.cross = values[1] || axis.cross;
if ( ALIGNMENT_MAIN_AXIS.indexOf(axis.main) < 0 ) axis.main = "start";
if ( ALIGNMENT_CROSS_AXIS.indexOf(axis.cross) < 0 ) axis.cross = "stretch";
return axis;
}
})();
/**
* @ngdoc module
* @name material.core.componentRegistry
*
* @description
* A component instance registration service.
* Note: currently this as a private service in the SideNav component.
*/
angular.module('material.core')
.factory('$mdComponentRegistry', ComponentRegistry);
/*
* @private
* @ngdoc factory
* @name ComponentRegistry
* @module material.core.componentRegistry
*
*/
function ComponentRegistry($log, $q) {
var self;
var instances = [ ];
var pendings = { };
return self = {
/**
* Used to print an error when an instance for a handle isn't found.
*/
notFoundError: function(handle) {
$log.error('No instance found for handle', handle);
},
/**
* Return all registered instances as an array.
*/
getInstances: function() {
return instances;
},
/**
* Get a registered instance.
* @param handle the String handle to look up for a registered instance.
*/
get: function(handle) {
if ( !isValidID(handle) ) return null;
var i, j, instance;
for(i = 0, j = instances.length; i < j; i++) {
instance = instances[i];
if(instance.$$mdHandle === handle) {
return instance;
}
}
return null;
},
/**
* Register an instance.
* @param instance the instance to register
* @param handle the handle to identify the instance under.
*/
register: function(instance, handle) {
if ( !handle ) return angular.noop;
instance.$$mdHandle = handle;
instances.push(instance);
resolveWhen();
return deregister;
/**
* Remove registration for an instance
*/
function deregister() {
var index = instances.indexOf(instance);
if (index !== -1) {
instances.splice(index, 1);
}
}
/**
* Resolve any pending promises for this instance
*/
function resolveWhen() {
var dfd = pendings[handle];
if ( dfd ) {
dfd.resolve( instance );
delete pendings[handle];
}
}
},
/**
* Async accessor to registered component instance
* If not available then a promise is created to notify
* all listeners when the instance is registered.
*/
when : function(handle) {
if ( isValidID(handle) ) {
var deferred = $q.defer();
var instance = self.get(handle);
if ( instance ) {
deferred.resolve( instance );
} else {
pendings[handle] = deferred;
}
return deferred.promise;
}
return $q.reject("Invalid `md-component-id` value.");
}
};
function isValidID(handle){
return handle && (handle !== "");
}
}
ComponentRegistry.$inject = ["$log", "$q"];
(function() {
'use strict';
/**
* @ngdoc service
* @name $mdButtonInkRipple
* @module material.core
*
* @description
* Provides ripple effects for md-button. See $mdInkRipple service for all possible configuration options.
*
* @param {object=} scope Scope within the current context
* @param {object=} element The element the ripple effect should be applied to
* @param {object=} options (Optional) Configuration options to override the default ripple configuration
*/
angular.module('material.core')
.factory('$mdButtonInkRipple', MdButtonInkRipple);
function MdButtonInkRipple($mdInkRipple) {
return {
attach: function attachRipple(scope, element, options) {
options = angular.extend(optionsForElement(element), options);
return $mdInkRipple.attach(scope, element, options);
}
};
function optionsForElement(element) {
if (element.hasClass('md-icon-button')) {
return {
isMenuItem: element.hasClass('md-menu-item'),
fitRipple: true,
center: true
};
} else {
return {
isMenuItem: element.hasClass('md-menu-item'),
dimBackground: true
}
}
};
}
MdButtonInkRipple.$inject = ["$mdInkRipple"];;
})();
(function() {
'use strict';
/**
* @ngdoc service
* @name $mdCheckboxInkRipple
* @module material.core
*
* @description
* Provides ripple effects for md-checkbox. See $mdInkRipple service for all possible configuration options.
*
* @param {object=} scope Scope within the current context
* @param {object=} element The element the ripple effect should be applied to
* @param {object=} options (Optional) Configuration options to override the defaultripple configuration
*/
angular.module('material.core')
.factory('$mdCheckboxInkRipple', MdCheckboxInkRipple);
function MdCheckboxInkRipple($mdInkRipple) {
return {
attach: attach
};
function attach(scope, element, options) {
return $mdInkRipple.attach(scope, element, angular.extend({
center: true,
dimBackground: false,
fitRipple: true
}, options));
};
}
MdCheckboxInkRipple.$inject = ["$mdInkRipple"];;
})();
(function() {
'use strict';
/**
* @ngdoc service
* @name $mdListInkRipple
* @module material.core
*
* @description
* Provides ripple effects for md-list. See $mdInkRipple service for all possible configuration options.
*
* @param {object=} scope Scope within the current context
* @param {object=} element The element the ripple effect should be applied to
* @param {object=} options (Optional) Configuration options to override the defaultripple configuration
*/
angular.module('material.core')
.factory('$mdListInkRipple', MdListInkRipple);
function MdListInkRipple($mdInkRipple) {
return {
attach: attach
};
function attach(scope, element, options) {
return $mdInkRipple.attach(scope, element, angular.extend({
center: false,
dimBackground: true,
outline: false,
rippleSize: 'full'
}, options));
};
}
MdListInkRipple.$inject = ["$mdInkRipple"];;
})();
/**
* @ngdoc module
* @name material.core.ripple
* @description
* Ripple
*/
angular.module('material.core')
.factory('$mdInkRipple', InkRippleService)
.directive('mdInkRipple', InkRippleDirective)
.directive('mdNoInk', attrNoDirective)
.directive('mdNoBar', attrNoDirective)
.directive('mdNoStretch', attrNoDirective);
var DURATION = 450;
/**
* @ngdoc directive
* @name mdInkRipple
* @module material.core.ripple
*
* @description
* The `md-ink-ripple` directive allows you to specify the ripple color or id a ripple is allowed.
*
* @param {string|boolean} md-ink-ripple A color string `#FF0000` or boolean (`false` or `0`) for preventing ripple
*
* @usage
* ### String values
* <hljs lang="html">
* <ANY md-ink-ripple="#FF0000">
* Ripples in red
* </ANY>
*
* <ANY md-ink-ripple="false">
* Not rippling
* </ANY>
* </hljs>
*
* ### Interpolated values
* <hljs lang="html">
* <ANY md-ink-ripple="{{ randomColor() }}">
* Ripples with the return value of 'randomColor' function
* </ANY>
*
* <ANY md-ink-ripple="{{ canRipple() }}">
* Ripples if 'canRipple' function return value is not 'false' or '0'
* </ANY>
* </hljs>
*/
function InkRippleDirective ($mdButtonInkRipple, $mdCheckboxInkRipple) {
return {
controller: angular.noop,
link: function (scope, element, attr) {
attr.hasOwnProperty('mdInkRippleCheckbox')
? $mdCheckboxInkRipple.attach(scope, element)
: $mdButtonInkRipple.attach(scope, element);
}
};
}
InkRippleDirective.$inject = ["$mdButtonInkRipple", "$mdCheckboxInkRipple"];
/**
* @ngdoc service
* @name $mdInkRipple
* @module material.core.ripple
*
* @description
* `$mdInkRipple` is a service for adding ripples to any element
*
* @usage
* <hljs lang="js">
* app.factory('$myElementInkRipple', function($mdInkRipple) {
* return {
* attach: function (scope, element, options) {
* return $mdInkRipple.attach(scope, element, angular.extend({
* center: false,
* dimBackground: true
* }, options));
* }
* };
* });
*
* app.controller('myController', function ($scope, $element, $myElementInkRipple) {
* $scope.onClick = function (ev) {
* $myElementInkRipple.attach($scope, angular.element(ev.target), { center: true });
* }
* });
* </hljs>
*/
/**
* @ngdoc method
* @name $mdInkRipple#attach
*
* @description
* Attaching given scope, element and options to inkRipple controller
*
* @param {object=} scope Scope within the current context
* @param {object=} element The element the ripple effect should be applied to
* @param {object=} options (Optional) Configuration options to override the defaultRipple configuration
* * `center` - Whether the ripple should start from the center of the container element
* * `dimBackground` - Whether the background should be dimmed with the ripple color
* * `colorElement` - The element the ripple should take its color from, defined by css property `color`
* * `fitRipple` - Whether the ripple should fill the element
*/
function InkRippleService ($injector) {
return { attach: attach };
function attach (scope, element, options) {
if (element.controller('mdNoInk')) return angular.noop;
return $injector.instantiate(InkRippleCtrl, {
$scope: scope,
$element: element,
rippleOptions: options
});
}
}
InkRippleService.$inject = ["$injector"];
/**
* Controller used by the ripple service in order to apply ripples
* ngInject
*/
function InkRippleCtrl ($scope, $element, rippleOptions, $window, $timeout, $mdUtil) {
this.$window = $window;
this.$timeout = $timeout;
this.$mdUtil = $mdUtil;
this.$scope = $scope;
this.$element = $element;
this.options = rippleOptions;
this.mousedown = false;
this.ripples = [];
this.timeout = null; // Stores a reference to the most-recent ripple timeout
this.lastRipple = null;
$mdUtil.valueOnUse(this, 'container', this.createContainer);
this.$element.addClass('md-ink-ripple');
// attach method for unit tests
($element.controller('mdInkRipple') || {}).createRipple = angular.bind(this, this.createRipple);
($element.controller('mdInkRipple') || {}).setColor = angular.bind(this, this.color);
this.bindEvents();
}
InkRippleCtrl.$inject = ["$scope", "$element", "rippleOptions", "$window", "$timeout", "$mdUtil"];
/**
* Either remove or unlock any remaining ripples when the user mouses off of the element (either by
* mouseup or mouseleave event)
*/
function autoCleanup (self, cleanupFn) {
if ( self.mousedown || self.lastRipple ) {
self.mousedown = false;
self.$mdUtil.nextTick( angular.bind(self, cleanupFn), false);
}
}
/**
* Returns the color that the ripple should be (either based on CSS or hard-coded)
* @returns {string}
*/
InkRippleCtrl.prototype.color = function (value) {
var self = this;
// If assigning a color value, apply it to background and the ripple color
if (angular.isDefined(value)) {
self._color = self._parseColor(value);
}
// If color lookup, use assigned, defined, or inherited
return self._color || self._parseColor( self.inkRipple() ) || self._parseColor( getElementColor() );
/**
* Finds the color element and returns its text color for use as default ripple color
* @returns {string}
*/
function getElementColor () {
var items = self.options && self.options.colorElement ? self.options.colorElement : [];
var elem = items.length ? items[ 0 ] : self.$element[ 0 ];
return elem ? self.$window.getComputedStyle(elem).color : 'rgb(0,0,0)';
}
};
/**
* Updating the ripple colors based on the current inkRipple value
* or the element's computed style color
*/
InkRippleCtrl.prototype.calculateColor = function () {
return this.color();
};
/**
* Takes a string color and converts it to RGBA format
* @param color {string}
* @param [multiplier] {int}
* @returns {string}
*/
InkRippleCtrl.prototype._parseColor = function parseColor (color, multiplier) {
multiplier = multiplier || 1;
if (!color) return;
if (color.indexOf('rgba') === 0) return color.replace(/\d?\.?\d*\s*\)\s*$/, (0.1 * multiplier).toString() + ')');
if (color.indexOf('rgb') === 0) return rgbToRGBA(color);
if (color.indexOf('#') === 0) return hexToRGBA(color);
/**
* Converts hex value to RGBA string
* @param color {string}
* @returns {string}
*/
function hexToRGBA (color) {
var hex = color[ 0 ] === '#' ? color.substr(1) : color,
dig = hex.length / 3,
red = hex.substr(0, dig),
green = hex.substr(dig, dig),
blue = hex.substr(dig * 2);
if (dig === 1) {
red += red;
green += green;
blue += blue;
}
return 'rgba(' + parseInt(red, 16) + ',' + parseInt(green, 16) + ',' + parseInt(blue, 16) + ',0.1)';
}
/**
* Converts an RGB color to RGBA
* @param color {string}
* @returns {string}
*/
function rgbToRGBA (color) {
return color.replace(')', ', 0.1)').replace('(', 'a(');
}
};
/**
* Binds events to the root element for
*/
InkRippleCtrl.prototype.bindEvents = function () {
this.$element.on('mousedown', angular.bind(this, this.handleMousedown));
this.$element.on('mouseup touchend', angular.bind(this, this.handleMouseup));
this.$element.on('mouseleave', angular.bind(this, this.handleMouseup));
this.$element.on('touchmove', angular.bind(this, this.handleTouchmove));
};
/**
* Create a new ripple on every mousedown event from the root element
* @param event {MouseEvent}
*/
InkRippleCtrl.prototype.handleMousedown = function (event) {
if ( this.mousedown ) return;
// When jQuery is loaded, we have to get the original event
if (event.hasOwnProperty('originalEvent')) event = event.originalEvent;
this.mousedown = true;
if (this.options.center) {
this.createRipple(this.container.prop('clientWidth') / 2, this.container.prop('clientWidth') / 2);
} else {
// We need to calculate the relative coordinates if the target is a sublayer of the ripple element
if (event.srcElement !== this.$element[0]) {
var layerRect = this.$element[0].getBoundingClientRect();
var layerX = event.clientX - layerRect.left;
var layerY = event.clientY - layerRect.top;
this.createRipple(layerX, layerY);
} else {
this.createRipple(event.offsetX, event.offsetY);
}
}
};
/**
* Either remove or unlock any remaining ripples when the user mouses off of the element (either by
* mouseup, touchend or mouseleave event)
*/
InkRippleCtrl.prototype.handleMouseup = function () {
autoCleanup(this, this.clearRipples);
};
/**
* Either remove or unlock any remaining ripples when the user mouses off of the element (by
* touchmove)
*/
InkRippleCtrl.prototype.handleTouchmove = function () {
autoCleanup(this, this.deleteRipples);
};
/**
* Cycles through all ripples and attempts to remove them.
*/
InkRippleCtrl.prototype.deleteRipples = function () {
for (var i = 0; i < this.ripples.length; i++) {
this.ripples[ i ].remove();
}
};
/**
* Cycles through all ripples and attempts to remove them with fade.
* Depending on logic within `fadeInComplete`, some removals will be postponed.
*/
InkRippleCtrl.prototype.clearRipples = function () {
for (var i = 0; i < this.ripples.length; i++) {
this.fadeInComplete(this.ripples[ i ]);
}
};
/**
* Creates the ripple container element
* @returns {*}
*/
InkRippleCtrl.prototype.createContainer = function () {
var container = angular.element('<div class="md-ripple-container"></div>');
this.$element.append(container);
return container;
};
InkRippleCtrl.prototype.clearTimeout = function () {
if (this.timeout) {
this.$timeout.cancel(this.timeout);
this.timeout = null;
}
};
InkRippleCtrl.prototype.isRippleAllowed = function () {
var element = this.$element[0];
do {
if (!element.tagName || element.tagName === 'BODY') break;
if (element && angular.isFunction(element.hasAttribute)) {
if (element.hasAttribute('disabled')) return false;
if (this.inkRipple() === 'false' || this.inkRipple() === '0') return false;
}
} while (element = element.parentNode);
return true;
};
/**
* The attribute `md-ink-ripple` may be a static or interpolated
* color value OR a boolean indicator (used to disable ripples)
*/
InkRippleCtrl.prototype.inkRipple = function () {
return this.$element.attr('md-ink-ripple');
};
/**
* Creates a new ripple and adds it to the container. Also tracks ripple in `this.ripples`.
* @param left
* @param top
*/
InkRippleCtrl.prototype.createRipple = function (left, top) {
if (!this.isRippleAllowed()) return;
var ctrl = this;
var ripple = angular.element('<div class="md-ripple"></div>');
var width = this.$element.prop('clientWidth');
var height = this.$element.prop('clientHeight');
var x = Math.max(Math.abs(width - left), left) * 2;
var y = Math.max(Math.abs(height - top), top) * 2;
var size = getSize(this.options.fitRipple, x, y);
var color = this.calculateColor();
ripple.css({
left: left + 'px',
top: top + 'px',
background: 'black',
width: size + 'px',
height: size + 'px',
backgroundColor: rgbaToRGB(color),
borderColor: rgbaToRGB(color)
});
this.lastRipple = ripple;
// we only want one timeout to be running at a time
this.clearTimeout();
this.timeout = this.$timeout(function () {
ctrl.clearTimeout();
if (!ctrl.mousedown) ctrl.fadeInComplete(ripple);
}, DURATION * 0.35, false);
if (this.options.dimBackground) this.container.css({ backgroundColor: color });
this.container.append(ripple);
this.ripples.push(ripple);
ripple.addClass('md-ripple-placed');
this.$mdUtil.nextTick(function () {
ripple.addClass('md-ripple-scaled md-ripple-active');
ctrl.$timeout(function () {
ctrl.clearRipples();
}, DURATION, false);
}, false);
function rgbaToRGB (color) {
return color
? color.replace('rgba', 'rgb').replace(/,[^\),]+\)/, ')')
: 'rgb(0,0,0)';
}
function getSize (fit, x, y) {
return fit
? Math.max(x, y)
: Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
};
/**
* After fadeIn finishes, either kicks off the fade-out animation or queues the element for removal on mouseup
* @param ripple
*/
InkRippleCtrl.prototype.fadeInComplete = function (ripple) {
if (this.lastRipple === ripple) {
if (!this.timeout && !this.mousedown) {
this.removeRipple(ripple);
}
} else {
this.removeRipple(ripple);
}
};
/**
* Kicks off the animation for removing a ripple
* @param ripple {Element}
*/
InkRippleCtrl.prototype.removeRipple = function (ripple) {
var ctrl = this;
var index = this.ripples.indexOf(ripple);
if (index < 0) return;
this.ripples.splice(this.ripples.indexOf(ripple), 1);
ripple.removeClass('md-ripple-active');
if (this.ripples.length === 0) this.container.css({ backgroundColor: '' });
// use a 2-second timeout in order to allow for the animation to finish
// we don't actually care how long the animation takes
this.$timeout(function () {
ctrl.fadeOutComplete(ripple);
}, DURATION, false);
};
/**
* Removes the provided ripple from the DOM
* @param ripple
*/
InkRippleCtrl.prototype.fadeOutComplete = function (ripple) {
ripple.remove();
this.lastRipple = null;
};
/**
* Used to create an empty directive. This is used to track flag-directives whose children may have
* functionality based on them.
*
* Example: `md-no-ink` will potentially be used by all child directives.
*/
function attrNoDirective () {
return { controller: angular.noop };
}
(function() {
'use strict';
/**
* @ngdoc service
* @name $mdTabInkRipple
* @module material.core
*
* @description
* Provides ripple effects for md-tabs. See $mdInkRipple service for all possible configuration options.
*
* @param {object=} scope Scope within the current context
* @param {object=} element The element the ripple effect should be applied to
* @param {object=} options (Optional) Configuration options to override the defaultripple configuration
*/
angular.module('material.core')
.factory('$mdTabInkRipple', MdTabInkRipple);
function MdTabInkRipple($mdInkRipple) {
return {
attach: attach
};
function attach(scope, element, options) {
return $mdInkRipple.attach(scope, element, angular.extend({
center: false,
dimBackground: true,
outline: false,
rippleSize: 'full'
}, options));
};
}
MdTabInkRipple.$inject = ["$mdInkRipple"];;
})();
angular.module('material.core.theming.palette', [])
.constant('$mdColorPalette', {
'red': {
'50': '#ffebee',
'100': '#ffcdd2',
'200': '#ef9a9a',
'300': '#e57373',
'400': '#ef5350',
'500': '#f44336',
'600': '#e53935',
'700': '#d32f2f',
'800': '#c62828',
'900': '#b71c1c',
'A100': '#ff8a80',
'A200': '#ff5252',
'A400': '#ff1744',
'A700': '#d50000',
'contrastDefaultColor': 'light',
'contrastDarkColors': '50 100 200 300 A100',
'contrastStrongLightColors': '400 500 600 700 A200 A400 A700'
},
'pink': {
'50': '#fce4ec',
'100': '#f8bbd0',
'200': '#f48fb1',
'300': '#f06292',
'400': '#ec407a',
'500': '#e91e63',
'600': '#d81b60',
'700': '#c2185b',
'800': '#ad1457',
'900': '#880e4f',
'A100': '#ff80ab',
'A200': '#ff4081',
'A400': '#f50057',
'A700': '#c51162',
'contrastDefaultColor': 'light',
'contrastDarkColors': '50 100 200 A100',
'contrastStrongLightColors': '500 600 A200 A400 A700'
},
'purple': {
'50': '#f3e5f5',
'100': '#e1bee7',
'200': '#ce93d8',
'300': '#ba68c8',
'400': '#ab47bc',
'500': '#9c27b0',
'600': '#8e24aa',
'700': '#7b1fa2',
'800': '#6a1b9a',
'900': '#4a148c',
'A100': '#ea80fc',
'A200': '#e040fb',
'A400': '#d500f9',
'A700': '#aa00ff',
'contrastDefaultColor': 'light',
'contrastDarkColors': '50 100 200 A100',
'contrastStrongLightColors': '300 400 A200 A400 A700'
},
'deep-purple': {
'50': '#ede7f6',
'100': '#d1c4e9',
'200': '#b39ddb',
'300': '#9575cd',
'400': '#7e57c2',
'500': '#673ab7',
'600': '#5e35b1',
'700': '#512da8',
'800': '#4527a0',
'900': '#311b92',
'A100': '#b388ff',
'A200': '#7c4dff',
'A400': '#651fff',
'A700': '#6200ea',
'contrastDefaultColor': 'light',
'contrastDarkColors': '50 100 200 A100',
'contrastStrongLightColors': '300 400 A200'
},
'indigo': {
'50': '#e8eaf6',
'100': '#c5cae9',
'200': '#9fa8da',
'300': '#7986cb',
'400': '#5c6bc0',
'500': '#3f51b5',
'600': '#3949ab',
'700': '#303f9f',
'800': '#283593',
'900': '#1a237e',
'A100': '#8c9eff',
'A200': '#536dfe',
'A400': '#3d5afe',
'A700': '#304ffe',
'contrastDefaultColor': 'light',
'contrastDarkColors': '50 100 200 A100',
'contrastStrongLightColors': '300 400 A200 A400'
},
'blue': {
'50': '#e3f2fd',
'100': '#bbdefb',
'200': '#90caf9',
'300': '#64b5f6',
'400': '#42a5f5',
'500': '#2196f3',
'600': '#1e88e5',
'700': '#1976d2',
'800': '#1565c0',
'900': '#0d47a1',
'A100': '#82b1ff',
'A200': '#448aff',
'A400': '#2979ff',
'A700': '#2962ff',
'contrastDefaultColor': 'light',
'contrastDarkColors': '50 100 200 300 400 A100',
'contrastStrongLightColors': '500 600 700 A200 A400 A700'
},
'light-blue': {
'50': '#e1f5fe',
'100': '#b3e5fc',
'200': '#81d4fa',
'300': '#4fc3f7',
'400': '#29b6f6',
'500': '#03a9f4',
'600': '#039be5',
'700': '#0288d1',
'800': '#0277bd',
'900': '#01579b',
'A100': '#80d8ff',
'A200': '#40c4ff',
'A400': '#00b0ff',
'A700': '#0091ea',
'contrastDefaultColor': 'dark',
'contrastLightColors': '600 700 800 900 A700',
'contrastStrongLightColors': '600 700 800 A700'
},
'cyan': {
'50': '#e0f7fa',
'100': '#b2ebf2',
'200': '#80deea',
'300': '#4dd0e1',
'400': '#26c6da',
'500': '#00bcd4',
'600': '#00acc1',
'700': '#0097a7',
'800': '#00838f',
'900': '#006064',
'A100': '#84ffff',
'A200': '#18ffff',
'A400': '#00e5ff',
'A700': '#00b8d4',
'contrastDefaultColor': 'dark',
'contrastLightColors': '700 800 900',
'contrastStrongLightColors': '700 800 900'
},
'teal': {
'50': '#e0f2f1',
'100': '#b2dfdb',
'200': '#80cbc4',
'300': '#4db6ac',
'400': '#26a69a',
'500': '#009688',
'600': '#00897b',
'700': '#00796b',
'800': '#00695c',
'900': '#004d40',
'A100': '#a7ffeb',
'A200': '#64ffda',
'A400': '#1de9b6',
'A700': '#00bfa5',
'contrastDefaultColor': 'dark',
'contrastLightColors': '500 600 700 800 900',
'contrastStrongLightColors': '500 600 700'
},
'green': {
'50': '#e8f5e9',
'100': '#c8e6c9',
'200': '#a5d6a7',
'300': '#81c784',
'400': '#66bb6a',
'500': '#4caf50',
'600': '#43a047',
'700': '#388e3c',
'800': '#2e7d32',
'900': '#1b5e20',
'A100': '#b9f6ca',
'A200': '#69f0ae',
'A400': '#00e676',
'A700': '#00c853',
'contrastDefaultColor': 'dark',
'contrastLightColors': '600 700 800 900',
'contrastStrongLightColors': '600 700'
},
'light-green': {
'50': '#f1f8e9',
'100': '#dcedc8',
'200': '#c5e1a5',
'300': '#aed581',
'400': '#9ccc65',
'500': '#8bc34a',
'600': '#7cb342',
'700': '#689f38',
'800': '#558b2f',
'900': '#33691e',
'A100': '#ccff90',
'A200': '#b2ff59',
'A400': '#76ff03',
'A700': '#64dd17',
'contrastDefaultColor': 'dark',
'contrastLightColors': '700 800 900',
'contrastStrongLightColors': '700 800 900'
},
'lime': {
'50': '#f9fbe7',
'100': '#f0f4c3',
'200': '#e6ee9c',
'300': '#dce775',
'400': '#d4e157',
'500': '#cddc39',
'600': '#c0ca33',
'700': '#afb42b',
'800': '#9e9d24',
'900': '#827717',
'A100': '#f4ff81',
'A200': '#eeff41',
'A400': '#c6ff00',
'A700': '#aeea00',
'contrastDefaultColor': 'dark',
'contrastLightColors': '900',
'contrastStrongLightColors': '900'
},
'yellow': {
'50': '#fffde7',
'100': '#fff9c4',
'200': '#fff59d',
'300': '#fff176',
'400': '#ffee58',
'500': '#ffeb3b',
'600': '#fdd835',
'700': '#fbc02d',
'800': '#f9a825',
'900': '#f57f17',
'A100': '#ffff8d',
'A200': '#ffff00',
'A400': '#ffea00',
'A700': '#ffd600',
'contrastDefaultColor': 'dark'
},
'amber': {
'50': '#fff8e1',
'100': '#ffecb3',
'200': '#ffe082',
'300': '#ffd54f',
'400': '#ffca28',
'500': '#ffc107',
'600': '#ffb300',
'700': '#ffa000',
'800': '#ff8f00',
'900': '#ff6f00',
'A100': '#ffe57f',
'A200': '#ffd740',
'A400': '#ffc400',
'A700': '#ffab00',
'contrastDefaultColor': 'dark'
},
'orange': {
'50': '#fff3e0',
'100': '#ffe0b2',
'200': '#ffcc80',
'300': '#ffb74d',
'400': '#ffa726',
'500': '#ff9800',
'600': '#fb8c00',
'700': '#f57c00',
'800': '#ef6c00',
'900': '#e65100',
'A100': '#ffd180',
'A200': '#ffab40',
'A400': '#ff9100',
'A700': '#ff6d00',
'contrastDefaultColor': 'dark',
'contrastLightColors': '800 900',
'contrastStrongLightColors': '800 900'
},
'deep-orange': {
'50': '#fbe9e7',
'100': '#ffccbc',
'200': '#ffab91',
'300': '#ff8a65',
'400': '#ff7043',
'500': '#ff5722',
'600': '#f4511e',
'700': '#e64a19',
'800': '#d84315',
'900': '#bf360c',
'A100': '#ff9e80',
'A200': '#ff6e40',
'A400': '#ff3d00',
'A700': '#dd2c00',
'contrastDefaultColor': 'light',
'contrastDarkColors': '50 100 200 300 400 A100 A200',
'contrastStrongLightColors': '500 600 700 800 900 A400 A700'
},
'brown': {
'50': '#efebe9',
'100': '#d7ccc8',
'200': '#bcaaa4',
'300': '#a1887f',
'400': '#8d6e63',
'500': '#795548',
'600': '#6d4c41',
'700': '#5d4037',
'800': '#4e342e',
'900': '#3e2723',
'A100': '#d7ccc8',
'A200': '#bcaaa4',
'A400': '#8d6e63',
'A700': '#5d4037',
'contrastDefaultColor': 'light',
'contrastDarkColors': '50 100 200',
'contrastStrongLightColors': '300 400'
},
'grey': {
'50': '#fafafa',
'100': '#f5f5f5',
'200': '#eeeeee',
'300': '#e0e0e0',
'400': '#bdbdbd',
'500': '#9e9e9e',
'600': '#757575',
'700': '#616161',
'800': '#424242',
'900': '#212121',
'1000': '#000000',
'A100': '#ffffff',
'A200': '#eeeeee',
'A400': '#bdbdbd',
'A700': '#616161',
'contrastDefaultColor': 'dark',
'contrastLightColors': '600 700 800 900'
},
'blue-grey': {
'50': '#eceff1',
'100': '#cfd8dc',
'200': '#b0bec5',
'300': '#90a4ae',
'400': '#78909c',
'500': '#607d8b',
'600': '#546e7a',
'700': '#455a64',
'800': '#37474f',
'900': '#263238',
'A100': '#cfd8dc',
'A200': '#b0bec5',
'A400': '#78909c',
'A700': '#455a64',
'contrastDefaultColor': 'light',
'contrastDarkColors': '50 100 200 300',
'contrastStrongLightColors': '400 500'
}
});
angular.module('material.core.theming', ['material.core.theming.palette'])
.directive('mdTheme', ThemingDirective)
.directive('mdThemable', ThemableDirective)
.provider('$mdTheming', ThemingProvider)
.run(generateAllThemes);
/**
* @ngdoc service
* @name $mdThemingProvider
* @module material.core.theming
*
* @description Provider to configure the `$mdTheming` service.
*/
/**
* @ngdoc method
* @name $mdThemingProvider#setNonce
* @param {string} nonceValue The nonce to be added as an attribute to the theme style tags.
* Setting a value allows the use CSP policy without using the unsafe-inline directive.
*/
/**
* @ngdoc method
* @name $mdThemingProvider#setDefaultTheme
* @param {string} themeName Default theme name to be applied to elements. Default value is `default`.
*/
/**
* @ngdoc method
* @name $mdThemingProvider#alwaysWatchTheme
* @param {boolean} watch Whether or not to always watch themes for changes and re-apply
* classes when they change. Default is `false`. Enabling can reduce performance.
*/
/* Some Example Valid Theming Expressions
* =======================================
*
* Intention group expansion: (valid for primary, accent, warn, background)
*
* {{primary-100}} - grab shade 100 from the primary palette
* {{primary-100-0.7}} - grab shade 100, apply opacity of 0.7
* {{primary-100-contrast}} - grab shade 100's contrast color
* {{primary-hue-1}} - grab the shade assigned to hue-1 from the primary palette
* {{primary-hue-1-0.7}} - apply 0.7 opacity to primary-hue-1
* {{primary-color}} - Generates .md-hue-1, .md-hue-2, .md-hue-3 with configured shades set for each hue
* {{primary-color-0.7}} - Apply 0.7 opacity to each of the above rules
* {{primary-contrast}} - Generates .md-hue-1, .md-hue-2, .md-hue-3 with configured contrast (ie. text) color shades set for each hue
* {{primary-contrast-0.7}} - Apply 0.7 opacity to each of the above rules
*
* Foreground expansion: Applies rgba to black/white foreground text
*
* {{foreground-1}} - used for primary text
* {{foreground-2}} - used for secondary text/divider
* {{foreground-3}} - used for disabled text
* {{foreground-4}} - used for dividers
*
*/
// In memory generated CSS rules; registered by theme.name
var GENERATED = { };
// In memory storage of defined themes and color palettes (both loaded by CSS, and user specified)
var PALETTES;
var THEMES;
var DARK_FOREGROUND = {
name: 'dark',
'1': 'rgba(0,0,0,0.87)',
'2': 'rgba(0,0,0,0.54)',
'3': 'rgba(0,0,0,0.26)',
'4': 'rgba(0,0,0,0.12)'
};
var LIGHT_FOREGROUND = {
name: 'light',
'1': 'rgba(255,255,255,1.0)',
'2': 'rgba(255,255,255,0.7)',
'3': 'rgba(255,255,255,0.3)',
'4': 'rgba(255,255,255,0.12)'
};
var DARK_SHADOW = '1px 1px 0px rgba(0,0,0,0.4), -1px -1px 0px rgba(0,0,0,0.4)';
var LIGHT_SHADOW = '';
var DARK_CONTRAST_COLOR = colorToRgbaArray('rgba(0,0,0,0.87)');
var LIGHT_CONTRAST_COLOR = colorToRgbaArray('rgba(255,255,255,0.87)');
var STRONG_LIGHT_CONTRAST_COLOR = colorToRgbaArray('rgb(255,255,255)');
var THEME_COLOR_TYPES = ['primary', 'accent', 'warn', 'background'];
var DEFAULT_COLOR_TYPE = 'primary';
// A color in a theme will use these hues by default, if not specified by user.
var LIGHT_DEFAULT_HUES = {
'accent': {
'default': 'A200',
'hue-1': 'A100',
'hue-2': 'A400',
'hue-3': 'A700'
},
'background': {
'default': 'A100',
'hue-1': '300',
'hue-2': '800',
'hue-3': '900'
}
};
var DARK_DEFAULT_HUES = {
'background': {
'default': '800',
'hue-1': '600',
'hue-2': '300',
'hue-3': '900'
}
};
THEME_COLOR_TYPES.forEach(function(colorType) {
// Color types with unspecified default hues will use these default hue values
var defaultDefaultHues = {
'default': '500',
'hue-1': '300',
'hue-2': '800',
'hue-3': 'A100'
};
if (!LIGHT_DEFAULT_HUES[colorType]) LIGHT_DEFAULT_HUES[colorType] = defaultDefaultHues;
if (!DARK_DEFAULT_HUES[colorType]) DARK_DEFAULT_HUES[colorType] = defaultDefaultHues;
});
var VALID_HUE_VALUES = [
'50', '100', '200', '300', '400', '500', '600',
'700', '800', '900', 'A100', 'A200', 'A400', 'A700'
];
// Whether or not themes are to be generated on-demand (vs. eagerly).
var generateOnDemand = false;
// Nonce to be added as an attribute to the generated themes style tags.
var nonce = null;
function ThemingProvider($mdColorPalette) {
PALETTES = { };
THEMES = { };
var themingProvider;
var defaultTheme = 'default';
var alwaysWatchTheme = false;
// Load JS Defined Palettes
angular.extend(PALETTES, $mdColorPalette);
// Default theme defined in core.js
ThemingService.$inject = ["$rootScope", "$log"];
return themingProvider = {
definePalette: definePalette,
extendPalette: extendPalette,
theme: registerTheme,
setNonce: function(nonceValue) {
nonce = nonceValue;
},
setDefaultTheme: function(theme) {
defaultTheme = theme;
},
alwaysWatchTheme: function(alwaysWatch) {
alwaysWatchTheme = alwaysWatch;
},
generateThemesOnDemand: function(onDemand) {
generateOnDemand = onDemand;
},
$get: ThemingService,
_LIGHT_DEFAULT_HUES: LIGHT_DEFAULT_HUES,
_DARK_DEFAULT_HUES: DARK_DEFAULT_HUES,
_PALETTES: PALETTES,
_THEMES: THEMES,
_parseRules: parseRules,
_rgba: rgba
};
// Example: $mdThemingProvider.definePalette('neonRed', { 50: '#f5fafa', ... });
function definePalette(name, map) {
map = map || {};
PALETTES[name] = checkPaletteValid(name, map);
return themingProvider;
}
// Returns an new object which is a copy of a given palette `name` with variables from
// `map` overwritten
// Example: var neonRedMap = $mdThemingProvider.extendPalette('red', { 50: '#f5fafafa' });
function extendPalette(name, map) {
return checkPaletteValid(name, angular.extend({}, PALETTES[name] || {}, map) );
}
// Make sure that palette has all required hues
function checkPaletteValid(name, map) {
var missingColors = VALID_HUE_VALUES.filter(function(field) {
return !map[field];
});
if (missingColors.length) {
throw new Error("Missing colors %1 in palette %2!"
.replace('%1', missingColors.join(', '))
.replace('%2', name));
}
return map;
}
// Register a theme (which is a collection of color palettes to use with various states
// ie. warn, accent, primary )
// Optionally inherit from an existing theme
// $mdThemingProvider.theme('custom-theme').primaryPalette('red');
function registerTheme(name, inheritFrom) {
if (THEMES[name]) return THEMES[name];
inheritFrom = inheritFrom || 'default';
var parentTheme = typeof inheritFrom === 'string' ? THEMES[inheritFrom] : inheritFrom;
var theme = new Theme(name);
if (parentTheme) {
angular.forEach(parentTheme.colors, function(color, colorType) {
theme.colors[colorType] = {
name: color.name,
// Make sure a COPY of the hues is given to the child color,
// not the same reference.
hues: angular.extend({}, color.hues)
};
});
}
THEMES[name] = theme;
return theme;
}
function Theme(name) {
var self = this;
self.name = name;
self.colors = {};
self.dark = setDark;
setDark(false);
function setDark(isDark) {
isDark = arguments.length === 0 ? true : !!isDark;
// If no change, abort
if (isDark === self.isDark) return;
self.isDark = isDark;
self.foregroundPalette = self.isDark ? LIGHT_FOREGROUND : DARK_FOREGROUND;
self.foregroundShadow = self.isDark ? DARK_SHADOW : LIGHT_SHADOW;
// Light and dark themes have different default hues.
// Go through each existing color type for this theme, and for every
// hue value that is still the default hue value from the previous light/dark setting,
// set it to the default hue value from the new light/dark setting.
var newDefaultHues = self.isDark ? DARK_DEFAULT_HUES : LIGHT_DEFAULT_HUES;
var oldDefaultHues = self.isDark ? LIGHT_DEFAULT_HUES : DARK_DEFAULT_HUES;
angular.forEach(newDefaultHues, function(newDefaults, colorType) {
var color = self.colors[colorType];
var oldDefaults = oldDefaultHues[colorType];
if (color) {
for (var hueName in color.hues) {
if (color.hues[hueName] === oldDefaults[hueName]) {
color.hues[hueName] = newDefaults[hueName];
}
}
}
});
return self;
}
THEME_COLOR_TYPES.forEach(function(colorType) {
var defaultHues = (self.isDark ? DARK_DEFAULT_HUES : LIGHT_DEFAULT_HUES)[colorType];
self[colorType + 'Palette'] = function setPaletteType(paletteName, hues) {
var color = self.colors[colorType] = {
name: paletteName,
hues: angular.extend({}, defaultHues, hues)
};
Object.keys(color.hues).forEach(function(name) {
if (!defaultHues[name]) {
throw new Error("Invalid hue name '%1' in theme %2's %3 color %4. Available hue names: %4"
.replace('%1', name)
.replace('%2', self.name)
.replace('%3', paletteName)
.replace('%4', Object.keys(defaultHues).join(', '))
);
}
});
Object.keys(color.hues).map(function(key) {
return color.hues[key];
}).forEach(function(hueValue) {
if (VALID_HUE_VALUES.indexOf(hueValue) == -1) {
throw new Error("Invalid hue value '%1' in theme %2's %3 color %4. Available hue values: %5"
.replace('%1', hueValue)
.replace('%2', self.name)
.replace('%3', colorType)
.replace('%4', paletteName)
.replace('%5', VALID_HUE_VALUES.join(', '))
);
}
});
return self;
};
self[colorType + 'Color'] = function() {
var args = Array.prototype.slice.call(arguments);
console.warn('$mdThemingProviderTheme.' + colorType + 'Color() has been deprecated. ' +
'Use $mdThemingProviderTheme.' + colorType + 'Palette() instead.');
return self[colorType + 'Palette'].apply(self, args);
};
});
}
/**
* @ngdoc service
* @name $mdTheming
*
* @description
*
* Service that makes an element apply theming related classes to itself.
*
* ```js
* app.directive('myFancyDirective', function($mdTheming) {
* return {
* restrict: 'e',
* link: function(scope, el, attrs) {
* $mdTheming(el);
* }
* };
* });
* ```
* @param {el=} element to apply theming to
*/
/* ngInject */
function ThemingService($rootScope, $log) {
applyTheme.inherit = function(el, parent) {
var ctrl = parent.controller('mdTheme');
var attrThemeValue = el.attr('md-theme-watch');
if ( (alwaysWatchTheme || angular.isDefined(attrThemeValue)) && attrThemeValue != 'false') {
var deregisterWatch = $rootScope.$watch(function() {
return ctrl && ctrl.$mdTheme || (defaultTheme == 'default' ? '' : defaultTheme);
}, changeTheme);
el.on('$destroy', deregisterWatch);
} else {
var theme = ctrl && ctrl.$mdTheme || (defaultTheme == 'default' ? '' : defaultTheme);
changeTheme(theme);
}
function changeTheme(theme) {
if (!theme) return;
if (!registered(theme)) {
$log.warn('Attempted to use unregistered theme \'' + theme + '\'. ' +
'Register it with $mdThemingProvider.theme().');
}
var oldTheme = el.data('$mdThemeName');
if (oldTheme) el.removeClass('md-' + oldTheme +'-theme');
el.addClass('md-' + theme + '-theme');
el.data('$mdThemeName', theme);
if (ctrl) {
el.data('$mdThemeController', ctrl);
}
}
};
applyTheme.THEMES = angular.extend({}, THEMES);
applyTheme.defaultTheme = function() { return defaultTheme; };
applyTheme.registered = registered;
applyTheme.generateTheme = function(name) { generateTheme(name, nonce); };
return applyTheme;
function registered(themeName) {
if (themeName === undefined || themeName === '') return true;
return applyTheme.THEMES[themeName] !== undefined;
}
function applyTheme(scope, el) {
// Allow us to be invoked via a linking function signature.
if (el === undefined) {
el = scope;
scope = undefined;
}
if (scope === undefined) {
scope = $rootScope;
}
applyTheme.inherit(el, el);
}
}
}
ThemingProvider.$inject = ["$mdColorPalette"];
function ThemingDirective($mdTheming, $interpolate, $log) {
return {
priority: 100,
link: {
pre: function(scope, el, attrs) {
var ctrl = {
$setTheme: function(theme) {
if (!$mdTheming.registered(theme)) {
$log.warn('attempted to use unregistered theme \'' + theme + '\'');
}
ctrl.$mdTheme = theme;
}
};
el.data('$mdThemeController', ctrl);
ctrl.$setTheme($interpolate(attrs.mdTheme)(scope));
attrs.$observe('mdTheme', ctrl.$setTheme);
}
}
};
}
ThemingDirective.$inject = ["$mdTheming", "$interpolate", "$log"];
function ThemableDirective($mdTheming) {
return $mdTheming;
}
ThemableDirective.$inject = ["$mdTheming"];
function parseRules(theme, colorType, rules) {
checkValidPalette(theme, colorType);
rules = rules.replace(/THEME_NAME/g, theme.name);
var generatedRules = [];
var color = theme.colors[colorType];
var themeNameRegex = new RegExp('.md-' + theme.name + '-theme', 'g');
// Matches '{{ primary-color }}', etc
var hueRegex = new RegExp('(\'|")?{{\\s*(' + colorType + ')-(color|contrast)-?(\\d\\.?\\d*)?\\s*}}(\"|\')?','g');
var simpleVariableRegex = /'?"?\{\{\s*([a-zA-Z]+)-(A?\d+|hue\-[0-3]|shadow)-?(\d\.?\d*)?(contrast)?\s*\}\}'?"?/g;
var palette = PALETTES[color.name];
// find and replace simple variables where we use a specific hue, not an entire palette
// eg. "{{primary-100}}"
//\(' + THEME_COLOR_TYPES.join('\|') + '\)'
rules = rules.replace(simpleVariableRegex, function(match, colorType, hue, opacity, contrast) {
if (colorType === 'foreground') {
if (hue == 'shadow') {
return theme.foregroundShadow;
} else {
return theme.foregroundPalette[hue] || theme.foregroundPalette['1'];
}
}
if (hue.indexOf('hue') === 0) {
hue = theme.colors[colorType].hues[hue];
}
return rgba( (PALETTES[ theme.colors[colorType].name ][hue] || '')[contrast ? 'contrast' : 'value'], opacity );
});
// For each type, generate rules for each hue (ie. default, md-hue-1, md-hue-2, md-hue-3)
angular.forEach(color.hues, function(hueValue, hueName) {
var newRule = rules
.replace(hueRegex, function(match, _, colorType, hueType, opacity) {
return rgba(palette[hueValue][hueType === 'color' ? 'value' : 'contrast'], opacity);
});
if (hueName !== 'default') {
newRule = newRule.replace(themeNameRegex, '.md-' + theme.name + '-theme.md-' + hueName);
}
// Don't apply a selector rule to the default theme, making it easier to override
// styles of the base-component
if (theme.name == 'default') {
var themeRuleRegex = /((?:(?:(?: |>|\.|\w|-|:|\(|\)|\[|\]|"|'|=)+) )?)((?:(?:\w|\.|-)+)?)\.md-default-theme((?: |>|\.|\w|-|:|\(|\)|\[|\]|"|'|=)*)/g;
newRule = newRule.replace(themeRuleRegex, function(match, prefix, target, suffix) {
return match + ', ' + prefix + target + suffix;
});
}
generatedRules.push(newRule);
});
return generatedRules;
}
var rulesByType = {};
// Generate our themes at run time given the state of THEMES and PALETTES
function generateAllThemes($injector) {
var head = document.head;
var firstChild = head ? head.firstElementChild : null;
var themeCss = $injector.has('$MD_THEME_CSS') ? $injector.get('$MD_THEME_CSS') : '';
if ( !firstChild ) return;
if (themeCss.length === 0) return; // no rules, so no point in running this expensive task
// Expose contrast colors for palettes to ensure that text is always readable
angular.forEach(PALETTES, sanitizePalette);
// MD_THEME_CSS is a string generated by the build process that includes all the themable
// components as templates
// Break the CSS into individual rules
var rules = themeCss
.split(/\}(?!(\}|'|"|;))/)
.filter(function(rule) { return rule && rule.length; })
.map(function(rule) { return rule.trim() + '}'; });
var ruleMatchRegex = new RegExp('md-(' + THEME_COLOR_TYPES.join('|') + ')', 'g');
THEME_COLOR_TYPES.forEach(function(type) {
rulesByType[type] = '';
});
// Sort the rules based on type, allowing us to do color substitution on a per-type basis
rules.forEach(function(rule) {
var match = rule.match(ruleMatchRegex);
// First: test that if the rule has '.md-accent', it goes into the accent set of rules
for (var i = 0, type; type = THEME_COLOR_TYPES[i]; i++) {
if (rule.indexOf('.md-' + type) > -1) {
return rulesByType[type] += rule;
}
}
// If no eg 'md-accent' class is found, try to just find 'accent' in the rule and guess from
// there
for (i = 0; type = THEME_COLOR_TYPES[i]; i++) {
if (rule.indexOf(type) > -1) {
return rulesByType[type] += rule;
}
}
// Default to the primary array
return rulesByType[DEFAULT_COLOR_TYPE] += rule;
});
// If themes are being generated on-demand, quit here. The user will later manually
// call generateTheme to do this on a theme-by-theme basis.
if (generateOnDemand) return;
angular.forEach(THEMES, function(theme) {
if (!GENERATED[theme.name]) {
generateTheme(theme.name, nonce);
}
});
// *************************
// Internal functions
// *************************
// The user specifies a 'default' contrast color as either light or dark,
// then explicitly lists which hues are the opposite contrast (eg. A100 has dark, A200 has light)
function sanitizePalette(palette) {
var defaultContrast = palette.contrastDefaultColor;
var lightColors = palette.contrastLightColors || [];
var strongLightColors = palette.contrastStrongLightColors || [];
var darkColors = palette.contrastDarkColors || [];
// These colors are provided as space-separated lists
if (typeof lightColors === 'string') lightColors = lightColors.split(' ');
if (typeof strongLightColors === 'string') strongLightColors = strongLightColors.split(' ');
if (typeof darkColors === 'string') darkColors = darkColors.split(' ');
// Cleanup after ourselves
delete palette.contrastDefaultColor;
delete palette.contrastLightColors;
delete palette.contrastStrongLightColors;
delete palette.contrastDarkColors;
// Change { 'A100': '#fffeee' } to { 'A100': { value: '#fffeee', contrast:DARK_CONTRAST_COLOR }
angular.forEach(palette, function(hueValue, hueName) {
if (angular.isObject(hueValue)) return; // Already converted
// Map everything to rgb colors
var rgbValue = colorToRgbaArray(hueValue);
if (!rgbValue) {
throw new Error("Color %1, in palette %2's hue %3, is invalid. Hex or rgb(a) color expected."
.replace('%1', hueValue)
.replace('%2', palette.name)
.replace('%3', hueName));
}
palette[hueName] = {
value: rgbValue,
contrast: getContrastColor()
};
function getContrastColor() {
if (defaultContrast === 'light') {
if (darkColors.indexOf(hueName) > -1) {
return DARK_CONTRAST_COLOR;
} else {
return strongLightColors.indexOf(hueName) > -1 ? STRONG_LIGHT_CONTRAST_COLOR
: LIGHT_CONTRAST_COLOR;
}
} else {
if (lightColors.indexOf(hueName) > -1) {
return strongLightColors.indexOf(hueName) > -1 ? STRONG_LIGHT_CONTRAST_COLOR
: LIGHT_CONTRAST_COLOR;
} else {
return DARK_CONTRAST_COLOR;
}
}
}
});
}
}
generateAllThemes.$inject = ["$injector"];
function generateTheme(name, nonce) {
var theme = THEMES[name];
var head = document.head;
var firstChild = head ? head.firstElementChild : null;
if (!GENERATED[name]) {
// For each theme, use the color palettes specified for
// `primary`, `warn` and `accent` to generate CSS rules.
THEME_COLOR_TYPES.forEach(function(colorType) {
var styleStrings = parseRules(theme, colorType, rulesByType[colorType]);
while (styleStrings.length) {
var styleContent = styleStrings.shift();
if (styleContent) {
var style = document.createElement('style');
style.setAttribute('md-theme-style', '');
if (nonce) {
style.setAttribute('nonce', nonce);
}
style.appendChild(document.createTextNode(styleContent));
head.insertBefore(style, firstChild);
}
}
});
if (theme.colors.primary.name == theme.colors.accent.name) {
console.warn('$mdThemingProvider: Using the same palette for primary and' +
' accent. This violates the material design spec.');
}
GENERATED[theme.name] = true;
}
}
function checkValidPalette(theme, colorType) {
// If theme attempts to use a palette that doesnt exist, throw error
if (!PALETTES[ (theme.colors[colorType] || {}).name ]) {
throw new Error(
"You supplied an invalid color palette for theme %1's %2 palette. Available palettes: %3"
.replace('%1', theme.name)
.replace('%2', colorType)
.replace('%3', Object.keys(PALETTES).join(', '))
);
}
}
function colorToRgbaArray(clr) {
if (angular.isArray(clr) && clr.length == 3) return clr;
if (/^rgb/.test(clr)) {
return clr.replace(/(^\s*rgba?\(|\)\s*$)/g, '').split(',').map(function(value, i) {
return i == 3 ? parseFloat(value, 10) : parseInt(value, 10);
});
}
if (clr.charAt(0) == '#') clr = clr.substring(1);
if (!/^([a-fA-F0-9]{3}){1,2}$/g.test(clr)) return;
var dig = clr.length / 3;
var red = clr.substr(0, dig);
var grn = clr.substr(dig, dig);
var blu = clr.substr(dig * 2);
if (dig === 1) {
red += red;
grn += grn;
blu += blu;
}
return [parseInt(red, 16), parseInt(grn, 16), parseInt(blu, 16)];
}
function rgba(rgbArray, opacity) {
if ( !rgbArray ) return "rgb('0,0,0')";
if (rgbArray.length == 4) {
rgbArray = angular.copy(rgbArray);
opacity ? rgbArray.pop() : opacity = rgbArray.pop();
}
return opacity && (typeof opacity == 'number' || (typeof opacity == 'string' && opacity.length)) ?
'rgba(' + rgbArray.join(',') + ',' + opacity + ')' :
'rgb(' + rgbArray.join(',') + ')';
}
// Polyfill angular < 1.4 (provide $animateCss)
angular
.module('material.core')
.factory('$$mdAnimate', ["$q", "$timeout", "$mdConstant", "$animateCss", function($q, $timeout, $mdConstant, $animateCss){
// Since $$mdAnimate is injected into $mdUtil... use a wrapper function
// to subsequently inject $mdUtil as an argument to the AnimateDomUtils
return function($mdUtil) {
return AnimateDomUtils( $mdUtil, $q, $timeout, $mdConstant, $animateCss);
};
}]);
/**
* Factory function that requires special injections
*/
function AnimateDomUtils($mdUtil, $q, $timeout, $mdConstant, $animateCss) {
var self;
return self = {
/**
*
*/
translate3d : function( target, from, to, options ) {
return $animateCss(target,{
from:from,
to:to,
addClass:options.transitionInClass
})
.start()
.then(function(){
// Resolve with reverser function...
return reverseTranslate;
});
/**
* Specific reversal of the request translate animation above...
*/
function reverseTranslate (newFrom) {
return $animateCss(target, {
to: newFrom || from,
addClass: options.transitionOutClass,
removeClass: options.transitionInClass
}).start();
}
},
/**
* Listen for transitionEnd event (with optional timeout)
* Announce completion or failure via promise handlers
*/
waitTransitionEnd: function (element, opts) {
var TIMEOUT = 3000; // fallback is 3 secs
return $q(function(resolve, reject){
opts = opts || { };
var timer = $timeout(finished, opts.timeout || TIMEOUT);
element.on($mdConstant.CSS.TRANSITIONEND, finished);
/**
* Upon timeout or transitionEnd, reject or resolve (respectively) this promise.
* NOTE: Make sure this transitionEnd didn't bubble up from a child
*/
function finished(ev) {
if ( ev && ev.target !== element[0]) return;
if ( ev ) $timeout.cancel(timer);
element.off($mdConstant.CSS.TRANSITIONEND, finished);
// Never reject since ngAnimate may cause timeouts due missed transitionEnd events
resolve();
}
});
},
/**
* Calculate the zoom transform from dialog to origin.
*
* We use this to set the dialog position immediately;
* then the md-transition-in actually translates back to
* `translate3d(0,0,0) scale(1.0)`...
*
* NOTE: all values are rounded to the nearest integer
*/
calculateZoomToOrigin: function (element, originator) {
var origin = originator.element;
var bounds = originator.bounds;
var zoomTemplate = "translate3d( {centerX}px, {centerY}px, 0 ) scale( {scaleX}, {scaleY} )";
var buildZoom = angular.bind(null, $mdUtil.supplant, zoomTemplate);
var zoomStyle = buildZoom({centerX: 0, centerY: 0, scaleX: 0.5, scaleY: 0.5});
if (origin || bounds) {
var originBnds = origin ? self.clientRect(origin) || currentBounds() : self.copyRect(bounds);
var dialogRect = self.copyRect(element[0].getBoundingClientRect());
var dialogCenterPt = self.centerPointFor(dialogRect);
var originCenterPt = self.centerPointFor(originBnds);
// Build the transform to zoom from the dialog center to the origin center
zoomStyle = buildZoom({
centerX: originCenterPt.x - dialogCenterPt.x,
centerY: originCenterPt.y - dialogCenterPt.y,
scaleX: Math.round(100 * Math.min(0.5, originBnds.width / dialogRect.width))/100,
scaleY: Math.round(100 * Math.min(0.5, originBnds.height / dialogRect.height))/100
});
}
return zoomStyle;
/**
* This is a fallback if the origin information is no longer valid, then the
* origin bounds simply becomes the current bounds for the dialogContainer's parent
*/
function currentBounds() {
var cntr = element ? element.parent() : null;
var parent = cntr ? cntr.parent() : null;
return parent ? self.clientRect(parent) : null;
}
},
/**
* Enhance raw values to represent valid css stylings...
*/
toCss : function( raw ) {
var css = { };
var lookups = 'left top right bottom width height x y min-width min-height max-width max-height';
angular.forEach(raw, function(value,key) {
if ( angular.isUndefined(value) ) return;
if ( lookups.indexOf(key) >= 0 ) {
css[key] = value + 'px';
} else {
switch (key) {
case 'transition':
convertToVendor(key, $mdConstant.CSS.TRANSITION, value);
break;
case 'transform':
convertToVendor(key, $mdConstant.CSS.TRANSFORM, value);
break;
case 'transformOrigin':
convertToVendor(key, $mdConstant.CSS.TRANSFORM_ORIGIN, value);
break;
}
}
});
return css;
function convertToVendor(key, vendor, value) {
angular.forEach(vendor.split(' '), function (key) {
css[key] = value;
});
}
},
/**
* Convert the translate CSS value to key/value pair(s).
*/
toTransformCss: function (transform, addTransition, transition) {
var css = {};
angular.forEach($mdConstant.CSS.TRANSFORM.split(' '), function (key) {
css[key] = transform;
});
if (addTransition) {
transition = transition || "all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1) !important";
css['transition'] = transition;
}
return css;
},
/**
* Clone the Rect and calculate the height/width if needed
*/
copyRect: function (source, destination) {
if (!source) return null;
destination = destination || {};
angular.forEach('left top right bottom width height'.split(' '), function (key) {
destination[key] = Math.round(source[key])
});
destination.width = destination.width || (destination.right - destination.left);
destination.height = destination.height || (destination.bottom - destination.top);
return destination;
},
/**
* Calculate ClientRect of element; return null if hidden or zero size
*/
clientRect: function (element) {
var bounds = angular.element(element)[0].getBoundingClientRect();
var isPositiveSizeClientRect = function (rect) {
return rect && (rect.width > 0) && (rect.height > 0);
};
// If the event origin element has zero size, it has probably been hidden.
return isPositiveSizeClientRect(bounds) ? self.copyRect(bounds) : null;
},
/**
* Calculate 'rounded' center point of Rect
*/
centerPointFor: function (targetRect) {
return targetRect ? {
x: Math.round(targetRect.left + (targetRect.width / 2)),
y: Math.round(targetRect.top + (targetRect.height / 2))
} : { x : 0, y : 0 };
}
};
};
"use strict";
if (angular.version.minor >= 4) {
angular.module('material.core.animate', []);
} else {
(function() {
var forEach = angular.forEach;
var WEBKIT = angular.isDefined(document.documentElement.style.WebkitAppearance);
var TRANSITION_PROP = WEBKIT ? 'WebkitTransition' : 'transition';
var ANIMATION_PROP = WEBKIT ? 'WebkitAnimation' : 'animation';
var PREFIX = WEBKIT ? '-webkit-' : '';
var TRANSITION_EVENTS = (WEBKIT ? 'webkitTransitionEnd ' : '') + 'transitionend';
var ANIMATION_EVENTS = (WEBKIT ? 'webkitAnimationEnd ' : '') + 'animationend';
var $$ForceReflowFactory = ['$document', function($document) {
return function() {
return $document[0].body.clientWidth + 1;
}
}];
var $$rAFMutexFactory = ['$$rAF', function($$rAF) {
return function() {
var passed = false;
$$rAF(function() {
passed = true;
});
return function(fn) {
passed ? fn() : $$rAF(fn);
};
};
}];
var $$AnimateRunnerFactory = ['$q', '$$rAFMutex', function($q, $$rAFMutex) {
var INITIAL_STATE = 0;
var DONE_PENDING_STATE = 1;
var DONE_COMPLETE_STATE = 2;
function AnimateRunner(host) {
this.setHost(host);
this._doneCallbacks = [];
this._runInAnimationFrame = $$rAFMutex();
this._state = 0;
}
AnimateRunner.prototype = {
setHost: function(host) {
this.host = host || {};
},
done: function(fn) {
if (this._state === DONE_COMPLETE_STATE) {
fn();
} else {
this._doneCallbacks.push(fn);
}
},
progress: angular.noop,
getPromise: function() {
if (!this.promise) {
var self = this;
this.promise = $q(function(resolve, reject) {
self.done(function(status) {
status === false ? reject() : resolve();
});
});
}
return this.promise;
},
then: function(resolveHandler, rejectHandler) {
return this.getPromise().then(resolveHandler, rejectHandler);
},
'catch': function(handler) {
return this.getPromise()['catch'](handler);
},
'finally': function(handler) {
return this.getPromise()['finally'](handler);
},
pause: function() {
if (this.host.pause) {
this.host.pause();
}
},
resume: function() {
if (this.host.resume) {
this.host.resume();
}
},
end: function() {
if (this.host.end) {
this.host.end();
}
this._resolve(true);
},
cancel: function() {
if (this.host.cancel) {
this.host.cancel();
}
this._resolve(false);
},
complete: function(response) {
var self = this;
if (self._state === INITIAL_STATE) {
self._state = DONE_PENDING_STATE;
self._runInAnimationFrame(function() {
self._resolve(response);
});
}
},
_resolve: function(response) {
if (this._state !== DONE_COMPLETE_STATE) {
forEach(this._doneCallbacks, function(fn) {
fn(response);
});
this._doneCallbacks.length = 0;
this._state = DONE_COMPLETE_STATE;
}
}
};
return AnimateRunner;
}];
angular
.module('material.core.animate', [])
.factory('$$forceReflow', $$ForceReflowFactory)
.factory('$$AnimateRunner', $$AnimateRunnerFactory)
.factory('$$rAFMutex', $$rAFMutexFactory)
.factory('$animateCss', ['$window', '$$rAF', '$$AnimateRunner', '$$forceReflow', '$$jqLite', '$timeout',
function($window, $$rAF, $$AnimateRunner, $$forceReflow, $$jqLite, $timeout) {
function init(element, options) {
var temporaryStyles = [];
var node = getDomNode(element);
if (options.transitionStyle) {
temporaryStyles.push([PREFIX + 'transition', options.transitionStyle]);
}
if (options.keyframeStyle) {
temporaryStyles.push([PREFIX + 'animation', options.keyframeStyle]);
}
if (options.delay) {
temporaryStyles.push([PREFIX + 'transition-delay', options.delay + 's']);
}
if (options.duration) {
temporaryStyles.push([PREFIX + 'transition-duration', options.duration + 's']);
}
var hasCompleteStyles = options.keyframeStyle ||
(options.to && (options.duration > 0 || options.transitionStyle));
var hasCompleteClasses = !!options.addClass || !!options.removeClass;
var hasCompleteAnimation = hasCompleteStyles || hasCompleteClasses;
blockTransition(element, true);
applyAnimationFromStyles(element, options);
var animationClosed = false;
var events, eventFn;
return {
close: $window.close,
start: function() {
var runner = new $$AnimateRunner();
waitUntilQuiet(function() {
blockTransition(element, false);
if (!hasCompleteAnimation) {
return close();
}
forEach(temporaryStyles, function(entry) {
var key = entry[0];
var value = entry[1];
node.style[camelCase(key)] = value;
});
applyClasses(element, options);
var timings = computeTimings(element);
if (timings.duration === 0) {
return close();
}
var moreStyles = [];
if (options.easing) {
if (timings.transitionDuration) {
moreStyles.push([PREFIX + 'transition-timing-function', options.easing]);
}
if (timings.animationDuration) {
moreStyles.push([PREFIX + 'animation-timing-function', options.easing]);
}
}
if (options.delay && timings.animationDelay) {
moreStyles.push([PREFIX + 'animation-delay', options.delay + 's']);
}
if (options.duration && timings.animationDuration) {
moreStyles.push([PREFIX + 'animation-duration', options.duration + 's']);
}
forEach(moreStyles, function(entry) {
var key = entry[0];
var value = entry[1];
node.style[camelCase(key)] = value;
temporaryStyles.push(entry);
});
var maxDelay = timings.delay;
var maxDelayTime = maxDelay * 1000;
var maxDuration = timings.duration;
var maxDurationTime = maxDuration * 1000;
var startTime = Date.now();
events = [];
if (timings.transitionDuration) {
events.push(TRANSITION_EVENTS);
}
if (timings.animationDuration) {
events.push(ANIMATION_EVENTS);
}
events = events.join(' ');
eventFn = function(event) {
event.stopPropagation();
var ev = event.originalEvent || event;
var timeStamp = ev.timeStamp || Date.now();
var elapsedTime = parseFloat(ev.elapsedTime.toFixed(3));
if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
close();
}
};
element.on(events, eventFn);
applyAnimationToStyles(element, options);
$timeout(close, maxDelayTime + maxDurationTime * 1.5, false);
});
return runner;
function close() {
if (animationClosed) return;
animationClosed = true;
if (events && eventFn) {
element.off(events, eventFn);
}
applyClasses(element, options);
applyAnimationStyles(element, options);
forEach(temporaryStyles, function(entry) {
node.style[camelCase(entry[0])] = '';
});
runner.complete(true);
return runner;
}
}
}
}
function applyClasses(element, options) {
if (options.addClass) {
$$jqLite.addClass(element, options.addClass);
options.addClass = null;
}
if (options.removeClass) {
$$jqLite.removeClass(element, options.removeClass);
options.removeClass = null;
}
}
function computeTimings(element) {
var node = getDomNode(element);
var cs = $window.getComputedStyle(node)
var tdr = parseMaxTime(cs[prop('transitionDuration')]);
var adr = parseMaxTime(cs[prop('animationDuration')]);
var tdy = parseMaxTime(cs[prop('transitionDelay')]);
var ady = parseMaxTime(cs[prop('animationDelay')]);
adr *= (parseInt(cs[prop('animationIterationCount')], 10) || 1);
var duration = Math.max(adr, tdr);
var delay = Math.max(ady, tdy);
return {
duration: duration,
delay: delay,
animationDuration: adr,
transitionDuration: tdr,
animationDelay: ady,
transitionDelay: tdy
};
function prop(key) {
return WEBKIT ? 'Webkit' + key.charAt(0).toUpperCase() + key.substr(1)
: key;
}
}
function parseMaxTime(str) {
var maxValue = 0;
var values = (str || "").split(/\s*,\s*/);
forEach(values, function(value) {
// it's always safe to consider only second values and omit `ms` values since
// getComputedStyle will always handle the conversion for us
if (value.charAt(value.length - 1) == 's') {
value = value.substring(0, value.length - 1);
}
value = parseFloat(value) || 0;
maxValue = maxValue ? Math.max(value, maxValue) : value;
});
return maxValue;
}
var cancelLastRAFRequest;
var rafWaitQueue = [];
function waitUntilQuiet(callback) {
if (cancelLastRAFRequest) {
cancelLastRAFRequest(); //cancels the request
}
rafWaitQueue.push(callback);
cancelLastRAFRequest = $$rAF(function() {
cancelLastRAFRequest = null;
// DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable.
// PLEASE EXAMINE THE `$$forceReflow` service to understand why.
var pageWidth = $$forceReflow();
// we use a for loop to ensure that if the queue is changed
// during this looping then it will consider new requests
for (var i = 0; i < rafWaitQueue.length; i++) {
rafWaitQueue[i](pageWidth);
}
rafWaitQueue.length = 0;
});
}
function applyAnimationStyles(element, options) {
applyAnimationFromStyles(element, options);
applyAnimationToStyles(element, options);
}
function applyAnimationFromStyles(element, options) {
if (options.from) {
element.css(options.from);
options.from = null;
}
}
function applyAnimationToStyles(element, options) {
if (options.to) {
element.css(options.to);
options.to = null;
}
}
function getDomNode(element) {
for (var i = 0; i < element.length; i++) {
if (element[i].nodeType === 1) return element[i];
}
}
function blockTransition(element, bool) {
var node = getDomNode(element);
var key = camelCase(PREFIX + 'transition-delay');
node.style[key] = bool ? '-9999s' : '';
}
return init;
}]);
/**
* Older browsers [FF31] expect camelCase
* property keys.
* e.g.
* animation-duration --> animationDuration
*/
function camelCase(str) {
return str.replace(/-[a-z]/g, function(str) {
return str.charAt(1).toUpperCase();
});
}
})();
}
(function(){
angular.module("material.core").constant("$MD_THEME_CSS", "md-backdrop { background-color: '{{background-900-0.0}}'; } md-backdrop.md-opaque.md-THEME_NAME-theme { background-color: '{{background-900-1.0}}'; }md-autocomplete.md-THEME_NAME-theme { background: '{{background-50}}'; } md-autocomplete.md-THEME_NAME-theme[disabled] { background: '{{background-100}}'; } md-autocomplete.md-THEME_NAME-theme button md-icon path { fill: '{{background-600}}'; } md-autocomplete.md-THEME_NAME-theme button:after { background: '{{background-600-0.3}}'; }.md-autocomplete-suggestions-container.md-THEME_NAME-theme { background: '{{background-50}}'; } .md-autocomplete-suggestions-container.md-THEME_NAME-theme li { color: '{{background-900}}'; } .md-autocomplete-suggestions-container.md-THEME_NAME-theme li .highlight { color: '{{background-600}}'; } .md-autocomplete-suggestions-container.md-THEME_NAME-theme li:hover, .md-autocomplete-suggestions-container.md-THEME_NAME-theme li.selected { background: '{{background-200}}'; }md-bottom-sheet.md-THEME_NAME-theme { background-color: '{{background-50}}'; border-top-color: '{{background-300}}'; } md-bottom-sheet.md-THEME_NAME-theme.md-list md-list-item { color: '{{foreground-1}}'; } md-bottom-sheet.md-THEME_NAME-theme .md-subheader { background-color: '{{background-50}}'; } md-bottom-sheet.md-THEME_NAME-theme .md-subheader { color: '{{foreground-1}}'; }a.md-button.md-THEME_NAME-theme:not([disabled]):hover,.md-button.md-THEME_NAME-theme:not([disabled]):hover { background-color: '{{background-500-0.2}}'; }a.md-button.md-THEME_NAME-theme:not([disabled]).md-focused,.md-button.md-THEME_NAME-theme:not([disabled]).md-focused { background-color: '{{background-500-0.2}}'; }a.md-button.md-THEME_NAME-theme:not([disabled]).md-icon-button:hover,.md-button.md-THEME_NAME-theme:not([disabled]).md-icon-button:hover { background-color: transparent; }a.md-button.md-THEME_NAME-theme.md-fab,.md-button.md-THEME_NAME-theme.md-fab { background-color: '{{accent-color}}'; color: '{{accent-contrast}}'; } a.md-button.md-THEME_NAME-theme.md-fab md-icon, .md-button.md-THEME_NAME-theme.md-fab md-icon { color: '{{accent-contrast}}'; } a.md-button.md-THEME_NAME-theme.md-fab:not([disabled]):hover, .md-button.md-THEME_NAME-theme.md-fab:not([disabled]):hover { background-color: '{{accent-color}}'; } a.md-button.md-THEME_NAME-theme.md-fab:not([disabled]).md-focused, .md-button.md-THEME_NAME-theme.md-fab:not([disabled]).md-focused { background-color: '{{accent-A700}}'; }a.md-button.md-THEME_NAME-theme.md-primary,.md-button.md-THEME_NAME-theme.md-primary { color: '{{primary-color}}'; } a.md-button.md-THEME_NAME-theme.md-primary.md-raised, a.md-button.md-THEME_NAME-theme.md-primary.md-fab, .md-button.md-THEME_NAME-theme.md-primary.md-raised, .md-button.md-THEME_NAME-theme.md-primary.md-fab { color: '{{primary-contrast}}'; background-color: '{{primary-color}}'; } a.md-button.md-THEME_NAME-theme.md-primary.md-raised:not([disabled]) md-icon, a.md-button.md-THEME_NAME-theme.md-primary.md-fab:not([disabled]) md-icon, .md-button.md-THEME_NAME-theme.md-primary.md-raised:not([disabled]) md-icon, .md-button.md-THEME_NAME-theme.md-primary.md-fab:not([disabled]) md-icon { color: '{{primary-contrast}}'; } a.md-button.md-THEME_NAME-theme.md-primary.md-raised:not([disabled]):hover, a.md-button.md-THEME_NAME-theme.md-primary.md-fab:not([disabled]):hover, .md-button.md-THEME_NAME-theme.md-primary.md-raised:not([disabled]):hover, .md-button.md-THEME_NAME-theme.md-primary.md-fab:not([disabled]):hover { background-color: '{{primary-color}}'; } a.md-button.md-THEME_NAME-theme.md-primary.md-raised:not([disabled]).md-focused, a.md-button.md-THEME_NAME-theme.md-primary.md-fab:not([disabled]).md-focused, .md-button.md-THEME_NAME-theme.md-primary.md-raised:not([disabled]).md-focused, .md-button.md-THEME_NAME-theme.md-primary.md-fab:not([disabled]).md-focused { background-color: '{{primary-600}}'; } a.md-button.md-THEME_NAME-theme.md-primary:not([disabled]) md-icon, .md-button.md-THEME_NAME-theme.md-primary:not([disabled]) md-icon { color: '{{primary-color}}'; }a.md-button.md-THEME_NAME-theme.md-fab,.md-button.md-THEME_NAME-theme.md-fab { background-color: '{{accent-color}}'; color: '{{accent-contrast}}'; } a.md-button.md-THEME_NAME-theme.md-fab:not([disabled]) .md-icon, .md-button.md-THEME_NAME-theme.md-fab:not([disabled]) .md-icon { color: '{{accent-contrast}}'; } a.md-button.md-THEME_NAME-theme.md-fab:not([disabled]):hover, .md-button.md-THEME_NAME-theme.md-fab:not([disabled]):hover { background-color: '{{accent-color}}'; } a.md-button.md-THEME_NAME-theme.md-fab:not([disabled]).md-focused, .md-button.md-THEME_NAME-theme.md-fab:not([disabled]).md-focused { background-color: '{{accent-A700}}'; }a.md-button.md-THEME_NAME-theme.md-raised,.md-button.md-THEME_NAME-theme.md-raised { color: '{{background-900}}'; background-color: '{{background-50}}'; } a.md-button.md-THEME_NAME-theme.md-raised:not([disabled]) .md-icon, .md-button.md-THEME_NAME-theme.md-raised:not([disabled]) .md-icon { color: '{{background-contrast}}'; } a.md-button.md-THEME_NAME-theme.md-raised:not([disabled]):hover, .md-button.md-THEME_NAME-theme.md-raised:not([disabled]):hover { background-color: '{{background-50}}'; } a.md-button.md-THEME_NAME-theme.md-raised:not([disabled]).md-focused, .md-button.md-THEME_NAME-theme.md-raised:not([disabled]).md-focused { background-color: '{{background-200}}'; }a.md-button.md-THEME_NAME-theme.md-warn,.md-button.md-THEME_NAME-theme.md-warn { color: '{{warn-color}}'; } a.md-button.md-THEME_NAME-theme.md-warn.md-raised, a.md-button.md-THEME_NAME-theme.md-warn.md-fab, .md-button.md-THEME_NAME-theme.md-warn.md-raised, .md-button.md-THEME_NAME-theme.md-warn.md-fab { color: '{{warn-contrast}}'; background-color: '{{warn-color}}'; } a.md-button.md-THEME_NAME-theme.md-warn.md-raised:not([disabled]) md-icon, a.md-button.md-THEME_NAME-theme.md-warn.md-fab:not([disabled]) md-icon, .md-button.md-THEME_NAME-theme.md-warn.md-raised:not([disabled]) md-icon, .md-button.md-THEME_NAME-theme.md-warn.md-fab:not([disabled]) md-icon { color: '{{warn-contrast}}'; } a.md-button.md-THEME_NAME-theme.md-warn.md-raised:not([disabled]):hover, a.md-button.md-THEME_NAME-theme.md-warn.md-fab:not([disabled]):hover, .md-button.md-THEME_NAME-theme.md-warn.md-raised:not([disabled]):hover, .md-button.md-THEME_NAME-theme.md-warn.md-fab:not([disabled]):hover { background-color: '{{warn-color}}'; } a.md-button.md-THEME_NAME-theme.md-warn.md-raised:not([disabled]).md-focused, a.md-button.md-THEME_NAME-theme.md-warn.md-fab:not([disabled]).md-focused, .md-button.md-THEME_NAME-theme.md-warn.md-raised:not([disabled]).md-focused, .md-button.md-THEME_NAME-theme.md-warn.md-fab:not([disabled]).md-focused { background-color: '{{warn-700}}'; } a.md-button.md-THEME_NAME-theme.md-warn:not([disabled]) md-icon, .md-button.md-THEME_NAME-theme.md-warn:not([disabled]) md-icon { color: '{{warn-color}}'; }a.md-button.md-THEME_NAME-theme.md-accent,.md-button.md-THEME_NAME-theme.md-accent { color: '{{accent-color}}'; } a.md-button.md-THEME_NAME-theme.md-accent.md-raised, a.md-button.md-THEME_NAME-theme.md-accent.md-fab, .md-button.md-THEME_NAME-theme.md-accent.md-raised, .md-button.md-THEME_NAME-theme.md-accent.md-fab { color: '{{accent-contrast}}'; background-color: '{{accent-color}}'; } a.md-button.md-THEME_NAME-theme.md-accent.md-raised:not([disabled]) md-icon, a.md-button.md-THEME_NAME-theme.md-accent.md-fab:not([disabled]) md-icon, .md-button.md-THEME_NAME-theme.md-accent.md-raised:not([disabled]) md-icon, .md-button.md-THEME_NAME-theme.md-accent.md-fab:not([disabled]) md-icon { color: '{{accent-contrast}}'; } a.md-button.md-THEME_NAME-theme.md-accent.md-raised:not([disabled]):hover, a.md-button.md-THEME_NAME-theme.md-accent.md-fab:not([disabled]):hover, .md-button.md-THEME_NAME-theme.md-accent.md-raised:not([disabled]):hover, .md-button.md-THEME_NAME-theme.md-accent.md-fab:not([disabled]):hover { background-color: '{{accent-color}}'; } a.md-button.md-THEME_NAME-theme.md-accent.md-raised:not([disabled]).md-focused, a.md-button.md-THEME_NAME-theme.md-accent.md-fab:not([disabled]).md-focused, .md-button.md-THEME_NAME-theme.md-accent.md-raised:not([disabled]).md-focused, .md-button.md-THEME_NAME-theme.md-accent.md-fab:not([disabled]).md-focused { background-color: '{{accent-700}}'; } a.md-button.md-THEME_NAME-theme.md-accent:not([disabled]) md-icon, .md-button.md-THEME_NAME-theme.md-accent:not([disabled]) md-icon { color: '{{accent-color}}'; }a.md-button.md-THEME_NAME-theme[disabled], a.md-button.md-THEME_NAME-theme.md-raised[disabled], a.md-button.md-THEME_NAME-theme.md-fab[disabled], a.md-button.md-THEME_NAME-theme.md-accent[disabled], a.md-button.md-THEME_NAME-theme.md-warn[disabled],.md-button.md-THEME_NAME-theme[disabled],.md-button.md-THEME_NAME-theme.md-raised[disabled],.md-button.md-THEME_NAME-theme.md-fab[disabled],.md-button.md-THEME_NAME-theme.md-accent[disabled],.md-button.md-THEME_NAME-theme.md-warn[disabled] { color: '{{foreground-3}}' !important; cursor: default; } a.md-button.md-THEME_NAME-theme[disabled] md-icon, a.md-button.md-THEME_NAME-theme.md-raised[disabled] md-icon, a.md-button.md-THEME_NAME-theme.md-fab[disabled] md-icon, a.md-button.md-THEME_NAME-theme.md-accent[disabled] md-icon, a.md-button.md-THEME_NAME-theme.md-warn[disabled] md-icon, .md-button.md-THEME_NAME-theme[disabled] md-icon, .md-button.md-THEME_NAME-theme.md-raised[disabled] md-icon, .md-button.md-THEME_NAME-theme.md-fab[disabled] md-icon, .md-button.md-THEME_NAME-theme.md-accent[disabled] md-icon, .md-button.md-THEME_NAME-theme.md-warn[disabled] md-icon { color: '{{foreground-3}}'; }a.md-button.md-THEME_NAME-theme.md-raised[disabled], a.md-button.md-THEME_NAME-theme.md-fab[disabled],.md-button.md-THEME_NAME-theme.md-raised[disabled],.md-button.md-THEME_NAME-theme.md-fab[disabled] { background-color: '{{foreground-4}}'; }a.md-button.md-THEME_NAME-theme[disabled],.md-button.md-THEME_NAME-theme[disabled] { background-color: transparent; }md-card.md-THEME_NAME-theme { background-color: '{{background-color}}'; border-radius: 2px; } md-card.md-THEME_NAME-theme .md-card-image { border-radius: 2px 2px 0 0; } md-card.md-THEME_NAME-theme md-card-header md-card-avatar md-icon { color: '{{background-color}}'; background-color: '{{foreground-3}}'; } md-card.md-THEME_NAME-theme md-card-header md-card-header-text .md-subhead { color: '{{foreground-2}}'; } md-card.md-THEME_NAME-theme md-card-title md-card-title-text:not(:only-child) .md-subhead { color: '{{foreground-2}}'; }md-checkbox.md-THEME_NAME-theme .md-ripple { color: '{{accent-600}}'; }md-checkbox.md-THEME_NAME-theme.md-checked .md-ripple { color: '{{background-600}}'; }md-checkbox.md-THEME_NAME-theme.md-checked.md-focused .md-container:before { background-color: '{{accent-color-0.26}}'; }md-checkbox.md-THEME_NAME-theme .md-ink-ripple { color: '{{foreground-2}}'; }md-checkbox.md-THEME_NAME-theme.md-checked .md-ink-ripple { color: '{{accent-color-0.87}}'; }md-checkbox.md-THEME_NAME-theme .md-icon { border-color: '{{foreground-2}}'; }md-checkbox.md-THEME_NAME-theme.md-checked .md-icon { background-color: '{{accent-color-0.87}}'; }md-checkbox.md-THEME_NAME-theme.md-checked .md-icon:after { border-color: '{{accent-contrast-0.87}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-primary .md-ripple { color: '{{primary-600}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-ripple { color: '{{background-600}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-primary .md-ink-ripple { color: '{{foreground-2}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-ink-ripple { color: '{{primary-color-0.87}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-primary .md-icon { border-color: '{{foreground-2}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-icon { background-color: '{{primary-color-0.87}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked.md-focused .md-container:before { background-color: '{{primary-color-0.26}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-icon:after { border-color: '{{primary-contrast-0.87}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-warn .md-ripple { color: '{{warn-600}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-warn .md-ink-ripple { color: '{{foreground-2}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-ink-ripple { color: '{{warn-color-0.87}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-warn .md-icon { border-color: '{{foreground-2}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-icon { background-color: '{{warn-color-0.87}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked.md-focused:not([disabled]) .md-container:before { background-color: '{{warn-color-0.26}}'; }md-checkbox.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-icon:after { border-color: '{{background-200}}'; }md-checkbox.md-THEME_NAME-theme[disabled] .md-icon { border-color: '{{foreground-3}}'; }md-checkbox.md-THEME_NAME-theme[disabled].md-checked .md-icon { background-color: '{{foreground-3}}'; }md-checkbox.md-THEME_NAME-theme[disabled].md-checked .md-icon:after { border-color: '{{background-200}}'; }md-checkbox.md-THEME_NAME-theme[disabled] .md-label { color: '{{foreground-3}}'; }md-chips.md-THEME_NAME-theme .md-chips { box-shadow: 0 1px '{{background-300}}'; } md-chips.md-THEME_NAME-theme .md-chips.md-focused { box-shadow: 0 2px '{{primary-color}}'; }md-chips.md-THEME_NAME-theme .md-chip { background: '{{background-300}}'; color: '{{background-800}}'; } md-chips.md-THEME_NAME-theme .md-chip.md-focused { background: '{{primary-color}}'; color: '{{primary-contrast}}'; } md-chips.md-THEME_NAME-theme .md-chip.md-focused md-icon { color: '{{primary-contrast}}'; }md-chips.md-THEME_NAME-theme md-chip-remove .md-button md-icon path { fill: '{{background-500}}'; }.md-contact-suggestion span.md-contact-email { color: '{{background-400}}'; }md-content.md-THEME_NAME-theme { color: '{{foreground-1}}'; background-color: '{{background-color}}'; }/** Theme styles for mdCalendar. */.md-calendar.md-THEME_NAME-theme { color: '{{foreground-1}}'; } .md-calendar.md-THEME_NAME-theme tr:last-child td { border-bottom-color: '{{background-200}}'; }.md-THEME_NAME-theme .md-calendar-day-header { background: '{{background-hue-1}}'; color: '{{foreground-1}}'; }.md-THEME_NAME-theme .md-calendar-date.md-calendar-date-today .md-calendar-date-selection-indicator { border: 1px solid '{{primary-500}}'; }.md-THEME_NAME-theme .md-calendar-date.md-calendar-date-today.md-calendar-date-disabled { color: '{{primary-500-0.6}}'; }.md-THEME_NAME-theme .md-calendar-date.md-focus .md-calendar-date-selection-indicator { background: '{{background-hue-1}}'; }.md-THEME_NAME-theme .md-calendar-date-selection-indicator:hover { background: '{{background-hue-1}}'; }.md-THEME_NAME-theme .md-calendar-date.md-calendar-selected-date .md-calendar-date-selection-indicator,.md-THEME_NAME-theme .md-calendar-date.md-focus.md-calendar-selected-date .md-calendar-date-selection-indicator { background: '{{primary-500}}'; color: '{{primary-500-contrast}}'; border-color: transparent; }.md-THEME_NAME-theme .md-calendar-date-disabled,.md-THEME_NAME-theme .md-calendar-month-label-disabled { color: '{{foreground-3}}'; }/** Theme styles for mdDatepicker. */md-datepicker.md-THEME_NAME-theme { background: '{{background-color}}'; }.md-THEME_NAME-theme .md-datepicker-input { color: '{{background-contrast}}'; background: '{{background-color}}'; } .md-THEME_NAME-theme .md-datepicker-input::-webkit-input-placeholder, .md-THEME_NAME-theme .md-datepicker-input::-moz-placeholder, .md-THEME_NAME-theme .md-datepicker-input:-moz-placeholder, .md-THEME_NAME-theme .md-datepicker-input:-ms-input-placeholder { color: \"{{foreground-3}}\"; }.md-THEME_NAME-theme .md-datepicker-input-container { border-bottom-color: '{{background-300}}'; } .md-THEME_NAME-theme .md-datepicker-input-container.md-datepicker-focused { border-bottom-color: '{{primary-500}}'; } .md-THEME_NAME-theme .md-datepicker-input-container.md-datepicker-invalid { border-bottom-color: '{{warn-A700}}'; }.md-THEME_NAME-theme .md-datepicker-calendar-pane { border-color: '{{background-300}}'; }.md-THEME_NAME-theme .md-datepicker-triangle-button .md-datepicker-expand-triangle { border-top-color: '{{foreground-3}}'; }.md-THEME_NAME-theme .md-datepicker-triangle-button:hover .md-datepicker-expand-triangle { border-top-color: '{{foreground-2}}'; }.md-THEME_NAME-theme .md-datepicker-open .md-datepicker-calendar-icon { fill: '{{primary-500}}'; }.md-THEME_NAME-theme .md-datepicker-calendar,.md-THEME_NAME-theme .md-datepicker-input-mask-opaque { background: '{{background-color}}'; }md-dialog.md-THEME_NAME-theme { border-radius: 4px; background-color: '{{background-color}}'; } md-dialog.md-THEME_NAME-theme.md-content-overflow .md-actions, md-dialog.md-THEME_NAME-theme.md-content-overflow md-dialog-actions { border-top-color: '{{foreground-4}}'; }md-divider.md-THEME_NAME-theme { border-top-color: '{{foreground-4}}'; }.layout-row > md-divider.md-THEME_NAME-theme { border-right-color: '{{foreground-4}}'; }md-icon.md-THEME_NAME-theme { color: '{{foreground-2}}'; } md-icon.md-THEME_NAME-theme.md-primary { color: '{{primary-color}}'; } md-icon.md-THEME_NAME-theme.md-accent { color: '{{accent-color}}'; } md-icon.md-THEME_NAME-theme.md-warn { color: '{{warn-color}}'; }md-input-container.md-THEME_NAME-theme .md-input { color: '{{foreground-1}}'; border-color: '{{foreground-4}}'; text-shadow: '{{foreground-shadow}}'; } md-input-container.md-THEME_NAME-theme .md-input::-webkit-input-placeholder, md-input-container.md-THEME_NAME-theme .md-input::-moz-placeholder, md-input-container.md-THEME_NAME-theme .md-input:-moz-placeholder, md-input-container.md-THEME_NAME-theme .md-input:-ms-input-placeholder { color: \"{{foreground-3}}\"; }md-input-container.md-THEME_NAME-theme > md-icon { color: '{{foreground-1}}'; }md-input-container.md-THEME_NAME-theme label,md-input-container.md-THEME_NAME-theme .md-placeholder { text-shadow: '{{foreground-shadow}}'; color: '{{foreground-3}}'; }md-input-container.md-THEME_NAME-theme ng-messages :not(.md-char-counter), md-input-container.md-THEME_NAME-theme [ng-messages] :not(.md-char-counter),md-input-container.md-THEME_NAME-theme ng-message :not(.md-char-counter), md-input-container.md-THEME_NAME-theme data-ng-message :not(.md-char-counter), md-input-container.md-THEME_NAME-theme x-ng-message :not(.md-char-counter),md-input-container.md-THEME_NAME-theme [ng-message] :not(.md-char-counter), md-input-container.md-THEME_NAME-theme [data-ng-message] :not(.md-char-counter), md-input-container.md-THEME_NAME-theme [x-ng-message] :not(.md-char-counter),md-input-container.md-THEME_NAME-theme [ng-message-exp] :not(.md-char-counter), md-input-container.md-THEME_NAME-theme [data-ng-message-exp] :not(.md-char-counter), md-input-container.md-THEME_NAME-theme [x-ng-message-exp] :not(.md-char-counter) { color: '{{warn-A700}}'; }md-input-container.md-THEME_NAME-theme:not(.md-input-invalid).md-input-has-value label { color: '{{foreground-2}}'; }md-input-container.md-THEME_NAME-theme:not(.md-input-invalid).md-input-focused .md-input { border-color: '{{primary-500}}'; }md-input-container.md-THEME_NAME-theme:not(.md-input-invalid).md-input-focused label { color: '{{primary-500}}'; }md-input-container.md-THEME_NAME-theme:not(.md-input-invalid).md-input-focused md-icon { color: '{{primary-500}}'; }md-input-container.md-THEME_NAME-theme:not(.md-input-invalid).md-input-focused.md-accent .md-input { border-color: '{{accent-500}}'; }md-input-container.md-THEME_NAME-theme:not(.md-input-invalid).md-input-focused.md-accent label { color: '{{accent-500}}'; }md-input-container.md-THEME_NAME-theme:not(.md-input-invalid).md-input-focused.md-warn .md-input { border-color: '{{warn-A700}}'; }md-input-container.md-THEME_NAME-theme:not(.md-input-invalid).md-input-focused.md-warn label { color: '{{warn-A700}}'; }md-input-container.md-THEME_NAME-theme.md-input-invalid .md-input { border-color: '{{warn-A700}}'; }md-input-container.md-THEME_NAME-theme.md-input-invalid.md-input-focused label { color: '{{warn-A700}}'; }md-input-container.md-THEME_NAME-theme.md-input-invalid ng-message, md-input-container.md-THEME_NAME-theme.md-input-invalid data-ng-message, md-input-container.md-THEME_NAME-theme.md-input-invalid x-ng-message,md-input-container.md-THEME_NAME-theme.md-input-invalid [ng-message], md-input-container.md-THEME_NAME-theme.md-input-invalid [data-ng-message], md-input-container.md-THEME_NAME-theme.md-input-invalid [x-ng-message],md-input-container.md-THEME_NAME-theme.md-input-invalid [ng-message-exp], md-input-container.md-THEME_NAME-theme.md-input-invalid [data-ng-message-exp], md-input-container.md-THEME_NAME-theme.md-input-invalid [x-ng-message-exp],md-input-container.md-THEME_NAME-theme.md-input-invalid .md-char-counter { color: '{{warn-A700}}'; }md-input-container.md-THEME_NAME-theme .md-input[disabled],md-input-container.md-THEME_NAME-theme .md-input [disabled] { border-bottom-color: transparent; color: '{{foreground-3}}'; background-image: linear-gradient(to right, \"{{foreground-3}}\" 0%, \"{{foreground-3}}\" 33%, transparent 0%); background-image: -ms-linear-gradient(left, transparent 0%, \"{{foreground-3}}\" 100%); }md-list.md-THEME_NAME-theme md-list-item.md-2-line .md-list-item-text h3, md-list.md-THEME_NAME-theme md-list-item.md-2-line .md-list-item-text h4,md-list.md-THEME_NAME-theme md-list-item.md-3-line .md-list-item-text h3,md-list.md-THEME_NAME-theme md-list-item.md-3-line .md-list-item-text h4 { color: '{{foreground-1}}'; }md-list.md-THEME_NAME-theme md-list-item.md-2-line .md-list-item-text p,md-list.md-THEME_NAME-theme md-list-item.md-3-line .md-list-item-text p { color: '{{foreground-2}}'; }md-list.md-THEME_NAME-theme .md-proxy-focus.md-focused div.md-no-style { background-color: '{{background-100}}'; }md-list.md-THEME_NAME-theme md-list-item > .md-avatar-icon { background-color: '{{foreground-3}}'; color: '{{background-color}}'; }md-list.md-THEME_NAME-theme md-list-item > md-icon { color: '{{foreground-2}}'; } md-list.md-THEME_NAME-theme md-list-item > md-icon.md-highlight { color: '{{primary-color}}'; } md-list.md-THEME_NAME-theme md-list-item > md-icon.md-highlight.md-accent { color: '{{accent-color}}'; }md-menu-content.md-THEME_NAME-theme { background-color: '{{background-color}}'; } md-menu-content.md-THEME_NAME-theme md-menu-divider { background-color: '{{foreground-4}}'; }md-menu-bar.md-THEME_NAME-theme > button.md-button { color: '{{foreground-2}}'; border-radius: 2px; }md-menu-bar.md-THEME_NAME-theme md-menu.md-open > button, md-menu-bar.md-THEME_NAME-theme md-menu > button:focus { outline: none; background: '{{background-200}}'; }md-menu-bar.md-THEME_NAME-theme.md-open:not(.md-keyboard-mode) md-menu:hover > button { background-color: '{{ background-500-0.2}}'; }md-menu-bar.md-THEME_NAME-theme:not(.md-keyboard-mode):not(.md-open) md-menu button:hover,md-menu-bar.md-THEME_NAME-theme:not(.md-keyboard-mode):not(.md-open) md-menu button:focus { background: transparent; }md-menu-content.md-THEME_NAME-theme .md-menu > .md-button:after { color: '{{foreground-2}}'; }md-menu-content.md-THEME_NAME-theme .md-menu.md-open > .md-button { background-color: '{{ background-500-0.2}}'; }md-toolbar.md-THEME_NAME-theme.md-menu-toolbar { background-color: '{{background-color}}'; color: '{{foreground-1}}'; } md-toolbar.md-THEME_NAME-theme.md-menu-toolbar md-toolbar-filler { background-color: '{{primary-color}}'; color: '{{primary-contrast}}'; } md-toolbar.md-THEME_NAME-theme.md-menu-toolbar md-toolbar-filler md-icon { color: '{{primary-contrast}}'; }md-progress-circular.md-THEME_NAME-theme { background-color: transparent; } md-progress-circular.md-THEME_NAME-theme .md-inner .md-gap { border-top-color: '{{primary-color}}'; border-bottom-color: '{{primary-color}}'; } md-progress-circular.md-THEME_NAME-theme .md-inner .md-left .md-half-circle, md-progress-circular.md-THEME_NAME-theme .md-inner .md-right .md-half-circle { border-top-color: '{{primary-color}}'; } md-progress-circular.md-THEME_NAME-theme .md-inner .md-right .md-half-circle { border-right-color: '{{primary-color}}'; } md-progress-circular.md-THEME_NAME-theme .md-inner .md-left .md-half-circle { border-left-color: '{{primary-color}}'; } md-progress-circular.md-THEME_NAME-theme.md-warn .md-inner .md-gap { border-top-color: '{{warn-color}}'; border-bottom-color: '{{warn-color}}'; } md-progress-circular.md-THEME_NAME-theme.md-warn .md-inner .md-left .md-half-circle, md-progress-circular.md-THEME_NAME-theme.md-warn .md-inner .md-right .md-half-circle { border-top-color: '{{warn-color}}'; } md-progress-circular.md-THEME_NAME-theme.md-warn .md-inner .md-right .md-half-circle { border-right-color: '{{warn-color}}'; } md-progress-circular.md-THEME_NAME-theme.md-warn .md-inner .md-left .md-half-circle { border-left-color: '{{warn-color}}'; } md-progress-circular.md-THEME_NAME-theme.md-accent .md-inner .md-gap { border-top-color: '{{accent-color}}'; border-bottom-color: '{{accent-color}}'; } md-progress-circular.md-THEME_NAME-theme.md-accent .md-inner .md-left .md-half-circle, md-progress-circular.md-THEME_NAME-theme.md-accent .md-inner .md-right .md-half-circle { border-top-color: '{{accent-color}}'; } md-progress-circular.md-THEME_NAME-theme.md-accent .md-inner .md-right .md-half-circle { border-right-color: '{{accent-color}}'; } md-progress-circular.md-THEME_NAME-theme.md-accent .md-inner .md-left .md-half-circle { border-left-color: '{{accent-color}}'; }md-progress-linear.md-THEME_NAME-theme .md-container { background-color: '{{primary-100}}'; }md-progress-linear.md-THEME_NAME-theme .md-bar { background-color: '{{primary-color}}'; }md-progress-linear.md-THEME_NAME-theme.md-warn .md-container { background-color: '{{warn-100}}'; }md-progress-linear.md-THEME_NAME-theme.md-warn .md-bar { background-color: '{{warn-color}}'; }md-progress-linear.md-THEME_NAME-theme.md-accent .md-container { background-color: '{{accent-100}}'; }md-progress-linear.md-THEME_NAME-theme.md-accent .md-bar { background-color: '{{accent-color}}'; }md-progress-linear.md-THEME_NAME-theme[md-mode=buffer].md-warn .md-bar1 { background-color: '{{warn-100}}'; }md-progress-linear.md-THEME_NAME-theme[md-mode=buffer].md-warn .md-dashed:before { background: radial-gradient(\"{{warn-100}}\" 0%, \"{{warn-100}}\" 16%, transparent 42%); }md-progress-linear.md-THEME_NAME-theme[md-mode=buffer].md-accent .md-bar1 { background-color: '{{accent-100}}'; }md-progress-linear.md-THEME_NAME-theme[md-mode=buffer].md-accent .md-dashed:before { background: radial-gradient(\"{{accent-100}}\" 0%, \"{{accent-100}}\" 16%, transparent 42%); }md-radio-button.md-THEME_NAME-theme .md-off { border-color: '{{foreground-2}}'; }md-radio-button.md-THEME_NAME-theme .md-on { background-color: '{{accent-color-0.87}}'; }md-radio-button.md-THEME_NAME-theme.md-checked .md-off { border-color: '{{accent-color-0.87}}'; }md-radio-button.md-THEME_NAME-theme.md-checked .md-ink-ripple { color: '{{accent-color-0.87}}'; }md-radio-button.md-THEME_NAME-theme .md-container .md-ripple { color: '{{accent-600}}'; }md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-on, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-on,md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-on,md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-on { background-color: '{{primary-color-0.87}}'; }md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-off,md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-off,md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-off,md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-off,md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-off { border-color: '{{primary-color-0.87}}'; }md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-ink-ripple,md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-ink-ripple,md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-ink-ripple,md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-ink-ripple,md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-ink-ripple { color: '{{primary-color-0.87}}'; }md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-container .md-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-container .md-ripple,md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-container .md-ripple,md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-container .md-ripple { color: '{{primary-600}}'; }md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-on, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-on,md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-on,md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-on { background-color: '{{warn-color-0.87}}'; }md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-off,md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-off,md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-off,md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-off,md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-off { border-color: '{{warn-color-0.87}}'; }md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-ink-ripple,md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-ink-ripple,md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-ink-ripple,md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-ink-ripple,md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-ink-ripple { color: '{{warn-color-0.87}}'; }md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-container .md-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-container .md-ripple,md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-container .md-ripple,md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-container .md-ripple { color: '{{warn-600}}'; }md-radio-group.md-THEME_NAME-theme[disabled],md-radio-button.md-THEME_NAME-theme[disabled] { color: '{{foreground-3}}'; } md-radio-group.md-THEME_NAME-theme[disabled] .md-container .md-off, md-radio-button.md-THEME_NAME-theme[disabled] .md-container .md-off { border-color: '{{foreground-3}}'; } md-radio-group.md-THEME_NAME-theme[disabled] .md-container .md-on, md-radio-button.md-THEME_NAME-theme[disabled] .md-container .md-on { border-color: '{{foreground-3}}'; }md-radio-group.md-THEME_NAME-theme .md-checked .md-ink-ripple { color: '{{accent-color-0.26}}'; }md-radio-group.md-THEME_NAME-theme.md-primary .md-checked:not([disabled]) .md-ink-ripple, md-radio-group.md-THEME_NAME-theme .md-checked:not([disabled]).md-primary .md-ink-ripple { color: '{{primary-color-0.26}}'; }md-radio-group.md-THEME_NAME-theme .md-checked.md-primary .md-ink-ripple { color: '{{warn-color-0.26}}'; }md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty) .md-checked .md-container:before { background-color: '{{accent-color-0.26}}'; }md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty).md-primary .md-checked .md-container:before,md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty) .md-checked.md-primary .md-container:before { background-color: '{{primary-color-0.26}}'; }md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty).md-warn .md-checked .md-container:before,md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty) .md-checked.md-warn .md-container:before { background-color: '{{warn-color-0.26}}'; }md-select.md-THEME_NAME-theme[disabled] .md-select-value { border-bottom-color: transparent; background-image: linear-gradient(to right, \"{{foreground-3}}\" 0%, \"{{foreground-3}}\" 33%, transparent 0%); background-image: -ms-linear-gradient(left, transparent 0%, \"{{foreground-3}}\" 100%); }md-select.md-THEME_NAME-theme .md-select-value { border-bottom-color: '{{foreground-4}}'; } md-select.md-THEME_NAME-theme .md-select-value.md-select-placeholder { color: '{{foreground-3}}'; }md-select.md-THEME_NAME-theme.ng-invalid.ng-dirty .md-select-value { color: '{{warn-A700}}' !important; border-bottom-color: '{{warn-A700}}' !important; }md-select.md-THEME_NAME-theme:not([disabled]):focus .md-select-value { border-bottom-color: '{{primary-color}}'; color: '{{ foreground-1 }}'; } md-select.md-THEME_NAME-theme:not([disabled]):focus .md-select-value.md-select-placeholder { color: '{{ foreground-1 }}'; }md-select.md-THEME_NAME-theme:not([disabled]):focus.md-accent .md-select-value { border-bottom-color: '{{accent-color}}'; }md-select.md-THEME_NAME-theme:not([disabled]):focus.md-warn .md-select-value { border-bottom-color: '{{warn-color}}'; }md-select.md-THEME_NAME-theme[disabled] .md-select-value { color: '{{foreground-3}}'; } md-select.md-THEME_NAME-theme[disabled] .md-select-value.md-select-placeholder { color: '{{foreground-3}}'; }md-select-menu.md-THEME_NAME-theme md-option[disabled] { color: '{{foreground-3}}'; }md-select-menu.md-THEME_NAME-theme md-optgroup { color: '{{foreground-2}}'; } md-select-menu.md-THEME_NAME-theme md-optgroup md-option { color: '{{foreground-1}}'; }md-select-menu.md-THEME_NAME-theme md-option[selected] { color: '{{primary-500}}'; } md-select-menu.md-THEME_NAME-theme md-option[selected]:focus { color: '{{primary-600}}'; } md-select-menu.md-THEME_NAME-theme md-option[selected].md-accent { color: '{{accent-500}}'; } md-select-menu.md-THEME_NAME-theme md-option[selected].md-accent:focus { color: '{{accent-600}}'; }md-select-menu.md-THEME_NAME-theme md-option:focus:not([disabled]):not([selected]) { background: '{{background-200}}'; }md-sidenav.md-THEME_NAME-theme { background-color: '{{background-color}}'; }md-slider.md-THEME_NAME-theme .md-track { background-color: '{{foreground-3}}'; }md-slider.md-THEME_NAME-theme .md-track-ticks { background-color: '{{foreground-4}}'; }md-slider.md-THEME_NAME-theme .md-focus-thumb { background-color: '{{foreground-2}}'; }md-slider.md-THEME_NAME-theme .md-focus-ring { background-color: '{{accent-color}}'; }md-slider.md-THEME_NAME-theme .md-disabled-thumb { border-color: '{{background-color}}'; }md-slider.md-THEME_NAME-theme.md-min .md-thumb:after { background-color: '{{background-color}}'; }md-slider.md-THEME_NAME-theme .md-track.md-track-fill { background-color: '{{accent-color}}'; }md-slider.md-THEME_NAME-theme .md-thumb:after { border-color: '{{accent-color}}'; background-color: '{{accent-color}}'; }md-slider.md-THEME_NAME-theme .md-sign { background-color: '{{accent-color}}'; } md-slider.md-THEME_NAME-theme .md-sign:after { border-top-color: '{{accent-color}}'; }md-slider.md-THEME_NAME-theme .md-thumb-text { color: '{{accent-contrast}}'; }md-slider.md-THEME_NAME-theme.md-warn .md-focus-ring { background-color: '{{warn-color}}'; }md-slider.md-THEME_NAME-theme.md-warn .md-track.md-track-fill { background-color: '{{warn-color}}'; }md-slider.md-THEME_NAME-theme.md-warn .md-thumb:after { border-color: '{{warn-color}}'; background-color: '{{warn-color}}'; }md-slider.md-THEME_NAME-theme.md-warn .md-sign { background-color: '{{warn-color}}'; } md-slider.md-THEME_NAME-theme.md-warn .md-sign:after { border-top-color: '{{warn-color}}'; }md-slider.md-THEME_NAME-theme.md-warn .md-thumb-text { color: '{{warn-contrast}}'; }md-slider.md-THEME_NAME-theme.md-primary .md-focus-ring { background-color: '{{primary-color}}'; }md-slider.md-THEME_NAME-theme.md-primary .md-track.md-track-fill { background-color: '{{primary-color}}'; }md-slider.md-THEME_NAME-theme.md-primary .md-thumb:after { border-color: '{{primary-color}}'; background-color: '{{primary-color}}'; }md-slider.md-THEME_NAME-theme.md-primary .md-sign { background-color: '{{primary-color}}'; } md-slider.md-THEME_NAME-theme.md-primary .md-sign:after { border-top-color: '{{primary-color}}'; }md-slider.md-THEME_NAME-theme.md-primary .md-thumb-text { color: '{{primary-contrast}}'; }md-slider.md-THEME_NAME-theme[disabled] .md-thumb:after { border-color: '{{foreground-3}}'; }md-slider.md-THEME_NAME-theme[disabled]:not(.md-min) .md-thumb:after { background-color: '{{foreground-3}}'; }.md-subheader.md-THEME_NAME-theme { color: '{{ foreground-2-0.23 }}'; background-color: '{{background-color}}'; } .md-subheader.md-THEME_NAME-theme.md-primary { color: '{{primary-color}}'; } .md-subheader.md-THEME_NAME-theme.md-accent { color: '{{accent-color}}'; } .md-subheader.md-THEME_NAME-theme.md-warn { color: '{{warn-color}}'; }md-switch.md-THEME_NAME-theme .md-ink-ripple { color: '{{background-500}}'; }md-switch.md-THEME_NAME-theme .md-thumb { background-color: '{{background-50}}'; }md-switch.md-THEME_NAME-theme .md-bar { background-color: '{{background-500}}'; }md-switch.md-THEME_NAME-theme.md-checked .md-ink-ripple { color: '{{accent-color}}'; }md-switch.md-THEME_NAME-theme.md-checked .md-thumb { background-color: '{{accent-color}}'; }md-switch.md-THEME_NAME-theme.md-checked .md-bar { background-color: '{{accent-color-0.5}}'; }md-switch.md-THEME_NAME-theme.md-checked.md-focused .md-thumb:before { background-color: '{{accent-color-0.26}}'; }md-switch.md-THEME_NAME-theme.md-checked.md-primary .md-ink-ripple { color: '{{primary-color}}'; }md-switch.md-THEME_NAME-theme.md-checked.md-primary .md-thumb { background-color: '{{primary-color}}'; }md-switch.md-THEME_NAME-theme.md-checked.md-primary .md-bar { background-color: '{{primary-color-0.5}}'; }md-switch.md-THEME_NAME-theme.md-checked.md-primary.md-focused .md-thumb:before { background-color: '{{primary-color-0.26}}'; }md-switch.md-THEME_NAME-theme.md-checked.md-warn .md-ink-ripple { color: '{{warn-color}}'; }md-switch.md-THEME_NAME-theme.md-checked.md-warn .md-thumb { background-color: '{{warn-color}}'; }md-switch.md-THEME_NAME-theme.md-checked.md-warn .md-bar { background-color: '{{warn-color-0.5}}'; }md-switch.md-THEME_NAME-theme.md-checked.md-warn.md-focused .md-thumb:before { background-color: '{{warn-color-0.26}}'; }md-switch.md-THEME_NAME-theme[disabled] .md-thumb { background-color: '{{background-400}}'; }md-switch.md-THEME_NAME-theme[disabled] .md-bar { background-color: '{{foreground-4}}'; }md-tabs.md-THEME_NAME-theme md-tabs-wrapper { background-color: transparent; border-color: '{{foreground-4}}'; }md-tabs.md-THEME_NAME-theme .md-paginator md-icon { color: '{{primary-color}}'; }md-tabs.md-THEME_NAME-theme md-ink-bar { color: '{{accent-color}}'; background: '{{accent-color}}'; }md-tabs.md-THEME_NAME-theme .md-tab { color: '{{foreground-2}}'; } md-tabs.md-THEME_NAME-theme .md-tab[disabled], md-tabs.md-THEME_NAME-theme .md-tab[disabled] md-icon { color: '{{foreground-3}}'; } md-tabs.md-THEME_NAME-theme .md-tab.md-active, md-tabs.md-THEME_NAME-theme .md-tab.md-active md-icon, md-tabs.md-THEME_NAME-theme .md-tab.md-focused, md-tabs.md-THEME_NAME-theme .md-tab.md-focused md-icon { color: '{{primary-color}}'; } md-tabs.md-THEME_NAME-theme .md-tab.md-focused { background: '{{primary-color-0.1}}'; } md-tabs.md-THEME_NAME-theme .md-tab .md-ripple-container { color: '{{accent-100}}'; }md-tabs.md-THEME_NAME-theme.md-accent > md-tabs-wrapper { background-color: '{{accent-color}}'; } md-tabs.md-THEME_NAME-theme.md-accent > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]) { color: '{{accent-100}}'; } md-tabs.md-THEME_NAME-theme.md-accent > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-active, md-tabs.md-THEME_NAME-theme.md-accent > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-active md-icon, md-tabs.md-THEME_NAME-theme.md-accent > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused, md-tabs.md-THEME_NAME-theme.md-accent > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused md-icon { color: '{{accent-contrast}}'; } md-tabs.md-THEME_NAME-theme.md-accent > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused { background: '{{accent-contrast-0.1}}'; } md-tabs.md-THEME_NAME-theme.md-accent > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-ink-bar { color: '{{primary-600-1}}'; background: '{{primary-600-1}}'; }md-tabs.md-THEME_NAME-theme.md-primary > md-tabs-wrapper { background-color: '{{primary-color}}'; } md-tabs.md-THEME_NAME-theme.md-primary > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]) { color: '{{primary-100}}'; } md-tabs.md-THEME_NAME-theme.md-primary > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-active, md-tabs.md-THEME_NAME-theme.md-primary > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-active md-icon, md-tabs.md-THEME_NAME-theme.md-primary > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused, md-tabs.md-THEME_NAME-theme.md-primary > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused md-icon { color: '{{primary-contrast}}'; } md-tabs.md-THEME_NAME-theme.md-primary > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused { background: '{{primary-contrast-0.1}}'; }md-tabs.md-THEME_NAME-theme.md-warn > md-tabs-wrapper { background-color: '{{warn-color}}'; } md-tabs.md-THEME_NAME-theme.md-warn > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]) { color: '{{warn-100}}'; } md-tabs.md-THEME_NAME-theme.md-warn > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-active, md-tabs.md-THEME_NAME-theme.md-warn > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-active md-icon, md-tabs.md-THEME_NAME-theme.md-warn > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused, md-tabs.md-THEME_NAME-theme.md-warn > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused md-icon { color: '{{warn-contrast}}'; } md-tabs.md-THEME_NAME-theme.md-warn > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused { background: '{{warn-contrast-0.1}}'; }md-toolbar > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper { background-color: '{{primary-color}}'; } md-toolbar > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]) { color: '{{primary-100}}'; } md-toolbar > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-active, md-toolbar > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-active md-icon, md-toolbar > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused, md-toolbar > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused md-icon { color: '{{primary-contrast}}'; } md-toolbar > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused { background: '{{primary-contrast-0.1}}'; }md-toolbar.md-accent > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper { background-color: '{{accent-color}}'; } md-toolbar.md-accent > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]) { color: '{{accent-100}}'; } md-toolbar.md-accent > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-active, md-toolbar.md-accent > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-active md-icon, md-toolbar.md-accent > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused, md-toolbar.md-accent > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused md-icon { color: '{{accent-contrast}}'; } md-toolbar.md-accent > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused { background: '{{accent-contrast-0.1}}'; } md-toolbar.md-accent > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-ink-bar { color: '{{primary-600-1}}'; background: '{{primary-600-1}}'; }md-toolbar.md-warn > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper { background-color: '{{warn-color}}'; } md-toolbar.md-warn > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]) { color: '{{warn-100}}'; } md-toolbar.md-warn > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-active, md-toolbar.md-warn > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-active md-icon, md-toolbar.md-warn > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused, md-toolbar.md-warn > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused md-icon { color: '{{warn-contrast}}'; } md-toolbar.md-warn > md-tabs.md-THEME_NAME-theme > md-tabs-wrapper > md-tabs-canvas > md-pagination-wrapper > md-tab-item:not([disabled]).md-focused { background: '{{warn-contrast-0.1}}'; }md-toast.md-THEME_NAME-theme .md-toast-content { background-color: #323232; color: '{{background-50}}'; } md-toast.md-THEME_NAME-theme .md-toast-content .md-button { color: '{{background-50}}'; } md-toast.md-THEME_NAME-theme .md-toast-content .md-button.md-highlight { color: '{{primary-A200}}'; } md-toast.md-THEME_NAME-theme .md-toast-content .md-button.md-highlight.md-accent { color: '{{accent-A200}}'; } md-toast.md-THEME_NAME-theme .md-toast-content .md-button.md-highlight.md-warn { color: '{{warn-A200}}'; }md-toolbar.md-THEME_NAME-theme:not(.md-menu-toolbar) { background-color: '{{primary-color}}'; color: '{{primary-contrast}}'; } md-toolbar.md-THEME_NAME-theme:not(.md-menu-toolbar) md-icon { color: '{{primary-contrast}}'; } md-toolbar.md-THEME_NAME-theme:not(.md-menu-toolbar).md-accent { background-color: '{{accent-color}}'; color: '{{accent-contrast}}'; } md-toolbar.md-THEME_NAME-theme:not(.md-menu-toolbar).md-warn { background-color: '{{warn-color}}'; color: '{{warn-contrast}}'; }md-tooltip.md-THEME_NAME-theme { color: '{{background-A100}}'; } md-tooltip.md-THEME_NAME-theme .md-content { background-color: '{{foreground-2}}'; }");
})();
})(window, window.angular);
|
module.exports={A:{A:{"2":"J E F G A B lB"},B:{"1":"N O P Q R U V W X Y Z a b c S d e H","2":"C K L D M"},C:{"1":"5 6 7 8 9 AB BB CB DB EB FB GB HB IB JB eB KB fB LB MB T NB OB PB QB RB SB TB UB VB WB XB YB ZB aB P Q R nB U V W X Y Z a b c S d e H gB","2":"mB dB I f J E F G A B C K L D M N O g h i j k l m n o p oB pB","132":"0 1 2 3 4 q r s t u v w x y z"},D:{"1":"AB BB CB DB EB FB GB HB IB JB eB KB fB LB MB T NB OB PB QB RB SB TB UB VB WB XB YB ZB aB P Q R U V W X Y Z a b c S d e H gB qB rB sB","2":"0 1 2 3 4 5 6 7 8 9 I f J E F G A B C K L D M N O g h i j k l m n o p q r s t u v w x y z"},E:{"1":"B C K L D iB bB cB yB zB 0B 1B","2":"I f J E F G A tB hB uB vB wB xB"},F:{"1":"0 1 2 3 4 5 6 7 8 9 x y z AB BB CB DB EB FB GB HB IB JB KB LB MB T NB OB PB QB RB SB TB UB VB WB XB YB ZB aB P Q R","2":"G B C D M N O g h i j k l m n o p q r s t u v w 2B 3B 4B 5B bB jB 6B cB"},G:{"1":"D FC GC HC IC JC KC LC MC NC OC PC","2":"F hB 7B kB 8B 9B AC BC CC DC EC"},H:{"2":"QC"},I:{"1":"H","2":"dB I RC SC TC UC kB VC WC"},J:{"2":"E A"},K:{"1":"T","2":"A B C bB jB cB"},L:{"1":"H"},M:{"1":"S"},N:{"2":"A B"},O:{"1":"XC"},P:{"1":"YC ZC aC bC cC iB dC eC fC gC hC","2":"I"},Q:{"1":"iC"},R:{"2":"jC"},S:{"1":"kC"}},B:1,C:"URLSearchParams"};
|
import { light, dark } from './color-modes'
const colors = {
mode: {
light,
dark,
},
transparent: 'transparent',
current: 'currentColor',
black: '#000000',
white: '#ffffff',
whiteAlpha: {
50: 'rgba(255, 255, 255, 0.04)',
100: 'rgba(255, 255, 255, 0.06)',
200: 'rgba(255, 255, 255, 0.08)',
300: 'rgba(255, 255, 255, 0.16)',
400: 'rgba(255, 255, 255, 0.24)',
500: 'rgba(255, 255, 255, 0.36)',
600: 'rgba(255, 255, 255, 0.48)',
700: 'rgba(255, 255, 255, 0.64)',
800: 'rgba(255, 255, 255, 0.80)',
900: 'rgba(255, 255, 255, 0.92)',
},
blackAlpha: {
50: 'rgba(0, 0, 0, 0.04)',
100: 'rgba(0, 0, 0, 0.06)',
200: 'rgba(0, 0, 0, 0.08)',
300: 'rgba(0, 0, 0, 0.16)',
400: 'rgba(0, 0, 0, 0.24)',
500: 'rgba(0, 0, 0, 0.36)',
600: 'rgba(0, 0, 0, 0.48)',
700: 'rgba(0, 0, 0, 0.64)',
800: 'rgba(0, 0, 0, 0.80)',
900: 'rgba(0, 0, 0, 0.92)',
},
gray: {
50: '#f9fafb',
100: '#f4f5f7',
200: '#e5e7eb',
300: '#d2d6dc',
400: '#9fa6b2',
500: '#6b7280',
600: '#4b5563',
700: '#374151',
800: '#252f3f',
900: '#161e2e',
},
'cool-gray': {
50: '#fbfdfe',
100: '#f1f5f9',
200: '#e2e8f0',
300: '#cfd8e3',
400: '#97a6ba',
500: '#64748b',
600: '#475569',
700: '#364152',
800: '#27303f',
900: '#1a202e',
},
red: {
50: '#fdf2f2',
100: '#fde8e8',
200: '#fbd5d5',
300: '#f8b4b4',
400: '#f98080',
500: '#f05252',
600: '#e02424',
700: '#c81e1e',
800: '#9b1c1c',
900: '#771d1d',
},
orange: {
50: '#fff8f1',
100: '#feecdc',
200: '#fcd9bd',
300: '#fdba8c',
400: '#ff8a4c',
500: '#ff5a1f',
600: '#d03801',
700: '#b43403',
800: '#8a2c0d',
900: '#771d1d',
},
yellow: {
50: '#fdfdea',
100: '#fdf6b2',
200: '#fce96a',
300: '#faca15',
400: '#e3a008',
500: '#c27803',
600: '#9f580a',
700: '#8e4b10',
800: '#723b13',
900: '#633112',
},
green: {
50: '#f3faf7',
100: '#def7ec',
200: '#bcf0da',
300: '#84e1bc',
400: '#31c48d',
500: '#0e9f6e',
600: '#057a55',
700: '#046c4e',
800: '#03543f',
900: '#014737',
},
teal: {
50: '#edfafa',
100: '#d5f5f6',
200: '#afecef',
300: '#7edce2',
400: '#16bdca',
500: '#0694a2',
600: '#047481',
700: '#036672',
800: '#05505c',
900: '#014451',
},
blue: {
50: '#ebf5ff',
100: '#e1effe',
200: '#c3ddfd',
300: '#a4cafe',
400: '#76a9fa',
500: '#3f83f8',
600: '#1c64f2',
700: '#1a56db',
800: '#1e429f',
900: '#233876',
},
indigo: {
50: '#f0f5ff',
100: '#e5edff',
200: '#cddbfe',
300: '#b4c6fc',
400: '#8da2fb',
500: '#6875f5',
600: '#5850ec',
700: '#5145cd',
800: '#42389d',
900: '#362f78',
},
purple: {
50: '#f6f5ff',
100: '#edebfe',
200: '#dcd7fe',
300: '#cabffd',
400: '#ac94fa',
500: '#9061f9',
600: '#7e3af2',
700: '#6c2bd9',
800: '#5521b5',
900: '#4a1d96',
},
pink: {
50: '#fdf2f8',
100: '#fce8f3',
200: '#fad1e8',
300: '#f8b4d9',
400: '#f17eb8',
500: '#e74694',
600: '#d61f69',
700: '#bf125d',
800: '#99154b',
900: '#751a3d',
},
linkedin: {
50: '#E8F4F9',
100: '#CFEDFB',
200: '#9BDAF3',
300: '#68C7EC',
400: '#34B3E4',
500: '#00A0DC',
600: '#008CC9',
700: '#0077B5',
800: '#005E93',
900: '#004471',
},
facebook: {
50: '#E8F4F9',
100: '#D9DEE9',
200: '#B7C2DA',
300: '#6482C0',
400: '#4267B2',
500: '#385898',
600: '#314E89',
700: '#29487D',
800: '#223B67',
900: '#1E355B',
},
messenger: {
50: '#D0E6FF',
100: '#B9DAFF',
200: '#A2CDFF',
300: '#7AB8FF',
400: '#2E90FF',
500: '#0078FF',
600: '#0063D1',
700: '#0052AC',
800: '#003C7E',
900: '#002C5C',
},
whatsapp: {
50: '#e2f7f4',
100: '#c3f0e9',
200: '#a0e7dc',
300: '#76dccd',
400: '#43cfba',
500: '#00BFA5',
600: '#00ac92',
700: '#009780',
800: '#007d6a',
900: '#005a4c',
},
twitter: {
signin: '#00aced',
50: '#e5f4fd',
100: '#c8e9fb',
200: '#a8dcfa',
300: '#83cdf7',
400: '#57bbf5',
500: '#1DA1F2',
600: '#1a94da',
700: '#1681bf',
800: '#136b9e',
900: '#0d4d71',
},
telegram: {
50: '#e3f2f9',
100: '#c5e4f3',
200: '#a2d4ec',
300: '#7ac1e4',
400: '#47a9da',
500: '#0088CC',
600: '#007ab8',
700: '#006ba1',
800: '#005885',
900: '#003f5e',
},
}
export default colors
|
/**
* @component Toast
* @version 3.0.0
* @description 面包屑提示组件,页面居中显示一条提示信息。
*
* - 是一个对象,包含show/hide函数,支持简单的链式调用。
* - 通过调用show函数打开组件,默认显示2s。
* - 通过调用hide函数立刻关闭组件。
*
* @instructions {instruInfo: ./toast.md}{instruUrl: toast.html?hideIcon}
* @author qingguo.xu
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
let that = null;
const container = document.createElement('div'),
defaultProps = {
show: false
},
propTypes = {
/**
* @property show
* @description 是否显示,默认false
* @type Boolean
* @default false
* @skip
*/
show: PropTypes.bool
};
document.body.appendChild(container);
class ToastReact extends Component {
constructor(props) {
super(props);
this.state = {
show: props.show,
content: ''
};
this._timer = null;
that = this;
}
componentWillUnmount() {
clearTimeout(this._timer);
document.body.removeChild(container);
}
render() {
const { show, content } = this.state;
return (
<div
className="yo-toast"
style={{
display: show ? null : 'none'
}}
>{content}</div>
);
}
}
ToastReact.propTypes = propTypes;
ToastReact.defaultProps = defaultProps;
ReactDOM.render(<ToastReact />, container);
/**
* Toast显隐函数
* @returns {Object}
*/
export default {
/**
* @method show
* @type Function
* @description 打开组件,显示传入的内容
* @param {String} content 组件显示的内容
* @param {Number} [autoHideTime] 内容显示的持续时间,默认2000ms
* @param {Function} [callback] 内容显示后触发的回调 <3.0.13>
*/
show(content = 'no content', autoHideTime = 2000, callback = () => {}) {
that.setState({
content,
show: true
}, callback);
if (!!that.timer) {
clearTimeout(that.timer);
that.timer = null;
}
that.timer = setTimeout(() => this.hide(), autoHideTime);
return this;
},
/**
* @method hide
* @type Function
* @description 关闭正在显示的组件
* @param {Function} [callback] 内容隐藏后触发的回调 <3.0.13>
*/
hide(callback = () => {}) {
if (!!that.timer) {
clearTimeout(that.timer);
that.timer = null;
}
that.setState({ show: false }, callback);
return this;
}
};
|
import {
getCommonHeader,
getTextField,
getSelectField,
getCommonContainer,
getCommonSubHeader,
getLabel,
getPattern
} from "egov-ui-framework/ui-config/screens/specs/utils";
import { showHideAdhocPopup } from "../../utils";
import {
handleScreenConfigurationFieldChange as handleField,
prepareFinalObject,
toggleSnackbar,
toggleSpinner
} from "egov-ui-framework/ui-redux/screen-configuration/actions";
import { resetAllFields } from "../../utils";
import { createUpdateItemMaster } from "../../../../../ui-utils/commons";
import jp from "jsonpath";
import get from "lodash/get";
import set from "lodash/set";
import {
getUserInfo,
setapplicationMode
} from "egov-ui-kit/utils/localStorageUtils";
import { searchResultApiResponse } from "../searchResource/searchResultApiResponse";
import { getQueryArg } from "egov-ui-framework/ui-utils/commons";
import { getCommonApplyFooter, validateFields } from "../../utils";
import "./index.css";
const hasButton = getQueryArg(window.location.href, "hasButton");
let enableButton = true;
enableButton = hasButton && hasButton === "false" ? false : true;
const checkDuplicteRecord = (state, dispatch) => {
try {
let isduplicate = false;
let obj = get(state.screenConfiguration.preparedFinalObject, "ItemMaster");
let obj2 = get(
state.screenConfiguration.preparedFinalObject,
"ItemMasterGrid"
);
obj2.forEach(element => {
if (obj.hasOwnProperty("itemUuid")) {
if (obj.itemUuid.toString() !== element[0].split('~')[0].toString()) {
if (
!isduplicate &&
element[1].trim().toLowerCase() == obj.itemName.trim().toLowerCase()
) {
isduplicate = true;
return true;
}
}
}
else {
if (!isduplicate && element[1].trim().toLowerCase() == obj.itemName.trim().toLowerCase()) {
isduplicate = true;
return true;
}
}
});
return isduplicate;
} catch (ex) {
console.log(ex);
}
};
const createUpdateItemMasterDetails = async (state, dispatch, applnid) => {
let isDuplicateCheck = false;
let isFormValid = true;
isFormValid = validateFields(
"components.adhocDialog.children.popup.children.addItemMasterCard.children.addItemMasterContainer.children",
state,
dispatch,
"search"
);
if (isFormValid) {
isDuplicateCheck = checkDuplicteRecord(state, dispatch);
if (!isDuplicateCheck) {
let response = await createUpdateItemMaster(state, dispatch, "APPROVED", true);
setapplicationMode("APPROVED");
let responseStatus = get(response, "status", "");
if (responseStatus == "SUCCESS" || responseStatus == "success") {
dispatch(
toggleSnackbar(
true,
{
labelName: "Item Master Inserted successfully!",
labelKey: "EC_SUCCESS_TOASTER"
},
"success"
)
);
dispatch(prepareFinalObject("ItemMaster", []));
// showHideAdhocPopup(state, dispatch, "search");
searchResultApiResponse("", state, dispatch);
setTimeout(() => window.location.reload(), 1000);
//setTimeout(() => window.location.reload(), 5000);
} else {
dispatch(
toggleSnackbar(
true,
{
labelName: "Submission Falied, Try Again later!",
labelKey: "EC_FAILED_TOASTER"
},
"error"
)
);
}
//const objectJsonPath = `components.adhocDialog.children.popup.children.addItemMasterCard.children`;
// const children = get(
// state.screenConfiguration.screenConfig["search"],
// objectJsonPath,
// {}
// );
// resetAllFields(children, dispatch, state, 'search');
} else {
dispatch(
toggleSnackbar(
true,
{
labelName: "Item already exist!",
labelKey: "EC_ITEM_ALREADY_EXIST_TOASTER"
},
"warning"
)
);
setTimeout(() => window.location.reload(), 5000);
}
}
};
const approveItemMasterDetails = async (state, dispatch, applnid) => {
let response = await createUpdateItemMaster(state, dispatch, "APPROVED");
setapplicationMode("APPROVED");
let responseStatus = get(response, "status", "");
if (responseStatus == "SUCCESS" || responseStatus == "success") {
dispatch(
toggleSnackbar(
true,
{
labelName: "Item Master Updated successfully!",
labelKey: "EC_UPDATE_SUCCESS_TOASTER"
},
"success"
)
);
dispatch(prepareFinalObject("ItemMaster", {}));
showHideAdhocPopup(state, dispatch, "search");
searchResultApiResponse("", state, dispatch);
} else {
dispatch(
toggleSnackbar(
true,
{
labelName: "Submission Falied, Try Again later!",
labelKey: "EC_FAILED_TOASTER"
},
"error"
)
);
}
};
const rejectItemMasterDetails = async (state, dispatch, applnid) => {
let response = await createUpdateItemMaster(state, dispatch, "REJECTED");
setapplicationMode("REJECTED");
let responseStatus = get(response, "status", "");
if (responseStatus == "SUCCESS" || responseStatus == "success") {
dispatch(
toggleSnackbar(
true,
{
labelName: "Item Master Updated successfully!",
labelKey: "EC_UPDATE_SUCCESS_TOASTER"
},
"success"
)
);
dispatch(prepareFinalObject("ItemMaster", {}));
showHideAdhocPopup(state, dispatch, "search");
searchResultApiResponse("", state, dispatch);
} else {
dispatch(
toggleSnackbar(
true,
{
labelName: "Submission Falied, Try Again later!",
labelKey: "EC_FAILED_TOASTER"
},
"error"
)
);
}
};
export const adhocPopup = getCommonContainer({
header: {
uiFramework: "custom-atoms",
componentPath: "Container",
props: {
style: {
width: "100%",
float: "right"
}
},
children: {
div1: {
uiFramework: "custom-atoms",
componentPath: "Div",
gridDefination: {
xs: 12,
sm: 12
},
props: {
style: {
width: "100%",
float: "right"
}
},
children: {
div: getCommonHeader(
{
labelName: "Add Item",
labelKey: "EC_POPUP_ITEM_MASTER_HEADER"
},
{
style: {
fontSize: "20px"
}
}
)
}
},
// submitbtns: {
// uiFramework: "custom-atoms",
// componentPath: "Div",
// gridDefination: {
// xs: 2,
// sm: 2
// },
// props: {
// style: {
// width: "100%",
// float: "right",
// cursor: "pointer"
// }
// },
// children: {
// closeButton: {
// componentPath: "Button",
// props: {
// style: {
// float: "right",
// color: "rgba(0, 0, 0, 0.60)"
// }
// },
// children: {
// // previousButtonIcon: {
// // uiFramework: "custom-atoms",
// // componentPath: "Icon",
// // props: {
// // iconName: "close"
// // }
// // }
// },
// onClickDefination: {
// action: "condition",
// callBack: (state, dispatch) =>{
// showHideAdhocPopup(state, dispatch, "create");
// setTimeout(() => window.location.reload(), 1000);
// }
// }
// }
// }
// }
}
},
addItemMasterCard: getCommonContainer(
{
addItemMasterContainer: getCommonContainer({
addItemMasterIdControl: getTextField({
label: {
labelName: "Item/Article ID",
labelKey: "EC_POPUP_ITEM_ARTICLE_ID_LABEL"
},
placeholder: {
labelName: "Item/Article ID",
labelKey: "EC_POPUP_ITEM_ARTICLE_ID_PLACEHOLDER"
},
gridDefination: {
xs: 12,
sm: 12
},
jsonPath: "ItemMaster.itemUuid",
props: {
style: {
width: "100%"
}
},
visible: false
}),
addItemMasterControl: getTextField({
label: {
labelName: "Name Of Item/Article",
labelKey: "EC_POPUP_ITEM_ARTICLE_NAME_LABEL"
},
placeholder: {
labelName: "Name Of Item/Article",
labelKey: "EC_POPUP_ITEM_ARTICLE_NAME_PLACEHOLDER"
},
gridDefination: {
xs: 12,
sm: 12
},
jsonPath: "ItemMaster.itemName",
required: true,
pattern: getPattern("ECItemName"), ///^[a-zA-Z0-9 ]*$/i, // /^[a-zA-Z0-9]*$/i,
// errorMessage: "EC_ERR_DEFAULT_INPUT_ADDRESS_FIELD_MSG",
errorMessage: "EC_ERR_DEFAULT_INPUT_ITEM_NAME_FIELD_MSG",
// props: {
// value: 'challanHOD',
// },
props: {
style: {
width: "100%"
},
className: "textfield-enterable-selection",
multiline: true,
rows: "4"
},
}),
addItemMasterDescriptionControl: getTextField({
label: {
labelName: "Description",
labelKey: "EC_POPUP_ITEM_ARTICLE_DESCRIPTION_LABEL"
},
placeholder: {
labelName: "Description",
labelKey: "EC_POPUP_ITEM_ARTICLE_DESCRIPTION_PLACEHOLDER"
},
gridDefination: {
xs: 12,
sm: 12
},
props: {
style: {
width: "100%"
},
className: "textfield-enterable-selection",
multiline: true,
rows: "4"
},
jsonPath: "ItemMaster.description",
required: true,
pattern: getPattern("ECItemDescription"), ///^[ A-Za-z0-9_@./#&+- ]{1,250}$/i,
errorMessage: "EC_ERR_DEFAULT_INPUT_ITEM_DESCRIPTION_FIELD_MSG",
//errorMessage: "Invalid input field",
})
})
},
{
style: {
marginTop: "24px"
}
}
),
div: {
uiFramework: "custom-atoms",
componentPath: "Div",
props: {
style: {
width: "100%",
//textAlign: "right",
display: "flex"
}
},
children: {
cancelApplicationButton: {
componentPath: "Button",
// gridDefination: {
// xs: 12,
// sm: 6,
// // align: "right"
// },
visible: enableButton,
props: {
variant: "outlined",
color: "primary",
style: {
// color: "white",
borderRadius: "2px",
minWidth: "180px",
height: "48px",
marginRight: "16px",
marginBottom: "8px"
}
},
children: {
// cancelIconInsideButton: {
// uiFramework: "custom-atoms",
// componentPath: "Icon",
// props: {
// // iconName: "close"
// // style: {
// // fontSize: "24px"
// // }
// }
// },
buttonLabel: getLabel({
labelName: "CANCEL",
labelKey: "EC_POPUP_SEARCH_RESULTS_CANCEL_APP_BUTTON"
})
},
onClickDefination: {
action: "condition",
callBack: (state, dispatch) => {
dispatch(prepareFinalObject("ItemMaster", []));
showHideAdhocPopup(state, dispatch, "search");
// const objectJsonPath = `components.adhocDialog.children.popup.children.addItemMasterCard.children`;
// const children = get(
// state.screenConfiguration.screenConfig["search"],
// objectJsonPath,
// {}
// );
// resetAllFields(children, dispatch, state, 'search');
setTimeout(() => window.location.reload(), 1000);
}
},
roleDefination: {
rolePath: "user-info.roles",
roles: ["challanEAO"]
//path : "tradelicence/apply"
}
},
saveApplicationButton: {
componentPath: "Button",
// gridDefination: {
// xs: 12,
// sm: 6,
// // align: "left"
// },
visible: enableButton,
props: {
variant: "contained",
color: "primary",
style: {
color: "white",
borderRadius: "2px",
minWidth: "180px",
height: "48px",
marginRight: "16px",
marginBottom: "8px"
}
},
children: {
// saveIconInsideButton: {
// uiFramework: "custom-atoms",
// componentPath: "Icon",
// props: {
// // iconName: "saveAlt"
// // style: {
// // fontSize: "24px"
// // }
// }
// },
buttonLabel: getLabel({
labelName: "SAVE",
labelKey: "EC_POPUP_SEARCH_RESULTS_SAVE_APP_BUTTON"
})
},
onClickDefination: {
action: "condition",
callBack: createUpdateItemMasterDetails
},
roleDefination: {
rolePath: "user-info.roles",
roles: ["challanEAO"]
//path : "tradelicence/apply"
}
},
RejectApplicationButton: {
componentPath: "Button",
// gridDefination: {
// xs: 12,
// sm: 6,
// // align: "right"
// },
visible: enableButton,
props: {
variant: "contained",
color: "primary",
style: {
color: "white",
borderRadius: "2px",
minWidth: "180px",
height: "48px",
marginRight: "16px",
marginBottom: "8px"
}
},
children: {
rejectIconInsideButton: {
uiFramework: "custom-atoms",
componentPath: "Icon"
// props: {
// iconName: "thumbDownAlt",
// style: {
// fontSize: "24px"
// }
// }
},
buttonLabel: getLabel({
labelName: "Reject",
labelKey: "EC_POPUP_SEARCH_RESULTS_REJECT_APP_BUTTON"
})
},
onClickDefination: {
action: "condition",
callBack: rejectItemMasterDetails
},
roleDefination: {
rolePath: "user-info.roles",
roles: ["challanHOD"]
//path : "tradelicence/apply"
}
},
approveApplicationButton: {
componentPath: "Button",
// gridDefination: {
// xs: 12,
// sm: 6,
// // align: "left"
// },
visible: enableButton,
props: {
variant: "contained",
color: "primary",
style: {
color: "white",
borderRadius: "2px",
minWidth: "180px",
height: "48px",
marginRight: "16px",
marginBottom: "8px"
}
},
children: {
approveIconInsideButton: {
uiFramework: "custom-atoms",
componentPath: "Icon"
// props: {
// iconName: "ThumbUpAlt",
// style: {
// fontSize: "24px"
// }
// }
},
buttonLabel: getLabel({
labelName: "APPROVE",
labelKey: "EC_POPUP_SEARCH_RESULTS_APPROVE_APP_BUTTON"
})
},
onClickDefination: {
action: "condition",
callBack: approveItemMasterDetails
},
roleDefination: {
rolePath: "user-info.roles",
roles: ["challanHOD"]
//path : "tradelicence/apply"
}
}
},
gridDefination: {
xs: 12,
sm: 12
}
}
});
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
* 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.
*/
ko.bindingHandlers.initializeValue = {
init: function (element, valueAccessor) {
var value = valueAccessor();
if (ko.isObservable(value)) {
value(element.value);
}
}
};
ko.subscribable.fn.trimmed = function () {
return ko.computed({
read: function () {
var value = this() || '';
return value.trim();
},
write: function (value) {
value = value || '';
this(value.trim());
this.valueHasMutated();
},
owner: this
}).extend({notify: 'always'});
};
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
|
import { createBasePlugin } from 'wix-rich-content-editor-common';
import { VERTICAL_EMBED_TYPE, DEFAULTS } from './constants';
import VerticalEmbedComponent from './components/vertical-embed-component';
import createToolbar from './toolbar';
const createVerticalEmbedPlugin = (config = {}) => {
const type = VERTICAL_EMBED_TYPE;
const { helpers, theme, t, [type]: settings = {}, isMobile, ...rest } = config;
return createBasePlugin({
component: VerticalEmbedComponent,
settings,
theme,
type,
toolbar: createToolbar({
settings,
helpers,
t,
isMobile,
}),
helpers,
t,
defaultPluginData: DEFAULTS,
isMobile,
...rest,
});
};
export { createVerticalEmbedPlugin };
|
import React from 'react'
import { Link, graphql, useStaticQuery } from "gatsby"
import headerStyles from './header.module.scss'
export default function Header() {
const data = useStaticQuery(graphql`
query {
site {
siteMetadata {
title
}
}
}
`)
return (
<header className={headerStyles.header}>
<h1><Link className={headerStyles.title} to='/'>{data.site.siteMetadata.title}</Link></h1>
<nav>
<ul className={headerStyles.navList}>
<li>
<Link className={headerStyles.navItem} activeClassName={headerStyles.activeNavItem} to='/'>Home</Link>
</li>
<li>
<Link className={headerStyles.navItem} activeClassName={headerStyles.activeNavItem} to='/items'>Products</Link>
</li>
<li>
<Link className={headerStyles.navItem} activeClassName={headerStyles.activeNavItem} to='/about'>About</Link>
</li>
<li>
<Link className={headerStyles.navItem} activeClassName={headerStyles.activeNavItem} to='/blog'>Blog</Link>
</li>
<li>
<Link className={headerStyles.navItem} activeClassName={headerStyles.activeNavItem} to='/contact'>Contact</Link>
</li>
</ul>
</nav>
</header>
)
}
|
/*
* Created by sv2 on 3/15/17.
* swagger-stats utilities
*/
'use strict';
var util = require('util');
// swagger-stats supported options
module.exports.supportedOptions = {
// Name. Defaults to hostname if not specified
name : "name",
// Version
version : "version",
// Hostname. Will attempt to detect if not explicitly provided
hostname : "hostname",
// IP Address. Will attempt to detect if not provided
ip : "ip",
// Swagger specification JSON document. Should be pre-validated and with resolved references. Optional.
swaggerSpec : "swaggerSpec",
// Base path for swagger-stats internal APIs.
// If specified, will be used to serve UI, stats and metrics like this:
// /<uriPath>/ui, /<uriPath>/stats, /<uriPath>/metrics
// overriding default /swagger-stats/ui
uriPath : "uriPath",
// Duration of timeline bucket in milliseconds, 60000 by default
timelineBucketDuration : "timelineBucketDuration",
// Buckets for duration histogram metrics, in Milliseconds
// Optional. Default value:
// [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000]
// The default buckets are tailored to broadly measure API response time.
// Most likely needs to be defined per app to account for application specifics.
durationBuckets : "durationBuckets",
// Buckets for request size histogram metric, in Bytes.
// Optional. Default value:
// [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000]
// The default buckets are tailored to broadly measure API request size.
// Most likely needs to be defined per app to account for application specifics.
requestSizeBuckets : "requestSizeBuckets",
// Buckets for response size histogram metric, in Bytes
// Optional. Default value:
// [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000]
// The default buckets are tailored to broadly measure API response size.
// Most likely needs to be defined per app to account for application specifics.
responseSizeBuckets : "responseSizeBuckets",
// Apdex threshold, in milliseconds
// 50 ms by default
apdexThreshold : "apdexThreshold",
// Callback to invoke when response is finished - https://github.com/slanatech/swagger-stats/issues/5
// Application may implement it to trace Request Response Record (RRR), which is passed as parameter
// the following parameters are passed to this callback:
// onResponseFinish(req,res,rrr)
// - req - request
// - res - response
// - rrr - Request Response Record (RRR)
onResponseFinish : "onResponseFinish",
// Enable Basic authentication: true or false. Default false.
// Only Basic authentication is supported
authentication : "authentication",
// Callback to invoke to authenticate request to /swagger-stats/stats and /swagger-stats/metrics
// If authentication is enabled (option authentication=true),
// Application must implement onAuthenticate to validate user credentials
// the following parameters are passed to this callback:
// onAuthenticate(req,username,password)
// - req - request
// - username - username
// - password - password
// callback must return true if user authenticated, false if not
onAuthenticate : "onAuthenticate",
// Max Age of the session, if authentication is enabled, in seconds
// Default is 900 seconds
sessionMaxAge : "sessionMaxAge",
// ElasticSearch URL. Enables storing of request response records in Elasticsearch.
// Default is empty (disabled).
elasticsearch : "elasticsearch",
// Prefix for Elasticsearch index. Default is "api-"
elasticsearchIndexPrefix : "elasticsearchIndexPrefix",
// Set to true to track only requests defined in swagger spec. Default false.
swaggerOnly : "swaggerOnly"
};
// Return response status code class
module.exports.getStatusCodeClass = function (code) {
if (code < 200) return "info";
if (code < 300) return "success";
if (code < 400) return "redirect";
if (code < 500) return "client_error";
return "server_error";
};
module.exports.isError = function (code) {
return (code >= 400);
};
// Supported Stat Fields with masks
module.exports.swsStatFields = {
method : 1 << 0,
timeline : 1 << 1,
lasterrors : 1 << 2,
longestreq : 1 << 3,
apidefs : 1 << 4,
apistats : 1 << 5,
apiop : 1 << 6,
errors : 1 << 7,
all : parseInt('11111111', 2),
"*" : parseInt('11111111', 2)
};
// Supported properties in Swagger Parameter object
module.exports.swsParameterProperties = {
name : "name",
in : "in",
description : "description",
required : "required",
/*schema : "schema",*/ // We will not be copying schema for "body" parameters
type : "type",
format : "format",
allowEmptyValue : "allowEmptyValue",
items : "items", // ????
collectionFormat: "collectionFormat",
default : "default",
maximum : "maximum",
exclusiveMaximum: "exclusiveMaximum",
minimum : "minimum",
exclusiveMinimum: "exclusiveMinimum",
maxLength : "maxLength",
minLength : "minLength",
pattern : "pattern",
maxItems : "maxItems",
minItems : "minItems",
uniqueItems : "uniqueItems",
enum : "enum",
multipleOf : "multipleOf"
};
// METRICS ////////////////////////////////////////////////////////////// //
module.exports.swsMetrics = {
// TOP level counters for all requests / responses, no labels
api_all_request_total: { name: 'api_all_request_total', type: 'counter', help: 'The total number of all API requests received'},
api_all_success_total: { name: 'api_all_success_total', type: 'counter', help: 'The total number of all API requests with success response'},
api_all_errors_total: { name: 'api_all_errors_total', type: 'counter', help: 'The total number of all API requests with error response'},
api_all_client_error_total: { name: 'api_all_client_error_total', type: 'counter', help: 'The total number of all API requests with client error response'},
api_all_server_error_total: { name: 'api_all_server_error_total', type: 'counter', help: 'The total number of all API requests with server error response'},
api_all_request_in_processing_total: { name: 'api_all_request_in_processing_total', type: 'gauge', help: 'The total number of all API requests currently in processing (no response yet)'},
// System metrics for node process
nodejs_process_memory_rss_bytes: { name: 'nodejs_process_memory_rss_bytes', type: 'gauge', help: 'Node.js process resident memory (RSS) bytes '},
nodejs_process_memory_heap_total_bytes: { name: 'nodejs_process_memory_heap_total_bytes', type: 'gauge', help: 'Node.js process memory heapTotal bytes'},
nodejs_process_memory_heap_used_bytes: { name: 'nodejs_process_memory_heap_used_bytes', type: 'gauge', help: 'Node.js process memory heapUsed bytes'},
nodejs_process_memory_external_bytes: { name: 'nodejs_process_memory_external_bytes', type: 'gauge', help: 'Node.js process memory external bytes'},
nodejs_process_cpu_usage_percentage: { name: 'nodejs_process_cpu_usage_percentage', type: 'gauge', help: 'Node.js process CPU usage percentage'},
// API Operation counters, labeled with method, path and code
api_request_total: { name: 'api_request_total', type: 'counter', help: 'The total number of all API requests'},
// DISABLED API Operation counters, labeled with method, path and codeclass
//api_request_codeclass_total: { name: 'api_request_codeclass_total', type: 'counter', help: 'The total number of all API requests by response code class'},
// API request duration histogram, labeled with method, path and code
api_request_duration_milliseconds: { name: 'api_request_duration_milliseconds', type: 'histogram', help: 'API requests duration'},
// API request size histogram, labeled with method, path and code
api_request_size_bytes: { name: 'api_request_size_bytes', type: 'histogram', help: 'API requests size'},
// API response size histogram, labeled with method, path and code
api_response_size_bytes: { name: 'api_response_size_bytes', type: 'histogram', help: 'API requests size'}
};
// ////////////////////////////////////////////////////////////////////// //
// returns string value of argument, depending on typeof
module.exports.swsStringValue = function (val) {
switch( typeof val ){
case "string": return val;
case "boolean":
case "number":
return val.toString();
case "object":
if(val === null) return '';
var res = '';
try {
res = JSON.stringify(val);
}catch(e){
res = '';
}
return res;
}
return '';
};
// returns object key values as string
module.exports.swsStringRecursive = function (output, val) {
if (typeof val === "object" && !Array.isArray(val)) {
for (var key in val) {
output[key] = this.swsStringValue(val);
}
} else {
output = this.swsStringValue(val);
}
return output;
}
// recursively cast properties of nested objects to strings
module.exports.swsCastStringR = function (val) {
switch( typeof val ){
case "string": return val;
case "boolean":
case "number":
return val.toString();
case "object":
var casted = {};
for(var prop in val){
casted[prop] = module.exports.swsCastStringR(val[prop]);
}
return casted;
}
return '';
};
// returns string value of argument, depending on typeof
module.exports.swsNumValue = function (val) {
var res = Number(val);
return Number.isNaN(res) ? 0: res;
};
// Calculate CPU Usage Percentage
module.exports.swsCPUUsagePct = function(starthrtime, startusage) {
// On CPU - see
// https://github.com/nodejs/node/pull/6157
var elapTime = process.hrtime(starthrtime);
const NS_PER_SEC = 1e9;
var elapsedns = elapTime[0] * NS_PER_SEC + elapTime[1]; // nanoseconds
var elapsedmcs = elapsedns/1000; // microseconds
var elapUsage = process.cpuUsage(startusage); // microseconds
var cpuPercent = (100 * (elapUsage.user + elapUsage.system) / elapsedmcs );
return cpuPercent;
};
module.exports.swsEmbeddedUIMarkup = '<!DOCTYPE html><html><head><title>Swagger Stats UI</title><link href="dist/css/sws.min.css" rel="stylesheet"></head>\
<body>\
<div id="SWSUI"></div>\
<script src="dist/js/sws.min.js"></script>\
<script>\
$(document).ready(function(){$("#SWSUI").swaggerstatsui({});});\
</script>\
</body>\
</html>';
|
import Document, { Head, Html, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
render() {
return (
<Html lang='en'>
<Head>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin />
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet" />
<meta property="og:title" content="Ryan Garay" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://ryangaray.com" />
<meta property="og:image" content="https://ryangaray.com/images/gitlet_infinite.gif" />
<meta property="og:description" content="I'm a first-generation college student at The University of California, Berkeley, where I study computer science!" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class TopologyResource(Model):
"""The network resource topology information for the given resource group.
:param name: Name of the resource.
:type name: str
:param id: ID of the resource.
:type id: str
:param location: Resource location.
:type location: str
:param associations: Holds the associations the resource has with other
resources in the resource group.
:type associations:
list[~azure.mgmt.network.v2016_09_01.models.TopologyAssociation]
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'associations': {'key': 'associations', 'type': '[TopologyAssociation]'},
}
def __init__(self, name=None, id=None, location=None, associations=None):
self.name = name
self.id = id
self.location = location
self.associations = associations
|
import { Layout, Menu, Breadcrumb, Icon } from 'antd';
import Link from 'umi/link';
import style from './style.less';
const { SubMenu } = Menu;
const { Header, Content, Sider } = Layout;
export default ({ children }) => {
return (
<Layout className={style.layout}>
<Sider width={200} className={style.sider}>
<Menu mode="inline" defaultSelectedKeys={['dashboard']} style={{ height: '100%', borderRight: 0 }}>
<Menu.Item key="dashboard">
<Link to="/">Dashboard</Link>
</Menu.Item>
<Menu.Item key="user">
<Link to="/user">User</Link>
</Menu.Item>
</Menu>
</Sider>
<Content
style={{
background: '#fff',
padding: 24,
margin: 0,
minHeight: 280,
}}
>
{children}
</Content>
</Layout>
);
};
|
const express = require("express");
const router = express.Router();
const mongoose = require('mongoose');
const Employee = require('../models/employee');
/*This is to get all the employees list and we customized sent only selected values*/
router.get('/', (req, res, next) => {
Employee.find()
.select('emp_id first_name last_name email job_type status')
.exec()
.then(result => {
const response = {
employee_count: result.length,
employee_list: result
}
res.status(200).json({
responseBody: response
})
})
.catch(err => {
res.status(500).json({
error: err
})
})
});
/*Global Employee Search*/
router.get('/search', (req, res, next) => {
let searchParam = {};
if (req.query && req.query.option && req.query.value) {
console.log(req.query.option);
switch (req.query.option) {
case 'User Id':
searchParam = { emp_id: req.query.value };
break;
case 'Email':
searchParam = { email: req.query.value };
break;
case 'First Name':
searchParam = { first_name: req.query.value };
break;
case '"Last Name':
searchParam = { last_name: req.query.value };
break;
default:
}
console.log("searchParam: " ,searchParam);
Employee.find(searchParam)
.exec()
.then(result => {
const response = {
employee_count: result.length,
employee_list: result
}
res.status(200).json(result)
})
.catch(err => {
res.status(500).json({
error: err
})
})
}
});
/*Retrive employee information by Employee Id*/
router.get('/byEmpId/:empId', (req, res, next) => {
const empId = req.params.empId;
Employee.find({ emp_id: empId })
//.select('emp_id first_name last_name email job_type status')
.exec()
.then(result => {
const response = {
employee_count: result.length,
employee_list: result
}
res.status(200).json({
responseBody: response
})
})
.catch(err => {
res.status(500).json({
error: err
})
})
});
router.get('/lastRecord', (req, res, next) => {
const empId = req.params.empId;
Employee.find().limit(1).sort({ $natural: -1 })
//.select('emp_id first_name last_name email job_type status')
.exec()
.then(result => {
const response = {
employee_count: result.length,
employee_list: result
}
res.status(200).json({
responseBody: response
})
})
.catch(err => {
res.status(500).json({
error: err
})
})
});
/*Retrive employee information by Email Id*/
router.get('/byEmailId/:emailId', (req, res, next) => {
const empId = req.params.emailId;
Employee.find({ email: empId })
.select('emp_id first_name last_name email job_type status')
.exec()
.then(result => {
const response = {
employee_count: result.length,
employee_list: result
}
res.status(200).json({
responseBody: response
})
})
.catch(err => {
res.status(500).json({
error: err
})
})
});
/*Inserting new employee details*/
router.post('/', (req, res, next) => {
Employee.find({ email: req.body.email.toUpperCase() })
.exec()
.then(result => {
if (result.length > 0) {
res.statusMessage = "Email Address Already Exists!!";
//res.statusText = 'Email Address :'+req.body.email.toUpperCase()+' already exists. Please choose different email address';
res.status(404).end();
} else {
Employee.find().limit(1).sort({ $natural: -1 })
.exec()
.then(result => {
if (result[0].emp_id) {
const employee = new Employee({
_id: new mongoose.Types.ObjectId,
emp_id: (parseInt(result[0].emp_id) + 1).toString(),
first_name: req.body.first_name.toUpperCase(),
last_name: req.body.last_name.toUpperCase(),
email: req.body.email.toUpperCase(),
phone: req.body.phone,
grade: req.body.grade,
role: req.body.role.toUpperCase(),
reporting_manager: req.body.reporting_manager.toUpperCase(),
joining_date: req.body.joining_date,
job_type: req.body.job_type,
status: req.body.status
})
employee.save()
.then(result => {
res.status(201).json(result);
})
.catch(err => {
res.status(500).json({
error: err
})
})
}
})
.catch(err => {
res.status(500).json({
error: err
})
})
}
})
});
/* Update the user details*/
router.patch('/:empId', (req, res, next) => {
const empId = req.params.empId;
const updateOps = {};
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
Employee.update({ emp_id: empId }, { $set: updateOps })
.exec()
.then(result => {
res.status(200).json({
product: result
})
})
.catch(err => {
res.status(500).json({
error: err
})
})
});
/* Delete the user entry*/
router.delete('/:empId', (req, res, next) => {
const empId = req.params.empId;
Employee.remove({ emp_id: empId })
.exec()
.then(result => {
res.status(200).json({ response: result });
})
.catch(err => {
res.status(500).json({ error: err })
})
});
module.exports = router;
|
var data;
GetData = async () => {
data = await fetch("/data").then((r) => r.json());
return data;
};
async function postData(data = {}) {
const dataVenues = await fetch("/venues", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
}).then((r) => r.json());
//console.log(dataVenues.venues);
return dataVenues.venues;
}
/* Formatting function for row details */
function format(venues) {
const start =
'<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
const end = "</table>";
var direlements = Object.values(venues)
.map(
(el) =>
"<tr>" +
"<td>Venue name:</td>" +
"<td>" +
el.name +
"</td>" +
"<td>Venue city:</td>" +
"<td>" +
el.city +
"</td>" +
"<td>Venue capacity:</td>" +
"<td>" +
el.capacity +
"</td>" +
"<tr>"
)
.join("");
//console.log(direlements);
return start + direlements + end;
}
//ready function
$(document).ready(async function () {
const json = await GetData();
//console.log(json);
// text input to each footer cell
$('#worldcups-table tfoot th').each(function () {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" style="width: 60px;" />');
});
var table = $("#worldcups-table").DataTable({
data: json,
columns: [{
data: "year"
},
{
data: "wikipediapage"
},
{
data: "host"
},
{
data: "beginning"
},
{
data: "ending"
},
{
data: "teamcount"
},
{
data: "champions"
},
{
data: "secondplace"
},
{
data: "thirdplace"
},
{
data: "fourthplace"
},
{
data: "matchcount"
},
{
data: "goalcount"
},
{
data: "attendance"
},
{
className: "details-control",
orderable: false,
data: null,
defaultContent: "click here",
}
],
order: [
[1, "asc"]
],
dom: 'Bfrtip',
buttons: [{
text: 'JSON',
action: function (e, dt, button, config) {
var years = dt.buttons.exportData().body.map(r => r[0]);
dataForExport = data.filter(r => years.includes(r.year));
console.log(dataForExport)
$.fn.dataTable.fileSave(
new Blob([JSON.stringify(dataForExport)]),
'FIFAWorldCups.json'
);
}
},
{
text: 'CSV',
action: function (e, dt, button, config) {
var years = dt.buttons.exportData().body.map(r => r[0]);
dataForExport = data.filter(r => years.includes(r.year));
var header = dt.buttons.exportData().header.toString() + 'venuename,venuecity,venuecapatity'
dataForExportCSV = dataForExport.map(r => {
var row = Object.keys(r).slice(0, -1).map(key => r[key].toString()).join(",");
var rowsForYear = r.venues.map(element => {
var venueRow = Object.keys(element).map(key => element[key].toString()).join(",");
return row + ',' + venueRow;
}).join('\n');
return rowsForYear;
}).join('\n');
var finalCSV = header + '\n' + dataForExportCSV
$.fn.dataTable.fileSave(
new Blob([finalCSV]),
'FIFAWorldCups.csv'
);
}
}
],
initComplete: function () {
// pretrazivanje po atributima
this.api().columns().every(function () {
var that = this;
$('input', this.footer()).on('keyup change clear', function () {
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
});
}
});
table.buttons().container()
.appendTo($('.col-sm-6:eq(0)', table.table().container()));
// event listener za prikaz i sakrivanje detalja o venueima
$("#worldcups-table tbody").on(
"click",
"td.details-control",
async function () {
var tr = $(this).closest("tr");
var row = table.row(tr);
console.log(row.value);
if (row.child.isShown()) {
row.child.hide();
tr.removeClass("shown");
} else {
var year = row.data().year;
var venues = await postData({
year
});
row.child(format(venues)).show();
tr.addClass("shown");
}
}
)
});
|
const config = {
testEnvironment: 'jest-environment-jsdom',
preset: "ts-jest",
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
// testEnvironment: "node",
transform: {
"^.+\\.ts?$": "ts-jest",
},
transformIgnorePatterns: ["<rootDir>/node_modules/"],
};
module.exports = config;
|
#!/usr/bin/env python
try:
from sugar.activity import bundlebuilder
bundlebuilder.start()
except ImportError:
print 'Cannot find a working sugar environment'
|
import React from "react"
export const headline1 = props => {
return <h1 className="toc-ignore">{props.children}</h1>
}
export const headline2 = props => {
return <h2 className="toc-ignore">{props.children}</h2>
}
export const headline3 = props => {
return <h3 className="toc-ignore">{props.children}</h3>
}
|
import React from 'react';
import CssBaseline from '@material-ui/core/CssBaseline';
import Typography from '@material-ui/core/Typography';
import Container from '@material-ui/core/Container';
import Paper from '@material-ui/core/Paper';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
const useStyles = makeStyles(theme => ({
root: {
padding: theme.spacing(3, 2),
width: 400,
height: 250,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
backgroundColor: 'rgba(255, 255, 255, 0.3)',
},
containerStyle: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
backgroundImage: "url(https://images.unsplash.com/photo-1495195134817-aeb325a55b65?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1955&q=80)",
backgroundRepeat: 'no-repeat',
backgroundSize: 'cover',
margin: '0 auto'
},
splashbtns: {
width: 100,
marginTop: 20,
backgroundColor: '#c62828',
'&:hover': {
backgroundColor: '#e53935'
}
},
btnCont: {
display: 'flex',
justifyContent: 'space-evenly'
},
}));
const Splash = props => {
const classes = useStyles();
const chefLogin = event => {
event.preventDefault();
props.history.push('/login');
};
const guestDirect = event => {
event.preventDefault();
props.history.push('/guest');
};
return (
<div>
<React.Fragment>
<CssBaseline />
<Container className={classes.containerStyle} maxWidth="100%" style = {{height: '100vh', width: '100vw'}} >
<Paper className={classes.root}>
<Typography variant="h4" component="h3">
Welcome to Chef Portfolio!
</Typography>
<Typography component="p">
Please choose one
</Typography>
<div className={classes.btnCont}>
<Button onClick={chefLogin} className={classes.splashbtns} variant="contained" color="primary">
Chef
</Button>
<Button onClick={guestDirect} className={classes.splashbtns} variant="contained" color="primary">
Guest
</Button>
</div>
</Paper>
</Container>
</React.Fragment>
</div>
);
};
export default Splash;
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Documents and Settings\John Creson\My Documents\maya\QtUi\makeStuff.ui'
#
# Created: Fri Feb 23 23:26:21 2007
# by: PyQt4 UI code generator 4.1.1
#
# WARNING! All changes made in this file will be lost!
import sys
from PyQt4 import QtCore, QtGui
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(QtCore.QSize(QtCore.QRect(0,0,200,137).size()).expandedTo(Dialog.minimumSizeHint()))
self.clickMake = QtGui.QPushButton(Dialog)
self.clickMake.setGeometry(QtCore.QRect(100,30,61,71))
self.clickMake.setObjectName("clickMake")
self.checkSphere = QtGui.QCheckBox(Dialog)
self.checkSphere.setGeometry(QtCore.QRect(20,30,71,18))
self.checkSphere.setObjectName("checkSphere")
self.checkTorus = QtGui.QCheckBox(Dialog)
self.checkTorus.setGeometry(QtCore.QRect(20,50,71,18))
self.checkTorus.setObjectName("checkTorus")
self.checkCube = QtGui.QCheckBox(Dialog)
self.checkCube.setGeometry(QtCore.QRect(20,70,71,18))
self.checkCube.setObjectName("checkCube")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
self.clickMake.setToolTip(QtGui.QApplication.translate("Dialog", "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal; text-decoration:none;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Choose your objects and push the Make button.</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.clickMake.setText(QtGui.QApplication.translate("Dialog", "Make", None, QtGui.QApplication.UnicodeUTF8))
self.checkSphere.setToolTip(QtGui.QApplication.translate("Dialog", "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal; text-decoration:none;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Check to choose Sphere to Make.</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"></p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.checkSphere.setText(QtGui.QApplication.translate("Dialog", "sphere", None, QtGui.QApplication.UnicodeUTF8))
self.checkTorus.setToolTip(QtGui.QApplication.translate("Dialog", "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal; text-decoration:none;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Check to choose Torus to Make.</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"></p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.checkTorus.setText(QtGui.QApplication.translate("Dialog", "torus", None, QtGui.QApplication.UnicodeUTF8))
self.checkCube.setToolTip(QtGui.QApplication.translate("Dialog", "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal; text-decoration:none;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Check to choose Cube to Make.</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"></p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
self.checkCube.setText(QtGui.QApplication.translate("Dialog", "cube", None, QtGui.QApplication.UnicodeUTF8))
# Copyright (C) 1997-2014 Autodesk, Inc., and/or its licensors.
# All rights reserved.
#
# The coded instructions, statements, computer programs, and/or related
# material (collectively the "Data") in these files contain unpublished
# information proprietary to Autodesk, Inc. ("Autodesk") and/or its licensors,
# which is protected by U.S. and Canadian federal copyright law and by
# international treaties.
#
# The Data is provided for use exclusively by You. You have the right to use,
# modify, and incorporate this Data into other products for purposes authorized
# by the Autodesk software license agreement, without fee.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. AUTODESK
# DOES NOT MAKE AND HEREBY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTIES
# INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF NON-INFRINGEMENT,
# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, OR ARISING FROM A COURSE
# OF DEALING, USAGE, OR TRADE PRACTICE. IN NO EVENT WILL AUTODESK AND/OR ITS
# LICENSORS BE LIABLE FOR ANY LOST REVENUES, DATA, OR PROFITS, OR SPECIAL,
# DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES, EVEN IF AUTODESK AND/OR ITS
# LICENSORS HAS BEEN ADVISED OF THE POSSIBILITY OR PROBABILITY OF SUCH DAMAGES.
|
/**
* Class representing a remote Fedora-based repository.
*/
/**
* WordPress dependencies.
*/
import apiFetch from '@wordpress/api-fetch';
/**
* External dependencies
*/
import parser from 'xml-js';
/**
* Represents a remote Fedora-based repository.
*
* Intended to be a general wrapper for the Fedora API, but currently
* ideosyncratic to the Humanities Commons CORE API, as many of its endpoints
* are locked down and so cannot organically discover URLs of datastreams, etc.
*
* @link https://wiki.lyrasis.org/display/FEDORA38/REST+API
*/
export default class FedoraRepository {
constructor( baseURL ) {
this.baseURL = baseURL;
// Descriptions based on field descriptions of Fedora API.
this.searchResultSchema = {
pid : {
description: 'Fedora persistent identifier',
type: 'string',
},
label : {
description: 'Label of object',
type: 'string',
},
state : {
description: 'State of object',
type: 'string'
},
ownerId : {
description: 'ID of object owner',
type: 'string'
},
cDate : {
description: 'Creation date of object',
type: 'string',
format: 'date-time'
},
mDate : {
description: 'Modification date',
type: 'string',
format: 'date-time'
},
dcmDate : {
description: 'Dublin core modification date',
type: 'string',
format: 'date-time'
},
title : {
description: 'Title of the object',
type: 'string'
},
creator : {
description: 'Creator(s) of object',
type: 'array',
items: {
type: 'string'
}
},
subject : {
description: 'Subject(s) of object',
type: 'array',
items: {
type: 'string'
}
},
description : {
description : 'Description of the object',
type: 'string'
},
publisher : {
description : 'Publisher(s) of the object',
type: 'array',
items: {
type: 'string'
}
},
contributor : {
description: 'Contributor(s) to the object',
type: 'array',
items: {
type: 'string'
}
},
date : {
description: 'Dublin Core date (publication date) of object',
type: 'string'
},
type : {
description: 'Dublin Core type of the object',
type: 'string'
},
format : {
description: 'Dublin Core format of the object',
type: 'string'
},
identifier : {
description: 'Dublin Core identifier(s) of the object',
type: 'array',
items: {
type: 'string'
}
},
source : {
description: 'Dublin Core source(s) of object',
type: 'array',
items: {
type: 'string'
}
},
language : {
description: 'Dublin Core language(s) of object',
type: 'array',
items: {
type: 'string'
}
},
relation : {
description: 'Dublin Core relation(s) of object',
type: 'array',
items: {
type: 'string'
}
},
coverage : {
description: 'Dublin Core coverage(s) of object',
type: 'array',
items: {
type: 'string'
}
},
rights : {
description: 'Dublin core rights of object',
type: 'array',
items: {
type: 'string'
}
}
}
}
/**
* Generates a query string from an array of key-comparator-value objects.
*
* @see: https://wiki.lyrasis.org/display/FEDORA38/REST+API#RESTAPI-findObjects
*
* query: a sequence of space-separated conditions. A condition consists of
* a metadata element name followed directly by an operator, followed
* directly by a value. Valid element names are (pid, label, state,
* ownerId, cDate, mDate, dcmDate, title, creator, subject, description,
* publisher, contributor, date, type, format, identifier, source,
* language, relation, coverage, rights). Valid operators are: contains (~),
* equals (=), greater than (>), less than (<), greater than or equals
* (>=), less than or equals (<=). The contains (~) operator may be used in
* combination with the ? and * wildcards to query for simple string
* patterns. Space-separators should be encoded in the URL as %20.
* Operators must be encoded when used in the URL syntax as follows: the
* (=) operator must be encoded as %3D, the (>) operator as %3E, the (<)
* operator as %3C, the (>=) operator as %3E%3D, the (<=) operator as
* %3C%3D, and the (~) operator as %7E. Values may be any string. If the
* string contains a space, the value should begin and end with a single
* quote character ('). If all conditions are met for an object, the object
* is considered a match. Do NOT use this parameter in combination with the
* "terms" parameter
*/
static generateQuery( searchParameters ) {
const comparatorEncodings = {
'=' : '%3D',
'>' : '%3E',
'<' : '%3C',
'~' : '%7E',
'>=' : '%3E%3D',
'<=' : '%3C%3D'
}
const queryString = searchParameters.reduce( ( qString, { field, comparator, searchText } ) => {
if ( searchText ) {
if ( qString ) {
qString += '%20'; // Space separator between query items
}
qString += field;
qString += comparatorEncodings[ comparator ];
qString += "'" + searchText.replace( ' ', '%20' ) + "'";
}
return qString;
}, '' );
return queryString;
}
/**
* Returns a list of fields based on the results schema.
*/
getFieldList() {
return Object.keys( this.searchResultSchema );
}
/**
* Find objects in the repository. Corresponds to the /objects endpoint of
* the Fedora API.
*
* @link https://wiki.lyrasis.org/display/FEDORA38/REST+API#RESTAPI-findObjects
*
* @param Object searchParameters Each object key corresponds to a search
* parameter and the value is the value of that parameter for the search.
*/
findObjects( searchParameters ) {
const fields = this.getFieldList();
const parameterDefaults = fields.reduce( ( params, field ) => {
params[ field ] = true;
return params;
}, {} );
parameterDefaults.maxResults = 25;
parameterDefaults.resultFormat = 'xml';
const newParameters = { ...searchParameters }
if ( newParameters.query && typeof newParameters.query !== 'string' ) {
newParameters.query = FedoraRepository.generateQuery( newParameters.query );
}
const finalParameters = {
...parameterDefaults,
...newParameters
}
const parameterString = Object.entries( finalParameters )
.reduce( ( paramString, params) => {
if ( paramString ) {
paramString += '&';
}
paramString += params[0] + '=' + params[1];
return paramString;
}, '' );
// Humanities Commons doesn't allow cross-origin requests, so need to
// make the request server-side, using the WordPress REST API.
return apiFetch( {
path: '/fem-embed/v1/find',
method: 'POST',
data: { baseURL: this.baseURL, parameterString: parameterString }
} ).then( result => {
return result
} );
}
/**
* Gets data for a particular Humanities Commons item.
*
* Corresponds to the objects/<pid>/datastreams/descMetadata/content
* endpoint of the Humanities Commons API.
*
* @param string pid The Persistent Identifier of the object. On HC, in the form HC:#####
*/
getItemData( pid ) {
return apiFetch( {
path: '/fem-embed/v1/item',
method: 'POST',
data: { baseURL: this.baseURL, pid: pid }
} ).then( result => {
return result
} );
}
}
|
//Test 1
import { convertToRoman } from './../src/roman-numerals.js'
describe('convertToRoman', () => {
test('should correctly convert numbers to roman numerals', () => {
var toRoman = convertToRoman(1);
console.log(toRoman);
expect(toRoman).toEqual("I");
});
test('can not be more than three same symbols in one line', () => {
var toRoman = convertToRoman(4);
console.log(toRoman);
expect(toRoman).toBe("IV");
});
test('the number can not be greater than 3999', () => {
var toRoman = convertToRoman(4000);
expect(toRoman).toBeFalsy();
})
});
|
var UsersList = Backbone.View.extend({
el: '.users',
initialize: function () {
this.initTooltips();
},
initTooltips: function () {
var _this = this;
this.$el.find('.user').each(function (index, el) {
_this.initTooltipByUser($(el));
});
},
initTooltipByUser: function (user) {
user.tooltipster({
content: this.getTooltipContent(user),
position: "right",
theme: "tooltipster-shadow"
});
},
getTooltipContent: function (user) {
var userBadges = user.find('.info').data('badges');
var userXp = user.find('.info').data('xp');
var wrapper = $("<div></div>").addClass('user-tooltip-wrapper');
wrapper.append($("<p></p>").text("Experienta (XP):").css("font-weight", "bold"));
$.each(userXp, function(index, value){
wrapper.append($("<li></li>").text(index + " : " + value + " xp"));
});
if(Object.keys(userBadges).length <= 0){
return wrapper;
}
wrapper.append($("<p></p>").text("Insigne obtinute:").css("font-weight", "bold"));
$.each(userBadges, function (index, value) {
var badge = $("<div></div>");
var ul = $('<ul></ul>');
badge.append(ul);
var img = $('<img>').attr('src', "/" + value.badge_logo_url).addClass('img-circle');
var name = $('<span></span>').text(value.badge_title);
ul.append($("<li></li>").append(img).append(name));
wrapper.append(badge);
});
return wrapper;
}
});
var obj = new UsersList();
|
import {
insertNode,
} from './tree-data-utils';
import {
memoizedInsertNode,
} from './memoized-tree-data-utils';
describe('insertNode', () => {
it('should handle empty data', () => {
const params = {
treeData: [],
depth: 0,
minimumTreeIndex: 0,
newNode: {},
getNodeKey: ({ treeIndex }) => treeIndex,
};
expect(insertNode(params) === insertNode(params)).toEqual(false);
expect(memoizedInsertNode(params) === memoizedInsertNode(params)).toEqual(true);
expect(memoizedInsertNode(params) === memoizedInsertNode({...params, treeData: [{}]})).toEqual(false);
});
});
|
import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import List from '@material-ui/core/List';
import Card from '@material-ui/core/Card';
import CardHeader from '@material-ui/core/CardHeader';
import ListItem from '@material-ui/core/ListItem';
import Checkbox from '@material-ui/core/Checkbox';
import Button from '@material-ui/core/Button';
import Divider from '@material-ui/core/Divider';
import { Table, TableCell, TableRow, TextField } from '@material-ui/core';
import {
MuiPickersUtilsProvider,
} from '@material-ui/pickers';
import DateFnsUtils from '@date-io/date-fns';
import { ThemeProvider } from '@material-ui/core'
import { createMuiTheme } from '@material-ui/core/styles';
import SaveIcon from '@material-ui/icons/Save';
const useStyles = makeStyles((theme) => ({
root: {
margin: 'auto',
},
cardHeader: {
padding: theme.spacing(1, 2),
},
list: {
width: 400,
height: 300,
backgroundColor: theme.palette.background.paper,
overflow: 'auto',
},
button: {
margin: theme.spacing(0.5, 0),
},
}));
function not(a, b) {
return a.filter((value) => b.indexOf(value) === -1);
}
function intersection(a, b) {
return a.filter((value) => b.indexOf(value) !== -1);
}
function union(a, b) {
return [...a, ...not(b, a)];
}
export default function TransferEmployeeList() {
const classes = useStyles();
const [checked, setChecked] = React.useState([]);
// const [left, setLeft] = React.useState([0, 1, 2, 3]);
// const [right, setRight] = React.useState([4, 5, 6, 88]);
const employee = [
{ id: 101, name: 'Peeraphut punsuwan', department: 'เคลือบ/พิมพ์ตรา', barnch: 'วังน้อย' },
{ id: 102, name: 'Sasipa', department: 'มัดท่อ', barnch: 'ปู่เจ้า' },
{ id: 103, name: 'Ponlawat', department: 'ชุบ', barnch: 'วังน้อย' },
{ id: 104, name: 'Ponlawat', department: 'ชุบ', barnch: 'วังน้อย' },
{ id: 105, name: 'Ponlawat', department: 'ชุบ', barnch: 'วังน้อย' },
{ id: 106, name: 'Ponlawat', department: 'ชุบ', barnch: 'วังน้อย' },
{ id: 107, name: 'Ponlawat', department: 'ชุบ', barnch: 'วังน้อย' },
{ id: 108, name: 'Ponlawat', department: 'ชุบ', barnch: 'วังน้อย' },
{ id: 109, name: 'Ponlawat', department: 'ชุบ', barnch: 'ปู่เจ้า' },
{ id: 110, name: 'Ponlawat', department: 'ชุบ', barnch: 'วังน้อย' },
{ id: 111, name: 'Ponlawat', department: 'ชุบ', barnch: 'ปู่เจ้า' },
{ id: 112, name: 'Ponlawat', department: 'ชุบ', barnch: 'วังน้อย' },
{ id: 113, name: 'Ponlawat', department: 'ชุบ', barnch: 'ปู่เจ้า' },
{ id: 114, name: 'Ponlawat', department: 'ชุบ', barnch: 'วังน้อย' }
]
const employeeSelected = [
{ id: 115, name: 'Peeraphut', department: 'A', startTime: '', endTime: '', task: '' },
{ id: 116, name: 'Ponlawat', department: 'B', startTime: '', endTime: '', task: '' }
]
const [left, setLeft] = React.useState(employee);
const [right, setRight] = React.useState(employeeSelected);
const leftChecked = intersection(checked, left);
const rightChecked = intersection(checked, right);
const handleToggle = (value) => () => {
const currentIndex = checked.indexOf(value);
const newChecked = [...checked];
if (currentIndex === -1) {
newChecked.push(value);
} else {
newChecked.splice(currentIndex, 1);
}
setChecked(newChecked);
};
const numberOfChecked = (items) => intersection(checked, items).length;
const handleToggleAll = (items) => () => {
if (numberOfChecked(items) === items.length) {
setChecked(not(checked, items));
} else {
setChecked(union(checked, items));
}
};
const handleCheckedRight = () => {
setRight(right.concat(leftChecked));
setLeft(not(left, leftChecked));
setChecked(not(checked, leftChecked));
};
const handleCheckedLeft = () => {
setLeft(left.concat(rightChecked));
setRight(not(right, rightChecked));
setChecked(not(checked, rightChecked));
};
const theme = createMuiTheme({
overrides: {
MuiTableCell: {
root: {
paddingTop: 8,
paddingBottom: 4,
"&:last-child": {
paddingRight: 5
}
}
},
},
});
//const [search, setSearch] = React.useState("");
const customList = (title, items, btnTransfer) => (
<Card style={{width:'100%'}}>
<CardHeader
className={classes.cardHeader}
avatar={
<Checkbox
onClick={handleToggleAll(items)}
checked={numberOfChecked(items) === items.length && items.length !== 0}
indeterminate={numberOfChecked(items) !== items.length && numberOfChecked(items) !== 0}
disabled={items.length === 0}
inputProps={{ 'aria-label': 'all items selected' }}
/>
}
title={title}
subheader={`${numberOfChecked(items)}/${items.length} selected`}
/>
<Divider />
{/* {title == 'เลือกรายชื่อเข้ารายการ' ? <TableCell component="th" scope="row">
<TextField
type="text"
onChange={e => {
const test = employee.filter(team => {
return team.name.toLowerCase().includes(e.target.value.toLowerCase());
});
console.log("test: ", test);
console.log("test: ", e.target.value);
setTeams(test);
setSearch(e.target.value);
}}
value={search}
hidden={true}
></TextField>
<div className="App" hidden>
{teams.map(team => (
<p>{team.name}</p>
))}
</div>
</TableCell> : ''} */}
<List style={{
// width: title == 'เลือกรายชื่อเข้ารายการ' ? 450 : 920,
height: 280,
overflow: 'auto',
}} dense component="div" role="list">
<ThemeProvider theme={theme}></ThemeProvider>
<Table size="small" >
{items.map((value) => {
const labelId = `transfer-list-all-item-${value}-label`;
return (
<TableRow key={value.id}>
<TableCell component="th" scope="row" style={{ padding: 0 }} >
<ListItem key={value} role="listitem" button >
<Checkbox
checked={checked.indexOf(value) !== -1}
tabIndex={-1}
disableRipple
inputProps={{ 'aria-labelledby': labelId }}
onClick={handleToggle(value)}
style={{ padding: 1 }}
/>
</ListItem>
</TableCell>
<TableCell component="th" scope="row" style={{ fontSize: '1vw', padding: 1 }}>
{value.name}({value.id})
</TableCell>
<TableCell component="th" scope="row" style={{ fontSize: '0.8vw', paddingLeft: 0,textAlign:'center' }}>
{value.department}
</TableCell>
<TableCell component="th" scope="row" style={{ fontSize: '0.8vw', paddingLeft: 0 }}>
{value.barnch}
</TableCell>
{title !== 'เลือกรายชื่อเข้ารายการ' ? <TableCell component="th" scope="row" style={{ padding: 0 }}>
<TextField
type="datetime-local"
defaultValue="2017-05-24T10:30"
InputLabelProps={{
shrink: true,
}}
className={classes.textField}
label="เวลาเข้า"
onChange={(e) => {
const elementsIndex = right.findIndex(element => element.id == value.id)
let newArray = [...right]
newArray[elementsIndex] = { ...newArray[elementsIndex], startTime: e.target.value }
setRight(newArray)
}}
inputProps={{ style: { fontSize: 10 } }}
></TextField>
</TableCell> : ''}
{title !== 'เลือกรายชื่อเข้ารายการ' ? <TableCell component="th" scope="row" style={{ fontSize: 10, padding: 0 }} >
<TextField
type="datetime-local"
defaultValue="2017-05-24T10:30"
InputLabelProps={{
shrink: true,
}}
className={classes.textField}
label="เวลาออก"
onChange={(e) => {
const elementsIndex = right.findIndex(element => element.id == value.id)
let newArray = [...right]
newArray[elementsIndex] = { ...newArray[elementsIndex], endTime: e.target.value }
setRight(newArray)
}}
inputProps={{ style: { fontSize: 10 } }}
></TextField>
</TableCell> : ''}
{title !== 'เลือกรายชื่อเข้ารายการ' ?
<TableCell component="th" scope="row" style={{ width: 210 }}>
<TextField
InputLabelProps={{
shrink: true,
}}
label="ระบุงานที่ทำ"
onChange={(e) => {
const elementsIndex = right.findIndex(element => element.id == value.id)
let newArray = [...right]
newArray[elementsIndex] = { ...newArray[elementsIndex], task: e.target.value }
setRight(newArray)
}}
inputProps={{ style: { fontSize: 10 } }}
style={{width:'100%'}}
>
</TextField>
</TableCell> : ''}
</TableRow>
);
})}
</Table>
<ListItem />
</List>
<List dense >
<Grid container >
<Grid item xs={12}>
{btnTransfer}
</Grid>
{/* <Grid item>
{title !== 'เลือกรายชื่อเข้ารายการ' ?
<Button
variant="contained"
color="primary"
size="large"
className={classes.button}
startIcon={<SaveIcon />}
>
Save
</Button> : ''}
</Grid> */}
</Grid>
</List>
</Card>
);
return (
<Grid container spacing={1} justify="center" alignItems="center" className={classes.root}>
<Grid item xs={4}>
<Grid item >
{customList('เลือกรายชื่อเข้ารายการ', left,
<Button
variant="outlined"
size="small"
className={classes.button}
onClick={handleCheckedRight}
disabled={leftChecked.length === 0}
aria-label="move selected right"
style={{ marginLeft: '15%' }}
color="primary"
>
เลือกรายชื่อเข้ารายการ
</Button>
)}
</Grid>
</Grid>
<Grid item xs={8}>
<div style={{ width: 300 }}>
{/* {JSON.stringify(right)} */}
</div>
{customList('เลือกรายชื่อออกรายการ', right,
<Button
variant="outlined"
size="small"
className={classes.button}
onClick={handleCheckedLeft}
disabled={rightChecked.length === 0}
aria-label="move selected left"
style={{ marginLeft: '15%' }}
color="default"
>
นำรายชื่อออกจากรายการ
</Button>
)}
</Grid>
</Grid>
);
}
|
from butiran.vect3 import Vect3
|
log_level = 'INFO'
load_from = None
resume_from = None
dist_params = dict(backend='nccl')
workflow = [('train', 1)]
checkpoint_config = dict(interval=5, create_symlink=False)
evaluation = dict(interval=10, metric='mAP', key_indicator='AP')
optimizer = dict(
type='Adam',
lr=5e-4,
)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=0.001,
step=[170, 200])
total_epochs = 210
log_config = dict(
interval=50,
hooks=[
dict(type='TextLoggerHook'),
# dict(type='TensorboardLoggerHook')
])
channel_cfg = dict(
num_output_channels=17,
dataset_joints=17,
dataset_channel=[
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
],
inference_channel=[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
])
# model settings
model = dict(
type='TopDown',
pretrained='torchvision://resnet101',
backbone=dict(type='ResNet', depth=101),
keypoint_head=dict(
type='TopDownSimpleHead',
in_channels=2048,
out_channels=channel_cfg['num_output_channels'],
loss_keypoint=dict(type='JointsMSELoss', use_target_weight=True)),
train_cfg=dict(),
test_cfg=dict(
flip_test=True,
post_process='default',
shift_heatmap=True,
modulate_kernel=11))
data_cfg = dict(
image_size=[288, 384],
heatmap_size=[72, 96],
num_output_channels=channel_cfg['num_output_channels'],
num_joints=channel_cfg['dataset_joints'],
dataset_channel=channel_cfg['dataset_channel'],
inference_channel=channel_cfg['inference_channel'],
soft_nms=False,
nms_thr=1.0,
oks_thr=0.9,
vis_thr=0.2,
use_gt_bbox=True,
det_bbox_thr=0.0,
bbox_file='data/person_detection_results/'
'COCO_val2017_detections_AP_H_56_person.json',
)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='TopDownRandomFlip', flip_prob=0.5),
dict(
type='TopDownHalfBodyTransform',
num_joints_half_body=8,
prob_half_body=0.3),
dict(
type='TopDownGetRandomScaleRotation', rot_factor=40, scale_factor=0.5),
dict(type='TopDownAffine'),
dict(type='ToTensor'),
dict(
type='NormalizeTensor',
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
dict(type='TopDownGenerateTarget', sigma=3),
dict(
type='Collect',
keys=['img', 'target', 'target_weight'],
meta_keys=[
'image_file', 'joints_3d', 'joints_3d_visible', 'center', 'scale',
'rotation', 'bbox_score', 'flip_pairs'
]),
]
val_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='TopDownAffine'),
dict(type='ToTensor'),
dict(
type='NormalizeTensor',
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
dict(
type='Collect',
keys=['img'],
meta_keys=[
'image_file', 'center', 'scale', 'rotation', 'bbox_score',
'flip_pairs'
]),
]
test_pipeline = val_pipeline
data_root = 'data/ochuman'
data = dict(
samples_per_gpu=32,
workers_per_gpu=2,
val_dataloader=dict(samples_per_gpu=256),
test_dataloader=dict(samples_per_gpu=256),
train=dict(
type='TopDownCocoDataset',
ann_file='data/coco/annotations/person_keypoints_train2017.json',
img_prefix='data/coco//train2017/',
data_cfg=data_cfg,
pipeline=train_pipeline),
val=dict(
type='TopDownOCHumanDataset',
ann_file=f'{data_root}/annotations/'
'ochuman_coco_format_val_range_0.00_1.00.json',
img_prefix=f'{data_root}/images/',
data_cfg=data_cfg,
pipeline=val_pipeline),
test=dict(
type='TopDownOCHumanDataset',
ann_file=f'{data_root}/annotations/'
'ochuman_coco_format_test_range_0.00_1.00.json',
img_prefix=f'{data_root}/images/',
data_cfg=data_cfg,
pipeline=val_pipeline),
)
|
var util = require("util")
, EventEmitter = require("events").EventEmitter
, Promise = require("bluebird")
, proxyEventKeys = ['success', 'error', 'sql']
, Utils = require('../utils')
var bindToProcess = function(fct) {
if (fct && process.domain) {
return process.domain.bind(fct)
}
return fct
};
module.exports = (function() {
var CustomEventEmitter = function(fct) {
this.fct = bindToProcess(fct)
}
util.inherits(CustomEventEmitter, EventEmitter)
CustomEventEmitter.prototype.run = function() {
Utils.tick(function() {
if (this.fct) {
this.fct.call(this, this)
}
}.bind(this))
return this
}
/**
Shortcut methods (success, ok) for listening for success events.
Params:
- fct: A function that gets executed once the *success* event was triggered.
Result:
The function returns the instance of the query.
*/
CustomEventEmitter.prototype.success =
CustomEventEmitter.prototype.ok =
function(fct) {
this.on('success', bindToProcess(fct))
return this
}
/**
Shortcut methods (failure, fail, error) for listening for error events.
Params:
- fct: A function that gets executed once the *error* event was triggered.
Result:
The function returns the instance of the query.
*/
CustomEventEmitter.prototype.failure =
CustomEventEmitter.prototype.fail =
CustomEventEmitter.prototype.error =
function(fct) {
this.on('error', bindToProcess(fct))
return this;
}
CustomEventEmitter.prototype.done =
CustomEventEmitter.prototype.complete =
function(fct) {
fct = bindToProcess(fct);
this.on('error', function(err) { fct(err, null) })
.on('success', function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(null);
fct.apply(fct, args);
})
return this
}
CustomEventEmitter.prototype.sql = function(fct) {
this.on('sql', bindToProcess(fct))
return this;
}
/**
* Proxy every event of this custom event emitter to another one.
*
* @param {CustomEventEmitter} emitter The event emitter that should receive the events.
* @return {void}
*/
CustomEventEmitter.prototype.proxy = function(emitter, options) {
options = Utils._.extend({
events: proxyEventKeys,
skipEvents: []
}, options || {})
options.events = Utils._.difference(options.events, options.skipEvents)
options.events.forEach(function (eventKey) {
this.on(eventKey, function (result) {
emitter.emit(eventKey, result)
})
}.bind(this))
return this
}
CustomEventEmitter.prototype.then = function(onFulfilled, onRejected) {
var self = this
onFulfilled = bindToProcess(onFulfilled)
onRejected = bindToProcess(onRejected)
return new Promise(function (resolve, reject) {
self.on('error', reject)
.on('success', resolve);
}).then(onFulfilled, onRejected)
}
return CustomEventEmitter;
})()
|
import numpy as np
#======================================================================================#
# Interaction Matrix Definition #
# s is the feature.
# cam is camera matrix
# Z is depth information of dimensions(p*q)
#======================================================================================#
def interactionMatrix(s, cam, Z):
p, q = 512, 384
KK = cam
px, py = KK[0, 0], KK[1, 1]
v0, u0 = KK[0, 2], KK[1, 2]
Lsd = np.zeros((p*q*2, 6))
for m in range(0, p*q*2 - 2, 2):
x = (int(s[m]) - int(u0))/px
y = (int(s[m+1]) - int(v0))/py
t = int(s[m])
u = int(s[m+1])
Zinv = 10/(Z[u, t] + 1)
Lsd[m, 0] = -Zinv
Lsd[m,1]=0
Lsd[m,2]=x*Zinv
Lsd[m,3]=x*y
Lsd[m,4]=-(1+x**2)
Lsd[m,5]=y
Lsd[m+1,0]= 0
Lsd[m+1,1]= -Zinv
Lsd[m+1,2]= y*Zinv
Lsd[m+1,3]= 1+y**2
Lsd[m+1,4]= -x*y
Lsd[m+1,5]= -x
return Lsd
#======================================================================================#
|
module.exports = function (error, _, response, next) {
if (error) {
console.error(error);
response
.status(500)
.json({
error: error.message
})
} else {
return next();
}
}
|
import React from 'react'
import {connect} from 'react-redux'
import WYSIWYGeditor from '../../components/articles/WYSIWYGeditor'
import {stateToHTML} from 'draft-js-export-html'
import {bindActionCreators} from 'redux'
import {Link} from 'react-router'
import articleActions from '../../actions/article'
import RaisedButton from 'material-ui/lib/raised-button'
import falcorModel from '../../falcorModel'
import ImgUploader from '../../components/articles/ImgUploader'
import DefaultInput from '../../components/DefaultInput'
import Formsy from 'formsy-react'
const mapStateToProps = (state) => ({
...state
})
//can add reducers here
const mapDispatchToProps = (dispatch) => ({
articleActions: bindActionCreators(articleActions, dispatch)
})
class AddArticleView extends React.Component {
constructor(props) {
super(props)
this._onDraftJSChange = this._onDraftJSChange.bind(this)
this._articleSubmit = this._articleSubmit.bind(this)
this.updateImgUrl = this.updateImgUrl.bind(this)
this.state = {
title: 'test',
contentJSON: {},
htmlContent: '',
newArticleID: null,
articlePicUrl: '/static/placeholder.png'
}
}
_onDraftJSChange(contentJSON, contentState) {
let htmlContent = stateToHTML(contentState)
this.setState({contentJSON, htmlContent})
}
async _articleSubmit(articleModel) {
let newArticle = {
articleTitle: articleModel.title,
articleSubTitle: articleModel.subTitle,
articleContent: this.state.htmlContent,
articleContentJSON: this.state.contentJSON,
articlePicUrl: this.state.articlePicUrl
}
let newArticleID = await falcorModel
.call('articles.add', [newArticle])
.then( (result) => {
return falcorModel.getValue(['articles', 'newArticleID'])
.then( (articleID) => {
return articleID
})
})
newArticle['_id'] = newArticleID
this.props.articleActions.pushNewArticle(newArticle)
this.setState({newArticleID: newArticleID})
}
updateImgUrl(articlePicUrl) {
this.setState({
articlePicUrl: articlePicUrl
})
}
render() {
if (this.state.newArticleID) {
return (
<div style={{height: '100%', width: '75%', margin: 'auto'}}>
<h3>Your new article ID is {this.state.newArticleID}</h3>
<Link to='/dashboard'>
<RaisedButton
secondary={true}
type='submit'
style={{margin: '10px auto', display: 'block', width: 150}}
label='Done'
/>
</Link>
</div>
)
}
return (
<div style={{height: '100%', width: '75%', margin: 'auto'}}>
<h1>Add Article</h1>
<Formsy.Form onSubmit={this._articleSubmit}>
<DefaultInput
onChange={ (event) => {}}
name='title'
title='Article Title (requried)'
required={true}
/>
<DefaultInput
onChange={ (event) => {}}
name='subTitle'
title='Article Subtitle'
/>
<WYSIWYGeditor
name='addarticle'
title='Create an Article'
onChangeTextJSON={this._onDraftJSChange}
/>
<div style={{margin: '10px'}}>
<ImgUploader
updateImgUrl={this.updateImgUrl}
articlePicUrl={this.state.articlePicUrl}
/>
</div>
<RaisedButton
onClick={this._articleSubmit}
secondary={true}
type='submit'
style={{margin: '10px auto', display: 'block', width: 150}}
label={'Submit Article'}
/>
</Formsy.Form>
</div>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AddArticleView)
|
var searchData=
[
['operator_28_29',['operator()',['../classscots_1_1_enf_pre.html#af0b723246ff1f6ed85c475bd5acc9cf4',1,'scots::EnfPre']]]
];
|
""".. Ignore pydocstyle D400.
=============
Flow Managers
=============
Workflow workload managers.
.. data:: manager
The global manager instance.
:type: :class:`~resolwe.flow.managers.dispatcher.Manager`
.. automodule:: resolwe.flow.managers.dispatcher
:members:
.. automodule:: resolwe.flow.managers.workload_connectors
.. automodule:: resolwe.flow.managers.listener
.. automodule:: resolwe.flow.managers.consumer
:members:
.. automodule:: resolwe.flow.managers.utils
:members:
"""
from .dispatcher import Manager
from .listener import ExecutorListener
__all__ = ("manager", "listener")
manager = Manager()
listener = ExecutorListener()
|
var ghostBookshelf = require('./base'),
App,
Apps;
App = ghostBookshelf.Model.extend({
tableName: 'apps',
saving: function (newPage, attr, options) {
/*jshint unused:false*/
var self = this;
ghostBookshelf.Model.prototype.saving.apply(this, arguments);
if (this.hasChanged('slug') || !this.get('slug')) {
// Pass the new slug through the generator to strip illegal characters, detect duplicates
return ghostBookshelf.Model.generateSlug(App, this.get('slug') || this.get('name'),
{transacting: options.transacting})
.then(function (slug) {
self.set({slug: slug});
});
}
},
permissions: function () {
return this.belongsToMany('Permission', 'permissions_apps');
},
settings: function () {
return this.belongsToMany('AppSetting', 'app_settings');
}
}, {
/**
* Returns an array of keys permitted in a method's `options` hash, depending on the current method.
* @param {String} methodName The name of the method to check valid options for.
* @return {Array} Keys allowed in the `options` hash of the model's method.
*/
permittedOptions: function (methodName) {
var options = ghostBookshelf.Model.permittedOptions(),
// whitelists for the `options` hash argument on methods, by method name.
// these are the only options that can be passed to Bookshelf / Knex.
validOptions = {
findOne: ['withRelated']
};
if (validOptions[methodName]) {
options = options.concat(validOptions[methodName]);
}
return options;
}
});
Apps = ghostBookshelf.Collection.extend({
model: App
});
module.exports = {
App: ghostBookshelf.model('App', App),
Apps: ghostBookshelf.collection('Apps', Apps)
};
|
var express = require('express');
var fs = require('fs');
var router = express.Router();
var connection = require('../index.js').connection;
let { PythonShell } = require('python-shell');
router.post("/show_all_mylist", function (req, res, next) {
var recv_uID = req.body.uID;
var SQL = 'SELECT p_code, title, apply_start, apply_end from policy, stored_policy where p_code = s_p_code AND uID = \'' + recv_uID + '\'';
console.log("API '/my_list/show_all_mylist' called");
console.log(SQL);
connection.query(SQL, function (err, data) {
if (!err) {
//console.log(data);
res.send(data);
}
else {
console.log(err);
res.send('error');
}
});
});
router.post("/store_in_mylist", function (req, res, next) {
var recv_uID = req.body.uID;
var recv_s_p_code = req.body.s_p_code;
console.log("API 'my_list/store_in_mylist' called");
const promise1 = function (recv_uID) {
return new Promise(function (resolve, reject) {
if (recv_uID) {
var SQL = 'INSERT INTO stored_policy (uID, s_p_code, s_p_time) SELECT ' +
'\'' + recv_uID + '\'' +
', ' + recv_s_p_code +
', ' + 'DATE_SUB(NOW(), INTERVAL -9 HOUR)' +
' WHERE NOT EXISTS (SELECT s_p_code FROM stored_policy WHERE uID = ' +
'\'' + recv_uID + '\'' + ' AND ' +
's_p_code = ' + recv_s_p_code + ')';
console.log(SQL);
//절 차
connection.query(SQL, function (err, data) {
if (!err) {
// finally
res.send(data);
resolve("complete");
}
else {
console.log(err);
res.send('error');
}
});
}
else {
reject("fail");
}
});
}
promise1(recv_uID).then(function (result) {
var options = {
mode: 'text',
pythonPath: '/usr/bin/python3.7',
pythonOptions: ['-u'],
scriptPath: 'KNN',
args: [recv_uID]
};
PythonShell.run('knn_base_rec.py', options, function (err, results) {
if (err) {
throw err;
}
console.log("result: " + results);
});
}, function (err) {
console.log(err);
res.send("fail");
});
});
router.post("/ordered_mylist", function (req, res, next) {
var recv_uID = req.body.uID;
var recv_Sort_by = req.body.Sort_by;
// my List 정렬 기준 두가지 (type: String)
// 1. "저장날짜순"
// 2. "지원날짜순"
var sortingList = ["저장날짜순", "지원날짜순"];
var after_sortingList = ["s_p_time DESC", "apply_end is null ASC, apply_end ASC"];
var ORDER_SQL = 'ORDER BY s_p_time DESC'; //default
//console.log("sortingList.lenth: " + sortingList.length);
for (var i = 0; i < sortingList.length; i++) {
//console.log("recv_Sort_by: " + recv_Sort_by);
if (recv_Sort_by == sortingList[i]) {
//console.log("same: " + recv_Sort_by);
ORDER_SQL = "ORDER BY " + after_sortingList[i];
}
}
var SQL = 'SELECT p_code, title, ' +
"DATE_SUB(apply_start, INTERVAL -9 HOUR) AS apply_start, " +
"DATE_SUB(apply_end, INTERVAL -9 HOUR) AS apply_end " +
'from stored_policy, policy ' +
'where p_code = s_p_code ' +
'AND uID = \'' + recv_uID + '\' ' +
ORDER_SQL;
console.log("API 'my_list/ordered_mylist' called");
console.log(SQL);
connection.query(SQL, function (err, data) {
if (!err) {
//console.log(data);
res.send(data);
}
else {
console.log(err);
res.send('error');
}
});
});
router.post("/delete", function (req, res, next) {
var recv_uID = req.body.uID;
var recv_s_p_code = req.body.s_p_code;
console.log("API 'my_list/delete' called");
const promise1 = function (recv_uID) {
return new Promise(function (resolve, reject) {
if (recv_uID) {
var SQL = 'DELETE FROM stored_policy where ' +
'uID = \'' + recv_uID + '\' AND ' +
's_p_code = ' + recv_s_p_code ;
console.log(SQL);
connection.query(SQL, function (err, data) {
if (!err) {
res.send(data);
resolve("complete");
}
else {
console.log(err);
res.send('error');
}
});
}
else {
reject("fail");
}
});
}
promise1(recv_uID).then(function (result) {
var options = {
mode: 'text',
pythonPath: '/usr/bin/python3.7',
pythonOptions: ['-u'],
scriptPath: 'KNN',
args: [recv_uID]
};
PythonShell.run('knn_base_rec.py', options, function (err, results) {
if (err) {
throw err;
}
console.log("result: " + results);
});
}, function (err) {
console.log(err);
res.send("fail");
});
});
module.exports = router;
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[21],{vpaw:function(l,n,e){"use strict";e.r(n);var u=e("CcnG"),t=e("lHUG");Object(t.a)("fr",t.d);var o=function(){return function(){}}(),i=e("pMnS"),a=e("73KY"),r=e("fSqE"),s=e("Ip0R"),c=e("xtZt"),d=e("lqqz"),p=e("Bi9T"),g=e("sivw"),f=e("6m5y"),m=e("Tw24"),h=e("tVhE"),v=e("J9Qv"),b=e("MdoF"),y=e("lTVp"),C=e("MJJn"),F=e("mPam"),w=e("gIcY"),T=e("ARl4"),x=e("7yHZ"),R=e("jVYb"),I=e("eajB"),P=e("NJnL"),E=e("Z7E6"),S=e("pKUh"),O=e("YAQW"),_=e("jvCn"),q=e("miAi"),D=e("DlHu"),M=e("YnkE"),N=e("mrSG"),V=function(l){function n(){return null!==l&&l.apply(this,arguments)||this}return N.__extends(n,l),n}(e("Gexc").a),k=e("OkQV"),L=(e("Jc0W"),e("BJcj")),A=e("+Ish"),U=e("avKP"),B=e("3wuH"),$=e("PajD"),j=e("K9Ia"),H=function(){function l(l,n,e){this.factureService=l,this.modalRef=n,this.toastr=e,this.facture=new V,this.factureSubscription=null,this.isLoading=!1}return l.prototype.ngOnInit=function(){this.onClose=new j.a},l.prototype.showRemoveModal=function(l,n){this.type=l,this.facture=n},l.prototype.confirm=function(){var l=this;this.isLoading=!0,"d"===this.type&&(this.factureSubscription=this.factureService.disableFacture(this.facture).subscribe(function(n){console.log(n);var e={type:l.type,facture:l.facture};l.showDisable("Facture d\xe9sactiv\xe9e avec succ\xe8s"),l.onClose.next(e),l.isLoading=!1,l.modalRef.hide()},function(n){console.log(n),l.isLoading=!1})),"r"===this.type&&(this.factureSubscription=this.factureService.removeFacture(this.facture).subscribe(function(n){var e={type:l.type,facture:l.facture};l.showRemove("Facture supprim\xe9e avec succ\xe8s"),l.onClose.next(e),l.isLoading=!1,l.modalRef.hide()},function(n){console.log(n),l.isLoading=!1})),"e"===this.type&&(this.factureSubscription=this.factureService.enableFacture(this.facture).subscribe(function(n){console.log(n);var e={type:l.type,facture:l.facture};l.showEnable("Facture activ\xe9e avec succ\xe8s"),l.onClose.next(e),l.isLoading=!1,l.modalRef.hide()},function(n){console.log(n),l.isLoading=!1}))},l.prototype.showEnable=function(l){this.toastr.success(l,"Activation",{closeButton:!0,timeOut:3e3})},l.prototype.showDisable=function(l){this.toastr.error(l,"D\xe9sactivation",{closeButton:!0,timeOut:3e3})},l.prototype.showRemove=function(l){this.toastr.error(l,"Suppression",{closeButton:!0,timeOut:3e3})},l.prototype.close=function(){this.modalRef.hide()},l.prototype.ngOnDestroy=function(){null!==this.factureSubscription&&this.factureSubscription.unsubscribe()},l}(),z=function(){function l(l,n,e,u,t,o,i,a,r,s,c,d){this.factureService=l,this.colisService=n,this.typeFactureService=e,this.tvaService=u,this.deviseService=t,this.userService=o,this.tokenService=i,this.fb=a,this.toastr=r,this.modalService=s,this.spinner=c,this.localeService=d,this.facture=new V,this.isLoading=!1,this.allColis=new Array,this.allTvas=new Array,this.allDevises=new Array,this.colis=null,this.montantHT=0,this.montantTTC=0,this.tva=0,this.exonereTva=!1,this.colorTheme="theme-blue",this.locale="fr",this.user=new B.a,this.factureSubscription=null,this.numeroFacture="",this.referenceColis="",this.nomTypeFacture="",this.enable=2,this.currentPage=0,this.size=10,this.page=this.currentPage+1,this.showBtn=!1,this.print=!1,this.alert={type:"danger",dismissible:!0},this.error=""}return l.prototype.ngOnInit=function(){this.type="i",this.bsConfig=Object.assign({},{containerClass:this.colorTheme}),this.applyLocale(),this.searchFactures(),this.getProfile(),this.getAllTvas(),this.getAllDevises(),this.getTypesFactures(),this.createFacture(),this.clearFormArray(this.ligneFactures)},l.prototype.applyLocale=function(){this.localeService.use(this.locale)},l.prototype.onSelect=function(l){"liste-facture"===l.id&&(this.type="i",this.factureForm.enable(),this.clearFactureForm(),this.showBtn=!1,console.log("false"))},l.prototype.clearFormArray=function(l){for(;0!==l.length;)l.removeAt(0)},l.prototype.clearFactureForm=function(){this.clearFormArray(this.ligneFactures),this.factureForm.reset({id:"",numeroFacture:"",dateEcheance:null,typeFacture:null,colis:null,ligneFactures:new w.d([])}),this.facture=new V,this.colis=null},l.prototype.clearSearchFacture=function(){this.numeroFacture="",this.nomTypeFacture="",this.referenceColis="",this.currentPage=0,this.searchFactures()},l.prototype.selectTab=function(l){this.staticTabs.tabs[l].active=!0},l.prototype.searchNumeroFacture=function(){this.searchFactures()},l.prototype.searchNomTypeFacture=function(l){console.log(l),this.nomTypeFacture=void 0!==l?l.nomTypeFacture:"",this.searchFactures()},l.prototype.getSendColisByReference=function(l){var n=this;console.log(l.term),""!==l.term&&this.colisService.getSendColisByReference(l.term).subscribe(function(l){n.allColis=l})},l.prototype.searchReferenceColis=function(){this.searchFactures()},l.prototype.searchStatut=function(){this.searchFactures()},l.prototype.searchFactures=function(){var l=this;this.factureSubscription=this.factureService.searchFactures(this.numeroFacture,this.referenceColis,this.nomTypeFacture,this.enable,this.currentPage,this.size).subscribe(function(n){l.allFactures=n,l.pages=new Array(n.totalPages),l.page=l.currentPage+1},function(l){console.log(l)})},l.prototype.getAllColis=function(){var l=this;this.colisService.getAllSendColis().subscribe(function(n){l.allColis=n})},l.prototype.getAllTvas=function(){var l=this;this.tvaService.getAllTvas().subscribe(function(n){l.allTvas=n})},l.prototype.getAllDevises=function(){var l=this;this.deviseService.getAllDevises().subscribe(function(n){l.allDevises=n})},l.prototype.getTypesFactures=function(){var l=this;this.typeFactureService.getAllTypeFacture().subscribe(function(n){l.allTypesFactures=n})},l.prototype.getProfile=function(){var l=this;this.userService.getProfile().subscribe(function(n){l.user=n,l.tva=n.personne.site.tva.valeurTva})},l.prototype.searchPage=function(l){this.currentPage=l,this.searchFactures()},l.prototype.searchLimit=function(l){this.size=l,this.searchFactures()},l.prototype.hasRole=function(l){return this.tokenService.hasRole(l)},l.prototype.nextPage=function(l){this.currentPage=l,this.searchFactures()},l.prototype.previousPage=function(l){this.currentPage=l,this.searchFactures()},l.prototype.firstPage=function(l){this.currentPage=l,this.searchFactures()},l.prototype.lastPage=function(l){this.currentPage=l,this.searchFactures()},l.prototype.reload=function(){this.currentPage=0,this.searchFactures()},l.prototype.getNomTypeFacture=function(l){void 0!==l?(this.factureForm.get("dateEcheance"),"avoir"===l.nomTypeFacture.toLowerCase()?(this.showBtn=!0,this.factureForm.contains("dateEcheance")&&this.factureForm.removeControl("dateEcheance")):(this.showBtn=!1,this.factureForm.addControl("dateEcheance",new w.g(null,w.t.required)))):this.showBtn=!1},l.prototype.searchNomColis=function(l){console.log(l),void 0!==l?(this.colis=l,l.detailsColis.length>0&&this.setDetailsColisToLigneFactures(l.detailsColis)):(this.colis=null,this.clearFormArray(this.ligneFactures))},l.prototype.createFacture=function(){this.factureForm=this.fb.group({id:[this.facture.id],numeroFacture:[this.facture.numeroFacture],dateEcheance:[this.facture.dateEcheance,w.t.required],typeFacture:[this.facture.typeFacture,w.t.required],colis:[this.facture.colis,w.t.required],ligneFactures:this.fb.array([this.createLigneFactures()])})},l.prototype.createLigneFactures=function(){return this.fb.group({id:[{value:"",disabled:!0}],detailsColis:[null],designation:[{value:"",disabled:!0},w.t.required],quantite:[{value:"",disabled:!0},w.t.required],poids:[{value:"",disabled:!0},w.t.required],prixUnitaire:["",w.t.required],prixTotal:[{value:"",disabled:!0},w.t.required]})},l.prototype.addLigneFacture=function(){this.ligneFactures.push(this.createLigneFactures())},Object.defineProperty(l.prototype,"ligneFactures",{get:function(){return this.factureForm.get("ligneFactures")},enumerable:!0,configurable:!0}),l.prototype.deleteligneFacture=function(l){this.ligneFactures.controls.splice(l,1)},l.prototype.editForm=function(l){var n=this;this.type="u",this.facture=l,this.colis=l.colis,this.clearFormArray(this.ligneFactures),this.factureForm.setValue({id:l.id,numeroFacture:l.numeroFacture,dateEcheance:null!==l.dateEcheance?new Date(l.dateEcheance):null,typeFacture:l.typeFacture,colis:l.colis,ligneFactures:[]}),this.showBtn="avoir"===l.typeFacture.nomTypeFacture.toLowerCase();var e=this.factureForm.get("id"),u=this.factureForm.get("numeroFacture"),t=this.factureForm.get("colis"),o=this.factureForm.get("typeFacture"),i=this.factureForm.get("dateEcheance");this.type?e.disable():e.enable(),this.type?u.disable():u.enable(),this.type?t.disable():t.enable(),this.type?o.disable():o.enable(),"avoir"===l.typeFacture.nomTypeFacture.toLowerCase()&&(this.type?i.disable():i.enable()),l.colis.detailsColis.length>0&&(this.setLigneFactures(l.colis.detailsColis),this.montantHT=0,l.colis.detailsColis.forEach(function(l){n.montantHT+=l.prixTotal}),this.montantTTC=(1+this.tva)*this.montantHT),this.selectTab(1)},l.prototype.showForm=function(l){var n=this;this.type="s",this.facture=l,this.colis=l.colis,this.clearFormArray(this.ligneFactures),this.factureForm.setValue({id:l.id,numeroFacture:l.numeroFacture,dateEcheance:null!==l.dateEcheance?new Date(l.dateEcheance):null,typeFacture:l.typeFacture,colis:l.colis,ligneFactures:[]}),this.showBtn="avoir"===l.typeFacture.nomTypeFacture.toLowerCase();var e=this.factureForm.get("id"),u=this.factureForm.get("numeroFacture"),t=this.factureForm.get("colis"),o=this.factureForm.get("typeFacture"),i=this.factureForm.get("dateEcheance");this.type?e.disable():e.enable(),this.type?u.disable():u.enable(),this.type?t.disable():t.enable(),this.type?o.disable():o.enable(),this.type?i.disable():i.enable(),l.colis.detailsColis.length>0&&(this.setLigneFactures(l.colis.detailsColis),this.montantHT=0,l.colis.detailsColis.forEach(function(l){n.montantHT+=l.prixTotal}),this.montantTTC=(1+this.tva)*this.montantHT),this.selectTab(1)},l.prototype.setLigneFactures=function(l){var n=this,e=l.map(function(l){return n.fb.group({id:[{value:l.id,disabled:!0}],designation:[{value:l.designation,disabled:!0}],quantite:[{value:l.quantite,disabled:!0}],poids:[{value:l.poids,disabled:!0}],prixUnitaire:[{value:l.prixUnitaire,disabled:"s"===n.type}],prixTotal:[{value:l.prixTotal,disabled:!0}]})});this.montantHT=0,l.forEach(function(l){n.montantHT+=l.prixTotal}),this.montantTTC=(1+this.tva)*this.montantHT;var u=this.fb.array(e);this.factureForm.setControl("ligneFactures",u)},l.prototype.setDetailsColisToLigneFactures=function(l){var n=this,e=l.map(function(l){return n.fb.group({id:[{value:l.id,disabled:!0}],designation:[{value:l.designation,disabled:!0}],quantite:[{value:l.quantite,disabled:!0}],poids:[{value:l.poids,disabled:!0}],prixUnitaire:[{value:l.prixUnitaire,disabled:!1}],prixTotal:l.prixUnitaire*l.poids})}),u=this.fb.array(e);this.factureForm.setControl("ligneFactures",u),this.montantHT=0,l.forEach(function(l){n.montantHT+=l.prixUnitaire*l.poids}),this.montantTTC=(1+this.tva)*this.montantHT},l.prototype.changeTva=function(l){console.log(l),console.log(this.exonereTva)},l.prototype.prixUnitaire=function(l,n){var e=this;console.log(l.target.value);var u=this.ligneFactures.controls[n];l.target.value?(this.ligneFactures.controls[n].reset({id:u.get("id").value,designation:u.get("designation").value,quantite:u.get("quantite").value,poids:u.get("poids").value,prixUnitaire:u.get("prixUnitaire").value,prixTotal:parseFloat(u.get("prixUnitaire").value)*parseInt(u.get("poids").value)}),this.montantHT=0,this.ligneFactures.controls.forEach(function(l){e.montantHT+=l.get("prixTotal").value}),this.montantTTC=(1+this.tva)*this.montantHT):this.ligneFactures.controls[n].reset({id:u.get("id").value,designation:u.get("designation").value,quantite:u.get("quantite").value,prixUnitaire:0,prixTotal:0})},l.prototype.saveFacture=function(){var l=this;if(this.isLoading=!0,this.facture.type="FACTURE",this.facture.typeFacture=this.factureForm.value.typeFacture,this.facture.colis=this.factureForm.value.colis,"facture"===this.facture.typeFacture.nomTypeFacture.toLowerCase()){var n=JSON.stringify(this.factureForm.getRawValue().dateEcheance);this.facture.dateEcheance=n.substr(1,n.length-2)}this.facture.colis.detailsColis=this.factureForm.getRawValue().ligneFactures,this.factureService.addFacture(this.facture).subscribe(function(n){console.log(n),l.clearSearchFacture(),l.clearFactureForm(),l.isLoading=!1,l.factureForm.addControl("dateEcheance",new w.g(null,w.t.required)),l.selectTab(0),l.showSave("Facture enregistr\xe9e avec succ\xe8s!")},function(n){console.log(n),l.error=n,l.isLoading=!1})},l.prototype.updateFacture=function(){var l=this;if(this.isLoading=!0,this.facture.type="FACTURE",this.facture.id=this.factureForm.getRawValue().id,this.facture.numeroFacture=this.factureForm.getRawValue().numeroFacture,this.facture.typeFacture=this.factureForm.getRawValue().typeFacture,this.facture.colis=this.factureForm.getRawValue().colis,"facture"===this.facture.typeFacture.nomTypeFacture.toLowerCase()){var n=JSON.stringify(this.factureForm.getRawValue().dateEcheance);this.facture.dateEcheance=n.substr(1,n.length-2)}this.facture.colis.detailsColis=this.factureForm.getRawValue().ligneFactures,this.factureService.updateFacture(this.facture).subscribe(function(n){console.log(n),l.clearSearchFacture(),l.clearFactureForm(),l.isLoading=!1,l.selectTab(0),l.showUpdate("Facture modifi\xe9e avec succ\xe8s!")},function(n){console.log(n),l.error=n,l.isLoading=!1})},l.prototype.hidePrint=function(){this.print=!1},l.prototype.downloadFacture=function(l){var n=this;this.print=!0,this.spinner.show(),this.factureService.getFacturePDF(l.numeroFacture).subscribe(function(l){var e=new Blob([l],{type:"application/pdf"});n.externalPdfViewer.pdfSrc=URL.createObjectURL(e),n.externalPdfViewer.refresh(),n.spinner.hide()},function(l){console.log(l),n.spinner.hide()})},l.prototype.showSave=function(l){this.toastr.success(l,"Enregistrement",{closeButton:!0,timeOut:3e3})},l.prototype.showUpdate=function(l){this.toastr.warning(l,"Modification",{closeButton:!0,timeOut:3e3})},l.prototype.openRemoveModal=function(l,n,e){var u=this;this.modalRef=this.modalService.show(H,{class:"modal-sm"}),this.modalRef.content.showRemoveModal(n,l),this.modalRef.content.onClose.subscribe(function(l){console.log(l),"d"===l.type&&(u.allFactures.factures[e].enable=0),"e"===l.type&&(u.allFactures.factures[e].enable=1),"r"===l.type&&u.searchFactures()})},l.prototype.ngOnDestroy=function(){null!==this.factureSubscription&&this.factureSubscription.unsubscribe()},l.prototype.dismiss=function(){this.error=""},l}(),J=e("SZbH"),K=e("DQlY"),Y=u["\u0275crt"]({encapsulation:0,styles:[['.card[_ngcontent-%COMP%]{margin-bottom:0!important;border-bottom:0!important}.card[_ngcontent-%COMP%]:last-child{border-bottom:1px solid #c2cfd6!important}.card-header[_ngcontent-%COMP%]{font-weight:700}.qrCode[_ngcontent-%COMP%]{margin-top:-15px!important;background:0 0!important}.new[_ngcontent-%COMP%]{color:#20a8d8;font-weight:600}.update[_ngcontent-%COMP%]{color:#ffc107;font-weight:600}.show[_ngcontent-%COMP%]{color:#000;font-weight:600}.timeline[_ngcontent-%COMP%]{list-style-type:none;display:flex;align-items:center;justify-content:center}.timeline[_ngcontent-%COMP%] .li[_ngcontent-%COMP%]{transition:all .2s ease-in}.timeline[_ngcontent-%COMP%] .timestamp[_ngcontent-%COMP%]{margin-bottom:20px;padding:0 100px;display:flex;flex-direction:column;align-items:center;font-weight:100;height:42px}.timeline[_ngcontent-%COMP%] .timestamp[_ngcontent-%COMP%] .author[_ngcontent-%COMP%]{font-weight:600}.timeline[_ngcontent-%COMP%] .timestamp[_ngcontent-%COMP%] .date[_ngcontent-%COMP%]{font-style:italic}.timeline[_ngcontent-%COMP%] .status[_ngcontent-%COMP%]{padding:0 120px;display:flex;justify-content:center;border-top:2px solid #d6dce0;position:relative;transition:all .2s ease-in;cursor:pointer}.timeline[_ngcontent-%COMP%] .status[_ngcontent-%COMP%] h4[_ngcontent-%COMP%]{font-weight:600;font-size:1.2em;margin-top:1.33em}.timeline[_ngcontent-%COMP%] .status[_ngcontent-%COMP%]:before{content:"";width:25px;height:25px;background-color:#fff;border-radius:25px;border:1px solid #ddd;position:absolute;top:-15px;transition:all .2s ease-in;cursor:pointer}.timeline[_ngcontent-%COMP%] .li.complete[_ngcontent-%COMP%] .status[_ngcontent-%COMP%]{border-top:2px solid #66dc71}.timeline[_ngcontent-%COMP%] .li.complete[_ngcontent-%COMP%] .status[_ngcontent-%COMP%]:before{background-color:#66dc71;border:none;transition:all .2s ease-in}.timeline[_ngcontent-%COMP%] .li.complete[_ngcontent-%COMP%] .status[_ngcontent-%COMP%] h4[_ngcontent-%COMP%]{color:#66dc71}@media (min-device-width:320px) and (max-device-width:700px){.timeline[_ngcontent-%COMP%]{list-style-type:none;display:block}.timeline[_ngcontent-%COMP%] .li[_ngcontent-%COMP%]{transition:all .2s ease-in;display:flex;width:inherit}.timeline[_ngcontent-%COMP%] .li[_ngcontent-%COMP%] .timestamp[_ngcontent-%COMP%]{width:100px}.timeline[_ngcontent-%COMP%] .li[_ngcontent-%COMP%] .status[_ngcontent-%COMP%]:before{left:-8%;top:30%;transition:all .2s ease-in}}.ligne-facture[_ngcontent-%COMP%] .table[_ngcontent-%COMP%]{width:100%;max-width:100%;margin-bottom:1rem;background-color:transparent;border:1px solid #a4b7c1}.ligne-facture[_ngcontent-%COMP%] .table[_ngcontent-%COMP%] td[_ngcontent-%COMP%]{padding:.4rem;vertical-align:middle}.ng-select[_ngcontent-%COMP%] .ng-clear-zone[_ngcontent-%COMP%]{position:absolute!important;margin-left:10px!important}.ng-dropdown-panel[_ngcontent-%COMP%] .ng-dropdown-panel-items[_ngcontent-%COMP%] .ng-option[_ngcontent-%COMP%]{text-align:right!important}.table[_ngcontent-%COMP%] .mb-4[_ngcontent-%COMP%], .table[_ngcontent-%COMP%] .my-4[_ngcontent-%COMP%]{margin-bottom:0!important}.tva[_ngcontent-%COMP%] .input-group-text[_ngcontent-%COMP%]{width:60.39px}.dropdown-item[_ngcontent-%COMP%]{padding:5px 20px!important;cursor:pointer}.font-weight-bold[_ngcontent-%COMP%]{font-weight:600!important}']],data:{}});function Z(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,7,"div",[["class","card"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,3,"div",[["class","card-header"]],null,null,null,null,null)),(l()(),u["\u0275eld"](2,0,null,null,2,"button",[["class","btn btn-light float-right"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.hidePrint()&&u),u},null,null)),(l()(),u["\u0275eld"](3,0,null,null,0,"i",[["class","fa fa-close"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Fermer "])),(l()(),u["\u0275eld"](5,0,null,null,2,"div",[["class","card-body"],["style","width: 100%; height: 500px"]],null,null,null,null,null)),(l()(),u["\u0275eld"](6,0,null,null,1,"ng2-pdfjs-viewer",[],null,null,null,a.b,a.a)),u["\u0275did"](7,114688,[[2,4],["externalPdfViewer",4]],0,r.PdfJsViewerComponent,[],{showSpinner:[0,"showSpinner"]},null)],function(l,n){l(n,7,0,!0)},null)}function G(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,2,"span",[["class","font-weight-bold"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,0,"i",[["class","icon-bag font-weight-bold"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Facture "]))],null,null)}function Q(l){return u["\u0275vid"](0,[(l()(),u["\u0275ted"](0,null,[" "," "])),u["\u0275ppd"](1,1)],null,function(l,n){var e=u["\u0275unv"](n,0,0,l(n,1,0,u["\u0275nov"](n.parent.parent,0),null==n.context.item?null:n.context.item.nomTypeFacture));l(n,0,0,e)})}function W(l){return u["\u0275vid"](0,[(l()(),u["\u0275ted"](0,null,[" "," "])),u["\u0275ppd"](1,1)],null,function(l,n){var e=u["\u0275unv"](n,0,0,l(n,1,0,u["\u0275nov"](n.parent.parent,0),null==n.context.item?null:n.context.item.nomTypeFacture));l(n,0,0,e)})}function X(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,2,"a",[["class","dropdown-item text-danger font-weight-bold"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.openRemoveModal(l.parent.parent.context.$implicit,"d",l.parent.parent.context.index)&&u),u},null,null)),(l()(),u["\u0275eld"](1,0,null,null,0,"i",[["class","fa fa-lock text-danger font-weight-bold"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" D\xe9sactiver"]))],null,null)}function ll(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,2,"a",[["class","dropdown-item text-success font-weight-bold"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.openRemoveModal(l.parent.parent.context.$implicit,"e",l.parent.parent.context.index)&&u),u},null,null)),(l()(),u["\u0275eld"](1,0,null,null,0,"i",[["class","fa fa-unlock-alt text-success font-weight-bold"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Activer"]))],null,null)}function nl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,23,"ul",[["aria-labelledby","button-basic"],["class","dropdown-menu"],["id","dropdown-basic"],["role","menu"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,3,"li",[["role","menuitem"]],null,null,null,null,null)),(l()(),u["\u0275eld"](2,0,null,null,2,"a",[["class","dropdown-item text-warning font-weight-bold"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.editForm(l.parent.context.$implicit)&&u),u},null,null)),(l()(),u["\u0275eld"](3,0,null,null,0,"i",[["class","fa fa-edit text-warning font-weight-bold"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Modifier"])),(l()(),u["\u0275eld"](5,0,null,null,3,"li",[["role","menuitem"]],null,null,null,null,null)),(l()(),u["\u0275eld"](6,0,null,null,2,"a",[["class","dropdown-item text-default font-weight-bold"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.showForm(l.parent.context.$implicit)&&u),u},null,null)),(l()(),u["\u0275eld"](7,0,null,null,0,"i",[["class","fa fa-eye text-default font-weight-bold"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Afficher"])),(l()(),u["\u0275eld"](9,0,null,null,3,"li",[["role","menuitem"]],null,null,null,null,null)),(l()(),u["\u0275eld"](10,0,null,null,2,"a",[["class","dropdown-item text-danger font-weight-bold"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.downloadFacture(l.parent.context.$implicit)&&u),u},null,null)),(l()(),u["\u0275eld"](11,0,null,null,0,"i",[["class","fa fa-file-pdf-o text-danger font-weight-bold"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" PDF"])),(l()(),u["\u0275eld"](13,0,null,null,2,"li",[["role","menuitem"]],null,null,null,null,null)),(l()(),u["\u0275and"](16777216,null,null,1,null,X)),u["\u0275did"](15,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275eld"](16,0,null,null,2,"li",[["role","menuitem"]],null,null,null,null,null)),(l()(),u["\u0275and"](16777216,null,null,1,null,ll)),u["\u0275did"](18,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275eld"](19,0,null,null,0,"li",[["class","divider dropdown-divider"]],null,null,null,null,null)),(l()(),u["\u0275eld"](20,0,null,null,3,"li",[["role","menuitem"]],null,null,null,null,null)),(l()(),u["\u0275eld"](21,0,null,null,2,"a",[["class","dropdown-item text-danger font-weight-bold"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.openRemoveModal(l.parent.context.$implicit,"r",l.parent.context.index)&&u),u},null,null)),(l()(),u["\u0275eld"](22,0,null,null,0,"i",[["class","fa fa-remove text-danger font-weight-bold"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Supprimer"]))],function(l,n){l(n,15,0,1===n.parent.context.$implicit.enable),l(n,18,0,0===n.parent.context.$implicit.enable)},null)}function el(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,26,"tr",[],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,1,"td",[["class","font-weight-bold"]],null,null,null,null,null)),(l()(),u["\u0275ted"](2,null,["",""])),(l()(),u["\u0275eld"](3,0,null,null,2,"td",[],null,null,null,null,null)),(l()(),u["\u0275ted"](4,null,["",""])),u["\u0275ppd"](5,1),(l()(),u["\u0275eld"](6,0,null,null,2,"td",[],null,null,null,null,null)),(l()(),u["\u0275ted"](7,null,["",""])),u["\u0275ppd"](8,1),(l()(),u["\u0275eld"](9,0,null,null,1,"td",[],null,null,null,null,null)),(l()(),u["\u0275ted"](10,null,["",""])),(l()(),u["\u0275eld"](11,0,null,null,2,"td",[["class","text-right font-weight-bold"]],null,null,null,null,null)),(l()(),u["\u0275ted"](12,null,[""," "," "])),u["\u0275ppd"](13,1),(l()(),u["\u0275eld"](14,0,null,null,2,"td",[["class","text-right font-weight-bold"]],null,null,null,null,null)),(l()(),u["\u0275ted"](15,null,[""," "," "])),u["\u0275ppd"](16,1),(l()(),u["\u0275eld"](17,0,null,null,9,"td",[["class","text-center"]],null,null,null,null,null)),(l()(),u["\u0275eld"](18,16777216,null,null,8,"div",[["class","btn-group"],["dropdown",""]],[[2,"dropup",null],[2,"open",null],[2,"show",null]],null,null,null,null)),u["\u0275prd"](512,null,c.f,c.f,[]),u["\u0275did"](20,212992,null,0,c.c,[u.ElementRef,u.Renderer2,u.ViewContainerRef,d.a,c.a,c.f],{dropup:[0,"dropup"]},null),(l()(),u["\u0275eld"](21,0,null,null,3,"button",[["aria-controls","dropdown-basic"],["class","btn btn-light dropdown-toggle"],["dropdownToggle",""],["id","button-basic"],["type","button"]],[[1,"aria-haspopup",0],[1,"disabled",0],[1,"aria-expanded",0]],[[null,"click"]],function(l,n,e){var t=!0;return"click"===n&&(t=!1!==u["\u0275nov"](l,22).onClick()&&t),t},null,null)),u["\u0275did"](22,147456,null,0,c.g,[u.ChangeDetectorRef,c.c,u.ElementRef,u.Renderer2,c.f],null,null),(l()(),u["\u0275ted"](-1,null,[" S\xe9lectionner "])),(l()(),u["\u0275eld"](24,0,null,null,0,"span",[["class","caret"]],null,null,null,null,null)),(l()(),u["\u0275and"](16777216,null,null,1,null,nl)),u["\u0275did"](26,16384,null,0,c.d,[c.f,u.ViewContainerRef,u.TemplateRef],null,null)],function(l,n){l(n,20,0,!1)},function(l,n){var e=n.component;l(n,2,0,null==n.context.$implicit?null:n.context.$implicit.numeroFacture);var t=u["\u0275unv"](n,4,0,l(n,5,0,u["\u0275nov"](n.parent.parent.parent,0),null==n.context.$implicit?null:null==n.context.$implicit.typeFacture?null:n.context.$implicit.typeFacture.nomTypeFacture));l(n,4,0,t);var o=u["\u0275unv"](n,7,0,l(n,8,0,u["\u0275nov"](n.parent.parent.parent,0),null==n.context.$implicit?null:null==n.context.$implicit.colis?null:null==n.context.$implicit.colis.client?null:n.context.$implicit.colis.client.raisonSociale));l(n,7,0,o),l(n,10,0,null==n.context.$implicit?null:null==n.context.$implicit.colis?null:n.context.$implicit.colis.reference);var i=u["\u0275unv"](n,12,0,l(n,13,0,u["\u0275nov"](n.parent.parent.parent,1),null==n.context.$implicit?null:n.context.$implicit.debit));l(n,12,0,i,null==e.user?null:null==e.user.personne?null:null==e.user.personne.site?null:null==e.user.personne.site.devise?null:e.user.personne.site.devise.nomDevise);var a=u["\u0275unv"](n,15,0,l(n,16,0,u["\u0275nov"](n.parent.parent.parent,1),null==n.context.$implicit?null:n.context.$implicit.credit));l(n,15,0,a,null==e.user?null:null==e.user.personne?null:null==e.user.personne.site?null:null==e.user.personne.site.devise?null:e.user.personne.site.devise.nomDevise),l(n,18,0,u["\u0275nov"](n,20).dropup,u["\u0275nov"](n,20).isOpen,u["\u0275nov"](n,20).isOpen&&u["\u0275nov"](n,20).isBs4),l(n,21,0,!0,u["\u0275nov"](n,22).isDisabled,u["\u0275nov"](n,22).isOpen)})}function ul(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,2,"tr",[],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,1,"td",[["class","text-center"],["colspan","7"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Aucun resultat trouv\xe9"]))],null,null)}function tl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,39,"div",[],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,36,"table",[["class","table table-condensed table-bordered data-table"]],null,null,null,null,null)),u["\u0275did"](2,868352,[["mf",4]],0,p.a,[g.a],{inputData:[0,"inputData"],rowsOnPage:[1,"rowsOnPage"]},null),(l()(),u["\u0275eld"](3,0,null,null,29,"thead",[],null,null,null,null,null)),(l()(),u["\u0275eld"](4,0,null,null,28,"tr",[],null,null,null,null,null)),(l()(),u["\u0275eld"](5,0,null,null,3,"th",[["class","text-center"],["style","width: 15%"]],null,null,null,null,null)),(l()(),u["\u0275eld"](6,0,null,null,2,"mfDefaultSorter",[["by","numeroFacture"]],null,null,null,f.b,f.a)),u["\u0275did"](7,49152,null,0,m.a,[p.a],{sortBy:[0,"sortBy"],showSortableArrows:[1,"showSortableArrows"]},null),(l()(),u["\u0275ted"](-1,0,["Num\xe9ro"])),(l()(),u["\u0275eld"](9,0,null,null,3,"th",[["class","text-center"],["style","width: 10%"]],null,null,null,null,null)),(l()(),u["\u0275eld"](10,0,null,null,2,"mfDefaultSorter",[["by","typeFacture"]],null,null,null,f.b,f.a)),u["\u0275did"](11,49152,null,0,m.a,[p.a],{sortBy:[0,"sortBy"],showSortableArrows:[1,"showSortableArrows"]},null),(l()(),u["\u0275ted"](-1,0,["Type "])),(l()(),u["\u0275eld"](13,0,null,null,3,"th",[["class","text-center"],["style","width: 15%"]],null,null,null,null,null)),(l()(),u["\u0275eld"](14,0,null,null,2,"mfDefaultSorter",[["by","client"]],null,null,null,f.b,f.a)),u["\u0275did"](15,49152,null,0,m.a,[p.a],{sortBy:[0,"sortBy"],showSortableArrows:[1,"showSortableArrows"]},null),(l()(),u["\u0275ted"](-1,0,["Client "])),(l()(),u["\u0275eld"](17,0,null,null,3,"th",[["class","text-center"],["style","width: 15%"]],null,null,null,null,null)),(l()(),u["\u0275eld"](18,0,null,null,2,"mfDefaultSorter",[["by","colis"]],null,null,null,f.b,f.a)),u["\u0275did"](19,49152,null,0,m.a,[p.a],{sortBy:[0,"sortBy"],showSortableArrows:[1,"showSortableArrows"]},null),(l()(),u["\u0275ted"](-1,0,["Colis"])),(l()(),u["\u0275eld"](21,0,null,null,3,"th",[["class","text-center"],["style","width: 15%"]],null,null,null,null,null)),(l()(),u["\u0275eld"](22,0,null,null,2,"mfDefaultSorter",[["by","debit"]],null,null,null,f.b,f.a)),u["\u0275did"](23,49152,null,0,m.a,[p.a],{sortBy:[0,"sortBy"],showSortableArrows:[1,"showSortableArrows"]},null),(l()(),u["\u0275ted"](-1,0,["D\xe9bit"])),(l()(),u["\u0275eld"](25,0,null,null,3,"th",[["class","text-center"],["style","width: 15%"]],null,null,null,null,null)),(l()(),u["\u0275eld"](26,0,null,null,2,"mfDefaultSorter",[["by","credit"]],null,null,null,f.b,f.a)),u["\u0275did"](27,49152,null,0,m.a,[p.a],{sortBy:[0,"sortBy"],showSortableArrows:[1,"showSortableArrows"]},null),(l()(),u["\u0275ted"](-1,0,["Cr\xe9dit"])),(l()(),u["\u0275eld"](29,0,null,null,3,"th",[["class","text-center"],["style","width: 15%"]],null,null,null,null,null)),(l()(),u["\u0275eld"](30,0,null,null,2,"mfDefaultSorter",[],null,null,null,f.b,f.a)),u["\u0275did"](31,49152,null,0,m.a,[p.a],null,null),(l()(),u["\u0275ted"](-1,0,["Actions"])),(l()(),u["\u0275eld"](33,0,null,null,4,"tbody",[],null,null,null,null,null)),(l()(),u["\u0275and"](16777216,null,null,1,null,el)),u["\u0275did"](35,278528,null,0,s.NgForOf,[u.ViewContainerRef,u.TemplateRef,u.IterableDiffers],{ngForOf:[0,"ngForOf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,ul)),u["\u0275did"](37,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275eld"](38,0,null,null,1,"app-pagination",[],null,[[null,"search"],[null,"limit"],[null,"first"],[null,"next"],[null,"previous"],[null,"last"]],function(l,n,e){var u=!0,t=l.component;return"search"===n&&(u=!1!==t.searchPage(e)&&u),"limit"===n&&(u=!1!==t.searchLimit(e)&&u),"first"===n&&(u=!1!==t.firstPage(e)&&u),"next"===n&&(u=!1!==t.nextPage(e)&&u),"previous"===n&&(u=!1!==t.previousPage(e)&&u),"last"===n&&(u=!1!==t.lastPage(e)&&u),u},h.b,h.a)),u["\u0275did"](39,638976,null,0,v.a,[],{pages:[0,"pages"],nombreElements:[1,"nombreElements"],totalElements:[2,"totalElements"],totalPages:[3,"totalPages"],currentPage:[4,"currentPage"],size:[5,"size"],page:[6,"page"]},{search:"search",limit:"limit",first:"first",previous:"previous",next:"next",last:"last"})],function(l,n){var e=n.component;l(n,2,0,null==e.allFactures?null:e.allFactures.factures,e.size),l(n,7,0,"numeroFacture",!0),l(n,11,0,"typeFacture",!1),l(n,15,0,"client",!1),l(n,19,0,"colis",!0),l(n,23,0,"debit",!0),l(n,27,0,"credit",!0),l(n,35,0,u["\u0275nov"](n,2).data),l(n,37,0,0===(null==e.allFactures?null:e.allFactures.factures.length)),l(n,39,0,e.pages,null==e.allFactures?null:e.allFactures.nombreFactures,null==e.allFactures?null:e.allFactures.totalFactures,null==e.allFactures?null:e.allFactures.totalPages,e.currentPage,e.size,e.page)},null)}function ol(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,2,"span",[["class","new"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,0,"i",[["class","fa fa-plus"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Cr\xe9er facture "]))],null,null)}function il(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,2,"span",[["class","update"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,0,"i",[["class","fa fa-edit"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Modifier facture "]))],null,null)}function al(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,2,"span",[["class","show"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,0,"i",[["class","fa fa-eye"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Afficher facture "]))],null,null)}function rl(l){return u["\u0275vid"](0,[(l()(),u["\u0275and"](16777216,null,null,1,null,ol)),u["\u0275did"](1,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,il)),u["\u0275did"](3,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,al)),u["\u0275did"](5,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](0,null,null,0))],function(l,n){var e=n.component;l(n,1,0,"i"===e.type),l(n,3,0,"u"===e.type),l(n,5,0,"s"===e.type)},null)}function sl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,4,"div",[["class","card-title"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,3,"alert",[["class","text-center"]],null,[[null,"onClose"]],function(l,n,e){var u=!0;return"onClose"===n&&(u=!1!==l.component.dismiss()&&u),u},b.c,b.b)),u["\u0275did"](2,114688,null,0,y.a,[y.b,u.ChangeDetectorRef],{type:[0,"type"],dismissible:[1,"dismissible"]},{onClose:"onClose"}),(l()(),u["\u0275eld"](3,0,null,0,1,"strong",[],null,null,null,null,null)),(l()(),u["\u0275ted"](4,null,["",""]))],function(l,n){var e=n.component;l(n,2,0,e.alert.type,e.alert.dismissible)},function(l,n){l(n,4,0,n.component.error)})}function cl(l){return u["\u0275vid"](0,[(l()(),u["\u0275ted"](0,null,[" "," "])),u["\u0275ppd"](1,1)],null,function(l,n){var e=u["\u0275unv"](n,0,0,l(n,1,0,u["\u0275nov"](n.parent.parent.parent,0),null==n.context.item?null:n.context.item.nomTypeFacture));l(n,0,0,e)})}function dl(l){return u["\u0275vid"](0,[(l()(),u["\u0275ted"](0,null,[" "," "])),u["\u0275ppd"](1,1)],null,function(l,n){var e=u["\u0275unv"](n,0,0,l(n,1,0,u["\u0275nov"](n.parent.parent.parent,0),null==n.context.item?null:n.context.item.nomTypeFacture));l(n,0,0,e)})}function pl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,25,"ng-select",[["bindLabel","nomTypeFacture"],["class","form-control ng-select"],["formControlName","typeFacture"],["id","typeFacture"],["placeholder","Aucun type s\xe9lectionn\xe9e"],["role","listbox"]],[[2,"ng-select-single",null],[2,"ng-select-typeahead",null],[2,"ng-select-multiple",null],[2,"ng-select-taggable",null],[2,"ng-select-searchable",null],[2,"ng-select-clearable",null],[2,"ng-select-opened",null],[2,"ng-select-disabled",null],[2,"ng-select-filtered",null],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"change"],[null,"keydown"]],function(l,n,e){var t=!0,o=l.component;return"keydown"===n&&(t=!1!==u["\u0275nov"](l,5).handleKeyDown(e)&&t),"change"===n&&(t=!1!==o.getNomTypeFacture(e)&&t),t},C.c,C.a)),u["\u0275prd"](4608,null,F.f,F.f,[]),u["\u0275prd"](512,null,s["\u0275NgClassImpl"],s["\u0275NgClassR2Impl"],[u.IterableDiffers,u.KeyValueDiffers,u.ElementRef,u.Renderer2]),u["\u0275did"](3,278528,null,0,s.NgClass,[s["\u0275NgClassImpl"]],{klass:[0,"klass"],ngClass:[1,"ngClass"]},null),u["\u0275pod"](4,{"is-invalid":0,"is-valid":1}),u["\u0275did"](5,4964352,null,12,F.a,[[8,"form-control"],[8,null],F.b,F.d,u.ElementRef,u.ChangeDetectorRef,F.l],{bindLabel:[0,"bindLabel"],placeholder:[1,"placeholder"],items:[2,"items"]},{changeEvent:"change"}),u["\u0275qud"](335544320,27,{optionTemplate:0}),u["\u0275qud"](335544320,28,{optgroupTemplate:0}),u["\u0275qud"](335544320,29,{labelTemplate:0}),u["\u0275qud"](335544320,30,{multiLabelTemplate:0}),u["\u0275qud"](603979776,31,{headerTemplate:0}),u["\u0275qud"](603979776,32,{footerTemplate:0}),u["\u0275qud"](335544320,33,{notFoundTemplate:0}),u["\u0275qud"](335544320,34,{typeToSearchTemplate:0}),u["\u0275qud"](335544320,35,{loadingTextTemplate:0}),u["\u0275qud"](335544320,36,{tagTemplate:0}),u["\u0275qud"](335544320,37,{loadingSpinnerTemplate:0}),u["\u0275qud"](603979776,38,{ngOptions:1}),u["\u0275prd"](1024,null,w.m,function(l){return[l]},[F.a]),u["\u0275did"](19,671744,null,0,w.h,[[3,w.b],[8,null],[8,null],[6,w.m],[2,w.w]],{name:[0,"name"]},null),u["\u0275prd"](2048,null,w.n,null,[w.h]),u["\u0275did"](21,16384,null,0,w.o,[[4,w.n]],null,null),(l()(),u["\u0275and"](0,[[29,2]],null,1,null,cl)),u["\u0275did"](23,16384,null,0,F.i,[u.TemplateRef],null,null),(l()(),u["\u0275and"](0,[[27,2]],null,1,null,dl)),u["\u0275did"](25,16384,null,0,F.h,[u.TemplateRef],null,null)],function(l,n){var e=n.component,u=l(n,4,0,!(null==e.factureForm||null==e.factureForm.controls.typeFacture||null==e.factureForm.controls.typeFacture.errors||!e.factureForm.controls.typeFacture.errors.required)&&e.factureForm.controls.typeFacture.errors&&(e.factureForm.controls.typeFacture.dirty||e.factureForm.controls.typeFacture.touched),!(null!=e.factureForm&&null!=e.factureForm.controls.typeFacture&&null!=e.factureForm.controls.typeFacture.errors&&e.factureForm.controls.typeFacture.errors.required)&&!e.factureForm.controls.typeFacture.errors&&(e.factureForm.controls.typeFacture.dirty||e.factureForm.controls.typeFacture.touched));l(n,3,0,"form-control",u),l(n,5,0,"nomTypeFacture","Aucun type s\xe9lectionn\xe9e",e.allTypesFactures),l(n,19,0,"typeFacture")},function(l,n){l(n,0,1,[!u["\u0275nov"](n,5).multiple,u["\u0275nov"](n,5).typeahead,u["\u0275nov"](n,5).multiple,u["\u0275nov"](n,5).addTag,u["\u0275nov"](n,5).searchable,u["\u0275nov"](n,5).clearable,u["\u0275nov"](n,5).isOpen,u["\u0275nov"](n,5).disabled,u["\u0275nov"](n,5).filtered,u["\u0275nov"](n,21).ngClassUntouched,u["\u0275nov"](n,21).ngClassTouched,u["\u0275nov"](n,21).ngClassPristine,u["\u0275nov"](n,21).ngClassDirty,u["\u0275nov"](n,21).ngClassValid,u["\u0275nov"](n,21).ngClassInvalid,u["\u0275nov"](n,21).ngClassPending])})}function gl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,5,"div",[["class","invalid-perso"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,4,"span",[],[[8,"hidden",0]],null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Veuillez s\xe9lectionner un "])),(l()(),u["\u0275eld"](3,0,null,null,1,"strong",[],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["type"])),(l()(),u["\u0275ted"](-1,null,["."]))],null,function(l,n){var e=n.component;l(n,1,0,!(null!=e.factureForm.controls.typeFacture.errors&&e.factureForm.controls.typeFacture.errors.required))})}function fl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,5,"div",[["class","invalid-perso"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,4,"span",[],[[8,"hidden",0]],null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Le "])),(l()(),u["\u0275eld"](3,0,null,null,1,"strong",[],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["colis"])),(l()(),u["\u0275ted"](-1,null,[" est obligatoire."]))],null,function(l,n){var e=n.component;l(n,1,0,!(null!=e.factureForm.controls.colis.errors&&e.factureForm.controls.colis.errors.required))})}function ml(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,9,"div",[["class","form-group row col-md-6"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,1,"label",[["class","control-label col-md-4 text-right"],["for","numeroFacture"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Num\xe9ro"])),(l()(),u["\u0275eld"](3,0,null,null,6,"div",[["class","col-md-8"]],null,null,null,null,null)),(l()(),u["\u0275eld"](4,0,null,null,5,"input",[["class","form-control"],["formControlName","numeroFacture"],["id","numeroFacture"],["type","text"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(l,n,e){var t=!0;return"input"===n&&(t=!1!==u["\u0275nov"](l,5)._handleInput(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,5).onTouched()&&t),"compositionstart"===n&&(t=!1!==u["\u0275nov"](l,5)._compositionStart()&&t),"compositionend"===n&&(t=!1!==u["\u0275nov"](l,5)._compositionEnd(e.target.value)&&t),t},null,null)),u["\u0275did"](5,16384,null,0,w.c,[u.Renderer2,u.ElementRef,[2,w.a]],null,null),u["\u0275prd"](1024,null,w.m,function(l){return[l]},[w.c]),u["\u0275did"](7,671744,null,0,w.h,[[3,w.b],[8,null],[8,null],[6,w.m],[2,w.w]],{name:[0,"name"]},null),u["\u0275prd"](2048,null,w.n,null,[w.h]),u["\u0275did"](9,16384,null,0,w.o,[[4,w.n]],null,null)],function(l,n){l(n,7,0,"numeroFacture")},function(l,n){l(n,4,0,u["\u0275nov"](n,9).ngClassUntouched,u["\u0275nov"](n,9).ngClassTouched,u["\u0275nov"](n,9).ngClassPristine,u["\u0275nov"](n,9).ngClassDirty,u["\u0275nov"](n,9).ngClassValid,u["\u0275nov"](n,9).ngClassInvalid,u["\u0275nov"](n,9).ngClassPending)})}function hl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,5,"div",[["class","invalid-perso"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,4,"span",[],[[8,"hidden",0]],null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["La "])),(l()(),u["\u0275eld"](3,0,null,null,1,"strong",[],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["date d'\xe9ch\xe9ance"])),(l()(),u["\u0275ted"](-1,null,[" est obligatoire."]))],null,function(l,n){var e=n.component;l(n,1,0,!(null!=e.factureForm.controls.dateEcheance.errors&&e.factureForm.controls.dateEcheance.errors.required))})}function vl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,17,"div",[["class","form-group row col-md-6"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,1,"label",[["class","control-label col-md-4 text-right"],["for","dateEcheance"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Date Ech\xe9ance"])),(l()(),u["\u0275eld"](3,0,null,null,14,"div",[["class","col-md-8"]],null,null,null,null,null)),(l()(),u["\u0275eld"](4,16777216,null,null,11,"input",[["bsDatepicker",""],["class","form-control"],["formControlName","dateEcheance"],["id","dateEcheance"],["placeholder","Aucune date s\xe9lectionn\xe9e"],["type","text"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"],[null,"keyup.esc"]],function(l,n,e){var t=!0;return"input"===n&&(t=!1!==u["\u0275nov"](l,8)._handleInput(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,8).onTouched()&&t),"compositionstart"===n&&(t=!1!==u["\u0275nov"](l,8)._compositionStart()&&t),"compositionend"===n&&(t=!1!==u["\u0275nov"](l,8)._compositionEnd(e.target.value)&&t),"change"===n&&(t=!1!==u["\u0275nov"](l,10).onChange(e)&&t),"keyup.esc"===n&&(t=!1!==u["\u0275nov"](l,10).hide()&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,10).onBlur()&&t),t},null,null)),u["\u0275prd"](512,null,s["\u0275NgClassImpl"],s["\u0275NgClassR2Impl"],[u.IterableDiffers,u.KeyValueDiffers,u.ElementRef,u.Renderer2]),u["\u0275did"](6,278528,null,0,s.NgClass,[s["\u0275NgClassImpl"]],{klass:[0,"klass"],ngClass:[1,"ngClass"]},null),u["\u0275pod"](7,{"is-invalid":0,"is-valid":1}),u["\u0275did"](8,16384,null,0,w.c,[u.Renderer2,u.ElementRef,[2,w.a]],null,null),u["\u0275did"](9,737280,null,0,T.c,[T.a,u.ElementRef,u.Renderer2,u.ViewContainerRef,d.a],{bsConfig:[0,"bsConfig"]},null),u["\u0275did"](10,16384,null,0,T.f,[T.c,T.j,u.Renderer2,u.ElementRef,u.ChangeDetectorRef],null,null),u["\u0275prd"](1024,null,w.l,function(l){return[l]},[T.f]),u["\u0275prd"](1024,null,w.m,function(l,n){return[l,n]},[w.c,T.f]),u["\u0275did"](13,671744,null,0,w.h,[[3,w.b],[6,w.l],[8,null],[6,w.m],[2,w.w]],{name:[0,"name"]},null),u["\u0275prd"](2048,null,w.n,null,[w.h]),u["\u0275did"](15,16384,null,0,w.o,[[4,w.n]],null,null),(l()(),u["\u0275and"](16777216,null,null,1,null,hl)),u["\u0275did"](17,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null)],function(l,n){var e=n.component,u=l(n,7,0,(!(null==e.factureForm||null==e.factureForm.controls.dateEcheance||null==e.factureForm.controls.dateEcheance.errors||!e.factureForm.controls.dateEcheance.errors.required)||!(null==e.factureForm||null==e.factureForm.controls.dateEcheance||null==e.factureForm.controls.dateEcheance.errors||!e.factureForm.controls.dateEcheance.errors.matchDate))&&e.factureForm.controls.dateEcheance.errors&&(e.factureForm.controls.dateEcheance.dirty||e.factureForm.controls.dateEcheance.touched),(!(null!=e.factureForm&&null!=e.factureForm.controls.dateEcheance&&null!=e.factureForm.controls.dateEcheance.errors&&e.factureForm.controls.dateEcheance.errors.required)||!(null!=e.factureForm&&null!=e.factureForm.controls.dateEcheance&&null!=e.factureForm.controls.dateEcheance.errors&&e.factureForm.controls.dateEcheance.errors.matchDate))&&!e.factureForm.controls.dateEcheance.errors&&(e.factureForm.controls.dateEcheance.dirty||e.factureForm.controls.dateEcheance.touched));l(n,6,0,"form-control",u),l(n,9,0,e.bsConfig),l(n,13,0,"dateEcheance"),l(n,17,0,e.factureForm.controls.dateEcheance.errors&&(e.factureForm.controls.dateEcheance.dirty||e.factureForm.controls.dateEcheance.touched))},function(l,n){l(n,4,0,u["\u0275nov"](n,15).ngClassUntouched,u["\u0275nov"](n,15).ngClassTouched,u["\u0275nov"](n,15).ngClassPristine,u["\u0275nov"](n,15).ngClassDirty,u["\u0275nov"](n,15).ngClassValid,u["\u0275nov"](n,15).ngClassInvalid,u["\u0275nov"](n,15).ngClassPending)})}function bl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,24,"div",[["class","card"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,1,"div",[["class","card-header"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["COLIS"])),(l()(),u["\u0275eld"](3,0,null,null,21,"div",[["class","card-body"]],null,null,null,null,null)),(l()(),u["\u0275eld"](4,0,null,null,20,"div",[["class","row"]],null,null,null,null,null)),(l()(),u["\u0275eld"](5,0,null,null,4,"div",[["class","form-group row col-md-6"]],null,null,null,null,null)),(l()(),u["\u0275eld"](6,0,null,null,1,"label",[["class","control-label col-md-4 text-right"],["for","client"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Exp\xe9diteur"])),(l()(),u["\u0275eld"](8,0,null,null,1,"div",[["class","col-md-8"]],null,null,null,null,null)),(l()(),u["\u0275eld"](9,0,null,null,0,"input",[["class","form-control"],["disabled",""],["id","client"],["type","text"]],[[8,"value",0]],null,null,null,null)),(l()(),u["\u0275eld"](10,0,null,null,4,"div",[["class","form-group row col-md-6"]],null,null,null,null,null)),(l()(),u["\u0275eld"](11,0,null,null,1,"label",[["class","control-label col-md-4 text-right"],["for","nomDestinataire"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Destinataire"])),(l()(),u["\u0275eld"](13,0,null,null,1,"div",[["class","col-md-8"]],null,null,null,null,null)),(l()(),u["\u0275eld"](14,0,null,null,0,"input",[["class","form-control"],["disabled",""],["id","nomDestinataire"],["type","text"]],[[8,"value",0]],null,null,null,null)),(l()(),u["\u0275eld"](15,0,null,null,3,"div",[["class","form-group row col-md-6"]],null,null,null,null,null)),(l()(),u["\u0275eld"](16,0,null,null,2,"div",[["class","col-md-12 text-center qrCode"]],null,null,null,null,null)),(l()(),u["\u0275eld"](17,0,null,null,1,"ngx-qrcode",[["disabled",""],["qrc-class","qrCode"],["qrc-errorCorrectionLevel","L"]],null,null,null,x.b,x.a)),u["\u0275did"](18,573440,null,0,R.a,[u.Renderer2],{cssClass:[0,"cssClass"],value:[1,"value"],errorCorrectionLevel:[2,"errorCorrectionLevel"]},null),(l()(),u["\u0275eld"](19,0,null,null,5,"div",[["class","form-group row col-md-6"]],null,null,null,null,null)),(l()(),u["\u0275eld"](20,0,null,null,1,"label",[["class","control-label col-md-4 text-right"],["for","description"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Description"])),(l()(),u["\u0275eld"](22,0,null,null,2,"div",[["class","col-md-8"]],null,null,null,null,null)),(l()(),u["\u0275eld"](23,0,null,null,1,"textarea",[["class","form-control"],["cols","30"],["disabled",""],["id","description"],["rows","3"]],null,null,null,null,null)),(l()(),u["\u0275ted"](24,null,["",""]))],function(l,n){var e=n.component;l(n,18,0,"qrCode",null==e.colis?null:e.colis.qrCode,"L")},function(l,n){var e=n.component;l(n,9,0,null==e.colis?null:null==e.colis.client?null:e.colis.client.raisonSociale),l(n,14,0,null==e.colis?null:e.colis.nomDestinataire),l(n,24,0,null==e.colis?null:e.colis.description)})}function yl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,1,"th",[["class","text-center"],["style","width: 10%"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Action "]))],null,null)}function Cl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,3,"td",[["class","text-center"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,16777216,null,null,2,"button",[["class","btn btn-danger"],["placement","top"],["tooltip","Supprimer"]],[[1,"aria-describedby",0]],[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.deleteligneFacture(l.parent.context.index)&&u),u},null,null)),u["\u0275did"](2,212992,null,0,I.c,[u.ViewContainerRef,d.a,I.a,u.ElementRef,u.Renderer2,P.a],{tooltip:[0,"tooltip"],placement:[1,"placement"]},null),(l()(),u["\u0275eld"](3,0,null,null,0,"i",[["class","fa fa-remove"]],null,null,null,null,null))],function(l,n){l(n,2,0,"Supprimer","top")},function(l,n){l(n,1,0,u["\u0275nov"](n,2).ariaDescribedby)})}function Fl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,53,"tr",[],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],null,null,null,null)),u["\u0275did"](1,212992,null,0,w.j,[[3,w.b],[8,null],[8,null]],{name:[0,"name"]},null),u["\u0275prd"](2048,null,w.b,null,[w.j]),u["\u0275did"](3,16384,null,0,w.p,[[4,w.b]],null,null),(l()(),u["\u0275eld"](4,0,null,null,6,"td",[],null,null,null,null,null)),(l()(),u["\u0275eld"](5,0,null,null,5,"input",[["class","form-control"],["formControlName","designation"],["type","text"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(l,n,e){var t=!0;return"input"===n&&(t=!1!==u["\u0275nov"](l,6)._handleInput(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,6).onTouched()&&t),"compositionstart"===n&&(t=!1!==u["\u0275nov"](l,6)._compositionStart()&&t),"compositionend"===n&&(t=!1!==u["\u0275nov"](l,6)._compositionEnd(e.target.value)&&t),t},null,null)),u["\u0275did"](6,16384,null,0,w.c,[u.Renderer2,u.ElementRef,[2,w.a]],null,null),u["\u0275prd"](1024,null,w.m,function(l){return[l]},[w.c]),u["\u0275did"](8,671744,null,0,w.h,[[3,w.b],[8,null],[8,null],[6,w.m],[2,w.w]],{name:[0,"name"]},null),u["\u0275prd"](2048,null,w.n,null,[w.h]),u["\u0275did"](10,16384,null,0,w.o,[[4,w.n]],null,null),(l()(),u["\u0275eld"](11,0,null,null,7,"td",[],null,null,null,null,null)),(l()(),u["\u0275eld"](12,0,null,null,6,"input",[["class","form-control text-right"],["formControlName","quantite"],["type","number"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(l,n,e){var t=!0;return"input"===n&&(t=!1!==u["\u0275nov"](l,13)._handleInput(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,13).onTouched()&&t),"compositionstart"===n&&(t=!1!==u["\u0275nov"](l,13)._compositionStart()&&t),"compositionend"===n&&(t=!1!==u["\u0275nov"](l,13)._compositionEnd(e.target.value)&&t),"change"===n&&(t=!1!==u["\u0275nov"](l,14).onChange(e.target.value)&&t),"input"===n&&(t=!1!==u["\u0275nov"](l,14).onChange(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,14).onTouched()&&t),t},null,null)),u["\u0275did"](13,16384,null,0,w.c,[u.Renderer2,u.ElementRef,[2,w.a]],null,null),u["\u0275did"](14,16384,null,0,w.r,[u.Renderer2,u.ElementRef],null,null),u["\u0275prd"](1024,null,w.m,function(l,n){return[l,n]},[w.c,w.r]),u["\u0275did"](16,671744,null,0,w.h,[[3,w.b],[8,null],[8,null],[6,w.m],[2,w.w]],{name:[0,"name"]},null),u["\u0275prd"](2048,null,w.n,null,[w.h]),u["\u0275did"](18,16384,null,0,w.o,[[4,w.n]],null,null),(l()(),u["\u0275eld"](19,0,null,null,7,"td",[],null,null,null,null,null)),(l()(),u["\u0275eld"](20,0,null,null,6,"input",[["class","form-control text-right"],["formControlName","poids"],["type","number"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(l,n,e){var t=!0;return"input"===n&&(t=!1!==u["\u0275nov"](l,21)._handleInput(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,21).onTouched()&&t),"compositionstart"===n&&(t=!1!==u["\u0275nov"](l,21)._compositionStart()&&t),"compositionend"===n&&(t=!1!==u["\u0275nov"](l,21)._compositionEnd(e.target.value)&&t),"change"===n&&(t=!1!==u["\u0275nov"](l,22).onChange(e.target.value)&&t),"input"===n&&(t=!1!==u["\u0275nov"](l,22).onChange(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,22).onTouched()&&t),t},null,null)),u["\u0275did"](21,16384,null,0,w.c,[u.Renderer2,u.ElementRef,[2,w.a]],null,null),u["\u0275did"](22,16384,null,0,w.r,[u.Renderer2,u.ElementRef],null,null),u["\u0275prd"](1024,null,w.m,function(l,n){return[l,n]},[w.c,w.r]),u["\u0275did"](24,671744,null,0,w.h,[[3,w.b],[8,null],[8,null],[6,w.m],[2,w.w]],{name:[0,"name"]},null),u["\u0275prd"](2048,null,w.n,null,[w.h]),u["\u0275did"](26,16384,null,0,w.o,[[4,w.n]],null,null),(l()(),u["\u0275eld"](27,0,null,null,11,"td",[],null,null,null,null,null)),(l()(),u["\u0275eld"](28,0,null,null,10,"div",[["class","input-group mb-4"]],null,null,null,null,null)),(l()(),u["\u0275eld"](29,0,null,null,6,"input",[["class","form-control text-right"],["formControlName","prixUnitaire"],["type","number"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"change"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(l,n,e){var t=!0,o=l.component;return"input"===n&&(t=!1!==u["\u0275nov"](l,30)._handleInput(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,30).onTouched()&&t),"compositionstart"===n&&(t=!1!==u["\u0275nov"](l,30)._compositionStart()&&t),"compositionend"===n&&(t=!1!==u["\u0275nov"](l,30)._compositionEnd(e.target.value)&&t),"change"===n&&(t=!1!==u["\u0275nov"](l,31).onChange(e.target.value)&&t),"input"===n&&(t=!1!==u["\u0275nov"](l,31).onChange(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,31).onTouched()&&t),"change"===n&&(t=!1!==o.prixUnitaire(e,l.context.index)&&t),t},null,null)),u["\u0275did"](30,16384,null,0,w.c,[u.Renderer2,u.ElementRef,[2,w.a]],null,null),u["\u0275did"](31,16384,null,0,w.r,[u.Renderer2,u.ElementRef],null,null),u["\u0275prd"](1024,null,w.m,function(l,n){return[l,n]},[w.c,w.r]),u["\u0275did"](33,671744,null,0,w.h,[[3,w.b],[8,null],[8,null],[6,w.m],[2,w.w]],{name:[0,"name"]},null),u["\u0275prd"](2048,null,w.n,null,[w.h]),u["\u0275did"](35,16384,null,0,w.o,[[4,w.n]],null,null),(l()(),u["\u0275eld"](36,0,null,null,2,"div",[["class","input-group-prepend"]],null,null,null,null,null)),(l()(),u["\u0275eld"](37,0,null,null,1,"span",[["class","input-group-text"]],null,null,null,null,null)),(l()(),u["\u0275ted"](38,null,["",""])),(l()(),u["\u0275eld"](39,0,null,null,12,"td",[],null,null,null,null,null)),(l()(),u["\u0275eld"](40,0,null,null,11,"div",[["class","input-group mb-4"]],null,null,null,null,null)),(l()(),u["\u0275eld"](41,0,null,null,7,"input",[["class","form-control text-right"],["formControlName","prixTotal"],["type","number"]],[[8,"value",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(l,n,e){var t=!0;return"input"===n&&(t=!1!==u["\u0275nov"](l,42)._handleInput(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,42).onTouched()&&t),"compositionstart"===n&&(t=!1!==u["\u0275nov"](l,42)._compositionStart()&&t),"compositionend"===n&&(t=!1!==u["\u0275nov"](l,42)._compositionEnd(e.target.value)&&t),"change"===n&&(t=!1!==u["\u0275nov"](l,43).onChange(e.target.value)&&t),"input"===n&&(t=!1!==u["\u0275nov"](l,43).onChange(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,43).onTouched()&&t),t},null,null)),u["\u0275did"](42,16384,null,0,w.c,[u.Renderer2,u.ElementRef,[2,w.a]],null,null),u["\u0275did"](43,16384,null,0,w.r,[u.Renderer2,u.ElementRef],null,null),u["\u0275prd"](1024,null,w.m,function(l,n){return[l,n]},[w.c,w.r]),u["\u0275did"](45,671744,null,0,w.h,[[3,w.b],[8,null],[8,null],[6,w.m],[2,w.w]],{name:[0,"name"]},null),u["\u0275prd"](2048,null,w.n,null,[w.h]),u["\u0275did"](47,16384,null,0,w.o,[[4,w.n]],null,null),u["\u0275ppd"](48,1),(l()(),u["\u0275eld"](49,0,null,null,2,"div",[["class","input-group-prepend"]],null,null,null,null,null)),(l()(),u["\u0275eld"](50,0,null,null,1,"span",[["class","input-group-text"]],null,null,null,null,null)),(l()(),u["\u0275ted"](51,null,["",""])),(l()(),u["\u0275and"](16777216,null,null,1,null,Cl)),u["\u0275did"](53,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null)],function(l,n){var e=n.component;l(n,1,0,n.context.index),l(n,8,0,"designation"),l(n,16,0,"quantite"),l(n,24,0,"poids"),l(n,33,0,"prixUnitaire"),l(n,45,0,"prixTotal"),l(n,53,0,!0===e.showBtn&&"s"!==e.type)},function(l,n){var e=n.component;l(n,0,0,u["\u0275nov"](n,3).ngClassUntouched,u["\u0275nov"](n,3).ngClassTouched,u["\u0275nov"](n,3).ngClassPristine,u["\u0275nov"](n,3).ngClassDirty,u["\u0275nov"](n,3).ngClassValid,u["\u0275nov"](n,3).ngClassInvalid,u["\u0275nov"](n,3).ngClassPending),l(n,5,0,u["\u0275nov"](n,10).ngClassUntouched,u["\u0275nov"](n,10).ngClassTouched,u["\u0275nov"](n,10).ngClassPristine,u["\u0275nov"](n,10).ngClassDirty,u["\u0275nov"](n,10).ngClassValid,u["\u0275nov"](n,10).ngClassInvalid,u["\u0275nov"](n,10).ngClassPending),l(n,12,0,u["\u0275nov"](n,18).ngClassUntouched,u["\u0275nov"](n,18).ngClassTouched,u["\u0275nov"](n,18).ngClassPristine,u["\u0275nov"](n,18).ngClassDirty,u["\u0275nov"](n,18).ngClassValid,u["\u0275nov"](n,18).ngClassInvalid,u["\u0275nov"](n,18).ngClassPending),l(n,20,0,u["\u0275nov"](n,26).ngClassUntouched,u["\u0275nov"](n,26).ngClassTouched,u["\u0275nov"](n,26).ngClassPristine,u["\u0275nov"](n,26).ngClassDirty,u["\u0275nov"](n,26).ngClassValid,u["\u0275nov"](n,26).ngClassInvalid,u["\u0275nov"](n,26).ngClassPending),l(n,29,0,u["\u0275nov"](n,35).ngClassUntouched,u["\u0275nov"](n,35).ngClassTouched,u["\u0275nov"](n,35).ngClassPristine,u["\u0275nov"](n,35).ngClassDirty,u["\u0275nov"](n,35).ngClassValid,u["\u0275nov"](n,35).ngClassInvalid,u["\u0275nov"](n,35).ngClassPending),l(n,38,0,null==e.user?null:null==e.user.personne?null:null==e.user.personne.site?null:null==e.user.personne.site.devise?null:e.user.personne.site.devise.nomDevise);var t=u["\u0275unv"](n,41,0,l(n,48,0,u["\u0275nov"](n.parent.parent,1),n.context.$implicit.get("prixTotal").value));l(n,41,0,t,u["\u0275nov"](n,47).ngClassUntouched,u["\u0275nov"](n,47).ngClassTouched,u["\u0275nov"](n,47).ngClassPristine,u["\u0275nov"](n,47).ngClassDirty,u["\u0275nov"](n,47).ngClassValid,u["\u0275nov"](n,47).ngClassInvalid,u["\u0275nov"](n,47).ngClassPending),l(n,51,0,null==e.user?null:null==e.user.personne?null:null==e.user.personne.site?null:null==e.user.personne.site.devise?null:e.user.personne.site.devise.nomDevise)})}function wl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,0,"td",[],null,null,null,null,null))],null,null)}function Tl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,11,"tr",[],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,1,"td",[["class","text-right font-weight-bold"],["colspan","4"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Montant HT"])),(l()(),u["\u0275eld"](3,0,null,null,6,"td",[],null,null,null,null,null)),(l()(),u["\u0275eld"](4,0,null,null,5,"div",[["class","input-group mb-4"]],null,null,null,null,null)),(l()(),u["\u0275eld"](5,0,null,null,1,"input",[["class","form-control text-right font-weight-bold"],["disabled",""],["type","number"]],[[8,"value",0]],null,null,null,null)),u["\u0275ppd"](6,1),(l()(),u["\u0275eld"](7,0,null,null,2,"div",[["class","input-group-prepend"]],null,null,null,null,null)),(l()(),u["\u0275eld"](8,0,null,null,1,"span",[["class","input-group-text"]],null,null,null,null,null)),(l()(),u["\u0275ted"](9,null,["",""])),(l()(),u["\u0275and"](16777216,null,null,1,null,wl)),u["\u0275did"](11,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null)],function(l,n){var e=n.component;l(n,11,0,!0===e.showBtn&&"s"!==e.type)},function(l,n){var e=n.component,t=u["\u0275unv"](n,5,0,l(n,6,0,u["\u0275nov"](n.parent.parent,1),e.montantHT));l(n,5,0,t),l(n,9,0,null==e.user?null:null==e.user.personne?null:null==e.user.personne.site?null:null==e.user.personne.site.devise?null:e.user.personne.site.devise.nomDevise)})}function xl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,0,"td",[],null,null,null,null,null))],null,null)}function Rl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,10,"tr",[["class","tva"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,1,"td",[["class","text-right font-weight-bold"],["colspan","4"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["TVA"])),(l()(),u["\u0275eld"](3,0,null,null,5,"td",[],null,null,null,null,null)),(l()(),u["\u0275eld"](4,0,null,null,4,"div",[["class","input-group mb-4"]],null,null,null,null,null)),(l()(),u["\u0275eld"](5,0,null,null,0,"input",[["class","form-control text-right"],["disabled",""],["type","number"]],[[8,"value",0]],null,null,null,null)),(l()(),u["\u0275eld"](6,0,null,null,2,"div",[["class","input-group-prepend"]],null,null,null,null,null)),(l()(),u["\u0275eld"](7,0,null,null,1,"span",[["class","input-group-text"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["%"])),(l()(),u["\u0275and"](16777216,null,null,1,null,xl)),u["\u0275did"](10,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null)],function(l,n){var e=n.component;l(n,10,0,!0===e.showBtn&&"s"!==e.type)},function(l,n){l(n,5,0,100*n.component.tva)})}function Il(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,0,"td",[],null,null,null,null,null))],null,null)}function Pl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,11,"tr",[],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,1,"td",[["class","text-right font-weight-bold"],["colspan","4"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Montant TTC"])),(l()(),u["\u0275eld"](3,0,null,null,6,"td",[],null,null,null,null,null)),(l()(),u["\u0275eld"](4,0,null,null,5,"div",[["class","input-group mb-4"]],null,null,null,null,null)),(l()(),u["\u0275eld"](5,0,null,null,1,"input",[["class","form-control text-right font-weight-bold"],["disabled",""],["type","number"]],[[8,"value",0]],null,null,null,null)),u["\u0275ppd"](6,1),(l()(),u["\u0275eld"](7,0,null,null,2,"div",[["class","input-group-prepend"]],null,null,null,null,null)),(l()(),u["\u0275eld"](8,0,null,null,1,"span",[["class","input-group-text"]],null,null,null,null,null)),(l()(),u["\u0275ted"](9,null,["",""])),(l()(),u["\u0275and"](16777216,null,null,1,null,Il)),u["\u0275did"](11,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null)],function(l,n){var e=n.component;l(n,11,0,!0===e.showBtn&&"s"!==e.type)},function(l,n){var e=n.component,t=u["\u0275unv"](n,5,0,l(n,6,0,u["\u0275nov"](n.parent.parent,1),e.montantTTC));l(n,5,0,t),l(n,9,0,null==e.user?null:null==e.user.personne?null:null==e.user.personne.site?null:null==e.user.personne.site.devise?null:e.user.personne.site.devise.nomDevise)})}function El(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,2,"button",[["class","btn btn-light float-left"],["type","reset"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.clearFactureForm()&&u),u},null,null)),(l()(),u["\u0275eld"](1,0,null,null,0,"i",[["class","fa fa-refresh"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Effacer "]))],null,null)}function Sl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,2,"button",[["class","btn btn-primary float-right"],["type","button"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.saveFacture()&&u),u},null,null)),u["\u0275did"](1,737280,null,0,E.b,[u.ElementRef,[2,E.a]],{loading:[0,"loading"],disabled:[1,"disabled"]},null),(l()(),u["\u0275ted"](-1,null,[" Enregistrer "]))],function(l,n){var e=n.component;l(n,1,0,e.isLoading,"INVALID"===e.factureForm.status)},null)}function Ol(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,2,"button",[["class","btn btn-warning float-right"],["type","button"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.updateFacture()&&u),u},null,null)),u["\u0275did"](1,737280,null,0,E.b,[u.ElementRef,[2,E.a]],{loading:[0,"loading"],disabled:[1,"disabled"]},null),(l()(),u["\u0275ted"](-1,null,[" Modifier "]))],function(l,n){var e=n.component;l(n,1,0,e.isLoading,"INVALID"===e.factureForm.status)},null)}function _l(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,194,"tabset",[],[[2,"tab-container",null]],null,null,S.b,S.a)),u["\u0275did"](1,180224,[[1,4],["staticTabs",4]],0,O.e,[O.f,u.Renderer2,u.ElementRef],null,null),(l()(),u["\u0275eld"](2,0,null,0,92,"tab",[["id","liste-facture"]],[[1,"id",0],[2,"active",null],[2,"tab-pane",null]],[[null,"selectTab"]],function(l,n,e){var u=!0;return"selectTab"===n&&(u=!1!==l.component.onSelect(e)&&u),u},null,null)),u["\u0275did"](3,212992,null,0,O.b,[O.e,u.ElementRef,u.Renderer2],{id:[0,"id"]},{selectTab:"selectTab"}),(l()(),u["\u0275and"](0,null,null,1,null,G)),u["\u0275did"](5,16384,null,0,O.c,[u.TemplateRef,O.b],null,null),(l()(),u["\u0275eld"](6,0,null,null,88,"div",[["class","card"]],null,null,null,null,null)),(l()(),u["\u0275eld"](7,0,null,null,3,"div",[["class","card-header"]],null,null,null,null,null)),(l()(),u["\u0275eld"](8,0,null,null,2,"button",[["class","btn btn-light float-right"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.reload()&&u),u},null,null)),(l()(),u["\u0275eld"](9,0,null,null,0,"i",[["class","fa fa-refresh"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Actualiser "])),(l()(),u["\u0275eld"](11,0,null,null,83,"div",[["class","card-body"]],null,null,null,null,null)),(l()(),u["\u0275eld"](12,0,null,null,80,"div",[["class","row"]],null,null,null,null,null)),(l()(),u["\u0275eld"](13,0,null,null,10,"div",[["class","col-md-3"]],null,null,null,null,null)),(l()(),u["\u0275eld"](14,0,null,null,9,"div",[["class","input-group mb-4"]],null,null,null,null,null)),(l()(),u["\u0275eld"](15,0,null,null,2,"div",[["class","input-group-prepend"]],null,null,null,null,null)),(l()(),u["\u0275eld"](16,0,null,null,1,"span",[["class","input-group-text"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Num\xe9ro"])),(l()(),u["\u0275eld"](18,0,null,null,5,"input",[["class","form-control"],["type","text"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"keyup"],[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(l,n,e){var t=!0,o=l.component;return"input"===n&&(t=!1!==u["\u0275nov"](l,19)._handleInput(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,19).onTouched()&&t),"compositionstart"===n&&(t=!1!==u["\u0275nov"](l,19)._compositionStart()&&t),"compositionend"===n&&(t=!1!==u["\u0275nov"](l,19)._compositionEnd(e.target.value)&&t),"keyup"===n&&(t=!1!==o.searchNumeroFacture()&&t),"ngModelChange"===n&&(t=!1!==(o.numeroFacture=e)&&t),t},null,null)),u["\u0275did"](19,16384,null,0,w.c,[u.Renderer2,u.ElementRef,[2,w.a]],null,null),u["\u0275prd"](1024,null,w.m,function(l){return[l]},[w.c]),u["\u0275did"](21,671744,null,0,w.q,[[8,null],[8,null],[8,null],[6,w.m]],{model:[0,"model"]},{update:"ngModelChange"}),u["\u0275prd"](2048,null,w.n,null,[w.q]),u["\u0275did"](23,16384,null,0,w.o,[[4,w.n]],null,null),(l()(),u["\u0275eld"](24,0,null,null,10,"div",[["class","col-md-3"]],null,null,null,null,null)),(l()(),u["\u0275eld"](25,0,null,null,9,"div",[["class","input-group mb-4"]],null,null,null,null,null)),(l()(),u["\u0275eld"](26,0,null,null,2,"div",[["class","input-group-prepend"]],null,null,null,null,null)),(l()(),u["\u0275eld"](27,0,null,null,1,"span",[["class","input-group-text"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Colis"])),(l()(),u["\u0275eld"](29,0,null,null,5,"input",[["class","form-control"],["type","text"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"keyup"],[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(l,n,e){var t=!0,o=l.component;return"input"===n&&(t=!1!==u["\u0275nov"](l,30)._handleInput(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,30).onTouched()&&t),"compositionstart"===n&&(t=!1!==u["\u0275nov"](l,30)._compositionStart()&&t),"compositionend"===n&&(t=!1!==u["\u0275nov"](l,30)._compositionEnd(e.target.value)&&t),"keyup"===n&&(t=!1!==o.searchReferenceColis()&&t),"ngModelChange"===n&&(t=!1!==(o.referenceColis=e)&&t),t},null,null)),u["\u0275did"](30,16384,null,0,w.c,[u.Renderer2,u.ElementRef,[2,w.a]],null,null),u["\u0275prd"](1024,null,w.m,function(l){return[l]},[w.c]),u["\u0275did"](32,671744,null,0,w.q,[[8,null],[8,null],[8,null],[6,w.m]],{model:[0,"model"]},{update:"ngModelChange"}),u["\u0275prd"](2048,null,w.n,null,[w.q]),u["\u0275did"](34,16384,null,0,w.o,[[4,w.n]],null,null),(l()(),u["\u0275eld"](35,0,null,null,24,"div",[["class","col-md-3"]],null,null,null,null,null)),(l()(),u["\u0275eld"](36,0,null,null,23,"div",[["class","input-group mb-4"]],null,null,null,null,null)),(l()(),u["\u0275eld"](37,0,null,null,2,"div",[["class","input-group-prepend"]],null,null,null,null,null)),(l()(),u["\u0275eld"](38,0,null,null,1,"span",[["class","input-group-text"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Type"])),(l()(),u["\u0275eld"](40,0,null,null,19,"ng-select",[["bindLabel","nomTypeFacture"],["class","form-control ng-select"],["placeholder","Aucun type s\xe9lectionn\xe9"],["role","listbox"]],[[2,"ng-select-single",null],[2,"ng-select-typeahead",null],[2,"ng-select-multiple",null],[2,"ng-select-taggable",null],[2,"ng-select-searchable",null],[2,"ng-select-clearable",null],[2,"ng-select-opened",null],[2,"ng-select-disabled",null],[2,"ng-select-filtered",null]],[[null,"change"],[null,"keydown"]],function(l,n,e){var t=!0,o=l.component;return"keydown"===n&&(t=!1!==u["\u0275nov"](l,43).handleKeyDown(e)&&t),"change"===n&&(t=!1!==o.searchNomTypeFacture(e)&&t),t},C.c,C.a)),u["\u0275prd"](5120,null,w.m,function(l){return[l]},[F.a]),u["\u0275prd"](4608,null,F.f,F.f,[]),u["\u0275did"](43,4964352,null,12,F.a,[[8,"form-control"],[8,null],F.b,F.d,u.ElementRef,u.ChangeDetectorRef,F.l],{bindLabel:[0,"bindLabel"],placeholder:[1,"placeholder"],items:[2,"items"]},{changeEvent:"change"}),u["\u0275qud"](335544320,3,{optionTemplate:0}),u["\u0275qud"](335544320,4,{optgroupTemplate:0}),u["\u0275qud"](335544320,5,{labelTemplate:0}),u["\u0275qud"](335544320,6,{multiLabelTemplate:0}),u["\u0275qud"](603979776,7,{headerTemplate:0}),u["\u0275qud"](603979776,8,{footerTemplate:0}),u["\u0275qud"](335544320,9,{notFoundTemplate:0}),u["\u0275qud"](335544320,10,{typeToSearchTemplate:0}),u["\u0275qud"](335544320,11,{loadingTextTemplate:0}),u["\u0275qud"](335544320,12,{tagTemplate:0}),u["\u0275qud"](335544320,13,{loadingSpinnerTemplate:0}),u["\u0275qud"](603979776,14,{ngOptions:1}),(l()(),u["\u0275and"](0,[[5,2]],null,1,null,Q)),u["\u0275did"](57,16384,null,0,F.i,[u.TemplateRef],null,null),(l()(),u["\u0275and"](0,[[3,2]],null,1,null,W)),u["\u0275did"](59,16384,null,0,F.h,[u.TemplateRef],null,null),(l()(),u["\u0275eld"](60,0,null,null,32,"div",[["class","col-md-3"]],null,null,null,null,null)),(l()(),u["\u0275eld"](61,0,null,null,31,"div",[["class","input-group mb-4"]],null,null,null,null,null)),(l()(),u["\u0275eld"](62,0,null,null,2,"div",[["class","input-group-prepend"]],null,null,null,null,null)),(l()(),u["\u0275eld"](63,0,null,null,1,"span",[["class","input-group-text text-color-blue"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Statut"])),(l()(),u["\u0275eld"](65,0,null,null,27,"ng-select",[["class","form-control ng-select"],["role","listbox"]],[[2,"ng-select-single",null],[2,"ng-select-typeahead",null],[2,"ng-select-multiple",null],[2,"ng-select-taggable",null],[2,"ng-select-searchable",null],[2,"ng-select-clearable",null],[2,"ng-select-opened",null],[2,"ng-select-disabled",null],[2,"ng-select-filtered",null],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"change"],[null,"keydown"]],function(l,n,e){var t=!0,o=l.component;return"keydown"===n&&(t=!1!==u["\u0275nov"](l,67).handleKeyDown(e)&&t),"ngModelChange"===n&&(t=!1!==(o.enable=e)&&t),"change"===n&&(t=!1!==o.searchStatut()&&t),t},C.c,C.a)),u["\u0275prd"](4608,null,F.f,F.f,[]),u["\u0275did"](67,4964352,null,12,F.a,[[8,"form-control"],[8,null],F.b,F.d,u.ElementRef,u.ChangeDetectorRef,F.l],{clearable:[0,"clearable"]},{changeEvent:"change"}),u["\u0275qud"](335544320,15,{optionTemplate:0}),u["\u0275qud"](335544320,16,{optgroupTemplate:0}),u["\u0275qud"](335544320,17,{labelTemplate:0}),u["\u0275qud"](335544320,18,{multiLabelTemplate:0}),u["\u0275qud"](603979776,19,{headerTemplate:0}),u["\u0275qud"](603979776,20,{footerTemplate:0}),u["\u0275qud"](335544320,21,{notFoundTemplate:0}),u["\u0275qud"](335544320,22,{typeToSearchTemplate:0}),u["\u0275qud"](335544320,23,{loadingTextTemplate:0}),u["\u0275qud"](335544320,24,{tagTemplate:0}),u["\u0275qud"](335544320,25,{loadingSpinnerTemplate:0}),u["\u0275qud"](603979776,26,{ngOptions:1}),u["\u0275prd"](1024,null,w.m,function(l){return[l]},[F.a]),u["\u0275did"](81,671744,null,0,w.q,[[8,null],[8,null],[8,null],[6,w.m]],{model:[0,"model"]},{update:"ngModelChange"}),u["\u0275prd"](2048,null,w.n,null,[w.q]),u["\u0275did"](83,16384,null,0,w.o,[[4,w.n]],null,null),(l()(),u["\u0275eld"](84,0,null,null,2,"ng-option",[],null,null,null,C.d,C.b)),u["\u0275did"](85,9093120,[[26,4]],0,F.k,[u.ElementRef],{value:[0,"value"]},null),(l()(),u["\u0275ted"](-1,0,["Tout"])),(l()(),u["\u0275eld"](87,0,null,null,2,"ng-option",[],null,null,null,C.d,C.b)),u["\u0275did"](88,9093120,[[26,4]],0,F.k,[u.ElementRef],{value:[0,"value"]},null),(l()(),u["\u0275ted"](-1,0,["Actif"])),(l()(),u["\u0275eld"](90,0,null,null,2,"ng-option",[],null,null,null,C.d,C.b)),u["\u0275did"](91,9093120,[[26,4]],0,F.k,[u.ElementRef],{value:[0,"value"]},null),(l()(),u["\u0275ted"](-1,0,["Inactif"])),(l()(),u["\u0275and"](16777216,null,null,1,null,tl)),u["\u0275did"](94,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275eld"](95,0,null,0,99,"tab",[["id","creer-facture"]],[[1,"id",0],[2,"active",null],[2,"tab-pane",null]],[[null,"selectTab"]],function(l,n,e){var u=!0;return"selectTab"===n&&(u=!1!==l.component.onSelect(e)&&u),u},null,null)),u["\u0275did"](96,212992,null,0,O.b,[O.e,u.ElementRef,u.Renderer2],{id:[0,"id"]},{selectTab:"selectTab"}),(l()(),u["\u0275and"](0,null,null,1,null,rl)),u["\u0275did"](98,16384,null,0,O.c,[u.TemplateRef,O.b],null,null),(l()(),u["\u0275and"](16777216,null,null,1,null,sl)),u["\u0275did"](100,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275eld"](101,0,null,null,93,"form",[["novalidate",""]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"submit"],[null,"reset"]],function(l,n,e){var t=!0;return"submit"===n&&(t=!1!==u["\u0275nov"](l,103).onSubmit(e)&&t),"reset"===n&&(t=!1!==u["\u0275nov"](l,103).onReset()&&t),t},null,null)),u["\u0275did"](102,16384,null,0,w.x,[],null,null),u["\u0275did"](103,540672,null,0,w.i,[[8,null],[8,null]],{form:[0,"form"]},null),u["\u0275prd"](2048,null,w.b,null,[w.i]),u["\u0275did"](105,16384,null,0,w.p,[[4,w.b]],null,null),(l()(),u["\u0275eld"](106,0,null,null,48,"div",[["class","card"]],null,null,null,null,null)),(l()(),u["\u0275eld"](107,0,null,null,47,"div",[["class","card-body"]],null,null,null,null,null)),(l()(),u["\u0275eld"](108,0,null,null,46,"div",[["class","row"]],null,null,null,null,null)),(l()(),u["\u0275eld"](109,0,null,null,5,"input",[["formControlName","id"],["id","id"],["type","hidden"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(l,n,e){var t=!0;return"input"===n&&(t=!1!==u["\u0275nov"](l,110)._handleInput(e.target.value)&&t),"blur"===n&&(t=!1!==u["\u0275nov"](l,110).onTouched()&&t),"compositionstart"===n&&(t=!1!==u["\u0275nov"](l,110)._compositionStart()&&t),"compositionend"===n&&(t=!1!==u["\u0275nov"](l,110)._compositionEnd(e.target.value)&&t),t},null,null)),u["\u0275did"](110,16384,null,0,w.c,[u.Renderer2,u.ElementRef,[2,w.a]],null,null),u["\u0275prd"](1024,null,w.m,function(l){return[l]},[w.c]),u["\u0275did"](112,671744,null,0,w.h,[[3,w.b],[8,null],[8,null],[6,w.m],[2,w.w]],{name:[0,"name"]},null),u["\u0275prd"](2048,null,w.n,null,[w.h]),u["\u0275did"](114,16384,null,0,w.o,[[4,w.n]],null,null),(l()(),u["\u0275eld"](115,0,null,null,7,"div",[["class","form-group row col-md-6"]],null,null,null,null,null)),(l()(),u["\u0275eld"](116,0,null,null,1,"label",[["class","control-label col-md-4 text-right"],["for","typeFacture"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Type"])),(l()(),u["\u0275eld"](118,0,null,null,4,"div",[["class","col-md-8"]],null,null,null,null,null)),(l()(),u["\u0275and"](16777216,null,null,1,null,pl)),u["\u0275did"](120,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,gl)),u["\u0275did"](122,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275eld"](123,0,null,null,27,"div",[["class","form-group row col-md-6"]],null,null,null,null,null)),(l()(),u["\u0275eld"](124,0,null,null,1,"label",[["class","control-label col-md-4 text-right"],["for","colis"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Colis"])),(l()(),u["\u0275eld"](126,0,null,null,24,"div",[["class","col-md-8"]],null,null,null,null,null)),(l()(),u["\u0275eld"](127,0,null,null,21,"ng-select",[["bindLabel","reference"],["class","form-control ng-select"],["formControlName","colis"],["id","colis"],["placeholder","Aucun colis s\xe9lectionn\xe9"],["role","listbox"]],[[2,"ng-select-single",null],[2,"ng-select-typeahead",null],[2,"ng-select-multiple",null],[2,"ng-select-taggable",null],[2,"ng-select-searchable",null],[2,"ng-select-clearable",null],[2,"ng-select-opened",null],[2,"ng-select-disabled",null],[2,"ng-select-filtered",null],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"change"],[null,"search"],[null,"keydown"]],function(l,n,e){var t=!0,o=l.component;return"keydown"===n&&(t=!1!==u["\u0275nov"](l,132).handleKeyDown(e)&&t),"change"===n&&(t=!1!==o.searchNomColis(e)&&t),"search"===n&&(t=!1!==o.getSendColisByReference(e)&&t),t},C.c,C.a)),u["\u0275prd"](4608,null,F.f,F.f,[]),u["\u0275prd"](512,null,s["\u0275NgClassImpl"],s["\u0275NgClassR2Impl"],[u.IterableDiffers,u.KeyValueDiffers,u.ElementRef,u.Renderer2]),u["\u0275did"](130,278528,null,0,s.NgClass,[s["\u0275NgClassImpl"]],{klass:[0,"klass"],ngClass:[1,"ngClass"]},null),u["\u0275pod"](131,{"is-invalid":0,"is-valid":1}),u["\u0275did"](132,4964352,null,12,F.a,[[8,"form-control"],[8,null],F.b,F.d,u.ElementRef,u.ChangeDetectorRef,F.l],{bindLabel:[0,"bindLabel"],placeholder:[1,"placeholder"],items:[2,"items"]},{changeEvent:"change",searchEvent:"search"}),u["\u0275qud"](335544320,39,{optionTemplate:0}),u["\u0275qud"](335544320,40,{optgroupTemplate:0}),u["\u0275qud"](335544320,41,{labelTemplate:0}),u["\u0275qud"](335544320,42,{multiLabelTemplate:0}),u["\u0275qud"](603979776,43,{headerTemplate:0}),u["\u0275qud"](603979776,44,{footerTemplate:0}),u["\u0275qud"](335544320,45,{notFoundTemplate:0}),u["\u0275qud"](335544320,46,{typeToSearchTemplate:0}),u["\u0275qud"](335544320,47,{loadingTextTemplate:0}),u["\u0275qud"](335544320,48,{tagTemplate:0}),u["\u0275qud"](335544320,49,{loadingSpinnerTemplate:0}),u["\u0275qud"](603979776,50,{ngOptions:1}),u["\u0275prd"](1024,null,w.m,function(l){return[l]},[F.a]),u["\u0275did"](146,671744,null,0,w.h,[[3,w.b],[8,null],[8,null],[6,w.m],[2,w.w]],{name:[0,"name"]},null),u["\u0275prd"](2048,null,w.n,null,[w.h]),u["\u0275did"](148,16384,null,0,w.o,[[4,w.n]],null,null),(l()(),u["\u0275and"](16777216,null,null,1,null,fl)),u["\u0275did"](150,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,ml)),u["\u0275did"](152,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,vl)),u["\u0275did"](154,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,bl)),u["\u0275did"](156,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275eld"](157,0,null,null,37,"div",[["class","card"]],null,null,null,null,null)),(l()(),u["\u0275eld"](158,0,null,null,1,"div",[["class","card-header"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["LIGNES FACTURES"])),(l()(),u["\u0275eld"](160,0,null,null,27,"div",[["class","card-body ligne-facture"]],null,null,null,null,null)),(l()(),u["\u0275eld"](161,0,null,null,26,"table",[["class","table table-condensed data-table"]],null,null,null,null,null)),(l()(),u["\u0275eld"](162,0,null,null,13,"thead",[],null,null,null,null,null)),(l()(),u["\u0275eld"](163,0,null,null,12,"tr",[],null,null,null,null,null)),(l()(),u["\u0275eld"](164,0,null,null,1,"th",[["class","text-center"],["style","width: 20%"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Designation "])),(l()(),u["\u0275eld"](166,0,null,null,1,"th",[["class","text-center"],["style","width: 15%"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Quantit\xe9 "])),(l()(),u["\u0275eld"](168,0,null,null,1,"th",[["class","text-center"],["style","width: 15%"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Poids (Kg) "])),(l()(),u["\u0275eld"](170,0,null,null,1,"th",[["class","text-center"],["style","width: 20%"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Prix Unitaire "])),(l()(),u["\u0275eld"](172,0,null,null,1,"th",[["class","text-center"],["style","width: 20%"]],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,[" Prix Total "])),(l()(),u["\u0275and"](16777216,null,null,1,null,yl)),u["\u0275did"](175,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275eld"](176,0,null,null,11,"tbody",[["formArrayName","ligneFactures"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],null,null,null,null)),u["\u0275did"](177,212992,null,0,w.e,[[3,w.b],[8,null],[8,null]],{name:[0,"name"]},null),u["\u0275prd"](2048,null,w.b,null,[w.e]),u["\u0275did"](179,16384,null,0,w.p,[[4,w.b]],null,null),(l()(),u["\u0275and"](16777216,null,null,1,null,Fl)),u["\u0275did"](181,278528,null,0,s.NgForOf,[u.ViewContainerRef,u.TemplateRef,u.IterableDiffers],{ngForOf:[0,"ngForOf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,Tl)),u["\u0275did"](183,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,Rl)),u["\u0275did"](185,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,Pl)),u["\u0275did"](187,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275eld"](188,0,null,null,6,"div",[["class","card-footer"]],null,null,null,null,null)),(l()(),u["\u0275and"](16777216,null,null,1,null,El)),u["\u0275did"](190,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,Sl)),u["\u0275did"](192,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,Ol)),u["\u0275did"](194,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null)],function(l,n){var e=n.component;l(n,3,0,"liste-facture"),l(n,21,0,e.numeroFacture),l(n,32,0,e.referenceColis),l(n,43,0,"nomTypeFacture","Aucun type s\xe9lectionn\xe9",e.allTypesFactures),l(n,67,0,!1),l(n,81,0,e.enable),l(n,85,0,2),l(n,88,0,1),l(n,91,0,0),l(n,94,0,null==e.allFactures?null:e.allFactures.factures),l(n,96,0,"creer-facture"),l(n,100,0,e.error),l(n,103,0,e.factureForm),l(n,112,0,"id"),l(n,120,0,(null==e.allTypesFactures?null:e.allTypesFactures.length)>0),l(n,122,0,e.factureForm.controls.typeFacture.errors&&(e.factureForm.controls.typeFacture.dirty||e.factureForm.controls.typeFacture.touched));var u=l(n,131,0,!(null==e.factureForm||null==e.factureForm.controls.colis||null==e.factureForm.controls.colis.errors||!e.factureForm.controls.colis.errors.required)&&e.factureForm.controls.colis.errors&&(e.factureForm.controls.colis.dirty||e.factureForm.controls.colis.touched),!(null!=e.factureForm&&null!=e.factureForm.controls.colis&&null!=e.factureForm.controls.colis.errors&&e.factureForm.controls.colis.errors.required)&&!e.factureForm.controls.colis.errors&&(e.factureForm.controls.colis.dirty||e.factureForm.controls.colis.touched));l(n,130,0,"form-control",u),l(n,132,0,"reference","Aucun colis s\xe9lectionn\xe9",e.allColis),l(n,146,0,"colis"),l(n,150,0,e.factureForm.controls.colis.errors&&(e.factureForm.controls.colis.dirty||e.factureForm.controls.colis.touched)),l(n,152,0,"u"===e.type||"s"===e.type),l(n,154,0,!e.showBtn),l(n,156,0,e.colis),l(n,175,0,!0===e.showBtn&&"s"!==e.type),l(n,177,0,"ligneFactures"),l(n,181,0,null==e.ligneFactures?null:e.ligneFactures.controls),l(n,183,0,(null==e.colis?null:e.colis.detailsColis)&&(null==e.ligneFactures?null:e.ligneFactures.controls.length)>0),l(n,185,0,(null==e.colis?null:e.colis.detailsColis)&&(null==e.ligneFactures?null:e.ligneFactures.controls.length)>0),l(n,187,0,(null==e.colis?null:e.colis.detailsColis)&&(null==e.ligneFactures?null:e.ligneFactures.controls.length)>0),l(n,190,0,"i"===e.type),l(n,192,0,"i"===e.type),l(n,194,0,"u"===e.type)},function(l,n){l(n,0,0,u["\u0275nov"](n,1).clazz),l(n,2,0,u["\u0275nov"](n,3).id,u["\u0275nov"](n,3).active,u["\u0275nov"](n,3).addClass),l(n,18,0,u["\u0275nov"](n,23).ngClassUntouched,u["\u0275nov"](n,23).ngClassTouched,u["\u0275nov"](n,23).ngClassPristine,u["\u0275nov"](n,23).ngClassDirty,u["\u0275nov"](n,23).ngClassValid,u["\u0275nov"](n,23).ngClassInvalid,u["\u0275nov"](n,23).ngClassPending),l(n,29,0,u["\u0275nov"](n,34).ngClassUntouched,u["\u0275nov"](n,34).ngClassTouched,u["\u0275nov"](n,34).ngClassPristine,u["\u0275nov"](n,34).ngClassDirty,u["\u0275nov"](n,34).ngClassValid,u["\u0275nov"](n,34).ngClassInvalid,u["\u0275nov"](n,34).ngClassPending),l(n,40,0,!u["\u0275nov"](n,43).multiple,u["\u0275nov"](n,43).typeahead,u["\u0275nov"](n,43).multiple,u["\u0275nov"](n,43).addTag,u["\u0275nov"](n,43).searchable,u["\u0275nov"](n,43).clearable,u["\u0275nov"](n,43).isOpen,u["\u0275nov"](n,43).disabled,u["\u0275nov"](n,43).filtered),l(n,65,1,[!u["\u0275nov"](n,67).multiple,u["\u0275nov"](n,67).typeahead,u["\u0275nov"](n,67).multiple,u["\u0275nov"](n,67).addTag,u["\u0275nov"](n,67).searchable,u["\u0275nov"](n,67).clearable,u["\u0275nov"](n,67).isOpen,u["\u0275nov"](n,67).disabled,u["\u0275nov"](n,67).filtered,u["\u0275nov"](n,83).ngClassUntouched,u["\u0275nov"](n,83).ngClassTouched,u["\u0275nov"](n,83).ngClassPristine,u["\u0275nov"](n,83).ngClassDirty,u["\u0275nov"](n,83).ngClassValid,u["\u0275nov"](n,83).ngClassInvalid,u["\u0275nov"](n,83).ngClassPending]),l(n,95,0,u["\u0275nov"](n,96).id,u["\u0275nov"](n,96).active,u["\u0275nov"](n,96).addClass),l(n,101,0,u["\u0275nov"](n,105).ngClassUntouched,u["\u0275nov"](n,105).ngClassTouched,u["\u0275nov"](n,105).ngClassPristine,u["\u0275nov"](n,105).ngClassDirty,u["\u0275nov"](n,105).ngClassValid,u["\u0275nov"](n,105).ngClassInvalid,u["\u0275nov"](n,105).ngClassPending),l(n,109,0,u["\u0275nov"](n,114).ngClassUntouched,u["\u0275nov"](n,114).ngClassTouched,u["\u0275nov"](n,114).ngClassPristine,u["\u0275nov"](n,114).ngClassDirty,u["\u0275nov"](n,114).ngClassValid,u["\u0275nov"](n,114).ngClassInvalid,u["\u0275nov"](n,114).ngClassPending),l(n,127,1,[!u["\u0275nov"](n,132).multiple,u["\u0275nov"](n,132).typeahead,u["\u0275nov"](n,132).multiple,u["\u0275nov"](n,132).addTag,u["\u0275nov"](n,132).searchable,u["\u0275nov"](n,132).clearable,u["\u0275nov"](n,132).isOpen,u["\u0275nov"](n,132).disabled,u["\u0275nov"](n,132).filtered,u["\u0275nov"](n,148).ngClassUntouched,u["\u0275nov"](n,148).ngClassTouched,u["\u0275nov"](n,148).ngClassPristine,u["\u0275nov"](n,148).ngClassDirty,u["\u0275nov"](n,148).ngClassValid,u["\u0275nov"](n,148).ngClassInvalid,u["\u0275nov"](n,148).ngClassPending]),l(n,176,0,u["\u0275nov"](n,179).ngClassUntouched,u["\u0275nov"](n,179).ngClassTouched,u["\u0275nov"](n,179).ngClassPristine,u["\u0275nov"](n,179).ngClassDirty,u["\u0275nov"](n,179).ngClassValid,u["\u0275nov"](n,179).ngClassInvalid,u["\u0275nov"](n,179).ngClassPending)})}function ql(l){return u["\u0275vid"](0,[u["\u0275pid"](0,s.UpperCasePipe,[]),u["\u0275pid"](0,s.DecimalPipe,[u.LOCALE_ID]),u["\u0275qud"](671088640,1,{staticTabs:0}),u["\u0275qud"](671088640,2,{externalPdfViewer:0}),(l()(),u["\u0275eld"](4,0,null,null,9,"div",[["class","animated fadeIn"]],null,null,null,null,null)),(l()(),u["\u0275eld"](5,0,null,null,8,"div",[["class","row"]],null,null,null,null,null)),(l()(),u["\u0275eld"](6,0,null,null,7,"div",[["class","col-md-12 mb-4"]],null,null,null,null,null)),(l()(),u["\u0275eld"](7,0,null,null,4,"div",[["class","col-md-12"]],null,null,null,null,null)),(l()(),u["\u0275eld"](8,0,null,null,1,"ngx-spinner",[["bdColor","rgba(51,51,51,0.8)"],["color","#fff"],["size","medium"],["type","ball-scale-multiple"]],null,null,null,_.b,_.a)),u["\u0275did"](9,770048,null,0,q.a,[q.c,u.ChangeDetectorRef],{bdColor:[0,"bdColor"],size:[1,"size"],color:[2,"color"],type:[3,"type"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,Z)),u["\u0275did"](11,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,_l)),u["\u0275did"](13,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null)],function(l,n){var e=n.component;l(n,9,0,"rgba(51,51,51,0.8)","medium","#fff","ball-scale-multiple"),l(n,11,0,e.print),l(n,13,0,!e.print)},null)}function Dl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,1,"app-factures",[],null,null,null,ql,Y)),u["\u0275did"](1,245760,null,0,z,[M.a,k.a,L.a,A.a,U.a,$.a,D.a,w.f,J.j,K.b,q.c,T.j],null,null)],function(l,n){l(n,1,0)},null)}var Ml=u["\u0275ccf"]("app-factures",z,Dl,{},{},[]),Nl=e("iutN"),Vl=e("XePT"),kl=e("ES0t"),Ll=e("Xg1U"),Al=e("z5nN"),Ul=e("atuK"),Bl=u["\u0275crt"]({encapsulation:0,styles:[[""]],data:{}});function $l(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,1,"span",[],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["d\xe9sactiver"]))],null,null)}function jl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,1,"span",[],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["activer"]))],null,null)}function Hl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,1,"span",[],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["supprimer"]))],null,null)}function zl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,2,"button",[["class","btn btn-danger"],["type","button"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.confirm()&&u),u},null,null)),u["\u0275did"](1,737280,null,0,E.b,[u.ElementRef,[2,E.a]],{loading:[0,"loading"]},null),(l()(),u["\u0275ted"](-1,null,["Oui"]))],function(l,n){l(n,1,0,n.component.isLoading)},null)}function Jl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,1,"button",[["class","btn btn-success"],["type","button"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.confirm()&&u),u},null,null)),(l()(),u["\u0275ted"](-1,null,["Oui"]))],null,null)}function Kl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,19,"div",[["class","modal-body text-center"]],null,null,null,null,null)),(l()(),u["\u0275eld"](1,0,null,null,12,"p",[],null,null,null,null,null)),(l()(),u["\u0275ted"](-1,null,["Voulez-vous "])),(l()(),u["\u0275eld"](3,0,null,null,6,"strong",[],null,null,null,null,null)),(l()(),u["\u0275and"](16777216,null,null,1,null,$l)),u["\u0275did"](5,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,jl)),u["\u0275did"](7,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,Hl)),u["\u0275did"](9,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275ted"](-1,null,[" la facture "])),(l()(),u["\u0275eld"](11,0,null,null,1,"strong",[],null,null,null,null,null)),(l()(),u["\u0275ted"](12,null,["",""])),(l()(),u["\u0275ted"](-1,null,["?"])),(l()(),u["\u0275eld"](14,0,null,null,1,"button",[["class","btn btn-light"],["type","button"]],null,[[null,"click"]],function(l,n,e){var u=!0;return"click"===n&&(u=!1!==l.component.close()&&u),u},null,null)),(l()(),u["\u0275ted"](-1,null,["Non"])),(l()(),u["\u0275and"](16777216,null,null,1,null,zl)),u["\u0275did"](17,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null),(l()(),u["\u0275and"](16777216,null,null,1,null,Jl)),u["\u0275did"](19,16384,null,0,s.NgIf,[u.ViewContainerRef,u.TemplateRef],{ngIf:[0,"ngIf"]},null)],function(l,n){var e=n.component;l(n,5,0,"d"===e.type),l(n,7,0,"e"===e.type),l(n,9,0,"r"===e.type),l(n,17,0,"d"===e.type||"r"===e.type),l(n,19,0,"e"===e.type)},function(l,n){l(n,12,0,n.component.facture.numeroFacture)})}function Yl(l){return u["\u0275vid"](0,[(l()(),u["\u0275eld"](0,0,null,null,1,"app-modal-remove-facture",[],null,null,null,Kl,Bl)),u["\u0275did"](1,245760,null,0,H,[M.a,K.a,J.j],null,null)],function(l,n){l(n,1,0)},null)}var Zl=u["\u0275ccf"]("app-modal-remove-facture",H,Yl,{},{},[]),Gl=e("8e6m"),Ql=e("OZfm"),Wl=e("Da1D"),Xl=e("t/Na"),ln=e("BLsq"),nn=e("ZYCi"),en={title:"Finances"},un={title:"Factures"},tn=function(){return function(){}}(),on=e("SY1r"),an=e("yD1i"),rn=e("O43q");e.d(n,"FactureModuleNgFactory",function(){return sn});var sn=u["\u0275cmf"](o,[],function(l){return u["\u0275mod"]([u["\u0275mpd"](512,u.ComponentFactoryResolver,u["\u0275CodegenComponentFactoryResolver"],[[8,[i.a,Ml,Nl.a,Vl.a,kl.a,Ll.a,b.a,Al.a,Al.b,Ul.a,Ul.c,Ul.b,Zl]],[3,u.ComponentFactoryResolver],u.NgModuleRef]),u["\u0275mpd"](4608,s.NgLocalization,s.NgLocaleLocalization,[u.LOCALE_ID,[2,s["\u0275angular_packages_common_common_a"]]]),u["\u0275mpd"](4608,w.v,w.v,[]),u["\u0275mpd"](4608,w.f,w.f,[]),u["\u0275mpd"](4608,g.a,g.a,[]),u["\u0275mpd"](4608,Gl.a,Gl.a,[]),u["\u0275mpd"](4608,P.a,P.a,[u.RendererFactory2,u.PLATFORM_ID]),u["\u0275mpd"](4608,d.a,d.a,[u.ComponentFactoryResolver,u.NgZone,u.Injector,P.a,u.ApplicationRef]),u["\u0275mpd"](4608,c.f,c.f,[]),u["\u0275mpd"](4608,Ql.a,Ql.a,[]),u["\u0275mpd"](4608,Wl.a,Wl.a,[]),u["\u0275mpd"](4608,I.a,I.a,[]),u["\u0275mpd"](4608,y.b,y.b,[]),u["\u0275mpd"](4608,K.b,K.b,[u.RendererFactory2,d.a]),u["\u0275mpd"](4608,T.r,T.r,[]),u["\u0275mpd"](4608,T.t,T.t,[]),u["\u0275mpd"](4608,T.a,T.a,[]),u["\u0275mpd"](4608,T.h,T.h,[]),u["\u0275mpd"](4608,T.d,T.d,[]),u["\u0275mpd"](4608,T.j,T.j,[]),u["\u0275mpd"](4608,T.s,T.s,[T.t,T.j]),u["\u0275mpd"](4608,k.a,k.a,[Xl.c,ln.a,Xl.b]),u["\u0275mpd"](4608,M.a,M.a,[Xl.c,ln.a]),u["\u0275mpd"](4608,L.a,L.a,[Xl.c,ln.a]),u["\u0275mpd"](4608,A.a,A.a,[Xl.c,ln.a]),u["\u0275mpd"](4608,U.a,U.a,[Xl.c,ln.a]),u["\u0275mpd"](4608,$.a,$.a,[Xl.c,ln.a]),u["\u0275mpd"](1073742336,s.CommonModule,s.CommonModule,[]),u["\u0275mpd"](1073742336,nn.p,nn.p,[[2,nn.u],[2,nn.l]]),u["\u0275mpd"](1073742336,tn,tn,[]),u["\u0275mpd"](1073742336,w.u,w.u,[]),u["\u0275mpd"](1073742336,w.k,w.k,[]),u["\u0275mpd"](1073742336,w.s,w.s,[]),u["\u0275mpd"](1073742336,F.c,F.c,[]),u["\u0275mpd"](1073742336,on.a,on.a,[]),u["\u0275mpd"](1073742336,E.c,E.c,[]),u["\u0275mpd"](1073742336,c.e,c.e,[]),u["\u0275mpd"](1073742336,O.d,O.d,[]),u["\u0275mpd"](1073742336,J.i,J.i,[]),u["\u0275mpd"](1073742336,Gl.b,Gl.b,[]),u["\u0275mpd"](1073742336,an.a,an.a,[]),u["\u0275mpd"](1073742336,Ql.c,Ql.c,[]),u["\u0275mpd"](1073742336,Wl.b,Wl.b,[]),u["\u0275mpd"](1073742336,I.d,I.d,[]),u["\u0275mpd"](1073742336,y.c,y.c,[]),u["\u0275mpd"](1073742336,K.e,K.e,[]),u["\u0275mpd"](1073742336,T.g,T.g,[]),u["\u0275mpd"](1073742336,R.b,R.b,[]),u["\u0275mpd"](1073742336,rn.a,rn.a,[]),u["\u0275mpd"](1073742336,r.PdfJsViewerModule,r.PdfJsViewerModule,[]),u["\u0275mpd"](1073742336,q.b,q.b,[]),u["\u0275mpd"](1073742336,o,o,[]),u["\u0275mpd"](1024,nn.j,function(){return[[{path:"",component:z,data:en,children:[{path:"",data:un}]}]]},[]),u["\u0275mpd"](256,F.d,F.e,[]),u["\u0275mpd"](256,E.a,{style:"expand-left",spinnerSize:40,spinnerColor:"white",spinnerLines:12},[]),u["\u0275mpd"](256,c.a,{autoClose:!0,insideClick:!1},[]),u["\u0275mpd"](256,J.b,{default:J.a,config:{}},[])])})}}]);
|
/****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
//---------------------- Customer render cmd --------------------
cc.CustomRenderCmd = function (target, func) {
this._needDraw = true;
this._target = target;
this._callback = func;
this.rendering = function (ctx, scaleX, scaleY) {
if (!this._callback)
return;
this._callback.call(this._target, ctx, scaleX, scaleY);
}
};
cc.Node._dirtyFlags = {transformDirty: 1 << 0, visibleDirty: 1 << 1, colorDirty: 1 << 2, opacityDirty: 1 << 3, cacheDirty: 1 << 4,
orderDirty: 1 << 5, textDirty: 1 << 6, gradientDirty:1 << 7, all: (1 << 8) - 1};
//-------------------------Base -------------------------
cc.Node.RenderCmd = function(renderable){
this._dirtyFlag = 1; //need update the transform at first.
this._node = renderable;
this._needDraw = false;
this._anchorPointInPoints = new cc.Vec2(0,0);
this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
this._inverse = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
this._displayedOpacity = 255;
this._displayedColor = cc.color(255, 255, 255, 255);
this._cascadeColorEnabledDirty = false;
this._cascadeOpacityEnabledDirty = false;
this._curLevel = -1;
};
cc.Node.RenderCmd.prototype = {
constructor: cc.Node.RenderCmd,
getAnchorPointInPoints: function(){
return cc.p(this._anchorPointInPoints);
},
getDisplayedColor: function(){
var tmpColor = this._displayedColor;
return cc.color(tmpColor.r, tmpColor.g, tmpColor.b, tmpColor.a);
},
getDisplayedOpacity: function(){
return this._displayedOpacity;
},
setCascadeColorEnabledDirty: function(){
this._cascadeColorEnabledDirty = true;
this.setDirtyFlag(cc.Node._dirtyFlags.colorDirty);
},
setCascadeOpacityEnabledDirty:function(){
this._cascadeOpacityEnabledDirty = true;
this.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty);
},
getParentToNodeTransform: function(){
if(this._dirtyFlag & cc.Node._dirtyFlags.transformDirty)
this._inverse = cc.affineTransformInvert(this.getNodeToParentTransform());
return this._inverse;
},
detachFromParent: function(){},
_updateAnchorPointInPoint: function() {
var locAPP = this._anchorPointInPoints, locSize = this._node._contentSize, locAnchorPoint = this._node._anchorPoint;
locAPP.x = locSize.width * locAnchorPoint.x;
locAPP.y = locSize.height * locAnchorPoint.y;
this.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
},
setDirtyFlag: function(dirtyFlag){
if (this._dirtyFlag === 0 && dirtyFlag !== 0)
cc.renderer.pushDirtyNode(this);
this._dirtyFlag |= dirtyFlag;
},
getParentRenderCmd: function(){
if(this._node && this._node._parent && this._node._parent._renderCmd)
return this._node._parent._renderCmd;
return null;
},
_updateDisplayColor: function (parentColor) {
var node = this._node;
var locDispColor = this._displayedColor, locRealColor = node._realColor;
var i, len, selChildren, item;
if (this._cascadeColorEnabledDirty && !node._cascadeColorEnabled) {
locDispColor.r = locRealColor.r;
locDispColor.g = locRealColor.g;
locDispColor.b = locRealColor.b;
var whiteColor = new cc.Color(255, 255, 255, 255);
selChildren = node._children;
for (i = 0, len = selChildren.length; i < len; i++) {
item = selChildren[i];
if (item && item._renderCmd)
item._renderCmd._updateDisplayColor(whiteColor);
}
this._cascadeColorEnabledDirty = false;
} else {
if (parentColor === undefined) {
var locParent = node._parent;
if (locParent && locParent._cascadeColorEnabled)
parentColor = locParent.getDisplayedColor();
else
parentColor = cc.Color.WHITE;
}
locDispColor.r = 0 | (locRealColor.r * parentColor.r / 255.0);
locDispColor.g = 0 | (locRealColor.g * parentColor.g / 255.0);
locDispColor.b = 0 | (locRealColor.b * parentColor.b / 255.0);
if (node._cascadeColorEnabled) {
selChildren = node._children;
for (i = 0, len = selChildren.length; i < len; i++) {
item = selChildren[i];
if (item && item._renderCmd){
item._renderCmd._updateDisplayColor(locDispColor);
item._renderCmd._updateColor();
}
}
}
}
this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.colorDirty ^ this._dirtyFlag;
},
_updateDisplayOpacity: function (parentOpacity) {
var node = this._node;
var i, len, selChildren, item;
if (this._cascadeOpacityEnabledDirty && !node._cascadeOpacityEnabled) {
this._displayedOpacity = node._realOpacity;
selChildren = node._children;
for (i = 0, len = selChildren.length; i < len; i++) {
item = selChildren[i];
if (item && item._renderCmd)
item._renderCmd._updateDisplayOpacity(255);
}
this._cascadeOpacityEnabledDirty = false;
} else {
if (parentOpacity === undefined) {
var locParent = node._parent;
parentOpacity = 255;
if (locParent && locParent._cascadeOpacityEnabled)
parentOpacity = locParent.getDisplayedOpacity();
}
this._displayedOpacity = node._realOpacity * parentOpacity / 255.0;
if (node._cascadeOpacityEnabled) {
selChildren = node._children;
for (i = 0, len = selChildren.length; i < len; i++) {
item = selChildren[i];
if (item && item._renderCmd){
item._renderCmd._updateDisplayOpacity(this._displayedOpacity);
item._renderCmd._updateColor();
}
}
}
}
this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.opacityDirty ^ this._dirtyFlag;
},
_syncDisplayColor : function (parentColor) {
var node = this._node, locDispColor = this._displayedColor, locRealColor = node._realColor;
if (parentColor === undefined) {
var locParent = node._parent;
if (locParent && locParent._cascadeColorEnabled)
parentColor = locParent.getDisplayedColor();
else
parentColor = cc.Color.WHITE;
}
locDispColor.r = 0 | (locRealColor.r * parentColor.r / 255.0);
locDispColor.g = 0 | (locRealColor.g * parentColor.g / 255.0);
locDispColor.b = 0 | (locRealColor.b * parentColor.b / 255.0);
},
_syncDisplayOpacity : function (parentOpacity) {
var node = this._node;
if (parentOpacity === undefined) {
var locParent = node._parent;
parentOpacity = 255;
if (locParent && locParent._cascadeOpacityEnabled)
parentOpacity = locParent.getDisplayedOpacity();
}
this._displayedOpacity = node._realOpacity * parentOpacity / 255.0;
},
_updateColor: function(){},
updateStatus: function () {
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
var colorDirty = locFlag & flags.colorDirty,
opacityDirty = locFlag & flags.opacityDirty;
if(colorDirty)
this._updateDisplayColor();
if(opacityDirty)
this._updateDisplayOpacity();
if(colorDirty || opacityDirty)
this._updateColor();
if(locFlag & flags.transformDirty){
//update the transform
this.transform(this.getParentRenderCmd(), true);
this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.transformDirty ^ this._dirtyFlag;
}
},
getNodeToParentTransform: function () {
var node = this._node;
if (this._dirtyFlag & cc.Node._dirtyFlags.transformDirty) {
var t = this._transform;// quick reference
// base position
t.tx = node._position.x;
t.ty = node._position.y;
// rotation Cos and Sin
var a = 1, b = 0,
c = 0, d = 1;
if (node._rotationX) {
var rotationRadiansX = node._rotationX * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance
c = Math.sin(rotationRadiansX);
d = Math.cos(rotationRadiansX);
}
if (node._rotationY) {
var rotationRadiansY = node._rotationY * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance
a = Math.cos(rotationRadiansY);
b = -Math.sin(rotationRadiansY);
}
t.a = a;
t.b = b;
t.c = c;
t.d = d;
var lScaleX = node._scaleX, lScaleY = node._scaleY;
var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y;
// Firefox on Vista and XP crashes
// GPU thread in case of scale(0.0, 0.0)
var sx = (lScaleX < 0.000001 && lScaleX > -0.000001) ? 0.000001 : lScaleX,
sy = (lScaleY < 0.000001 && lScaleY > -0.000001) ? 0.000001 : lScaleY;
// scale
if (lScaleX !== 1 || lScaleY !== 1) {
a = t.a *= sx;
b = t.b *= sx;
c = t.c *= sy;
d = t.d *= sy;
}
// skew
if (node._skewX || node._skewY) {
// offset the anchorpoint
var skx = Math.tan(-node._skewX * Math.PI / 180);
var sky = Math.tan(-node._skewY * Math.PI / 180);
if (skx === Infinity)
skx = 99999999;
if (sky === Infinity)
sky = 99999999;
var xx = appY * skx;
var yy = appX * sky;
t.a = a - c * sky;
t.b = b - d * sky;
t.c = c - a * skx;
t.d = d - b * skx;
t.tx += a * xx + c * yy;
t.ty += b * xx + d * yy;
}
// adjust anchorPoint
t.tx -= a * appX + c * appY;
t.ty -= b * appX + d * appY;
// if ignore anchorPoint
if (node._ignoreAnchorPointForPosition) {
t.tx += appX;
t.ty += appY;
}
if (node._additionalTransformDirty)
this._transform = cc.affineTransformConcat(t, node._additionalTransform);
}
return this._transform;
},
_syncStatus: function (parentCmd) {
// In the visit logic does not restore the _dirtyFlag
// Because child elements need parent's _dirtyFlag to change himself
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
var parentNode = parentCmd ? parentCmd._node : null;
// There is a possibility:
// The parent element changed color, child element not change
// This will cause the parent element changed color
// But while the child element does not enter the circulation
// Here will be reset state in last
// In order the child elements get the parent state
if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty))
locFlag |= flags.colorDirty;
if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty))
locFlag |= flags.opacityDirty;
if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty))
locFlag |= flags.transformDirty;
var colorDirty = locFlag & flags.colorDirty,
opacityDirty = locFlag & flags.opacityDirty,
transformDirty = locFlag & flags.transformDirty;
this._dirtyFlag = locFlag;
if (colorDirty)
//update the color
this._syncDisplayColor();
if (opacityDirty)
//update the opacity
this._syncDisplayOpacity();
if(colorDirty)
this._updateColor();
if (transformDirty)
//update the transform
this.transform(parentCmd, true);
},
visitChildren: function(){
var node = this._node;
var i, children = node._children, child;
var len = children.length;
if (len > 0) {
node.sortAllChildren();
// draw children zOrder < 0
for (i = 0; i < len; i++) {
child = children[i];
if (child._localZOrder < 0)
child._renderCmd.visit(this);
else
break;
}
cc.renderer.pushRenderCommand(this);
for (; i < len; i++)
children[i]._renderCmd.visit(this);
} else {
cc.renderer.pushRenderCommand(this);
}
this._dirtyFlag = 0;
}
};
//-----------------------Canvas ---------------------------
(function() {
//The cc.Node's render command for Canvas
cc.Node.CanvasRenderCmd = function (renderable) {
cc.Node.RenderCmd.call(this, renderable);
this._cachedParent = null;
this._cacheDirty = false;
};
var proto = cc.Node.CanvasRenderCmd.prototype = Object.create(cc.Node.RenderCmd.prototype);
proto.constructor = cc.Node.CanvasRenderCmd;
proto.transform = function (parentCmd, recursive) {
// transform for canvas
var t = this.getNodeToParentTransform(),
worldT = this._worldTransform; //get the world transform
this._cacheDirty = true;
if (parentCmd) {
var pt = parentCmd._worldTransform;
// cc.AffineTransformConcat is incorrect at get world transform
worldT.a = t.a * pt.a + t.b * pt.c; //a
worldT.b = t.a * pt.b + t.b * pt.d; //b
worldT.c = t.c * pt.a + t.d * pt.c; //c
worldT.d = t.c * pt.b + t.d * pt.d; //d
worldT.tx = pt.a * t.tx + pt.c * t.ty + pt.tx;
worldT.ty = pt.d * t.ty + pt.ty + pt.b * t.tx;
} else {
worldT.a = t.a;
worldT.b = t.b;
worldT.c = t.c;
worldT.d = t.d;
worldT.tx = t.tx;
worldT.ty = t.ty;
}
if (recursive) {
var locChildren = this._node._children;
if (!locChildren || locChildren.length === 0)
return;
var i, len;
for (i = 0, len = locChildren.length; i < len; i++) {
locChildren[i]._renderCmd.transform(this, recursive);
}
}
};
proto.visit = function (parentCmd) {
var node = this._node;
// quick return if not visible
if (!node._visible)
return;
parentCmd = parentCmd || this.getParentRenderCmd();
if (parentCmd)
this._curLevel = parentCmd._curLevel + 1;
this._syncStatus(parentCmd);
this.visitChildren();
};
proto.setDirtyFlag = function (dirtyFlag, child) {
cc.Node.RenderCmd.prototype.setDirtyFlag.call(this, dirtyFlag, child);
this._setCacheDirty(child); //TODO it should remove from here.
if(this._cachedParent)
this._cachedParent.setDirtyFlag(dirtyFlag, true);
};
proto._setCacheDirty = function () {
if (this._cacheDirty === false) {
this._cacheDirty = true;
var cachedP = this._cachedParent;
cachedP && cachedP !== this && cachedP._setNodeDirtyForCache && cachedP._setNodeDirtyForCache();
}
};
proto._setCachedParent = function (cachedParent) {
if (this._cachedParent === cachedParent)
return;
this._cachedParent = cachedParent;
var children = this._node._children;
for (var i = 0, len = children.length; i < len; i++)
children[i]._renderCmd._setCachedParent(cachedParent);
};
proto.detachFromParent = function () {
this._cachedParent = null;
var selChildren = this._node._children, item;
for (var i = 0, len = selChildren.length; i < len; i++) {
item = selChildren[i];
if (item && item._renderCmd)
item._renderCmd.detachFromParent();
}
};
proto.setShaderProgram = function (shaderProgram) {
//do nothing.
};
proto.getShaderProgram = function () {
return null;
};
//util functions
cc.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc = function (blendFunc) {
if (!blendFunc)
return "source-over";
else {
if (( blendFunc.src === cc.SRC_ALPHA && blendFunc.dst === cc.ONE) || (blendFunc.src === cc.ONE && blendFunc.dst === cc.ONE))
return "lighter";
else if (blendFunc.src === cc.ZERO && blendFunc.dst === cc.SRC_ALPHA)
return "destination-in";
else if (blendFunc.src === cc.ZERO && blendFunc.dst === cc.ONE_MINUS_SRC_ALPHA)
return "destination-out";
else
return "source-over";
}
};
})();
|
import React, { Component, PropTypes } from 'react';
import styles from './Edit.css';
export default class Edit extends Component {
checkEnter = (e) => {
if (e.key === 'Enter') {
this.finishEdit(e);
}
}
finishEdit = (e) => {
const value = e.target.value;
if (this.props.onUpdate) {
this.props.onUpdate(value.trim());
}
}
renderDelete = () => {
return <button className={styles.delete} onClick={this.props.onDelete}>×</button>;
}
renderValue = () => {
const { value, onDelete, onValueClick } = this.props;
return (
<div>
<span className={styles.value} onClick={onValueClick}>{value}</span>
{onDelete ? this.renderDelete() : null}
</div>
);
}
renderEdit = () => {
return (
<input
type="text"
autoFocus
defaultValue={this.props.value}
onBlur={this.finishEdit}
onKeyPress={this.checkEnter}
/>
);
}
render() {
return (
<div className={styles.NoteEdit}>
{this.props.editing ? this.renderEdit() : this.renderValue()}
</div>
);
}
}
Edit.propTypes = {
className: PropTypes.string,
value: PropTypes.string,
onUpdate: PropTypes.func,
onValueClick: PropTypes.func,
onDelete: PropTypes.func,
editing: PropTypes.bool,
};
// <div className={this.props.className}>
|
export default () => ({
textField: {
},
});
|
import kol.Error as Error
from GenericRequest import GenericRequest
from kol.manager import PatternManager
import hashlib
class LoginRequest(GenericRequest):
"""
A request to login to The Kingdom of Loathing. This class will look for various login
errors. If any occur, than an appropriate exception is raised.
"""
def __init__(self, session, loginChallenge):
super(LoginRequest, self).__init__(session)
self.url = session.serverURL + "login.php"
self.requestData['loggingin'] = 'Yup.'
self.requestData['loginname'] = session.userName
self.requestData['secure'] = '1'
hashKey = self.session.userPasswordHash + ":" + loginChallenge
self.requestData['response'] = hashlib.md5(hashKey).hexdigest()
self.requestData['challenge'] = loginChallenge
def parseResponse(self):
mainFramesetPattern = PatternManager.getOrCompilePattern('mainFrameset')
if mainFramesetPattern.search(self.responseText):
self.session.isConnected = True
return
waitFifteenMinutesPattern = PatternManager.getOrCompilePattern('waitFifteenMinutesLoginError')
if waitFifteenMinutesPattern.search(self.responseText):
e = Error.Error("Too many login attempts in too short a span of time. Please wait fifteen minutes and try again.", Error.LOGIN_FAILED_GENERIC)
e.timeToWait = 900
raise e
waitFiveMinutesPattern = PatternManager.getOrCompilePattern('waitFiveMinutesLoginError')
if waitFiveMinutesPattern.search(self.responseText):
e = Error.Error("Too many login attempts in too short a span of time. Please wait five minutes and try again.", Error.LOGIN_FAILED_GENERIC)
e.timeToWait = 300
raise e
waitOneMinutePattern = PatternManager.getOrCompilePattern('waitOneMinuteLoginError')
if waitOneMinutePattern.search(self.responseText):
e = Error.Error("Too many login attempts in too short a span of time. Please wait a minute and try again.", Error.LOGIN_FAILED_GENERIC)
e.timeToWait = 60
raise e
waitTwoMinutesPattern = PatternManager.getOrCompilePattern('waitTwoMinutesLoginError')
if waitTwoMinutesPattern.search(self.responseText):
e = Error.Error("Your previous session did not close correctly. Please wait a couple of minutes and try again.", Error.LOGIN_FAILED_GENERIC)
e.timeToWait = 120
raise e
badPasswordPattern = PatternManager.getOrCompilePattern('badPassword')
if badPasswordPattern.search(self.responseText):
raise Error.Error("Login failed. Bad password.", Error.LOGIN_FAILED_BAD_PASSWORD)
tooManyFailuresFromIPPattern = PatternManager.getOrCompilePattern('tooManyLoginsFailuresFromThisIP')
if tooManyFailuresFromIPPattern.search(self.responseText):
e = Error.Error("Too many login failures from this IP. Please wait 15 minutes and try again.", Error.LOGIN_FAILED_GENERIC)
e.timeToWait = 900
raise e
e = Error.Error("Unknown login error.", Error.LOGIN_FAILED_GENERIC)
e.timeToWait = 900
raise e
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/React.createElement("path", {
d: "M11 15h2v2h-2v-2zm0-8h2v6h-2V7zm.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"
}), 'ErrorOutlineSharp');
exports.default = _default;
|
/* Copyright 2017 Infor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import declare from 'dojo/_base/declare';
import lang from 'dojo/_base/lang';
import string from 'dojo/string';
import utility from 'argos/Utility';
import Edit from 'argos/Edit';
import Adapter from 'argos/Models/Adapter';
import validator from 'crm/Validator';
import MODEL_NAMES from '../../Models/Names';
import CRM_MODEL_NAMES from 'crm/Models/Names';
import BusyIndicator from 'argos/Dialogs/BusyIndicator';
import getResource from 'argos/I18n';
import Utility from '../../Utility';
const resource = getResource('salesOrderEdit');
const contactResource = getResource('contactModel');
const dtFormatResource = getResource('salesOrderEditDateTimeFormat');
const __class = declare('crm.Integrations.BOE.Views.SalesOrders.Edit', [Edit], {
// View Properties
id: 'salesorder_edit',
detailView: 'salesorder_detail',
insertSecurity: 'Entities/SalesOrder/Add',
updateSecurity: 'Entities/SalesOrder/Edit',
resourceKind: 'salesOrders',
opportunityOpenCode: 'Open',
warehouseCode: 'Warehouse',
officeCode: 'Office',
siteCode: 'Site',
modelName: MODEL_NAMES.SALESORDER,
_busyIndicator: null,
locationType: '',
// Localization
titleText: resource.titleText,
orderNumberText: resource.orderNumberText,
orderIdText: resource.orderIdText,
accountText: resource.accountText,
opportunityText: resource.opportunityText,
dateCreatedText: resource.dateCreatedText,
erpStatusText: resource.erpStatusText,
subTotalText: resource.subTotalText,
grandTotalText: resource.grandTotalText,
billToText: resource.billToText,
shipToText: resource.shipToText,
payFromText: resource.payFromText,
dueDateText: resource.dueDateText,
dateFormat: dtFormatResource.dateFormat,
commentsText: resource.commentsText,
productsText: resource.productsText,
accountProducts: resource.accountProducts,
requestedByText: resource.requestedByText,
backOrderedText: resource.backOrderedText,
taxExemptText: resource.taxExemptText,
invoiceImmediatelyText: resource.invoiceImmediatelyText,
dropShipmentText: resource.dropShipmentText,
earlyShipmentText: resource.earlyShipmentText,
partialShipText: resource.partialShipText,
statusText: resource.statusText,
statusTitle: resource.statusTitle,
typeText: resource.typeText,
typeTitle: resource.typeTitle,
customerPOText: resource.customerPOText,
currencyText: resource.currencyText,
backOfficeText: resource.backOfficeText,
accountingEntityText: resource.accountingEntityText,
warehouseText: resource.warehouseText,
warehouseLocationText: resource.warehouseLocationText,
locationText: resource.locationText,
locationsTitleText: resource.locationsTitleText,
carrierText: resource.carrierText,
init: function init() {
this.inherited(init, arguments);
this.connect(this.fields.Account, 'onChange', this.onAccountChange);
this.connect(this.fields.RequestedBy, 'onChange', this.onContactChange);
this.connect(this.fields.Opportunity, 'onChange', this.onOpportunityChange);
this.connect(this.fields.BillTo, 'onChange', this.onBillToChange);
this.connect(this.fields.ShipTo, 'onChange', this.onShipToChange);
this.connect(this.fields.BackOffice, 'onChange', this.onBackOfficeChange);
this.connect(this.fields.BackOfficeAccountingEntity, 'onChange', this.onBackOfficeAccountingEntityChange);
this.connect(this.fields.Location, 'onChange', this.onLocationChange);
this.connect(this.fields.Warehouse, 'onChange', this.onWarehouseChange);
if (!this.locationType) {
this.locationType = App.context.integrationSettings && App.context.integrationSettings['Back Office Extension'] &&
App.context.integrationSettings['Back Office Extension']['Type of Order Location'] || '';
}
if (this.locationType === 'Warehouse') {
this.fields.Location.hide();
this.fields.Warehouse.show();
} else if (this.locationType !== 'Warehouse') {
this.fields.Location.show();
this.fields.Warehouse.hide();
this.fields.Warehouse.required = false;
this.fields.Warehouse.validator = undefined;
}
},
insert: function insert() {
this.fields.Location.show();
this.fields.Warehouse.show();
this.inherited(insert, arguments);
},
processData: function processData() {
this.showBusy();
this.inherited(processData, arguments);
this.getEntriesFromIds();
},
beforeTransitionTo: function beforeTransitionTo() {
this.inherited(beforeTransitionTo, arguments);
if (!this.fields.AccountManager.isDisabled) {
this.fields.AccountManager.disable();
}
if (this.fields.BillTo.isDisabled && this.fields.ShipTo.isDisabled) {
this.fields.BillTo.enable();
this.fields.ShipTo.enable();
}
},
disableBackOfficeData: function disableBackOfficeData() {
this.fields.BackOffice.disable();
this.fields.BackOfficeAccountingEntity.disable();
},
enableBackOfficeData: function enableBackOfficeData() {
this.fields.BackOffice.enable();
this.fields.BackOfficeAccountingEntity.enable();
},
convertValues: function convertValues(values) {
if (values.ErpBillTo) {
values.ErpBillTo = {
$key: values.ErpBillTo.$key,
};
}
if (values.ErpShipTo) {
values.ErpShipTo = {
$key: values.ErpShipTo.$key,
};
}
return values;
},
processEntry: function processEntry(entry) {
if (entry && entry.Account) {
['RequestedBy', 'Opportunity'].forEach((f) => {
this.fields[f].dependsOn = 'Account';
this.fields[f].where = `Account.Id eq "${entry.Account.AccountId || entry.Account.$key || entry.Account.key}"`;
if (f === 'Opportunity') {
this.fields[f].where = `${this.fields[f].where} and Status eq "${this.opportunityOpenCode}"`;
}
});
}
const warehouseField = this.fields.Warehouse;
const locationField = this.fields.Location;
if (entry && entry.ErpLogicalId) {
warehouseField.enable();
warehouseField.dependsOn = 'ErpLogicalId';
warehouseField.where = (logicalId) => {
return `ErpLogicalId eq "${logicalId}" and LocationType eq "${this.warehouseCode}"`;
};
locationField.enable();
locationField.dependsOn = 'ErpLogicalId';
locationField.where = (logicalId) => {
return `ErpLogicalId eq "${logicalId}" and (LocationType eq "${this.officeCode}" or LocationType eq "${this.siteCode}")`;
};
} else {
warehouseField.disable();
warehouseField.validator = undefined;
warehouseField.required = false;
locationField.disable();
}
if (entry.WarehouseLocation) {
warehouseField.setValue(entry.WarehouseLocation);
}
if (entry.Location) {
locationField.setValue(entry.Location);
}
if (entry && entry.ErpExtId) {
this.disableBackOfficeData();
} else {
this.enableBackOfficeData();
}
return entry;
},
setValues: function setValues() {
this.inherited(setValues, arguments);
if (!this.fields.CurrencyCode.getValue()) {
const account = this.fields.Account.currentSelection;
if (account && account.CurrencyCode) {
this.fields.CurrencyCode.setValue(account.CurrencyCode);
} else {
this.fields.CurrencyCode.setValue(App.getBaseExchangeRate().code);
}
}
},
onRefresh: function onRefresh() {
this.inherited(onRefresh, arguments);
['RequestedBy', 'Opportunity', 'Warehouse', 'Location'].forEach((f) => {
this.fields[f].dependsOn = null;
this.fields[f].where = null;
});
},
onRefreshInsert: function onRefreshInsert() {
this.inherited(onRefreshInsert, arguments);
this.enableBackOfficeData();
},
getEntriesFromIds: function getEntriesFromIds() {
const mappedLookups = [
'BackOffice',
'BackOfficeAccountingEntity',
];
const mappedProperties = [
'LogicalId',
'AcctEntityExtId',
];
const fields = ['ErpLogicalId', 'ErpAccountingEntityId'];
Utility.setFieldsFromIds(mappedLookups, mappedProperties, fields, this).then(() => {
this.hideBusy();
});
},
getPrimaryContact: function getPrimaryContact(entry) {
const accountModel = Adapter.getModel(CRM_MODEL_NAMES.ACCOUNT);
const relationship = {
name: 'Contacts',
displayName: contactResource.entityDisplayNamePlural,
type: 'OneToMany',
relatedEntity: 'Contact',
relatedProperty: 'Account',
relatedPropertyType: 'object',
where: 'IsPrimary eq true',
};
accountModel.getRelatedRequest(entry, relationship).then((result) => {
if (result && result.entities && result.entities.length) {
const contactField = this.fields.RequestedBy;
if (!contactField.currentSelection || contactField.currentSelection.Account && contactField.currentSelection.Account.$key !== entry.$key) {
contactField.setSelection(result.entities[0]);
}
}
});
},
onAccountChange: function onAccountChange(value, field) {
const entry = field.currentSelection;
['RequestedBy', 'Opportunity'].forEach((f) => {
if (value) {
this.fields[f].dependsOn = 'Account';
this.fields[f].where = `Account.Id eq "${value.AccountId || value.$key || value.key}"`;
}
});
if (entry) {
this.fields.CurrencyCode.setValue((entry.CurrencyCode) ? entry.CurrencyCode : App.getBaseExchangeRate().code);
if (this.fields.BillTo.isDisabled && this.fields.ShipTo.isDisabled) {
this.fields.BillTo.enable();
this.fields.ShipTo.enable();
}
if (entry.AccountManager) {
const accountManagerField = this.fields.AccountManager;
accountManagerField.setSelection({
$key: entry.AccountManager.$key,
});
}
field.setValue(field.currentSelection);
this.showBusy();
this.getPrimaryContact(entry);
Utility.setFieldsFromIds(
['BackOffice', 'BackOfficeAccountingEntity'],
['LogicalId', 'AcctEntityExtId'],
['ErpLogicalId', 'ErpAccountingEntityId'],
this,
entry
).then(() => {
this.hideBusy();
});
}
},
onAccountDependentChange: function onAccountDependentChange(value, field) {
if (value && !field.dependsOn && field.currentSelection && field.currentSelection.Account) {
const accountField = this.fields.Account;
accountField.setSelection(field.currentSelection.Account);
this.onAccountChange(accountField.getValue(), accountField);
}
},
onBackOfficeChange: function onBackOfficeChange(value, field) {
this.fields.BackOffice.setValue(field.currentSelection);
this.fields.ErpLogicalId.setValue(field.currentSelection.LogicalId);
const accountingField = this.fields.BackOfficeAccountingEntity;
accountingField.where = `BackOffice.Id eq "${field.currentSelection.$key}"`;
const accountingIsToBackOffice = accountingField.currentSelection && accountingField.currentSelection.BackOffice && accountingField.currentSelection.BackOffice.$key === field.currentSelection.$key;
if (field.currentSelection.BackOfficeAccountingEntities.$resources && !accountingIsToBackOffice) {
const entry = field.currentSelection.BackOfficeAccountingEntities.$resources[0];
if (entry) {
accountingField.setSelection(entry);
this.onBackOfficeAccountingEntityChange(accountingField.getValue(), accountingField);
}
}
const warehouseField = this.fields.Warehouse;
if (warehouseField.isDisabled) {
warehouseField.enable();
warehouseField.dependsOn = 'ErpLogicalId';
warehouseField.where = (logicalId) => {
return `ErpLogicalId eq "${logicalId}" and LocationType eq "${this.warehouseCode}"`;
};
}
const locationField = this.fields.Location;
if (locationField.isDisabled) {
locationField.enable();
locationField.dependsOn = 'ErpLogicalId';
locationField.where = (logicalId) => {
return `ErpLogicalId eq "${logicalId}" and (LocationType eq "${this.officeCode}" or LocationType eq "${this.siteCode}")`;
};
}
},
onBackOfficeAccountingEntityChange: function onBackOfficeAccountingEntityChange(value, field) {
this.fields.BackOfficeAccountingEntity.setValue(field.currentSelection);
this.fields.ErpAccountingEntityId.setValue(field.currentSelection.AcctEntityExtId);
},
onBillToChange: function onBillToChange(value, field) {
this.fields.BillTo.setValue(field.currentSelection);
},
onContactChange: function onContactChange(value, field) {
this.onAccountDependentChange(value, field);
},
onLocationChange: function onLocationChance(value, field) {
if (field.currentSelection.ErpExtId) {
this.fields.ErpLocation.setValue(field.currentSelection.ErpExtId);
}
this.fields.Location.setValue(field.currentSelection);
},
onOpportunityChange: function onOpportunityChange(value, field) {
this.onAccountDependentChange(value, field);
},
onShipToChange: function onShipToChange(value, field) {
this.fields.ShipTo.setValue(field.currentSelection);
},
onWarehouseChange: function onWarehouseChange(value, field) {
this.fields.Warehouse.setValue(field.currentSelection);
this.fields.Location.setValue(field.currentSelection);
},
applyContext: function applyContext() {
this.inherited(applyContext, arguments);
const found = this._getNavContext();
const accountField = this.fields.Account;
this.onAccountChange(accountField.getValue(), accountField);
const context = (found && found.options && found.options.source) || found;
const lookup = {
accounts: this.applyAccountContext,
contacts: this.applyContactContext,
opportunities: this.applyOpportunityContext,
};
if (context && lookup[context.resourceKind]) {
lookup[context.resourceKind].call(this, context);
}
if (!this.fields.Account.currentSelection && !this.fields.Account.currentValue) {
this.fields.BillTo.disable();
this.fields.ShipTo.disable();
}
if (!this.fields.BackOffice.currentSelection) {
this.fields.Location.disable();
this.fields.Warehouse.disable();
}
},
_getNavContext: function _getNavContext() {
const navContext = App.queryNavigationContext((o) => {
const context = (o.options && o.options.source) || o;
if (/^(accounts|contacts|opportunities)$/.test(context.resourceKind) && context.key) {
return true;
}
return false;
});
return navContext;
},
applyAccountContext: function applyAccountContext(context) {
const view = App.getView(context.id);
const entry = context.entry || (view && view.entry) || context;
if (!entry || !entry.$key) {
return;
}
const accountField = this.fields.Account;
accountField.setSelection(entry);
this.onAccountChange(accountField.getValue(), accountField);
},
applyContactContext: function applyContactContext(context) {
const view = App.getView(context.id);
const entry = context.entry || (view && view.entry) || context;
if (!entry || !entry.$key) {
return;
}
const contactField = this.fields.RequestedBy;
contactField.setSelection(entry);
this.onAccountDependentChange(contactField.getValue(), contactField);
},
applyOpportunityContext: function applyOpportunityContext(context) {
const view = App.getView(context.id);
const entry = context.entry || (view && view.entry) || context;
if (!entry || !entry.$key) {
return;
}
const opportunityField = this.fields.Opportunity;
opportunityField.setSelection(entry);
this.onAccountDependentChange(opportunityField.getValue(), opportunityField);
},
hideBusy: function hideBusy() {
if (this._busyIndicator) {
this._busyIndicator.complete();
App.modal.disableClose = false;
App.modal.hide();
}
},
showBusy: function showBusy() {
if (!this._busyIndicator || this._busyIndicator._destroyed) {
this._busyIndicator = new BusyIndicator({ id: `${this.id}-busyIndicator` });
}
this._busyIndicator.start();
App.modal.disableClose = true;
App.modal.showToolbar = false;
App.modal.add(this._busyIndicator);
},
formatDependentQuery: function formatDependentQuery(dependentValue, theFormat, property) {
return string.substitute(theFormat, [utility.getValue(dependentValue, property || '$key')]);
},
createLayout: function createLayout() {
return this.layout || (this.layout = [{
title: this.detailsText,
name: 'DetailsSection',
children: [{
label: this.accountText,
name: 'Account',
property: 'Account',
type: 'lookup',
emptyText: '',
valueTextProperty: 'AccountName',
view: 'account_related',
autoFocus: true,
required: true,
validator: validator.exists,
}, {
label: this.opportunityText,
name: 'Opportunity',
property: 'Opportunity',
type: 'lookup',
emptyText: '',
valueTextProperty: 'Description',
view: 'opportunity_related',
}, {
label: this.backOfficeText,
name: 'BackOffice',
type: 'lookup',
emptyText: '',
valueTextProperty: 'BackOfficeName',
view: 'salesorder_backoffice_related',
where: 'IsActive eq true',
include: false,
}, {
name: 'ErpLogicalId',
property: 'ErpLogicalId',
type: 'hidden',
emptyText: '',
}, {
label: this.accountingEntityText,
name: 'BackOfficeAccountingEntity',
type: 'lookup',
emptyText: '',
valueTextProperty: 'Name',
view: 'salesorder_backofficeaccountingentity_related',
include: false,
}, {
name: 'ErpAccountingEntityId',
property: 'ErpAccountingEntityId',
type: 'hidden',
emptyText: '',
}, {
label: this.currencyText,
name: 'CurrencyCode',
property: 'CurrencyCode',
type: 'picklist',
picklist: 'Currency Codes',
singleSelect: true,
textProperty: 'code',
keyProperty: 'code',
required: true,
requireSelection: true,
validator: validator.picklistExists,
}, {
label: this.dueDateText,
name: 'DueDate',
property: 'DueDate',
type: 'date',
timeless: false,
showTimePicker: true,
showRelativeDateTime: false,
dateFormatText: this.dateFormat,
minValue: (new Date(1900, 0, 1)),
validator: [
validator.isDateInRange,
],
}, {
label: this.customerPOText,
name: 'CustomerPONumber',
property: 'CustomerPurchaseOrderNumber',
type: 'text',
}, {
label: this.commentsText, // TODO: Make on save, append 'Created by <user> on <datetime>' to comment
noteProperty: false,
name: 'Comments',
property: 'Comments',
title: this.commentsText,
type: 'note',
view: 'text_edit',
}, {
label: this.locationText,
name: 'Location',
property: 'Location',
type: 'lookup',
emptyText: '',
valueTextProperty: 'Description',
view: 'order_location_list',
title: this.locationsTitleText,
}, {
name: 'ErpLocation',
property: 'ErpLocation',
type: 'hidden',
emptyText: '',
}, {
label: this.warehouseText,
name: 'Warehouse',
property: 'WarehouseLocation',
type: 'lookup',
emptyText: '',
valueTextProperty: 'Description',
view: 'order_warehouse_list',
title: this.warehouseLocationText,
required: true,
validator: validator.exists,
}, {
label: this.requestedByText,
name: 'RequestedBy',
property: 'RequestedBy',
type: 'lookup',
emptyText: '',
valueTextProperty: 'NameLF',
view: 'contact_related',
}, {
label: this.statusText,
name: 'Sales Order Status',
property: 'Status',
type: 'picklist',
picklist: 'ErpSalesOrderStatus',
singleSelect: true,
titleText: this.statusTitle,
}, {
dependsOn: 'Account',
label: this.billToText,
name: 'BillTo',
property: 'ErpBillTo',
type: 'lookup',
emptyText: '',
valueTextProperty: 'Address.FullAddress',
view: 'salesorder_billTo_related',
where: this.formatDependentQuery.bindDelegate(
this, 'ErpBillToAccounts.Account.Id eq "${0}"'
),
}, {
dependsOn: 'Account',
label: this.shipToText,
name: 'ShipTo',
property: 'ErpShipTo',
type: 'lookup',
emptyText: '',
valueTextProperty: 'Address.FullAddress',
view: 'salesorder_shipTo_related',
where: this.formatDependentQuery.bindDelegate(
this, 'ErpShipToAccounts.Account.Id eq "${0}"'
),
}, {
dependsOn: 'ErpLogicalId',
label: this.carrierText,
name: 'Carrier',
property: 'Carrier',
type: 'lookup',
emptyText: '',
valueTextProperty: 'CarrierName',
view: 'salesorder_carriers',
where: (value) => {
return `ErpLogicalId eq "${value}"`;
},
}, {
label: this.backOrderedText,
name: 'BackOrdered',
property: 'ErpBackOrdered',
include: true,
type: 'boolean',
onText: this.yesText,
offText: this.noText,
}, {
label: this.dropShipmentText,
name: 'DropShipment',
property: 'ErpDropShip',
include: true,
type: 'boolean',
onText: this.yesText,
offText: this.noText,
}, {
label: this.earlyShipmentText,
name: 'EarlyShipment',
property: 'ErpShipEarly',
include: true,
type: 'boolean',
onText: this.yesText,
offText: this.noText,
}, {
label: this.invoiceImmediatelyText,
name: 'InvoiceImmediately',
property: 'ErpInvoiceImmediately',
include: true,
type: 'boolean',
onText: this.yesText,
offText: this.noText,
}, {
label: this.partialShipText,
name: 'PartialShipment',
property: 'ErpPartialShipAllowed',
include: true,
type: 'boolean',
onText: this.yesText,
offText: this.noText,
}, {
label: this.taxExemptText,
name: 'TaxExempt',
property: 'ErpTaxExempt',
include: true,
type: 'boolean',
onText: this.yesText,
offText: this.noText,
}, {
label: this.accountManagerText,
name: 'AccountManager',
property: 'AccountManager',
include: true,
type: 'lookup',
emptyText: '',
valueTextProperty: 'Name',
},
] },
]);
},
});
lang.setObject('icboe.Views.SalesOrders.Edit', __class);
export default __class;
|
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib import admin
import sys
# Create your models here.
class UserData(models.Model):
# 유저 아이디 (카톡아이디).
UserID = models.CharField(max_length=40, blank = True, null = True)
# 인증 토큰.
Auth = models.CharField(max_length=40, blank = True, null = True)
# 최초 플레이 시간.
FirstPlayTime = models.DateTimeField(blank = True, null = True)
# 마지막 플레이 시간.
LastPlayTime = models.DateTimeField(blank = True, null = True)
# OS타입 (ios, android).
OSType = models.CharField(max_length = 10, blank = True, null = True)
# 국가코드.
ContryCode = models.CharField(max_length=10, blank = True, null = True)
#임시 필드...
UserName = models.CharField(max_length = 40, blank = True, null = True)
PictureURL = models.CharField(max_length = 200, blank = True, null = True)
def __str__(self):
return "%d-%s" % (self.id, self.UserName)
# 친구데이터.
class FriendData(models.Model):
#유저SN.
UserSN = models.IntegerField()
FriendSN = models.IntegerField()
def __str__(self):
return "%d-%d" % (self.UserSN, self.FriendSN)
admin.site.register(UserData)
admin.site.register(FriendData)
|
#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
# mysql_python_read.py
#
# Jul/25/2014
#
# ----------------------------------------------------------------
import sys
import json
import mysql.connector
#
sys.path.append ("/var/www/data_base/common/python_common")
from sql_manipulate import sql_to_dict_proc
# ----------------------------------------------------------------
#
conn = mysql.connector.connect (host="host_mysql", \
user="scott", passwd="tiger", \
db="city")
#
cursor = conn.cursor ()
#
dict_aa = sql_to_dict_proc (cursor)
#
conn.close ()
#
str_aa = json.dumps (dict_aa)
#
print ("Content-type: text/json\n\n")
print (str_aa)
#
# ----------------------------------------------------------------
|
"use strict";
Object.defineProperty(exports, '__esModule', {value: true});
exports.textBase = MathJax._.input.tex.textmacros.TextMacrosConfiguration.textBase;
exports.TextMacrosConfiguration = MathJax._.input.tex.textmacros.TextMacrosConfiguration.TextMacrosConfiguration;
|
const { GuildMember, MessageEmbed,Client} = require("discord.js");
const qDb = require("quick.db");
const cezaDb = new qDb.table("aCezalar");
const cezaNoDb = new qDb.table("aVeri");
const kDb = new qDb.table("aKullanici");
const moment = require('moment');
const acar = client.veri;
const ms = require('ms');
module.exports = {
Isim: "uyar",
Komut: ["uyarı","uyar"],
Kullanim: "uyarı @acar/ID <uyarı açıklaması>",
Aciklama: "Belirlenen üyeye uyarı belirleyerek ceza işlemi yapar.",
Kategori: "Yetkili",
TekSunucu: true,
/**
* @param {Client} client
*/
onLoad: function (client) {
},
/**
* @param {Client} client
* @param {Message} message
* @param {Array<String>} args
* @param {Guild} guild
*/
onRequest: async function (client, message, args, guild) {
let embed = new MessageEmbed().setColor('0x2f3136').setAuthor(acar.Tag + " " + acar.sunucuIsmi, message.guild.iconURL({dynamic: true, size: 2048}))
let cezano = cezaNoDb.get(`cezano.${client.sistem.a_SunucuID}`) + 1;
if(!acar.Roller.warnHammer) return message.channel.send("Sistemsel hata: Rol bulunamadı veya rol bilgileri girilemedi.").then(x => x.delete({timeout: 5000}));
if(!acar.Roller.warnHammer.some(rol => message.member.roles.cache.has(rol)) && !message.member.hasPermission('ADMINISTRATOR')) return message.channel.send(`Hata: Bu komutunu kullanabilmek için herhangi bir yetkiye sahip değilsin.`).then(x => x.delete({timeout: 5000}));
let uye = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
let reason = args.splice(1).join(" ");
if(!uye || !reason) return message.channel.send(`Hata: Lütfen bir üye etiketleyin veya Id girin! __Örn:__ \`${client.sistem.a_Prefix}uyarı @Antiperes/ID <sebep>\``).then(x => x.delete({timeout: 5000}));
if (message.member.roles.highest.position <= uye.roles.highest.position) return message.channel.send(`Hata: Belirttiğin kişi senden üstün veya onunla aynı yetkidesin!`).then(x => x.delete({timeout: 5000}));
let ceza = {
No: cezano,
Cezalanan: uye.id,
Yetkili: message.author.id,
Tip: "WARN",
Tur: "Uyarılma",
BitisZaman: "Uyarılma",
Sebep: reason,
Zaman: Date.now()
};
kDb.add(`k.${message.author.id}.uyari`, 1);
kDb.push(`k.${uye.id}.sicil`, ceza);
kDb.set(`ceza.${cezano}`, ceza);
cezaNoDb.add(`cezano.${client.sistem.a_SunucuID}`, 1)
message.channel.send(`${uye} (\`${uye.id}\`) üyesi, ${message.author} (\`${message.author.id}\`) tarafından **${reason}** nedeniyle uyarıldı. (Ceza Numarası: #${cezano})`).catch();
message.react("✅")
if(acar.Kanallar.uyarıLogKanali && client.channels.cache.has(acar.Kanallar.uyarıLogKanali)) client.channels.cache.get(acar.Kanallar.uyarıLogKanali).send(embed.setDescription(`$${uye} (\`${uye.id}\`) üyesi, ${message.author} (\`${message.author.id}\`) tarafından **${reason}** nedeniyle uyarıldı.`).setFooter(client.altbaslik + ` • Ceza Numarası: #${cezano}`)).catch();
}
};
|
import React, { useCallback, useState, useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { useLocation, Link as RouteLink } from "react-router-dom";
import tw, { styled } from "twin.macro";
import MoonLoader from "react-spinners/MoonLoader";
import Switch from "react-switch";
import useSWR from "swr";
import {
camelizeJson,
toastErrors,
updateInNewArray,
isSysLink,
} from "../helper";
import { loadSelected, receiveChats } from "../slices/chats";
const NavItemLink = styled(RouteLink)`
${tw`py-3 px-6 no-underline text-black tracking-wider`}
${tw`hover:bg-blue-100 hover:text-blue-500`}
${tw`border-0 border-l-2 border-r-2 border-solid border-transparent`}
${({ selected = false }) => selected && tw`text-blue-500 border-current`}
${({ ending = ending }) => ending && tw`rounded-b`}
border-right-color: transparent;
`;
const NavItem = ({
title: title,
href: href,
selected: selected,
ending: ending,
}) => {
return (
<NavItemLink to={href} selected={selected} ending={ending}>
<span tw="xl:text-lg">{title}</span>
</NavItemLink>
);
};
function isSelect(page, path) {
const re = new RegExp(`^/admin/chats/-\\d+/${page}`);
return re.test(path);
}
const Loading = () => {
return (
<div tw="flex justify-center my-6">
<MoonLoader size={25} color="#47A8D8" />
</div>
);
};
const MenuBox = ({
visibility = true,
isLoaded = true,
title,
miniTitle,
children,
}) => {
if (!visibility) return null;
return (
<div tw="flex flex-col bg-gray-100 rounded-lg mx-4 my-2 shadow">
<div tw="p-3 border border-solid border-0 border-b border-gray-200">
<span tw="hidden lg:inline text-xl text-black">{title}</span>
<span tw="lg:hidden block text-center text-xl text-black">
{miniTitle}
</span>
</div>
{isLoaded ? <>{children}</> : <Loading />}
</div>
);
};
const arrowDownIcon = (
<svg
xmlns="http://www.w3.org/2000/svg"
tw="h-3"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M14.707 12.293a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 111.414-1.414L9 14.586V3a1 1 0 012 0v11.586l2.293-2.293a1 1 0 011.414 0z"
clipRule="evenodd"
/>
</svg>
);
const arrowUpIcon = (
<svg
xmlns="http://www.w3.org/2000/svg"
tw="h-3"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M5.293 7.707a1 1 0 010-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 01-1.414 1.414L11 5.414V17a1 1 0 11-2 0V5.414L6.707 7.707a1 1 0 01-1.414 0z"
clipRule="evenodd"
/>
</svg>
);
const passedCount = (dayStatistic) => {
if (dayStatistic.passedStatistic == null) return 0;
return dayStatistic.passedStatistic.verificationsCount;
};
const notPassedCount = (dayStatistic) => {
let timeoutCount = 0;
let wrongedCount = 0;
if (dayStatistic.timeoutStatistic != null) {
timeoutCount = dayStatistic.timeoutStatistic.verificationsCount;
}
if (dayStatistic.wrongedStatistic != null) {
wrongedCount = dayStatistic.wrongedStatistic.verificationsCount;
}
return timeoutCount + wrongedCount;
};
const rate = (count1, count2) => {
if (count1 == count2) {
return ["--", 0.0];
} else if (count2 == 0) {
return ["rise", 100.0];
} else {
const r = parseFloat((((count1 - count2) / count2) * 100).toFixed(2));
if (r > 0) return ["rise", r];
else return ["decline", -r];
}
};
const changeTakeover = async ({ chatId, isTakeOver }) => {
const endpoint = `/admin/api/chats/${chatId}/takeover?value=${isTakeOver}`;
return fetch(endpoint, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
}).then((r) => camelizeJson(r));
};
const makeTodayStatisticsEndpoint = (chat_id) =>
`/admin/api/statistics/find_recently?chat_id=${chat_id}`;
export default () => {
const location = useLocation();
const dispatch = useDispatch();
const chatsState = useSelector((state) => state.chats);
const { data: recentStatisticsData, error } = useSWR(
chatsState && chatsState.isLoaded && chatsState.selected
? makeTodayStatisticsEndpoint(chatsState.selected)
: null
);
const [isTakeOver, setIsTakeOver] = useState(false);
const [isOnOwnerMenu, setIsOnOwnerMenu] = useState(
isSysLink({ path: location.pathname })
);
const [passedRate, setPassedRate] = useState(["--", 0]);
const [notPassedRate, setNotPassedRate] = useState(["--", 0]);
const handleTakeOverChange = useCallback(
(checked) => {
setIsTakeOver(checked);
changeTakeover({
chatId: chatsState.selected,
isTakeOver: checked,
}).then((result) => {
if (result.errors) {
toastErrors(result.errors);
setIsTakeOver(!checked);
} else {
// 更新 chats 状态中的 `loadedSelected` 和 `list` 数据。
if (result.chat.id == chatsState.selected) {
dispatch(loadSelected(result.chat));
}
const dirtyIndex = chatsState.list.findIndex(
(c) => c.id === result.chat.id
);
if (dirtyIndex > -1) {
const newList = updateInNewArray(
chatsState.list,
result.chat,
dirtyIndex
);
dispatch(receiveChats(newList));
}
}
});
},
[chatsState]
);
useEffect(() => {
if (chatsState.loadedSelected)
setIsTakeOver(chatsState.loadedSelected.isTakeOver);
}, [chatsState]);
useEffect(() => {
setIsOnOwnerMenu(isSysLink({ path: location.pathname }));
}, [location]);
useEffect(() => {
if (recentStatisticsData) {
const todayPassedCount = passedCount(recentStatisticsData.today);
const yesterdayPassedCount = passedCount(recentStatisticsData.yesterday);
setPassedRate(rate(todayPassedCount, yesterdayPassedCount));
const todayNotPassedCount = notPassedCount(recentStatisticsData.today);
const yesterdayNotPassedCount = notPassedCount(
recentStatisticsData.yesterday
);
setNotPassedRate(rate(todayNotPassedCount, yesterdayNotPassedCount));
}
}, [recentStatisticsData]);
return (
<nav>
<MenuBox
isLoaded={chatsState.isLoaded}
title="管理员菜单"
miniTitle="菜单"
>
<div tw="px-6 py-3 text-sm border-0 border-l-2 border-r-2 border-solid border-transparent flex items-center justify-between">
<div tw="font-medium text-gray-600 ">
{__GLOBAL__.userInfo.fullname}
</div>
<a
tw="underline text-gray-500 text-xs flex items-center"
href="/admin/logout"
>
<span>登出</span>
<svg
tw="w-3 h-3"
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
/>
</svg>
</a>
</div>
{/* <NavItem
title="数据统计"
href={`/admin/chats/${chatsState.selected}/statistics`}
selected={isSelect("statistics", location.pathname)}
/> */}
<NavItem
title="方案定制"
href={`/admin/chats/${chatsState.selected}/scheme`}
selected={isSelect("scheme", location.pathname)}
/>
{/* <NavItem
title="消息模板"
href={`/admin/chats/${chatsState.selected}/template`}
selected={isSelect("template", location.pathname)}
/> */}
<NavItem
title="验证记录"
href={`/admin/chats/${chatsState.selected}/verifications`}
selected={isSelect("verifications", location.pathname)}
/>
<NavItem
title="操作记录"
href={`/admin/chats/${chatsState.selected}/operations`}
selected={isSelect("operations", location.pathname)}
/>
<NavItem
title="管理员权限"
href={`/admin/chats/${chatsState.selected}/permissions`}
selected={isSelect("permissions", location.pathname)}
/>
{/* <NavItem
title="机器人属性"
href={`/admin/chats/${chatsState.selected}/properties`}
selected={isSelect("properties", location.pathname)}
/> */}
<NavItem
title="自定义"
href={`/admin/chats/${chatsState.selected}/custom`}
selected={isSelect("custom", location.pathname)}
ending={isOnOwnerMenu ? "true" : "false"}
/>
{chatsState.loadedSelected && !isOnOwnerMenu ? (
<>
{/*因为菜单链接有一个宽度为 2px 的左右边框,此处需要增加对应宽度的外边距以保持对齐。*/}
<div tw="pt-3 px-6" style={{ marginLeft: 2, marginRight: 2 }}>
<span tw="xl:text-lg text-gray-600">数据统计</span>
<div tw="flex items-center justify-between">
<div tw="flex flex-col items-center">
<span tw="text-xs lg:text-sm text-gray-500 mt-2">
今日验证通过
</span>
<span tw="text-sm font-bold mt-1 tracking-wide">
{recentStatisticsData == undefined
? "计算中"
: passedCount(recentStatisticsData.today)}
</span>
<div tw="mt-2 text-xs lg:text-sm">
<span tw="text-gray-600">较昨日</span>
{["--", "rise"].includes(passedRate[0]) ? (
<span tw="text-green-700"> {arrowUpIcon} </span>
) : (
<span tw="text-red-700"> {arrowDownIcon} </span>
)}
<span tw="text-black font-bold tracking-wide">
{Math.ceil(passedRate[1])}%
</span>
</div>
</div>
<div tw="bg-gray-300 h-10" style={{ width: 1 }}></div>
<div tw="flex flex-col items-center">
<span tw="text-xs lg:text-sm text-gray-500 mt-2">
今日验证失败
</span>
<span tw="text-sm font-bold mt-1 tracking-wider">
{recentStatisticsData == undefined
? "计算中"
: notPassedCount(recentStatisticsData.today)}
</span>
<div tw="mt-2 text-xs lg:text-sm">
<span tw="text-gray-600">较昨日</span>
{["--", "decline"].includes(notPassedRate[0]) ? (
<span tw="text-green-700"> {arrowDownIcon} </span>
) : (
<span tw="text-red-700"> {arrowUpIcon} </span>
)}
<span tw="text-black font-bold tracking-wide">
{Math.ceil(notPassedRate[1])}%
</span>
</div>
</div>
</div>
</div>
<div
tw="py-3 px-6 text-lg text-gray-600 flex justify-between"
style={{ marginLeft: 2, marginRight: 2 }}
>
<span>
{chatsState.loadedSelected.isTakeOver ? "已接管" : "未接管"}
</span>
<Switch
checked={isTakeOver}
checkedIcon={false}
uncheckedIcon={false}
onChange={handleTakeOverChange}
/>
</div>
</>
) : !isOnOwnerMenu ? (
<div tw="py-3 px-6 text-lg text-gray-600 flex justify-between">
<span>检查中…</span>
</div>
) : null}
</MenuBox>
<MenuBox
visibility={__GLOBAL__.userInfo.isOwner}
title="系统菜单"
miniTitle="系统"
>
<NavItem
title="批量管理"
href="/admin/sys/managements"
selected={isSysLink({ path: location.pathname, page: "managements" })}
/>
<NavItem
title="查阅日志"
href="/admin/sys/logs"
selected={isSysLink({ path: location.pathname, page: "logs" })}
/>
<NavItem
title="全局属性"
href="/admin/sys/profile"
selected={isSysLink({ path: location.pathname, page: "profile" })}
/>
<NavItem
title="服务条款"
href="/admin/sys/terms"
selected={isSysLink({ path: location.pathname, page: "terms" })}
/>
{!__GLOBAL__.botInfo.isThirdParty ? (
<NavItem
title="赞助记录"
href="/admin/sys/sponsorship"
selected={isSysLink({
path: location.pathname,
page: "sponsorship",
})}
/>
) : undefined}
{!__GLOBAL__.botInfo.isThirdParty ? (
<NavItem
title="第三方实例"
href="/admin/sys/third_parties"
selected={isSysLink({
path: location.pathname,
page: "third_parties",
})}
/>
) : undefined}
{/* <NavItem
title="定时任务"
href="/admin/sys/tasks"
selected={isSysLink({ path: location.pathname, page: "tasks" })}
/> */}
{/* <NavItem
title="模拟终端"
href="/admin/sys/terminal"
selected={isSysLink({ path: location.pathname, page: "terminal" })}
/> */}
</MenuBox>
</nav>
);
};
|
define("ace/snippets/php",["require","exports","module"],function(e,t,n){"use strict";t.snippetText="snippet <?\n <?php\n\n ${1}\nsnippet ec\n echo ${1};\nsnippet <?e\n <?php echo ${1} ?>\n# this one is for php5.4\nsnippet <?=\n <?=${1}?>\nsnippet ns\n namespace ${1:Foo\\Bar\\Baz};\n ${2}\nsnippet use\n use ${1:Foo\\Bar\\Baz};\n ${2}\nsnippet c\n ${1:abstract }class ${2:$FILENAME}\n {\n ${3}\n }\nsnippet i\n interface ${1:$FILENAME}\n {\n ${2}\n }\nsnippet t.\n $this->${1}\nsnippet f\n function ${1:foo}(${2:array }${3:$bar})\n {\n ${4}\n }\n# method\nsnippet m\n ${1:abstract }${2:protected}${3: static} function ${4:foo}(${5:array }${6:$bar})\n {\n ${7}\n }\n# setter method\nsnippet sm \n /**\n * Sets the value of ${1:foo}\n *\n * @param ${2:$1} $$1 ${3:description}\n *\n * @return ${4:$FILENAME}\n */\n ${5:public} function set${6:$2}(${7:$2 }$$1)\n {\n $this->${8:$1} = $$1;\n return $this;\n }${9}\n# getter method\nsnippet gm\n /**\n * Gets the value of ${1:foo}\n *\n * @return ${2:$1}\n */\n ${3:public} function get${4:$2}()\n {\n return $this->${5:$1};\n }${6}\n#setter\nsnippet $s\n ${1:$foo}->set${2:Bar}(${3});\n#getter\nsnippet $g\n ${1:$foo}->get${2:Bar}();\n\n# Tertiary conditional\nsnippet =?:\n $${1:foo} = ${2:true} ? ${3:a} : ${4};\nsnippet ?:\n ${1:true} ? ${2:a} : ${3}\n\nsnippet C\n $_COOKIE['${1:variable}']${2}\nsnippet E\n $_ENV['${1:variable}']${2}\nsnippet F\n $_FILES['${1:variable}']${2}\nsnippet G\n $_GET['${1:variable}']${2}\nsnippet P\n $_POST['${1:variable}']${2}\nsnippet R\n $_REQUEST['${1:variable}']${2}\nsnippet S\n $_SERVER['${1:variable}']${2}\nsnippet SS\n $_SESSION['${1:variable}']${2}\n \n# the following are old ones\nsnippet inc\n include '${1:file}';${2}\nsnippet inc1\n include_once '${1:file}';${2}\nsnippet req\n require '${1:file}';${2}\nsnippet req1\n require_once '${1:file}';${2}\n# Start Docblock\nsnippet /*\n /**\n * ${1}\n */\n# Class - post doc\nsnippet doc_cp\n /**\n * ${1:undocumented class}\n *\n * @package ${2:default}\n * @subpackage ${3:default}\n * @author ${4:`g:snips_author`}\n */${5}\n# Class Variable - post doc\nsnippet doc_vp\n /**\n * ${1:undocumented class variable}\n *\n * @var ${2:string}\n */${3}\n# Class Variable\nsnippet doc_v\n /**\n * ${3:undocumented class variable}\n *\n * @var ${4:string}\n */\n ${1:var} $${2};${5}\n# Class\nsnippet doc_c\n /**\n * ${3:undocumented class}\n *\n * @package ${4:default}\n * @subpackage ${5:default}\n * @author ${6:`g:snips_author`}\n */\n ${1:}class ${2:}\n {\n ${7}\n } // END $1class $2\n# Constant Definition - post doc\nsnippet doc_dp\n /**\n * ${1:undocumented constant}\n */${2}\n# Constant Definition\nsnippet doc_d\n /**\n * ${3:undocumented constant}\n */\n define(${1}, ${2});${4}\n# Function - post doc\nsnippet doc_fp\n /**\n * ${1:undocumented function}\n *\n * @return ${2:void}\n * @author ${3:`g:snips_author`}\n */${4}\n# Function signature\nsnippet doc_s\n /**\n * ${4:undocumented function}\n *\n * @return ${5:void}\n * @author ${6:`g:snips_author`}\n */\n ${1}function ${2}(${3});${7}\n# Function\nsnippet doc_f\n /**\n * ${4:undocumented function}\n *\n * @return ${5:void}\n * @author ${6:`g:snips_author`}\n */\n ${1}function ${2}(${3})\n {${7}\n }\n# Header\nsnippet doc_h\n /**\n * ${1}\n *\n * @author ${2:`g:snips_author`}\n * @version ${3:$Id$}\n * @copyright ${4:$2}, `strftime('%d %B, %Y')`\n * @package ${5:default}\n */\n \n# Interface\nsnippet interface\n /**\n * ${2:undocumented class}\n *\n * @package ${3:default}\n * @author ${4:`g:snips_author`}\n */\n interface ${1:$FILENAME}\n {\n ${5}\n }\n# class ...\nsnippet class\n /**\n * ${1}\n */\n class ${2:$FILENAME}\n {\n ${3}\n /**\n * ${4}\n */\n ${5:public} function ${6:__construct}(${7:argument})\n {\n ${8:// code...}\n }\n }\n# define(...)\nsnippet def\n define('${1}'${2});${3}\n# defined(...)\nsnippet def?\n ${1}defined('${2}')${3}\nsnippet wh\n while (${1:/* condition */}) {\n ${2:// code...}\n }\n# do ... while\nsnippet do\n do {\n ${2:// code... }\n } while (${1:/* condition */});\nsnippet if\n if (${1:/* condition */}) {\n ${2:// code...}\n }\nsnippet ifil\n <?php if (${1:/* condition */}): ?>\n ${2:<!-- code... -->}\n <?php endif; ?>\nsnippet ife\n if (${1:/* condition */}) {\n ${2:// code...}\n } else {\n ${3:// code...}\n }\n ${4}\nsnippet ifeil\n <?php if (${1:/* condition */}): ?>\n ${2:<!-- html... -->}\n <?php else: ?>\n ${3:<!-- html... -->}\n <?php endif; ?>\n ${4}\nsnippet else\n else {\n ${1:// code...}\n }\nsnippet elseif\n elseif (${1:/* condition */}) {\n ${2:// code...}\n }\nsnippet switch\n switch ($${1:variable}) {\n case '${2:value}':\n ${3:// code...}\n break;\n ${5}\n default:\n ${4:// code...}\n break;\n }\nsnippet case\n case '${1:value}':\n ${2:// code...}\n break;${3}\nsnippet for\n for ($${2:i} = 0; $$2 < ${1:count}; $$2${3:++}) {\n ${4: // code...}\n }\nsnippet foreach\n foreach ($${1:variable} as $${2:value}) {\n ${3:// code...}\n }\nsnippet foreachil\n <?php foreach ($${1:variable} as $${2:value}): ?>\n ${3:<!-- html... -->}\n <?php endforeach; ?>\nsnippet foreachk\n foreach ($${1:variable} as $${2:key} => $${3:value}) {\n ${4:// code...}\n }\nsnippet foreachkil\n <?php foreach ($${1:variable} as $${2:key} => $${3:value}): ?>\n ${4:<!-- html... -->}\n <?php endforeach; ?>\n# $... = array (...)\nsnippet array\n $${1:arrayName} = array('${2}' => ${3});${4}\nsnippet try\n try {\n ${2}\n } catch (${1:Exception} $e) {\n }\n# lambda with closure\nsnippet lambda\n ${1:static }function (${2:args}) use (${3:&$x, $y /*put vars in scope (closure) */}) {\n ${4}\n };\n# pre_dump();\nsnippet pd\n echo '<pre>'; var_dump(${1}); echo '</pre>';\n# pre_dump(); die();\nsnippet pdd\n echo '<pre>'; var_dump(${1}); echo '</pre>'; die(${2:});\nsnippet vd\n var_dump(${1});\nsnippet vdd\n var_dump(${1}); die(${2:});\nsnippet http_redirect\n header (\"HTTP/1.1 301 Moved Permanently\"); \n header (\"Location: \".URL); \n exit();\n# Getters & Setters\nsnippet gs\n /**\n * Gets the value of ${1:foo}\n *\n * @return ${2:$1}\n */\n public function get${3:$2}()\n {\n return $this->${4:$1};\n }\n\n /**\n * Sets the value of $1\n *\n * @param $2 $$1 ${5:description}\n *\n * @return ${6:$FILENAME}\n */\n public function set$3(${7:$2 }$$1)\n {\n $this->$4 = $$1;\n return $this;\n }${8}\n# anotation, get, and set, useful for doctrine\nsnippet ags\n /**\n * ${1:description}\n * \n * @${7}\n */\n ${2:protected} $${3:foo};\n\n public function get${4:$3}()\n {\n return $this->$3;\n }\n\n public function set$4(${5:$4 }$${6:$3})\n {\n $this->$3 = $$6;\n return $this;\n }\nsnippet rett\n return true;\nsnippet retf\n return false;\n",t.scope="php"});
(function() {
window.require(["ace/snippets/php"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
|
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Atsushi Togo
# All rights reserved.
#
# This file is part of phonopy.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# * Neither the name of the phonopy project nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import numpy as np
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
def read_vasp(filename):
with open(filename) as f:
lines = f.readlines()
return _get_cell(lines)
return None
def read_vasp_from_strings(strings):
return _get_cell(StringIO(strings).readlines())
def _get_cell(lines):
line1 = [x for x in lines[0].split()]
if _is_exist_symbols(line1):
symbols = line1
else:
symbols = None
scale = float(lines[1])
lattice = []
for i in range(2, 5):
lattice.append([float(x) for x in lines[i].split()[:3]])
lattice = np.array(lattice) * scale
try:
num_atoms = np.array([int(x) for x in lines[5].split()])
line_at = 6
except ValueError:
symbols = [x for x in lines[5].split()]
num_atoms = np.array([int(x) for x in lines[6].split()])
line_at = 7
numbers = _expand_symbols(num_atoms, symbols)
if lines[line_at][0].lower() == 's':
line_at += 1
is_cartesian = False
if (lines[line_at][0].lower() == 'c' or
lines[line_at][0].lower() == 'k'):
is_cartesian = True
line_at += 1
positions = []
for i in range(line_at, line_at + num_atoms.sum()):
positions.append([float(x) for x in lines[i].split()[:3]])
if is_cartesian:
positions = np.dot(positions, np.linalg.inv(lattice))
return (lattice, positions, numbers)
def _expand_symbols(num_atoms, symbols=None):
expanded_symbols = []
is_symbols = True
if symbols is None:
is_symbols = False
else:
if len(symbols) != len(num_atoms):
is_symbols = False
else:
for s in symbols:
if s not in symbol_map:
is_symbols = False
break
if is_symbols:
for s, num in zip(symbols, num_atoms):
expanded_symbols += [symbol_map[s], ] * num
else:
for i, num in enumerate(num_atoms):
expanded_symbols += [i + 1, ] * num
return expanded_symbols
def _is_exist_symbols(symbols):
for s in symbols:
if not (s in symbol_map):
return False
return True
symbol_map = {
"H": 1,
"He": 2,
"Li": 3,
"Be": 4,
"B": 5,
"C": 6,
"N": 7,
"O": 8,
"F": 9,
"Ne": 10,
"Na": 11,
"Mg": 12,
"Al": 13,
"Si": 14,
"P": 15,
"S": 16,
"Cl": 17,
"Ar": 18,
"K": 19,
"Ca": 20,
"Sc": 21,
"Ti": 22,
"V": 23,
"Cr": 24,
"Mn": 25,
"Fe": 26,
"Co": 27,
"Ni": 28,
"Cu": 29,
"Zn": 30,
"Ga": 31,
"Ge": 32,
"As": 33,
"Se": 34,
"Br": 35,
"Kr": 36,
"Rb": 37,
"Sr": 38,
"Y": 39,
"Zr": 40,
"Nb": 41,
"Mo": 42,
"Tc": 43,
"Ru": 44,
"Rh": 45,
"Pd": 46,
"Ag": 47,
"Cd": 48,
"In": 49,
"Sn": 50,
"Sb": 51,
"Te": 52,
"I": 53,
"Xe": 54,
"Cs": 55,
"Ba": 56,
"La": 57,
"Ce": 58,
"Pr": 59,
"Nd": 60,
"Pm": 61,
"Sm": 62,
"Eu": 63,
"Gd": 64,
"Tb": 65,
"Dy": 66,
"Ho": 67,
"Er": 68,
"Tm": 69,
"Yb": 70,
"Lu": 71,
"Hf": 72,
"Ta": 73,
"W": 74,
"Re": 75,
"Os": 76,
"Ir": 77,
"Pt": 78,
"Au": 79,
"Hg": 80,
"Tl": 81,
"Pb": 82,
"Bi": 83,
"Po": 84,
"At": 85,
"Rn": 86,
"Fr": 87,
"Ra": 88,
"Ac": 89,
"Th": 90,
"Pa": 91,
"U": 92,
"Np": 93,
"Pu": 94,
"Am": 95,
"Cm": 96,
"Bk": 97,
"Cf": 98,
"Es": 99,
"Fm": 100,
"Md": 101,
"No": 102,
"Lr": 103,
"Rf": 104,
"Db": 105,
"Sg": 106,
"Bh": 107,
"Hs": 108,
"Mt": 109,
"Ds": 110,
"Rg": 111,
"Cn": 112,
"Uut": 113,
"Uuq": 114,
"Uup": 115,
"Uuh": 116,
"Uus": 117,
"Uuo": 118,
}
|
#!/usr/bin/env python
# Python 3.6 added new string interpolation method called literal string interpolation and introduced a new literal prefix f. This new way of formatting strings is powerful and easy to use. It provides access to embedded Python expressions inside string constants.
import sys
sys.stdin.flush()
name = str(input('What is your name? '))
sys.stdin.flush()
age = int(input('How old are you? '))
sys.stdin.flush()
height = int(input('How tall are you? [cm] '))
sys.stdin.flush()
weight = int(input('How much do you weigh? [kg] '))
print(f'Hello {name}, so, you\'re {age} years old, {height} cm tall and {weight} kg heavy.')
|
/// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* Refer 13;
* The production FunctionBody : SourceElementsopt is evaluated as follows:
*
* @path ch13/13.0/13.0-7-s.js
* @description Strict Mode - SourceElements is evaluated as strict mode code when the code of this FunctionDeclaration is contained in non-strict mode but the call to eval is a direct call in strict mode code
* @onlyStrict
*/
function testcase() {
try {
eval("'use strict'; function _13_0_7_fun() {eval = 42;};");
_13_0_7_fun();
return false;
} catch (e) {
return e instanceof SyntaxError;
}
}
runTestCase(testcase);
|
//ref https://github.com/johngrantuk/todoDapp/blob/fcf586a113b693bec9b2ae40ce1b358cda0b1fcf/client/src/App.test.js
//docker build tests/e2e -t pp1
//docker run --shm-size 1G --rm -v /root/e2e/app:/app pp1
const puppeteer = require("puppeteer")
const dappeteer = require("dappeteer")
async function run() {
const browser = await dappeteer.launch(puppeteer,{
args: [
'--no-sandbox',
'--disable-setuid-sandbox'
]
})
const metamask = await dappeteer.getMetamask(browser)
console.log(metamask)
// create or import an account
//await metamask.createAccount()
await metamask.importPK('0x87a4e34fe562738085ad492a02f62774fb298efebb3bf3619e35ec0e7496f66b')
// you can change the network if you want
//console.log("swich to rinkeby")
await metamask.switchNetwork('rinkeby')
// go to a dapp and do something that prompts MetaMask to confirm a transaction
const page = await browser.newPage()
//const payButton = await page.$('#pay-with-eth')
//await payButton.click()
// 🏌
//await metamask.confirmTransaction()
await page.goto('https://ropsten.swaponline.io/');
//1
await page.waitFor(2000);
await page.screenshot({path: '/app/screenshots/screenshot1.png'});
console.log("click on Connect wallet ");
const [button] = await page.$x("//button[contains(., 'Connect')]");
await button.click();
/* TODO add catch, make screenshot with err descr */
console.log("click on MetaMask ");
await new Promise(r => setTimeout(r, 3000)); //TODO use waitFor instead
const [button2] = await page.$x("//button[contains(., 'MetaMask')]");
await button2.click();
await page.waitFor(1000);
await page.screenshot({path: '/app/screenshots/screenshot2.png'});
await metamask.approve();
await page.bringToFront();
await page.waitFor(3000);
await page.screenshot({path: '/app/screenshots/screenshot3.png', fullPage: true});
await browser.close();
}
run()
|
#!/usr/bin/env python
from panda import Panda
def get_panda_password():
try:
print("Trying to connect to Panda over USB...")
p = Panda()
except AssertionError:
print("USB connection failed")
sys.exit(0)
wifi = p.get_serial()
#print('[%s]' % ', '.join(map(str, wifi)))
print("SSID: " + wifi[0])
print("Password: " + wifi[1])
if __name__ == "__main__":
get_panda_password()
|
# Natural Language Toolkit: Interface to the HunPos POS-tagger
#
# Copyright (C) 2001-2021 NLTK Project
# Author: Peter Ljunglöf <peter.ljunglof@heatherleaf.se>
# Dávid Márk Nemeskey <nemeskeyd@gmail.com> (modifications)
# Attila Zséder <zseder@gmail.com> (modifications)
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
A module for interfacing with the HunPos open-source POS-tagger.
"""
import os
from subprocess import Popen, PIPE
from nltkma.internals import find_binary, find_file
from nltkma.tag.api import TaggerI
_hunpos_url = "http://code.google.com/p/hunpos/"
_hunpos_charset = "ISO-8859-1"
"""The default encoding used by hunpos: ISO-8859-1."""
class HunposTagger(TaggerI):
"""
A class for pos tagging with HunPos. The input is the paths to:
- a model trained on training data
- (optionally) the path to the hunpos-tag binary
- (optionally) the encoding of the training data (default: ISO-8859-1)
Example:
>>> from nltkma.tag import HunposTagger
>>> ht = HunposTagger('en_wsj.model')
>>> ht.tag('What is the airspeed of an unladen swallow ?'.split())
[('What', 'WP'), ('is', 'VBZ'), ('the', 'DT'), ('airspeed', 'NN'), ('of', 'IN'), ('an', 'DT'), ('unladen', 'NN'), ('swallow', 'VB'), ('?', '.')]
>>> ht.close()
This class communicates with the hunpos-tag binary via pipes. When the
tagger object is no longer needed, the close() method should be called to
free system resources. The class supports the context manager interface; if
used in a with statement, the close() method is invoked automatically:
>>> with HunposTagger('en_wsj.model') as ht:
... ht.tag('What is the airspeed of an unladen swallow ?'.split())
...
[('What', 'WP'), ('is', 'VBZ'), ('the', 'DT'), ('airspeed', 'NN'), ('of', 'IN'), ('an', 'DT'), ('unladen', 'NN'), ('swallow', 'VB'), ('?', '.')]
"""
def __init__(
self, path_to_model, path_to_bin=None, encoding=_hunpos_charset, verbose=False
):
"""
Starts the hunpos-tag executable and establishes a connection with it.
:param path_to_model: The model file.
:param path_to_bin: The hunpos-tag binary.
:param encoding: The encoding used by the model. Unicode tokens
passed to the tag() and tag_sents() methods are converted to
this charset when they are sent to hunpos-tag.
The default is ISO-8859-1 (Latin-1).
This parameter is ignored for str tokens, which are sent as-is.
The caller must ensure that tokens are encoded in the right charset.
"""
self._closed = True
hunpos_paths = [
".",
"/usr/bin",
"/usr/local/bin",
"/opt/local/bin",
"/Applications/bin",
"~/bin",
"~/Applications/bin",
]
hunpos_paths = list(map(os.path.expanduser, hunpos_paths))
self._hunpos_bin = find_binary(
"hunpos-tag",
path_to_bin,
env_vars=("HUNPOS_TAGGER",),
searchpath=hunpos_paths,
url=_hunpos_url,
verbose=verbose,
)
self._hunpos_model = find_file(
path_to_model, env_vars=("HUNPOS_TAGGER",), verbose=verbose
)
self._encoding = encoding
self._hunpos = Popen(
[self._hunpos_bin, self._hunpos_model],
shell=False,
stdin=PIPE,
stdout=PIPE,
stderr=PIPE,
)
self._closed = False
def __del__(self):
self.close()
def close(self):
"""Closes the pipe to the hunpos executable."""
if not self._closed:
self._hunpos.communicate()
self._closed = True
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def tag(self, tokens):
"""Tags a single sentence: a list of words.
The tokens should not contain any newline characters.
"""
for token in tokens:
assert "\n" not in token, "Tokens should not contain newlines"
if isinstance(token, str):
token = token.encode(self._encoding)
self._hunpos.stdin.write(token + b"\n")
# We write a final empty line to tell hunpos that the sentence is finished:
self._hunpos.stdin.write(b"\n")
self._hunpos.stdin.flush()
tagged_tokens = []
for token in tokens:
tagged = self._hunpos.stdout.readline().strip().split(b"\t")
tag = tagged[1] if len(tagged) > 1 else None
tagged_tokens.append((token, tag))
# We have to read (and dismiss) the final empty line:
self._hunpos.stdout.readline()
return tagged_tokens
|
/**
* Auto-generated action file for "reverb" API.
*
* Generated at: 2019-05-07T14:43:52.986Z
* Mass generator version: 1.1.0
*
* flowground :- Telekom iPaaS / reverb-com-connector
* Copyright © 2019, Deutsche Telekom AG
* contact: flowground@telekom.de
*
* All files of this connector are licensed under the Apache 2.0 License. For details
* see the file LICENSE on the toplevel directory.
*
*
* Operation: undefined
* Endpoint Path: '/shipping/providers'
* Method: 'get'
*
*/
const Swagger = require('swagger-client');
const processWrapper = require('../services/process-wrapper');
const spec = require('../spec.json');
// this wrapers offers a simplified emitData(data) function
module.exports.process = processWrapper(processAction);
// parameter names for this call
const PARAMETERS = [];
// mappings from connector field names to API field names
const FIELD_MAP = {};
function processAction(msg, cfg) {
var isVerbose = process.env.debug || cfg.verbose;
if (isVerbose) {
console.log(`---MSG: ${JSON.stringify(msg)}`);
console.log(`---CFG: ${JSON.stringify(cfg)}`);
console.log(`---ENV: ${JSON.stringify(process.env)}`);
}
const contentType = undefined;
const body = msg.body;
mapFieldNames(body);
let parameters = {};
for(let param of PARAMETERS) {
parameters[param] = body[param];
}
// credentials for this operation
let securities = {};
let callParams = {
spec: spec,
operationId: undefined,
pathName: '/shipping/providers',
method: 'get',
parameters: parameters,
requestContentType: contentType,
requestBody: body.requestBody,
securities: {authorized: securities},
server: spec.servers[cfg.server] || cfg.otherServer,
};
if (isVerbose) {
let out = Object.assign({}, callParams);
out.spec = '[omitted]';
console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`);
}
// Call operation via Swagger client
return Swagger.execute(callParams).then(data => {
// emit a single message with data
this.emitData(data);
// if the response contains an array of entities, you can emit them one by one:
// data.obj.someItems.forEach((item) => {
// this.emitData(item);
// }
});
}
function mapFieldNames(obj) {
if(Array.isArray(obj)) {
obj.forEach(mapFieldNames);
}
else if(typeof obj === 'object' && obj) {
Object.keys(obj).forEach(key => {
mapFieldNames(obj[key]);
let goodKey = FIELD_MAP[key];
if(goodKey && goodKey !== key) {
obj[goodKey] = obj[key];
delete obj[key];
}
});
}
}
|
'use stitck';
var fs = require("fs");
var readRepo = function( path , cb , depth , results){
var filePath , realPath , isGit , stat , data;
depth = depth || 0;
path = path.replace(/\/$/,'') + '/';
results = results || [];
data = fs.readdirSync(path);
if(!data) return cb.call(this,results);
data.forEach(function(name){
if( /^\./.test(name) )return;
filePath = path + name;
stat = fs.statSync(filePath);
if( stat.isDirectory() ){
isGit = fs.existsSync(filePath + "/.git");
realPath = fs.realpathSync(filePath);
results.push({path:filePath , isGit:isGit , realPath : realPath });
}
});
if( results.length < 10 && depth < 3 ){
results.forEach(function(pathData){
readRepo(pathData.path , cb , depth+1 , results)
});
}else{
cb.call(this,results)
}
};
module.exports = readRepo;
|
import React, { Component } from 'react';
import {TopojsonData} from '../../../data/kishanganj_shc_topojson';
import {
Circle,
FeatureGroup,
LayerGroup,
Map,
Popup,
Rectangle,
TileLayer, GeoJSON
} from 'react-leaflet';
import 'bootstrap/dist/css/bootstrap.css';
let config = {};
config.params = {
center: [25.09, 76.8],
zoomControl:true,
zoom: 10,
maxZoom: 13,
minZoom: 9,
scrollwheel: false,
legends: true,
infoControl: true,
attributionControl: true,
dragging:false
};
config.tileLayer = {
uri: 'https://api.mapbox.com/styles/v1/suchismitanaik/cj1nivbus001x2sqqlhmct7du/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic3VjaGlzbWl0YW5haWsiLCJhIjoiY2lqMmZ5N2N5MDAwZnVna25hcjE2b2Q1eCJ9.IYx8Zoc0yNPcp7Snd7yW2A',
params: {
minZoom: 4,
attribution: ' <a href="https://www.mapbox.com/about/maps/">Mapbox</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
id: '',
accessToken: ''
}
};
config.geojson = {
weight:"1",
color:"#183152",
fill:true
};
class YearSelector extends Component{
render(){
let props = this.props;
return (
<div className="btn-group " role="group" aria-label="...">
{this.props.fiscalYears.map(function(item,index){
return (
<button type="button" key={item} value={item} className={props.selectedYear===item ? "btn btn-default focus active" : "btn btn-default"} onClick={props.handleYearChange} >{item}</button>
);
})}
</div>
);
}
}
YearSelector.propTypes = {
fiscalYears: React.PropTypes.array
};
class StateToolTip extends React.Component{
render(){
if (this.props.statetooltip==null){
return(
<div className="statetoolPanelHeading">Select a Sub Centre from the Map</div>
);
}
return(
<div>
<div className="statetoolPanelHeading">
<span className="glyphicon glyphicon-map-marker"></span> {this.props.statetooltip}</div>
<div>
<AllocationDetails allocations={this.props.allocations} unit={this.props.unit} />
</div>
</div>
);
}
}
StateToolTip.propTypes = {
statetooltip: React.PropTypes.string,
allocations: React.PropTypes.number,
unit:React.PropTypes.string
};
class AllocationDetails extends React.Component{
render(){
if(this.props.allocations ==null || isNaN(parseFloat(this.props.allocations))){
return (
<span>Data unavailable</span>
);
}
return (
<span> {this.props.allocations} {this.props.unit =="Percentage" ? "%" : this.props.unit}</span>
);
}
}
AllocationDetails.propTypes = {
allocations: React.PropTypes.number,
unit:React.PropTypes.string
};
class LegendStep extends React.Component{
render(){
return (
<li>
<span className="legendspanside" style={{"background" :this.props.bgColor}}>{(this.props.range[0]).toFixed(2)} - {(this.props.range[1]).toFixed(2)}</span>
</li>
);
}
}
LegendStep.propTypes = {
bgColor: React.PropTypes.string,
range:React.PropTypes.array
};
export default class Choropleth extends Component {
constructor(){
super();
this.state = {
budgetAttr:"BE",
selectedYear:null,
selectedFigure:null,
hoverstate:null,
hoverFigure:null,
bandFigures:null
};
this.computeBands = this.computeBands.bind(this);
this.mungeData = this.mungeData.bind(this);
this.getYearList = this.getYearList.bind(this);
this.handleYearChange = this.handleYearChange.bind(this);
this.getstyle = this.getstyle.bind(this);
this.onEachFeature = this.onEachFeature.bind(this);
this.highlightFeature = this.highlightFeature.bind(this);
this.resetHighlight = this.resetHighlight.bind(this);
this.setToolTipContent = this.setToolTipContent.bind(this);
this.getBandNum = this.getBandNum.bind(this);
this.fillColor = this.fillColor.bind(this);
}
componentWillMount(){
let MappedFigures = this.mungeData();
this.setState({selectedFigure: MappedFigures});
let defaultYear = this.getYearList(this.props.data)[this.getYearList(this.props.data).length -1];
this.props.setYearChange(defaultYear);
this.setState({budgetAttr:this.props.budgetAttr,selectedYear:defaultYear });
this.computeBands(MappedFigures, defaultYear);
}
componentDidUpdate(prevProps, prevState){
if(prevProps.data != this.props.data || prevProps.budgetAttr != this.props.budgetAttr){
let MappedFigures = this.mungeData();
let yearList = this.getYearList(this.props.data);
let flag = 0;
for(let year in yearList){
if(this.state.selectedYear == yearList[year]){
flag=1;
break;
}
}
this.setState({selectedFigure: MappedFigures});
if(flag==0){
this.computeBands(MappedFigures, yearList[yearList.length-1]);
this.setState({selectedYear: yearList[yearList.length-1]});
this.props.setYearChange(yearList[yearList.length-1]);
}
else{
this.computeBands(MappedFigures, this.state.selectedYear);
}
}
}
computeBands(tempData, year){
let data = tempData;
let currentState = this.state;
let max = Math.max.apply(null, data.features.map(function(state, index) {
if(state.properties[year] != null && !isNaN(parseFloat(state.properties[year])) ){
return parseFloat(state.properties[year]);
}
else{
return -Infinity;
}
}));
max = max + max*0.1;
let min = Math.min.apply(null, data.features.map(function(state, index) {
if(state.properties[year] != null && !isNaN(parseFloat(state.properties[year])) ){
return parseFloat(state.properties[year]);
}
else{
return Infinity;
}
})) ;
min = min - min*0.1;
/*
let retvalue = {
"20%":[min,min+(20*(max-min))/100,1],
"40%":[min+(20*(max-min))/100,min+(40*(max-min))/100,2],
"60%":[min+(40*(max-min))/100,min+(60*(max-min))/100,3],
"80%":[min+(60*(max-min))/100,min+(80*(max-min))/100,4],
"100%":[min+(80*(max-min))/100,min+(100*(max-min))/100,5]
};
*/
let retvalue = {
"25%":[0,25,1],
"50%":[25,50,2],
"75%":[50,75,3],
"100%":[75,500,4]
};
this.setState({bandFigures:retvalue});
}
mungeData(){
let GeoJSONData = new topojson.feature(TopojsonData, TopojsonData.objects.shc_boundaries);
let record = this.props.data.record_figures;
let budgetAttr = this.props.budgetAttr;
let MappedFigures = new Array();
MappedFigures = GeoJSONData.features.map(function(state, index){
let temp = record.find(function(x){
if(x.grpby_name.toLowerCase()==state.properties.name.toLowerCase())
{
return x;
}
else{
return false;
}
});
for ( let variable in state.properties ){
if (variable != "villages" && variable != "name")
{
delete state.properties[variable];
}
}
if(temp != null){
let tempFigure = temp.figures[budgetAttr];
for (let fiscalFigure in tempFigure){
let tempYear = Object.keys(tempFigure[fiscalFigure])[0];
state.properties[tempYear] = parseFloat(tempFigure[fiscalFigure][tempYear]);
}
}
return state;
});
return {"type": "FeatureCollection", "features": MappedFigures};
}
getBandNum(figure){
if(figure!=null){
let bandFigures = this.state.bandFigures;
let bandKeys = Object.keys(bandFigures);
for(let band in bandKeys){
if(figure>=bandFigures[bandKeys[band]][0] && figure<=bandFigures[bandKeys[band]][1]){
return bandFigures[bandKeys[band]][2];
}
}
}
else{
return 0;
}
}
fillColor(band){
if (band===0 || band ==null){
return "#BFBFBF";
}
if(band===1){
return "#FF0000";
}
if(band===2){
return "#FFC000";
}
if(band===3){
return "#ED7D31";
}
if(band===4){
return "#70AD47";
}
}
getstyle (feature){
let selectedYear = this.state.selectedYear;
return{
fillColor: this.fillColor(this.getBandNum(feature.properties[selectedYear])),
weight: 1.3,
opacity: 1,
color: 'grey',
dashArray:0,
fillOpacity: 0.8
};
}
handleYearChange(e){
this.computeBands(this.state.selectedFigure, e.target.value);
this.setState({selectedYear:e.target.value});
this.props.setYearChange(e.target.value);
}
getYearList(data){
let yearList = [];
for (let key in data.record_figures[0].figures[this.props.budgetAttr]){
yearList.push(Object.keys(data.record_figures[0].figures[this.props.budgetAttr][key])[0]);
}
return yearList;
}
highlightFeature (e) {
let layer = e.target;
this.setToolTipContent(e.target);
layer.setStyle({
weight: 2,
color: '#000',
fillOpacity: 0.9
});
}
resetHighlight (e) {
this.refs.geojson.leafletElement.resetStyle(e.target);
this.resetTooltipContent();
}
onEachFeature (component, feature, layer) {
layer.on({
mouseover: this.highlightFeature,
mouseout: this.resetHighlight
});
}
setToolTipContent(values){
this.setState({hoverstate:values.feature.properties.name , hoverFigure:values.feature.properties[this.state.selectedYear]});
}
resetTooltipContent(){
this.setState({hoverstate:null, hoverFigure:null});
}
showConcordanceData(){
this.setState({vizActive:this.state.vizActive? false : true});
}
render (){
return (
<div className="row vis-wrapper" >
<Map center={config.params.center} zoom={config.params.zoom} zoomControl={config.params.zoomControl} dragging={config.params.dragging}>
<TileLayer
url={config.tileLayer.uri}
maxZoom={config.params.maxZoom}
minZoom={config.params.minZoom}
attribution={config.tileLayer.params.attribution}
/>
}
<div className="tcontainer">
<YearSelector handleYearChange = {this.handleYearChange} fiscalYears={this.getYearList(this.props.data)} selectedYear={this.state.selectedYear}/>
</div>
<div className="statetooltip">
<StateToolTip statetooltip={this.state.hoverstate} allocations={this.state.hoverFigure} unit={this.props.unit} />
</div>
<FeatureGroup >
<GeoJSON
data={this.state.selectedFigure}
weight={config.geojson.weight}
style={this.getstyle}
valueProperty={(feature) => feature.properties.name}
onEachFeature={this.onEachFeature.bind(null, this)}
ref="geojson"/>
</FeatureGroup>
<div className="legendcontainer">
<div className="legend-scale">
<ul className="legend-labels">
<LegendStep bgColor="#FF0000" band="25%" range={this.state.bandFigures["25%"]}/>
<LegendStep bgColor="#ED7D31" band="50%" range={this.state.bandFigures["50%"]}/>
<LegendStep bgColor="#FFC000" band="75%" range={this.state.bandFigures["75%"]}/>
<LegendStep bgColor="#70AD47" band="100%" range={this.state.bandFigures["100%"]}/>
<li>
<span className="legendspanside" style={{"background" :"#BFBFBF"}}>Data Unavailable</span>
</li>
</ul>
</div>
</div>
<div className="license-text">
License - <a href="https://creativecommons.org/licenses/by/4.0/" target="_blank">CC-BY 4.0</a> | <a href="http://www.datakind.org/chapters/datakind-blr" target="_blank">DataKind Bangalore</a>
</div>
</Map>
</div>
);
}
}
Choropleth.propTypes = {
data: React.PropTypes.object,
budgetAttr:React.PropTypes.string,
selectedSector:React.PropTypes.string,
selectedIndicator:React.PropTypes.string,
sectorName:React.PropTypes.string,
setYearChange:React.PropTypes.func,
unit:React.PropTypes.string
};
|
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],e):"object"==typeof exports?exports.ReactDraggable=e(require("react"),require("react-dom")):t.ReactDraggable=e(t.React,t.ReactDOM)}(window,function(t,e){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)n.d(r,o,function(e){return t[e]}.bind(null,o));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=4)}([function(t,e,n){t.exports=n(5)()},function(e,n){e.exports=t},function(t,n){t.exports=e},function(t,e,n){var r;
/*!
Copyright (c) 2017 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/!function(){"use strict";var n={}.hasOwnProperty;function o(){for(var t=[],e=0;e<arguments.length;e++){var r=arguments[e];if(r){var a=typeof r;if("string"===a||"number"===a)t.push(r);else if(Array.isArray(r)&&r.length){var i=o.apply(null,r);i&&t.push(i)}else if("object"===a)for(var s in r)n.call(r,s)&&r[s]&&t.push(s)}}return t.join(" ")}t.exports?(o.default=o,t.exports=o):void 0===(r=function(){return o}.apply(e,[]))||(t.exports=r)}()},function(t,e,n){var r=n(7),o=r.default,a=r.DraggableCore;t.exports=o,t.exports.default=o,t.exports.DraggableCore=a},function(t,e,n){"use strict";var r=n(6);function o(){}function a(){}a.resetWarningCache=o,t.exports=function(){function t(t,e,n,o,a,i){if(i!==r){var s=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name="Invariant Violation",s}}function e(){return t}t.isRequired=t;var n={array:t,bool:t,func:t,number:t,object:t,string:t,symbol:t,any:t,arrayOf:e,element:t,elementType:t,instanceOf:e,node:t,objectOf:e,oneOf:e,oneOfType:e,shape:e,exact:e,checkPropTypes:a,resetWarningCache:o};return n.PropTypes=n,n}},function(t,e,n){"use strict";t.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(t,e,n){"use strict";n.r(e);var r=n(1),o=n.n(r),a=n(0),i=n.n(a),s=n(2),u=n.n(s),c=n(3),l=n.n(c);function f(t,e){for(var n=0,r=t.length;n<r;n++)if(e.apply(e,[t[n],n,t]))return t[n]}function p(t){return"function"==typeof t||"[object Function]"===Object.prototype.toString.call(t)}function d(t){return"number"==typeof t&&!isNaN(t)}function g(t){return parseInt(t,10)}function y(t,e,n){if(t[e])return new Error("Invalid prop ".concat(e," passed to ").concat(n," - do not set this, set it on the child."))}var h=["Moz","Webkit","O","ms"];function b(t,e){return e?"".concat(e).concat(function(t){for(var e="",n=!0,r=0;r<t.length;r++)n?(e+=t[r].toUpperCase(),n=!1):"-"===t[r]?n=!0:e+=t[r];return e}(t)):t}var m=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"transform";if("undefined"==typeof window||void 0===window.document)return"";var e=window.document.documentElement.style;if(t in e)return"";for(var n=0;n<h.length;n++)if(b(t,h[n])in e)return h[n];return""}();function v(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}function w(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var O="";function S(t,e){return O||(O=f(["matches","webkitMatchesSelector","mozMatchesSelector","msMatchesSelector","oMatchesSelector"],function(e){return p(t[e])})),!!p(t[O])&&t[O](e)}function D(t,e,n){var r=t;do{if(S(r,e))return!0;if(r===n)return!1;r=r.parentNode}while(r);return!1}function x(t,e,n){t&&(t.attachEvent?t.attachEvent("on"+e,n):t.addEventListener?t.addEventListener(e,n,!0):t["on"+e]=n)}function P(t,e,n){t&&(t.detachEvent?t.detachEvent("on"+e,n):t.removeEventListener?t.removeEventListener(e,n,!0):t["on"+e]=null)}function j(t){var e=t.clientHeight,n=t.ownerDocument.defaultView.getComputedStyle(t);return e+=g(n.borderTopWidth),e+=g(n.borderBottomWidth)}function E(t){var e=t.clientWidth,n=t.ownerDocument.defaultView.getComputedStyle(t);return e+=g(n.borderLeftWidth),e+=g(n.borderRightWidth)}function T(t){var e=t.clientHeight,n=t.ownerDocument.defaultView.getComputedStyle(t);return e-=g(n.paddingTop),e-=g(n.paddingBottom)}function N(t){var e=t.clientWidth,n=t.ownerDocument.defaultView.getComputedStyle(t);return e-=g(n.paddingLeft),e-=g(n.paddingRight)}function C(t,e,n){var r=t.x,o=t.y,a="translate(".concat(r).concat(n,",").concat(o).concat(n,")");if(e){var i="".concat("string"==typeof e.x?e.x:e.x+n),s="".concat("string"==typeof e.y?e.y:e.y+n);a="translate(".concat(i,", ").concat(s,")")+a}return a}function M(t){if(t){var e,n,r=t.getElementById("react-draggable-style-el");r||((r=t.createElement("style")).type="text/css",r.id="react-draggable-style-el",r.innerHTML=".react-draggable-transparent-selection *::-moz-selection {all: inherit;}\n",r.innerHTML+=".react-draggable-transparent-selection *::selection {all: inherit;}\n",t.getElementsByTagName("head")[0].appendChild(r)),t.body&&(e=t.body,n="react-draggable-transparent-selection",e.classList?e.classList.add(n):e.className.match(new RegExp("(?:^|\\s)".concat(n,"(?!\\S)")))||(e.className+=" ".concat(n)))}}function k(t){try{t&&t.body&&(e=t.body,n="react-draggable-transparent-selection",e.classList?e.classList.remove(n):e.className=e.className.replace(new RegExp("(?:^|\\s)".concat(n,"(?!\\S)"),"g"),"")),t.selection?t.selection.empty():window.getSelection().removeAllRanges()}catch(t){}var e,n}function _(){return function(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?v(n,!0).forEach(function(e){w(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):v(n).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}({touchAction:"none"},arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}function X(t){return"both"===t.props.axis||"x"===t.props.axis}function Y(t){return"both"===t.props.axis||"y"===t.props.axis}function L(t,e,n){var r="number"==typeof e?function(t,e){return t.targetTouches&&f(t.targetTouches,function(t){return e===t.identifier})||t.changedTouches&&f(t.changedTouches,function(t){return e===t.identifier})}(t,e):null;if("number"==typeof e&&!r)return null;var o=I(n);return function(t,e){var n=e===e.ownerDocument.body?{left:0,top:0}:e.getBoundingClientRect();return{x:t.clientX+e.scrollLeft-n.left,y:t.clientY+e.scrollTop-n.top}}(r||t,n.props.offsetParent||o.offsetParent||o.ownerDocument.body)}function R(t,e,n){var r=t.state,o=!d(r.lastX),a=I(t);return o?{node:a,deltaX:0,deltaY:0,lastX:e,lastY:n,x:e,y:n}:{node:a,deltaX:e-r.lastX,deltaY:n-r.lastY,lastX:r.lastX,lastY:r.lastY,x:e,y:n}}function A(t,e){var n=t.props.scale;return{node:e.node,x:t.state.x+e.deltaX/n,y:t.state.y+e.deltaY/n,deltaX:e.deltaX/n,deltaY:e.deltaY/n,lastX:t.state.x,lastY:t.state.y}}function I(t){var e=u.a.findDOMNode(t);if(!e)throw new Error("<DraggableCore>: Unmounted during event!");return e}function U(t){return(U="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function V(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=[],r=!0,o=!1,a=void 0;try{for(var i,s=t[Symbol.iterator]();!(r=(i=s.next()).done)&&(n.push(i.value),!e||n.length!==e);r=!0);}catch(t){o=!0,a=t}finally{try{r||null==s.return||s.return()}finally{if(o)throw a}}return n}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function W(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function B(t){return(B=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function H(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function q(t,e){return(q=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function G(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var z={touch:{start:"touchstart",move:"touchmove",stop:"touchend"},mouse:{start:"mousedown",move:"mousemove",stop:"mouseup"}},F=z.mouse,J=function(t){function e(){var t,n,r,o;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);for(var a=arguments.length,i=new Array(a),s=0;s<a;s++)i[s]=arguments[s];return r=this,o=(t=B(e)).call.apply(t,[this].concat(i)),n=!o||"object"!==U(o)&&"function"!=typeof o?H(r):o,G(H(n),"state",{dragging:!1,lastX:NaN,lastY:NaN,touchIdentifier:null}),G(H(n),"handleDragStart",function(t){if(n.props.onMouseDown(t),!n.props.allowAnyClick&&"number"==typeof t.button&&0!==t.button)return!1;var e=u.a.findDOMNode(H(n));if(!e||!e.ownerDocument||!e.ownerDocument.body)throw new Error("<DraggableCore> not mounted on DragStart!");var r=e.ownerDocument;if(!(n.props.disabled||!(t.target instanceof r.defaultView.Node)||n.props.handle&&!D(t.target,n.props.handle,e)||n.props.cancel&&D(t.target,n.props.cancel,e))){var o=function(t){return t.targetTouches&&t.targetTouches[0]?t.targetTouches[0].identifier:t.changedTouches&&t.changedTouches[0]?t.changedTouches[0].identifier:void 0}(t);n.setState({touchIdentifier:o});var a=L(t,o,H(n));if(null!=a){var i=a.x,s=a.y,c=R(H(n),i,s);n.props.onStart,!1!==n.props.onStart(t,c)&&(n.props.enableUserSelectHack&&M(r),n.setState({dragging:!0,lastX:i,lastY:s}),x(r,F.move,n.handleDrag),x(r,F.stop,n.handleDragStop))}}}),G(H(n),"handleDrag",function(t){"touchmove"===t.type&&t.preventDefault();var e=L(t,n.state.touchIdentifier,H(n));if(null!=e){var r,o,a,i=e.x,s=e.y;if(Array.isArray(n.props.grid)){var u=i-n.state.lastX,c=s-n.state.lastY,l=V((r=n.props.grid,o=u,a=c,[Math.round(o/r[0])*r[0],Math.round(a/r[1])*r[1]]),2);if(u=l[0],c=l[1],!u&&!c)return;i=n.state.lastX+u,s=n.state.lastY+c}var f=R(H(n),i,s);if(!1!==n.props.onDrag(t,f))n.setState({lastX:i,lastY:s});else try{n.handleDragStop(new MouseEvent("mouseup"))}catch(t){var p=document.createEvent("MouseEvents");p.initMouseEvent("mouseup",!0,!0,window,0,0,0,0,0,!1,!1,!1,!1,0,null),n.handleDragStop(p)}}}),G(H(n),"handleDragStop",function(t){if(n.state.dragging){var e=L(t,n.state.touchIdentifier,H(n));if(null!=e){var r=e.x,o=e.y,a=R(H(n),r,o),i=u.a.findDOMNode(H(n));i&&n.props.enableUserSelectHack&&k(i.ownerDocument),n.setState({dragging:!1,lastX:NaN,lastY:NaN}),n.props.onStop(t,a),i&&(P(i.ownerDocument,F.move,n.handleDrag),P(i.ownerDocument,F.stop,n.handleDragStop))}}}),G(H(n),"onMouseDown",function(t){return F=z.mouse,n.handleDragStart(t)}),G(H(n),"onMouseUp",function(t){return F=z.mouse,n.handleDragStop(t)}),G(H(n),"onTouchStart",function(t){return F=z.touch,n.handleDragStart(t)}),G(H(n),"onTouchEnd",function(t){return F=z.touch,n.handleDragStop(t)}),n}var n,r,a;return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&q(t,e)}(e,o.a.Component),n=e,(r=[{key:"componentWillUnmount",value:function(){var t=u.a.findDOMNode(this);if(t){var e=t.ownerDocument;P(e,z.mouse.move,this.handleDrag),P(e,z.touch.move,this.handleDrag),P(e,z.mouse.stop,this.handleDragStop),P(e,z.touch.stop,this.handleDragStop),this.props.enableUserSelectHack&&k(e)}}},{key:"render",value:function(){return o.a.cloneElement(o.a.Children.only(this.props.children),{style:_(this.props.children.props.style),onMouseDown:this.onMouseDown,onTouchStart:this.onTouchStart,onMouseUp:this.onMouseUp,onTouchEnd:this.onTouchEnd})}}])&&W(n.prototype,r),a&&W(n,a),e}();function K(t){return(K="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function Q(){return(Q=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}function Z(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n,r,o={},a=Object.keys(t);for(r=0;r<a.length;r++)n=a[r],e.indexOf(n)>=0||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);for(r=0;r<a.length;r++)n=a[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}function $(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=[],r=!0,o=!1,a=void 0;try{for(var i,s=t[Symbol.iterator]();!(r=(i=s.next()).done)&&(n.push(i.value),!e||n.length!==e);r=!0);}catch(t){o=!0,a=t}finally{try{r||null==s.return||s.return()}finally{if(o)throw a}}return n}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function tt(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}function et(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?tt(n,!0).forEach(function(e){st(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):tt(n).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function nt(t){return(nt=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function rt(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function ot(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function at(t,e,n){return e&&ot(t.prototype,e),n&&ot(t,n),t}function it(t,e){return(it=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function st(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}G(J,"displayName","DraggableCore"),G(J,"propTypes",{allowAnyClick:i.a.bool,disabled:i.a.bool,enableUserSelectHack:i.a.bool,offsetParent:function(t,e){if(t[e]&&1!==t[e].nodeType)throw new Error("Draggable's offsetParent must be a DOM Node.")},grid:i.a.arrayOf(i.a.number),handle:i.a.string,cancel:i.a.string,onStart:i.a.func,onDrag:i.a.func,onStop:i.a.func,onMouseDown:i.a.func,className:y,style:y,transform:y}),G(J,"defaultProps",{allowAnyClick:!1,cancel:null,disabled:!1,enableUserSelectHack:!0,offsetParent:null,handle:null,grid:null,transform:null,onStart:function(){},onDrag:function(){},onStop:function(){},onMouseDown:function(){}}),n.d(e,"default",function(){return ut}),n.d(e,"DraggableCore",function(){return J});var ut=function(t){function e(t){var n,r,o;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),r=this,o=nt(e).call(this,t),n=!o||"object"!==K(o)&&"function"!=typeof o?rt(r):o,st(rt(n),"onDragStart",function(t,e){if(!1===n.props.onStart(t,A(rt(n),e)))return!1;n.setState({dragging:!0,dragged:!0})}),st(rt(n),"onDrag",function(t,e){if(!n.state.dragging)return!1;var r=A(rt(n),e),o={x:r.x,y:r.y};if(n.props.bounds){var a=o.x,i=o.y;o.x+=n.state.slackX,o.y+=n.state.slackY;var s=$(function(t,e,n){if(!t.props.bounds)return[e,n];var r=t.props.bounds;r="string"==typeof r?r:function(t){return{left:t.left,top:t.top,right:t.right,bottom:t.bottom}}(r);var o=I(t);if("string"==typeof r){var a,i=o.ownerDocument,s=i.defaultView;if(!((a="parent"===r?o.parentNode:i.querySelector(r))instanceof s.HTMLElement))throw new Error('Bounds selector "'+r+'" could not find an element.');var u=s.getComputedStyle(o),c=s.getComputedStyle(a);r={left:-o.offsetLeft+g(c.paddingLeft)+g(u.marginLeft),top:-o.offsetTop+g(c.paddingTop)+g(u.marginTop),right:N(a)-E(o)-o.offsetLeft+g(c.paddingRight)-g(u.marginRight),bottom:T(a)-j(o)-o.offsetTop+g(c.paddingBottom)-g(u.marginBottom)}}return d(r.right)&&(e=Math.min(e,r.right)),d(r.bottom)&&(n=Math.min(n,r.bottom)),d(r.left)&&(e=Math.max(e,r.left)),d(r.top)&&(n=Math.max(n,r.top)),[e,n]}(rt(n),o.x,o.y),2),u=s[0],c=s[1];o.x=u,o.y=c,o.slackX=n.state.slackX+(a-o.x),o.slackY=n.state.slackY+(i-o.y),r.x=o.x,r.y=o.y,r.deltaX=o.x-n.state.x,r.deltaY=o.y-n.state.y}if(!1===n.props.onDrag(t,r))return!1;n.setState(o)}),st(rt(n),"onDragStop",function(t,e){if(!n.state.dragging)return!1;if(!1===n.props.onStop(t,A(rt(n),e)))return!1;var r={dragging:!1,slackX:0,slackY:0};if(Boolean(n.props.position)){var o=n.props.position,a=o.x,i=o.y;r.x=a,r.y=i}n.setState(r)}),n.state={dragging:!1,dragged:!1,x:t.position?t.position.x:t.defaultPosition.x,y:t.position?t.position.y:t.defaultPosition.y,prevPropsPosition:et({},t.position),slackX:0,slackY:0,isElementSVG:!1},!t.position||t.onDrag||t.onStop||console.warn("A `position` was applied to this <Draggable>, without drag handlers. This will make this component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the `position` of this element."),n}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&it(t,e)}(e,o.a.Component),at(e,null,[{key:"getDerivedStateFromProps",value:function(t,e){var n=t.position,r=e.prevPropsPosition;return!n||r&&n.x===r.x&&n.y===r.y?null:{x:n.x,y:n.y,prevPropsPosition:et({},n)}}}]),at(e,[{key:"componentDidMount",value:function(){void 0!==window.SVGElement&&u.a.findDOMNode(this)instanceof window.SVGElement&&this.setState({isElementSVG:!0})}},{key:"componentWillUnmount",value:function(){this.setState({dragging:!1})}},{key:"render",value:function(){var t,e=this.props,n=(e.axis,e.bounds,e.children),r=e.defaultPosition,a=e.defaultClassName,i=e.defaultClassNameDragging,s=e.defaultClassNameDragged,u=e.position,c=e.positionOffset,f=(e.scale,Z(e,["axis","bounds","children","defaultPosition","defaultClassName","defaultClassNameDragging","defaultClassNameDragged","position","positionOffset","scale"])),p={},d=null,g=!Boolean(u)||this.state.dragging,y=u||r,h={x:X(this)&&g?this.state.x:y.x,y:Y(this)&&g?this.state.y:y.y};this.state.isElementSVG?d=function(t,e){return C(t,e,"")}(h,c):p=function(t,e){var n=C(t,e,"px");return w({},b("transform",m),n)}(h,c);var v=l()(n.props.className||"",a,(st(t={},i,this.state.dragging),st(t,s,this.state.dragged),t));return o.a.createElement(J,Q({},f,{onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop}),o.a.cloneElement(o.a.Children.only(n),{className:v,style:et({},n.props.style,{},p),transform:d}))}}]),e}();st(ut,"displayName","Draggable"),st(ut,"propTypes",et({},J.propTypes,{axis:i.a.oneOf(["both","x","y","none"]),bounds:i.a.oneOfType([i.a.shape({left:i.a.number,right:i.a.number,top:i.a.number,bottom:i.a.number}),i.a.string,i.a.oneOf([!1])]),defaultClassName:i.a.string,defaultClassNameDragging:i.a.string,defaultClassNameDragged:i.a.string,defaultPosition:i.a.shape({x:i.a.number,y:i.a.number}),positionOffset:i.a.shape({x:i.a.oneOfType([i.a.number,i.a.string]),y:i.a.oneOfType([i.a.number,i.a.string])}),position:i.a.shape({x:i.a.number,y:i.a.number}),className:y,style:y,transform:y})),st(ut,"defaultProps",et({},J.defaultProps,{axis:"both",bounds:!1,defaultClassName:"react-draggable",defaultClassNameDragging:"react-draggable-dragging",defaultClassNameDragged:"react-draggable-dragged",defaultPosition:{x:0,y:0},position:null,scale:1}))}])});
//# sourceMappingURL=react-draggable.min.js.map
|
document.addEventListener("DOMContentLoaded", (event) => {
let added = document.getElementById('added');
let waiting = document.getElementById('waiting');
let nisur = document.getElementById('nisur');
let inventory = document.getElementById('inventory');
let arrived = document.getElementById('arrived');
let returning = document.getElementById('returning');
let returned = document.getElementById('returned');
let lost = document.getElementById('lost');
let deleted = document.getElementById('deleted');
let admin = document.getElementById('admin');
let warehouse = document.getElementById('warehouse');
let postman = document.getElementById('postman');
let express = document.getElementById('express');
let normal = document.getElementById('normal');
let letter = document.getElementById('letter');
let packageSum = document.getElementById('package');
$.ajax({
url: "../api/getAdminMetrics",
type: 'GET',
context: document.body,
success: function (data, status, xhr) {
added.innerHTML = data.added
waiting.innerHTML = data.pritje
nisur.innerHTML = data.niusr
inventory.innerHTML = data.inventory
arrived.innerHTML = data.arrived
returning.innerHTML = data.returning
returned.innerHTML = data.returned
lost.innerHTML = data.lost
deleted.innerHTML = data.deleted
admin.innerHTML = data.admin
warehouse.innerHTML = data.warehouse
postman.innerHTML = data.postman
express.innerHTML = data.express
normal.innerHTML = data.normal
letter.innerHTML = data.letter
packageSum.innerHTML = data.package
},
error: function (jqXhr, textStatus, errorMessage) {
console.log("error")
}
})
});
function uploadImage() {
let imageSelect = document.getElementById('image');
let image = document.getElementById('image');
let userId = window.localStorage.getItem('userId');
var resp;
let formData = new FormData();
formData.append("image", imageSelect.files[0]);
formData.append("user_id", userId);
$.ajax({
mimeType: "multipart/form-data",
url: "../api/storeImage",
type: 'POST',
data: formData,
processData: false,
contentType: false,
context: document.body,
success: function (data, status, xhr) {
resp = JSON.parse(data);
},
error: function (jqXhr, textStatus, errorMessage) {
resp = jqXhr.responseJSON.message;
}
}).done(() => {
resp = resp['path'].replace('public', 'storage')
document.querySelector('#profile-image').src = resp;
document.querySelector('.image-input-container').classList.add('finished')
}).fail(() => {
console.log('err');
});
}
function onUpload() {
window.location = "../admin"
}
|
import React from 'react'
export default () => (
<svg fill="#2E83E6" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<path
fillRule="evenodd"
clipRule="evenodd"
d="M162 205c10 0 17-8 17-17v-17c0-10-7-17-17-17H60c-10 0-18 7-18 17v17c0 9 8 17 18 17h102zM60 171h102v17H60v-17zM77 222a26 26 0 100 51 26 26 0 000-51zm0 34a9 9 0 110-17 9 9 0 010 17zM51 307a26 26 0 1151 0 26 26 0 01-51 0zm17 0a9 9 0 1017 0 9 9 0 00-17 0zM77 341a26 26 0 100 52 26 26 0 000-52zm0 34a9 9 0 110-17 9 9 0 010 17zM120 247a26 26 0 1151 1 26 26 0 01-51-1zm17 0a9 9 0 1017 0 9 9 0 00-17 0zM145 282a26 26 0 100 51 26 26 0 000-51zm0 34a9 9 0 110-17 9 9 0 010 17zM120 367a26 26 0 1151 0 26 26 0 01-51 0zm17 0a9 9 0 1017 0 9 9 0 00-17 0zM410 341a9 9 0 0017 0c0-21-19-38-43-42v-9a9 9 0 00-17 0v9c-24 4-43 21-43 42s19 39 43 42v51c-15-3-26-13-26-24a9 9 0 00-17 0c0 21 19 38 43 42v9a9 9 0 0017 0v-9c24-4 43-21 43-42s-19-39-43-42v-51c15 3 26 12 26 24zm-69 0c0-12 11-21 26-24v49c-15-3-26-13-26-25zm69 69c0 11-11 21-26 24v-49c15 3 26 13 26 25z"
/>
<path d="M299 320c-4-2-10-1-12 3-17 29-19 65-5 96a9 9 0 1016-7 87 87 0 014-80c2-4 1-10-3-12zM449 332c-2-4-1-10 4-12 4-2 9-1 11 3 17 29 19 65 5 96a9 9 0 11-16-7c12-26 11-56-4-80z" />
<path
fillRule="evenodd"
clipRule="evenodd"
d="M324 179v70c60-24 128-4 164 49a137 137 0 01-181 196 60 60 0 01-43 18H60c-29 0-54-20-59-48a17 17 0 0117-20h84v-17H34c-14 0-26-12-26-26V145c0-14 12-26 26-26h68V60c0-33 27-60 60-60h205a9 9 0 110 17c-24 0-43 19-43 43v7l157 70a51 51 0 11-41 94l-116-52zM274 77l-18 40 13 14 24-54h-19zm-19 0h-33l22 25 11-25zm88 63c-2 0-3 0-23-9l-27-12-11 23 118 52 10-23-39-18a9 9 0 117-15l39 17 11-23-118-52-10 23 47 21a9 9 0 01-4 16zm88 68l28-62-16-7-28 62 16 7zm53 1c10-10 13-24 9-37-4-9-10-16-19-19l-27 62c12 6 27 3 37-6zM25 145v256c0 5 4 9 9 9h154c5 0 9-4 9-9V145c0-5-4-8-9-8H34c-5 0-9 3-9 8zm180 316H18c4 20 21 34 42 34h163c-10-9-16-21-18-34zm0-17c9 0 16 6 17 14a43 43 0 0071 26 136 136 0 0114-227v-85l-39-18h-1l-42-47-29-33a9 9 0 017-14h104c0-16 7-32 18-43H162c-23 0-42 19-42 43v59h68c14 0 26 12 26 26v256c0 14-12 26-26 26h-68v17h85zm60-23a120 120 0 00230-46 119 119 0 00-204-84c-34 34-45 86-26 130z"
/>
</svg>
)
|
/**
* Jquery language selector plugin.
*
* @author Muhammad Umer Farooq <lablnet01@gmail.com>
* @author-profile https://www.facebook.com/Muhammadumerfarooq01/
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT
*/
class LanguageSelector {
setLang(lang)
{
l = lang.toLowerCase();
localStorage.setItem('lang', l);
return true;
}
getLang()
{
var lang = localStorage.getItem('lang');
if (lang != null) {
return lang;
} else {
return 'en';
}
}
removeLang()
{
localStorage.removeItem('lang');
return true;
}
loadLang()
{
var l = this.getLang();
var strs = lang[l];
return strs;
}
parse()
{
var rtl = ['ar', 'ur', 'fa', 'he', 'arc', 'az', 'dv', 'arabic', 'aramaic', 'azeri', 'maldivian', 'dhivehi', 'hebrew', 'kurdish', 'persian', 'urdu'
];
var lang = this.loadLang();
var len = lang.length - 1;
var keys = Object.keys(lang);
var values = Object.values(lang);
for (var i = 0; i <= keys.length - 1; i++) {
$("body").children().each(function () {
$(this).html( $(this).html().replace(keys[i],values[i]) );
});
}
if (rtl.includes(this.getLang())) {
document.body.style.direction = 'rtl';
}
}
}
|
import sys
import redis
r_server = redis.StrictRedis('127.0.0.1', db=2)
i_key = "owner-info"
Hostname = sys.argv[1]
Email = sys.argv[2]
OrganizationName = sys.argv[3]
OrganizationalUnitName = sys.argv[4]
LocalityName = sys.argv[5]
Country = sys.argv[6]
i_data = '{"Hostname":"%s", "Email":"%s", "OrganizationName":"%s", "OrganizationalUnitName":"%s", "LocalityName":"%s", "Country":"%s"}' % (
Hostname, Email, OrganizationName, OrganizationalUnitName, LocalityName, Country)
r_server.set(i_key, i_data)
r_server.set("need_CSR", "1")
r_server.bgsave()
|
var classv8_1_1internal_1_1_store_data_property_in_literal_i_c_nexus =
[
[ "StoreDataPropertyInLiteralICNexus", "classv8_1_1internal_1_1_store_data_property_in_literal_i_c_nexus.html#ad2fd416edbeb9ebb56fa9c22d467ab3e", null ],
[ "StoreDataPropertyInLiteralICNexus", "classv8_1_1internal_1_1_store_data_property_in_literal_i_c_nexus.html#ace150c4b76dad96d01909eb86121cf91", null ],
[ "Clear", "classv8_1_1internal_1_1_store_data_property_in_literal_i_c_nexus.html#af2c3e2ad3b03701f3566043c30e7a4e7", null ],
[ "ConfigureMonomorphic", "classv8_1_1internal_1_1_store_data_property_in_literal_i_c_nexus.html#aa0db7e83eac4aa0c2c7a2e729f015bee", null ],
[ "StateFromFeedback", "classv8_1_1internal_1_1_store_data_property_in_literal_i_c_nexus.html#a87e93ed6cbb4739605b2352d12215e77", null ]
];
|
/** section: Language
* class Object
*
* Extensions to the built-in `Object` object.
*
* Because it is dangerous and invasive to augment `Object.prototype` (i.e.,
* add instance methods to objects), all these methods are static methods that
* take an `Object` as their first parameter.
*
**/
(function() {
var _toString = Object.prototype.toString;
/**
* Object.extend(destination, source) -> Object
* - destination (Object): The object to receive the new properties.
* - source (Object): The object whose properties will be duplicated.
*
* Copies all properties from the source to the destination object. Returns
* the destination object.
**/
function extend(destination, source) {
for (var property in source)
destination[property] = source[property];
return destination;
}
/**
* Object.inspect(object) -> String
* - object (Object): The item to be inspected.
*
* Returns the debug-oriented string representation of the object.
*
* `undefined` and `null` are represented as such.
*
* Other types are checked for a `inspect` method. If there is one, it is
* used; otherwise, it reverts to the `toString` method.
*
* Prototype provides `inspect` methods for many types, both built-in and
* library-defined — among them `String`, `Array`, `Enumerable` and `Hash`.
* These attempt to provide useful string representations (from a
* developer's standpoint) for their respective types.
**/
function inspect(object) {
try {
if (isUndefined(object)) return 'undefined';
if (object === null) return 'null';
return object.inspect ? object.inspect() : String(object);
} catch (e) {
if (e instanceof RangeError) return '...';
throw e;
}
}
/**
* Object.toJSON(object) -> String
* - object (Object): The object to be serialized.
*
* Returns a JSON string.
*
* `undefined` and `function` types have no JSON representation. `boolean`
* and `null` are coerced to strings.
*
* For other types, `Object.toJSON` looks for a `toJSON` method on `object`.
* If there is one, it is used; otherwise the object is treated like a
* generic `Object`.
**/
function toJSON(object) {
var type = typeof object;
switch (type) {
case 'undefined':
case 'function':
case 'unknown': return;
case 'boolean': return object.toString();
}
if (object === null) return 'null';
if (object.toJSON) return object.toJSON();
if (isElement(object)) return;
var results = [];
for (var property in object) {
var value = toJSON(object[property]);
if (!isUndefined(value))
results.push(property.toJSON() + ': ' + value);
}
return '{' + results.join(', ') + '}';
}
/**
* Object.toQueryString(object) -> String
* object (Object): The object whose property/value pairs will be converted.
*
* Turns an object into its URL-encoded query string representation.
*
* This is a form of serialization, and is mostly useful to provide complex
* parameter sets for stuff such as objects in the Ajax namespace (e.g.
* [[Ajax.Request]]).
*
* Undefined-value pairs will be serialized as if empty-valued. Array-valued
* pairs will get serialized with one name/value pair per array element. All
* values get URI-encoded using JavaScript's native `encodeURIComponent`
* function.
*
* The order of pairs in the serialized form is not guaranteed (and mostly
* irrelevant anyway) — except for array-based parts, which are serialized
* in array order.
**/
function toQueryString(object) {
return $H(object).toQueryString();
}
/**
* Object.toHTML(object) -> String
* - object (Object): The object to convert to HTML.
*
* Converts the object to its HTML representation.
*
* Returns the return value of `object`'s `toHTML` method if it exists; else
* runs `object` through [[String.interpret]].
**/
function toHTML(object) {
return object && object.toHTML ? object.toHTML() : String.interpret(object);
}
/**
* Object.keys(object) -> Array
* - object (Object): The object to pull keys from.
*
* Returns an array of the object's property names.
*
* Note that the order of the resulting array is browser-dependent — it
* relies on the `for…in` loop, for which the ECMAScript spec does not
* prescribe an enumeration order. Sort the resulting array if you wish to
* normalize the order of the object keys.
**/
function keys(object) {
var results = [];
for (var property in object)
results.push(property);
return results;
}
/**
* Object.values(object) -> Array
* - object (Object): The object to pull values from.
*
* Returns an array of the object's values.
*
* Note that the order of the resulting array is browser-dependent — it
* relies on the `for…in` loop, for which the ECMAScript spec does not
* prescribe an enumeration order.
*
* Also, remember that while property _names_ are unique, property _values_
* have no such constraint.
**/
function values(object) {
var results = [];
for (var property in object)
results.push(object[property]);
return results;
}
/**
* Object.clone(object) -> Object
* - object (Object): The object to clone.
*
* Creates and returns a shallow duplicate of the passed object by copying
* all of the original's key/value pairs onto an empty object.
*
* Do note that this is a _shallow_ copy, not a _deep_ copy. Nested objects
* will retain their references.
*
* <h5>Examples</h5>
*
* var original = {name: 'primaryColors', values: ['red', 'green', 'blue']};
* var copy = Object.clone(original);
* original.name;
* // -> "primaryColors"
* original.values[0];
* // -> "red"
* copy.name;
* // -> "primaryColors"
* copy.name = "secondaryColors";
* original.name;
* // -> "primaryColors"
* copy.name;
* // -> "secondaryColors"
* copy.values[0] = 'magenta';
* copy.values[1] = 'cyan';
* copy.values[2] = 'yellow';
* original.values[0];
* // -> "magenta" (it was a shallow copy, so they shared the array)
**/
function clone(object) {
return extend({ }, object);
}
/**
* Object.isElement(object) -> Boolean
* - object (Object): The object to test.
*
* Returns `true` if `object` is a DOM node of type 1; `false` otherwise.
**/
function isElement(object) {
return !!(object && object.nodeType == 1);
}
/**
* Object.isArray(object) -> Boolean
* - object (Object): The object to test.
*
* Returns `true` if `object` is an array; false otherwise.
**/
function isArray(object) {
return _toString.call(object) == "[object Array]";
}
var hasNativeIsArray = (typeof Array.isArray == 'function')
&& Array.isArray([]) && !Array.isArray({});
if (hasNativeIsArray) {
isArray = Array.isArray;
}
/**
* Object.isHash(object) -> Boolean
* - object (Object): The object to test.
*
* Returns `true` if `object` is an instance of the [[Hash]] class; `false`
* otherwise.
**/
function isHash(object) {
return object instanceof Hash;
}
/**
* Object.isFunction(object) -> Boolean
* - object (Object): The object to test.
*
* Returns `true` if `object` is of type `function`; `false` otherwise.
**/
function isFunction(object) {
return typeof object === "function";
}
/**
* Object.isString(object) -> Boolean
* - object (Object): The object to test.
*
* Returns `true` if `object` is of type `string`; `false` otherwise.
**/
function isString(object) {
return _toString.call(object) == "[object String]";
}
/**
* Object.isNumber(object) -> Boolean
* - object (Object): The object to test.
*
* Returns `true` if `object` is of type `number`; `false` otherwise.
**/
function isNumber(object) {
return _toString.call(object) == "[object Number]";
}
/**
* Object.isUndefined(object) -> Boolean
* - object (Object): The object to test.
*
* Returns `true` if `object` is of type `string`; `false` otherwise.
**/
function isUndefined(object) {
return typeof object === "undefined";
}
extend(Object, {
extend: extend,
inspect: inspect,
toJSON: toJSON,
toQueryString: toQueryString,
toHTML: toHTML,
keys: keys,
values: values,
clone: clone,
isElement: isElement,
isArray: isArray,
isHash: isHash,
isFunction: isFunction,
isString: isString,
isNumber: isNumber,
isUndefined: isUndefined
});
})();
|
const CustomError = require("../extensions/custom-error");
module.exports = function createDreamTeam(a) {
if (!Array.isArray(a)) {
return false
}
for (let j = 0; j < a.length; j++) {
if (typeof (a[j]) !== 'string') {
delete a[j]
}
}
a = a.map(i => i.trim())
let sum = ''
for (let i = 0; i < a.length; i++) {
if (typeof (a[i]) === 'string') {
let b = a.join(',').toUpperCase().split(',')
sum += b[i][0]
}
}
return sum.split('').sort().join('')
};
|
var FlightSuretyApp = artifacts.require("FlightSuretyApp");
var FlightSuretyData = artifacts.require("FlightSuretyData");
var BigNumber = require('bignumber.js');
var Config = async function(accounts) {
// These test addresses are useful when you need to add
// multiple users in test scripts
let testAddresses = [
"0x69e1CB5cFcA8A311586e3406ed0301C06fb839a2",
"0xF014343BDFFbED8660A9d8721deC985126f189F3",
"0x0E79EDbD6A727CfeE09A2b1d0A59F7752d5bf7C9",
"0x9bC1169Ca09555bf2721A5C9eC6D69c8073bfeB4",
"0xa23eAEf02F9E0338EEcDa8Fdd0A73aDD781b2A86",
"0x6b85cc8f612d5457d49775439335f83e12b8cfde",
"0xcbd22ff1ded1423fbc24a7af2148745878800024",
"0xc257274276a4e539741ca11b590b9447b26a8051",
"0x2f2899d6d35b1a48a4fbdc93a37a72f264a9fca7"
];
let owner = accounts[0];
let firstAirline = accounts[1]; // in line with migration file "2_deploy_contracts.js"
let flightSuretyData = await FlightSuretyData.new();
let flightSuretyApp = await FlightSuretyApp.new(flightSuretyData.address, firstAirline);
return {
owner: owner,
firstAirline: firstAirline,
weiMultiple: (new BigNumber(10)).pow(18),
testAddresses: testAddresses,
flightSuretyData: flightSuretyData,
flightSuretyApp: flightSuretyApp
}
}
module.exports = {
Config: Config
};
|
from tqdm import tqdm
from sklearn_crfsuite.metrics import flat_classification_report
import logging
import torch
from modules.utils.plot_metrics import get_mean_max_metric
from .optimization import BertAdam
import json
from modules.data.bert_data import BertNerData
from modules.models.released_models import released_models
logging.basicConfig(level=logging.INFO)
def train_step(dl, model, optimizer, lr_scheduler=None, clip=None, num_epoch=1):
model.train()
epoch_loss = 0
idx = 0
pr = tqdm(dl, total=len(dl), leave=False)
for batch in pr:
idx += 1
model.zero_grad()
try:
loss = model.score(batch)
except AttributeError:
loss = model.module.score(batch)
loss.backward()
if clip is not None:
_ = torch.nn.utils.clip_grad_norm(model.parameters(), clip)
optimizer.step()
optimizer.zero_grad()
loss = loss.data.cpu().tolist()
epoch_loss += loss
pr.set_description("train loss: {}".format(epoch_loss / idx))
if lr_scheduler is not None:
lr_scheduler.step()
torch.cuda.empty_cache()
if lr_scheduler is not None:
logging.info("\nlr after epoch: {}".format(lr_scheduler.lr))
logging.info("\nepoch {}, average train epoch loss={:.5}\n".format(
num_epoch, epoch_loss / idx))
def transformed_result(preds, mask, id2label, target_all=None, pad_idx=0):
preds_cpu = []
targets_cpu = []
lc = len(id2label)
if target_all is not None:
for batch_p, batch_t, batch_m in zip(preds, target_all, mask):
for pred, true_, bm in zip(batch_p, batch_t, batch_m):
sent = []
sent_t = []
bm = bm.sum().cpu().data.tolist()
for p, t in zip(pred[:bm], true_[:bm]):
p = p.cpu().data.tolist()
p = p if p < lc else pad_idx
sent.append(p)
sent_t.append(t.cpu().data.tolist())
preds_cpu.append([id2label[w] for w in sent])
targets_cpu.append([id2label[w] for w in sent_t])
else:
for batch_p, batch_m in zip(preds, mask):
for pred, bm in zip(batch_p, batch_m):
assert len(pred) == len(bm)
bm = bm.sum().cpu().data.tolist()
sent = pred[:bm].cpu().data.tolist()
preds_cpu.append([id2label[w] for w in sent])
if target_all is not None:
return preds_cpu, targets_cpu
else:
return preds_cpu
def transformed_result_cls(preds, target_all, cls2label, return_target=True):
preds_cpu = []
targets_cpu = []
for batch_p, batch_t in zip(preds, target_all):
for pred, true_ in zip(batch_p, batch_t):
preds_cpu.append(cls2label[pred.cpu().data.tolist()])
if return_target:
targets_cpu.append(cls2label[true_.cpu().data.tolist()])
if return_target:
return preds_cpu, targets_cpu
return preds_cpu
def validate_step(dl, model, id2label, sup_labels, id2cls=None):
model.eval()
idx = 0
preds_cpu, targets_cpu = [], []
preds_cpu_cls, targets_cpu_cls = [], []
for batch in tqdm(dl, total=len(dl), leave=False):
idx += 1
labels_mask, labels_ids = batch[-2:]
preds = model(batch)
if id2cls is not None:
preds, preds_cls = preds
preds_cpu_, targets_cpu_ = transformed_result_cls([preds_cls], [batch[-3]], id2cls)
preds_cpu_cls.extend(preds_cpu_)
targets_cpu_cls.extend(targets_cpu_)
preds_cpu_, targets_cpu_ = transformed_result([preds], [labels_mask], id2label, [labels_ids])
preds_cpu.extend(preds_cpu_)
targets_cpu.extend(targets_cpu_)
clf_report = flat_classification_report(targets_cpu, preds_cpu, labels=sup_labels, digits=3)
if id2cls is not None:
clf_report_cls = flat_classification_report([targets_cpu_cls], [preds_cpu_cls], digits=3)
return clf_report, clf_report_cls
return clf_report
def predict(dl, model, id2label, id2cls=None):
model.eval()
idx = 0
preds_cpu = []
preds_cpu_cls = []
for batch, sorted_idx in tqdm(dl, total=len(dl), leave=False):
idx += 1
labels_mask, labels_ids = batch[-2:]
preds = model.forward(batch)
bs = batch[0].shape[0]
if id2cls is not None:
preds, preds_cls = preds
unsorted_pred = [0] * bs
for idx, sidx in enumerate(sorted_idx):
unsorted_pred[sidx] = preds_cls[idx]
preds_cls = unsorted_pred
preds_cpu_ = transformed_result_cls([preds_cls], [preds_cls], id2cls, False)
preds_cpu_cls.extend(preds_cpu_)
unsorted_mask = [0] * bs
unsorted_pred = [0] * bs
for idx, sidx in enumerate(sorted_idx):
unsorted_pred[sidx] = preds[idx]
unsorted_mask[sidx] = labels_mask[idx]
preds_cpu_ = transformed_result([unsorted_pred], [unsorted_mask], id2label)
# print(len(preds_cpu_))
preds_cpu.extend(preds_cpu_)
if id2cls is not None:
return preds_cpu, preds_cpu_cls
# print(preds_cpu)
return preds_cpu
class NerLearner(object):
@property
def config(self):
config = {
"data": self.data.config,
"model": self.model.config,
"learner": {
"best_model_path": self.best_model_path,
"lr": self.lr,
"betas": self.betas,
"clip": self.clip,
"verbose": self.verbose,
"sup_labels": self.sup_labels,
"t_total": self.t_total,
"warmup": self.warmup,
"weight_decay": self.weight_decay,
"validate_every": self.validate_every,
"schedule": self.schedule,
"e": self.e
}
}
return config
def __init__(self, model, data, best_model_path, lr=0.001, betas=[0.8, 0.9], clip=5,
verbose=True, sup_labels=None, t_total=-1, warmup=0.1, weight_decay=0.01,
validate_every=1, schedule="warmup_linear", e=1e-6):
self.model = model
self.optimizer = BertAdam(model, lr, t_total=t_total, b1=betas[0], b2=betas[1], max_grad_norm=clip)
self.optimizer_defaults = dict(
model=model, lr=lr, warmup=warmup, t_total=t_total, schedule="warmup_linear",
b1=betas[0], b2=betas[1], e=1e-6, weight_decay=weight_decay,
max_grad_norm=clip)
self.lr = lr
self.betas = betas
self.clip = clip
self.sup_labels = sup_labels
self.t_total = t_total
self.warmup = warmup
self.weight_decay = weight_decay
self.validate_every = validate_every
self.schedule = schedule
self.data = data
self.e = e
if sup_labels is None:
sup_labels = data.id2label[1:]
self.sup_labels = sup_labels
self.best_model_path = best_model_path
self.verbose = verbose
self.history = []
self.cls_history = []
self.epoch = 0
self.clip = clip
self.best_target_metric = 0.
self.lr_scheduler = None
def save_config(self, path):
with open(path, "w") as file:
json.dump(self.config, file)
@classmethod
def from_config(cls, path, for_train=True):
with open(path, "r") as file:
config = json.load(file)
data = BertNerData.from_config(config["data"], for_train)
name = config["model"]["name"]
# TODO: release all models (now only for BertBiLSTMNCRF)
if name not in released_models:
raise NotImplemented("from_config is implemented only for {} model :(".format(config["name"]))
model = released_models[name].from_config(**config["model"]["params"])
return cls(data, model, **config["learner"])
def fit(self, epochs=100, resume_history=True, target_metric="f1"):
if not resume_history:
self.optimizer_defaults["t_total"] = epochs * len(self.data.train_dl)
self.optimizer = BertAdam(**self.optimizer_defaults)
self.history = []
self.cls_history = []
self.epoch = 0
self.best_target_metric = 0.
elif self.verbose:
logging.info("Resuming train... Current epoch {}.".format(self.epoch))
try:
for _ in range(epochs):
self.epoch += 1
self.fit_one_cycle(self.epoch, target_metric)
except KeyboardInterrupt:
pass
def fit_one_cycle(self, epoch, target_metric="f1"):
train_step(self.data.train_dl, self.model, self.optimizer, self.lr_scheduler, self.clip, epoch)
if epoch % self.validate_every == 0:
if self.data.is_cls:
rep, rep_cls = validate_step(self.data.valid_dl, self.model, self.data.id2label, self.sup_labels,
self.data.id2cls)
self.cls_history.append(rep_cls)
else:
rep = validate_step(self.data.valid_dl, self.model, self.data.id2label, self.sup_labels)
self.history.append(rep)
idx, metric = get_mean_max_metric(self.history, target_metric, True)
if self.verbose:
logging.info("on epoch {} by max_{}: {}".format(idx, target_metric, metric))
print(self.history[-1])
if self.data.is_cls:
logging.info("on epoch {} classification report:")
print(self.cls_history[-1])
# Store best model
if self.best_target_metric < metric:
self.best_target_metric = metric
if self.verbose:
logging.info("Saving new best model...")
self.save_model()
def predict(self, dl):
if self.data.is_cls:
return predict(dl, self.model, self.data.id2label, self.data.id2cls)
return predict(dl, self.model, self.data.id2label)
def save_model(self, path=None):
path = path if path else self.best_model_path
torch.save(self.model.state_dict(), path)
def load_model(self, path=None):
path = path if path else self.best_model_path
self.model.load_state_dict(torch.load(path, map_location="cuda:0"))
|
import axios from 'axios'
import global from '../global.json'
// import qs from "qs"
import store from '../store'
let request = axios.create({
baseURL: global.baseURL, // api的base_url
timeout: global.timeout // 请求超时时间
})
axios.defaults.headers.post['Content-Type'] = 'application/json';
const debug = false // 关闭后,不显示路由相关信息,用于调试
const loadingOtherUrl = [
"/work/yzmCode"
]
/****** 请求拦截器 ******/
request.interceptors.request.use(
config => {
if( loadingOtherUrl.indexOf(config.url) === -1) store.state.LOADING = true
let token = store.getters.TOKEN
let requestFormatData = config.data
config.method === 'get'
? config.params = {...config.data}
: config.data = {"data":requestFormatData}
config.headers['token'] = token
config.headers['Content-Type'] = 'application/json';
if (debug === true)
console.log( '====> ', config )
return config
}, error => { //请求错误处理
if (debug === true)
console.log('Request\'s error')
return Promise.reject(error)
})
/****** 返回拦截器 ******/
request.interceptors.response.use(
response => { //成功请求到数据
if (debug === true)
console.log('<==== ',response)
sended()
if ( parseInt( response.data.code ) === 200){
return Promise.resolve(response.data.data)
}else{
store.commit('SET_MESSAGE',{
"message" : response.data.msg,
"level" : "info"
})
}
},
error => { //响应错误处理
if (debug === true)
console.error('Response\'s error')
sended()
// store.state.globalMessage =
store.commit('SET_MESSAGE',{
"message" : error.message,
"level" : "warn"
})
Promise.reject(false)
}
)
function sended(){
store.state.LOADING = false
}
export default request
|
// The MIT License (MIT)
//
// Copyright (c) 2014 FusionCharts Technologies
//
// 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.
(function() {
var fc = angular.module('ng-fusioncharts', []);
fc.directive('fusioncharts', ['$http', function($http) {
return {
scope: {
width: '@',
height: '@',
data: '@',
dataset: '@',
categories: '@',
chart: '@',
linkeddata: '@',
trendlines: '@',
vtrendlines: '@',
annotations: '@',
colorrange: '@',
lineset: '@',
axis: '@',
connectors: '@',
pointers: '@',
value: '@',
processes: '@',
tasks: '@',
rows: '@',
columns: '@',
map: '@',
markers: '@'
},
link: function(scope, element, attrs) {
var observeConf = {
// non-data componenet observers
NDCObserver: {
'width': {
ifExist: false,
observer: function(newVal) {
if (newVal && chartConfigObject.width != newVal) {
chartConfigObject.width = newVal;
chart.resizeTo(scope.width, scope.height);
}
}
},
'height': {
ifExist: false,
observer: function(newVal) {
if (newVal && chartConfigObject.height != newVal) {
chartConfigObject.height = newVal;
chart.resizeTo(scope.width, scope.height);
}
}
},
'datasource': {
ifExist: true,
observer: function(newVal) {
if (dataStringStore.dataSource != newVal) {
dataStringStore.dataSource = newVal;
if (chartConfigObject.dataFormat === 'json') {
chartConfigObject.dataSource = JSON.parse(newVal);
setChartData();
} else {
chartConfigObject.dataSource = newVal;
if (chartConfigObject.dataFormat === 'xml') {
chart.setXMLData(newVal);
} else if (chartConfigObject.dataFormat === 'jsonurl') {
chart.setJSONUrl(newVal);
} else if (chartConfigObject.dataFormat === 'xmlurl') {
chart.setXMLUrl(newVal);
}
}
}
}
},
'type': {
ifExist: false,
observer: function(newVal) {
if (newVal && chartConfigObject.type != newVal) {
chartConfigObject.type = newVal;
createFCChart();
}
}
},
'config': {
ifExist: false,
observer: function(newVal) {
var configObj,
attr,
doReRender = false;
if (newVal) {
configObj = JSON.parse(newVal);
for (attr in configObj) {
// detect the value change
if (chartConfigObject[attr] != configObj[attr]) {
doReRender = true;
chartConfigObject[attr] = configObj[attr];
}
}
if (doReRender) {
createFCChart();
}
}
}
}
},
// data componenet observers
DCObserver: {
'chart': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.chart != newVal) {
dataStringStore.chart = newVal;
chartConfigObject.dataSource.chart = JSON.parse(newVal);
setChartData();
}
}
},
'data': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.data != newVal) {
dataStringStore.data = newVal;
chartConfigObject.dataSource.data = JSON.parse(newVal);
setChartData();
}
}
},
'categories': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.categories != newVal) {
dataStringStore.categories = newVal;
chartConfigObject.dataSource.categories = JSON.parse(newVal);
setChartData();
}
}
},
'dataset': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.dataset != newVal) {
dataStringStore.dataset = newVal;
chartConfigObject.dataSource.dataset = JSON.parse(newVal);
setChartData();
}
}
},
'linkeddata': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.linkeddata != newVal) {
dataStringStore.linkeddata = newVal;
chartConfigObject.dataSource.linkeddata = JSON.parse(newVal);
setChartData();
}
}
},
'trendlines': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.trendlines != newVal) {
dataStringStore.trendlines = newVal;
chartConfigObject.dataSource.trendlines = JSON.parse(newVal);
setChartData();
}
}
},
'vtrendlines': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.vtrendlines != newVal) {
dataStringStore.vtrendlines = newVal;
chartConfigObject.dataSource.vtrendlines = JSON.parse(newVal);
setChartData();
}
}
},
'annotations': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.annotations != newVal) {
dataStringStore.annotations = newVal;
chartConfigObject.dataSource.annotations = JSON.parse(newVal);
setChartData();
}
}
},
'colorrange': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.colorrange != newVal) {
dataStringStore.colorrange = newVal;
chartConfigObject.dataSource.colorrange = JSON.parse(newVal);
setChartData();
}
}
},
'lineset': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.lineset != newVal) {
dataStringStore.lineset = newVal;
chartConfigObject.dataSource.lineset = JSON.parse(newVal);
setChartData();
}
}
},
'axis': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.axis != newVal) {
dataStringStore.axis = newVal;
chartConfigObject.dataSource.axis = JSON.parse(newVal);
setChartData();
}
}
},
'connectors': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.connectors != newVal) {
dataStringStore.connectors = newVal;
chartConfigObject.dataSource.connectors = JSON.parse(newVal);
setChartData();
}
}
},
'pointers': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.pointers != newVal) {
dataStringStore.pointers = newVal;
chartConfigObject.dataSource.pointers = JSON.parse(newVal);
setChartData();
}
}
},
'value': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.value != newVal) {
dataStringStore.value = newVal;
chartConfigObject.dataSource.value = JSON.parse(newVal);
setChartData();
}
}
},
'processes': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.processes != newVal) {
dataStringStore.processes = newVal;
chartConfigObject.dataSource.processes = JSON.parse(newVal);
setChartData();
}
}
},
'tasks': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.tasks != newVal) {
dataStringStore.tasks = newVal;
chartConfigObject.dataSource.tasks = JSON.parse(newVal);
setChartData();
}
}
},
'rows': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.rows != newVal) {
dataStringStore.rows = newVal;
chartConfigObject.dataSource.rows = JSON.parse(newVal);
setChartData();
}
}
},
'columns': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.columns != newVal) {
dataStringStore.columns = newVal;
chartConfigObject.dataSource.columns = JSON.parse(newVal);
setChartData();
}
}
},
'map': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.map != newVal) {
dataStringStore.map = newVal;
chartConfigObject.dataSource.map = JSON.parse(newVal);
setChartData();
}
},
},
'markers': {
ifExist: true,
observer: function(newVal) {
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.markers != newVal) {
dataStringStore.markers = newVal;
chartConfigObject.dataSource.markers = JSON.parse(newVal);
setChartData();
}
}
},
}
},
eventsObj = {},
attribs = Object.keys(attrs),
chart = null,
events = {
'*': function(ev, props) {
if (eventsObj.hasOwnProperty(ev.eventType)) {
eventsObj[ev.eventType](ev, props);
}
}
},
setDataTimer,
setChartData = function() {
// clear previous dataUpdate timer
if (setDataTimer) {
clearTimeout(setDataTimer);
}
// Update the data with setTimeout
// This will solve the issue of consiquitive data update within very small interval
setDataTimer = setTimeout(function() {
if (chart && chart.setJSONData) {
chart.setJSONData(chartConfigObject.dataSource);
}
}, 100);
},
createFCChart = function() {
// dispose if previous chart exists
if (chart && chart.dispose) {
chart.dispose();
}
chart = new FusionCharts(chartConfigObject);
/* @todo validate the ready function whether it can be replaced in a better way */
angular.element(document).ready(function(){
element.ready(function(){
// Render the chart only when angular is done compiling the element and DOM.
chart = chart.render();
scope[attrs.chartobject] = chart;
});
});
},
dataStringStore = {},
i,
attr,
_eobj,
key,
observableAttr,
chartConfigObject,
configObj,
dataComponent,
eventScopeArr,
l;
if (attrs.events) {
eventScopeArr = attrs.events.split(".");
l = eventScopeArr.length;
_eobj = scope.$parent;
for (i = 0; i < l; i += 1){
_eobj = _eobj && _eobj[eventScopeArr[i]];
}
if (_eobj) {
for (key in _eobj) {
if (_eobj.hasOwnProperty(key)) {
eventsObj[key.toLowerCase()] = _eobj[key];
}
}
}
}
for (i = 0; i < attribs.length; i++) {
attr = attribs[i];
if (attr.match(/^on/i)) {
key = attr.slice(2).toLowerCase();
eventsObj[key] = scope.$parent[attrs[attr]];
}
}
chartConfigObject = {
type: attrs.type,
width: attrs.width,
height: attrs.height,
renderAt: element[0],
id: attrs.chartid,
dataFormat: attrs.dataformat || 'json',
dataSource: {},
events: events
};
for (observableAttr in observeConf.NDCObserver) {
attrConfig = observeConf.NDCObserver[observableAttr];
if (attrConfig.ifExist === false || attrs[observableAttr]) {
attrs.$observe(observableAttr, attrConfig.observer);
}
}
if (attrs.datasource) {
chartConfigObject.dataSource = (chartConfigObject.dataFormat === 'json') ? JSON.parse(attrs.datasource) : attrs.datasource;
dataStringStore.dataSource = attrs.datasource;
}
for (observableAttr in observeConf.DCObserver) {
attrConfig = observeConf.DCObserver[observableAttr];
dataComponent = attrs[observableAttr];
if (dataComponent) {
attrs.$observe(observableAttr, attrConfig.observer);
dataStringStore[observableAttr] = dataComponent;
if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource === "object") {
chartConfigObject.dataSource[observableAttr] = JSON.parse(dataComponent);
}
} else if (attrConfig.ifExist === false) {
attrs.$observe(observableAttr, attrConfig.observer);
}
}
// add configurations from config
if (attrs.config) {
configObj = JSON.parse(attrs.config);
for (attr in configObj) {
chartConfigObject[attr] = configObj[attr];
}
}
createFCChart();
}
};
}]);
}());
|
define(['vendor/lodash', 'vendor/jquery', 'resolvers/resolver'],
function (_, $, Resolver) {
'use strict';
var LocalResolver = Resolver.extend({
});
return LocalResolver;
});
|
import React from 'react';
import { CmsStaticPage } from 'crownpeak-dxm-react-sdk';
import { SimpleComponent } from './simple-component';
let SimplePage;
export default SimplePage = (props) => {
let isLoaded = CmsStaticPage.load(266812, useState, useEffect);
var cmsSuppressFolder = true;
var cmsSuppressModel = true;
var cmsUseTmf = true;
var cmsUseMetadata = true;
var cmsWrapper = "SimpleWrapper";
return (
isLoaded &&
<div>
<h1><SimpleComponent /></h1>
<h2><SimpleComponent /></h2>
</div>
)
}
|
const {
transformProfile,
transformAdvisers,
transformCheckboxes,
transformRadioButtons,
transformInvestorTypes,
transformRequiredChecks,
} = require('../transformers')
const {
getInvestorDetailsOptions,
getInvestorRequirementsOptions,
getLocationOptions,
} = require('../options')
const {
INVESTOR_DETAILS,
INVESTOR_REQUIREMENTS,
LOCATION,
} = require('../sections')
const { assetClassSectors } = require('../constants')
const { getCompanyProfiles } = require('../repos')
const { get } = require('lodash')
const urls = require('../../../../../../lib/urls')
const getCompanyProfile = async (req, company, editing) => {
const profiles = await getCompanyProfiles(req, company.id)
const profile = profiles.results && profiles.results[0]
return profile ? transformProfile(Object.freeze(profile), editing) : profile
}
const renderProfile = async (req, res, next) => {
const { company, returnUrl, dnbRelatedCompaniesCount } = res.locals
const { editing } = req.query
try {
const profile = await getCompanyProfile(req, company, editing)
const editType = get(profile, 'editing')
if (editType === INVESTOR_DETAILS) {
await Promise.all(getInvestorDetailsOptions(req)).then(
([investorTypeMD, requiredCheckMD, adviserMD]) => {
profile.investorDetails.investorType.items = transformInvestorTypes(
investorTypeMD,
profile.investorDetails
)
profile.investorDetails.requiredChecks = transformRequiredChecks(
requiredCheckMD,
profile.investorDetails
)
profile.investorDetails.requiredChecks.cleared.advisers = transformAdvisers(
adviserMD.results
)
profile.investorDetails.requiredChecks.issuesIdentified.advisers = transformAdvisers(
adviserMD.results
)
}
)
} else if (editType === INVESTOR_REQUIREMENTS) {
await Promise.all(getInvestorRequirementsOptions(req)).then(
([
dealTicketSizeMD,
assetClassesMD,
investmentTypeMD,
minimumReturnRateMD,
timeHorizonMD,
restrictionMD,
constructionRiskMD,
minimumEquityPercentageMD,
desiredDealRoleMD,
]) => {
const {
dealTicketSizes,
assetClasses,
investmentTypes,
minimumReturnRate,
timeHorizons,
restrictions,
constructionRisks,
minimumEquityPercentage,
desiredDealRoles,
} = profile.investorRequirements
profile.investorRequirements.dealTicketSizes.items = transformCheckboxes(
dealTicketSizeMD,
dealTicketSizes
)
const energyAndInfrastructureMD = assetClassesMD.filter(
(item) =>
item.sector === assetClassSectors.ENERGY_AND_INFRASTRUCTURE
)
profile.investorRequirements.assetClasses.energyAndInfrastructure.items = transformCheckboxes(
energyAndInfrastructureMD,
assetClasses.energyAndInfrastructure
)
const realEstateMD = assetClassesMD.filter(
(item) => item.sector === assetClassSectors.REAL_ESTATE
)
profile.investorRequirements.assetClasses.realEstate.items = transformCheckboxes(
realEstateMD,
assetClasses.realEstate
)
profile.investorRequirements.investmentTypes.items = transformCheckboxes(
investmentTypeMD,
investmentTypes
)
profile.investorRequirements.minimumReturnRate.items = transformRadioButtons(
minimumReturnRateMD,
minimumReturnRate
)
profile.investorRequirements.timeHorizons.items = transformCheckboxes(
timeHorizonMD,
timeHorizons
)
profile.investorRequirements.restrictions.items = transformCheckboxes(
restrictionMD,
restrictions
)
profile.investorRequirements.constructionRisks.items = transformCheckboxes(
constructionRiskMD,
constructionRisks
)
profile.investorRequirements.minimumEquityPercentage.items = transformRadioButtons(
minimumEquityPercentageMD,
minimumEquityPercentage
)
profile.investorRequirements.desiredDealRoles.items = transformCheckboxes(
desiredDealRoleMD,
desiredDealRoles
)
}
)
} else if (editType === LOCATION) {
await Promise.all(getLocationOptions(req)).then(
([regions, countries]) => {
profile.location.uk_region_locations.items = regions
profile.location.other_countries_being_considered.items = countries
}
)
}
res.render(
'companies/apps/investments/large-capital-profile/views/profile',
{
profile,
props: {
company,
breadcrumbs: [
{ link: urls.dashboard(), text: 'Home' },
{ link: urls.companies.index(), text: 'Companies' },
{ link: urls.companies.detail(company.id), text: company.name },
{ text: 'Investment' },
],
returnUrl,
dnbRelatedCompaniesCount,
},
}
)
} catch (error) {
next(error)
}
}
module.exports = renderProfile
|
var pug = require('pug')
var search = require('../search')
var config = require('../config')
module.exports = function (req, res) {
var locals = {
config: config.get(),
section: 'manage',
privateSubmissions: [],
publicSubmissions: [],
user: req.user
}
/*
var criteria = [
'?collection a sbol2:Collection .',
'?collection synbiohub:uploadedBy "' + req.user.email + '" .',
'?collection sbol2:member ?subject .'
].join('\n') */
var userCriteria = '{ ?subject synbiohub:uploadedBy "' + req.user.email + '" } UNION { ?subject sbh:ownedBy <' + config.get('databasePrefix') + 'user/' + req.user.username + '> } .'
var criteria = [
'?subject a sbol2:Collection . ' + userCriteria +
'FILTER NOT EXISTS { ?otherCollection sbol2:member ?subject }'
].join('\n')
var foundURIs = {}
Promise.all([
search(null, criteria, undefined, undefined).then((searchRes) => {
const results = searchRes.results
locals.publicSubmissions = results.map((result) => {
result.triplestore = 'public'
foundURIs[result.uri] = true
return result
})
}),
search(req.user.graphUri, criteria, undefined, undefined).then((searchRes) => {
const results = searchRes.results
locals.privateSubmissions = results.filter((result) => {
return !foundURIs[result.uri]
}).map((result) => {
result.triplestore = 'private'
return result
})
})
]).then(function renderPage (next) {
if (!req.accepts('text/html')) {
var result = locals.privateSubmissions.concat(locals.publicSubmissions)
return res.status(200).header('content-type', 'application/json').send(JSON.stringify(result))
} else {
locals.removePublicEnabled = config.get('removePublicEnabled')
res.send(pug.renderFile('templates/views/manage.jade', locals))
}
})
}
|
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-734d7fc7"],{"166a":function(t,a,e){},"1a5c":function(t,a,e){"use strict";var i=e("4a35"),n=e.n(i);n.a},3860:function(t,a,e){"use strict";var i=e("604c");a["a"]=i["a"].extend({name:"button-group",provide:function(){return{btnToggle:this}},computed:{classes:function(){return i["a"].options.computed.classes.call(this)}},methods:{genData:i["a"].options.methods.genData}})},"4a35":function(t,a,e){},"604c":function(t,a,e){"use strict";e.d(a,"a",(function(){return o}));e("4de4"),e("7db0"),e("c740"),e("4160"),e("caad"),e("c975"),e("fb6a"),e("a434"),e("a9e3"),e("2532"),e("159b");var i=e("5530"),n=(e("166a"),e("a452")),s=e("7560"),l=e("58df"),r=e("d9bd"),o=Object(l["a"])(n["a"],s["a"]).extend({name:"base-item-group",props:{activeClass:{type:String,default:"v-item--active"},mandatory:Boolean,max:{type:[Number,String],default:null},multiple:Boolean},data:function(){return{internalLazyValue:void 0!==this.value?this.value:this.multiple?[]:void 0,items:[]}},computed:{classes:function(){return Object(i["a"])({"v-item-group":!0},this.themeClasses)},selectedIndex:function(){return this.selectedItem&&this.items.indexOf(this.selectedItem)||-1},selectedItem:function(){if(!this.multiple)return this.selectedItems[0]},selectedItems:function(){var t=this;return this.items.filter((function(a,e){return t.toggleMethod(t.getValue(a,e))}))},selectedValues:function(){return null==this.internalValue?[]:Array.isArray(this.internalValue)?this.internalValue:[this.internalValue]},toggleMethod:function(){var t=this;if(!this.multiple)return function(a){return t.internalValue===a};var a=this.internalValue;return Array.isArray(a)?function(t){return a.includes(t)}:function(){return!1}}},watch:{internalValue:"updateItemsState",items:"updateItemsState"},created:function(){this.multiple&&!Array.isArray(this.internalValue)&&Object(r["c"])("Model must be bound to an array if the multiple property is true.",this)},methods:{genData:function(){return{class:this.classes}},getValue:function(t,a){return null==t.value||""===t.value?a:t.value},onClick:function(t){this.updateInternalValue(this.getValue(t,this.items.indexOf(t)))},register:function(t){var a=this,e=this.items.push(t)-1;t.$on("change",(function(){return a.onClick(t)})),this.mandatory&&!this.selectedValues.length&&this.updateMandatory(),this.updateItem(t,e)},unregister:function(t){if(!this._isDestroyed){var a=this.items.indexOf(t),e=this.getValue(t,a);this.items.splice(a,1);var i=this.selectedValues.indexOf(e);if(!(i<0)){if(!this.mandatory)return this.updateInternalValue(e);this.multiple&&Array.isArray(this.internalValue)?this.internalValue=this.internalValue.filter((function(t){return t!==e})):this.internalValue=void 0,this.selectedItems.length||this.updateMandatory(!0)}}},updateItem:function(t,a){var e=this.getValue(t,a);t.isActive=this.toggleMethod(e)},updateItemsState:function(){var t=this;this.$nextTick((function(){if(t.mandatory&&!t.selectedItems.length)return t.updateMandatory();t.items.forEach(t.updateItem)}))},updateInternalValue:function(t){this.multiple?this.updateMultiple(t):this.updateSingle(t)},updateMandatory:function(t){if(this.items.length){var a=this.items.slice();t&&a.reverse();var e=a.find((function(t){return!t.disabled}));if(e){var i=this.items.indexOf(e);this.updateInternalValue(this.getValue(e,i))}}},updateMultiple:function(t){var a=Array.isArray(this.internalValue)?this.internalValue:[],e=a.slice(),i=e.findIndex((function(a){return a===t}));this.mandatory&&i>-1&&e.length-1<1||null!=this.max&&i<0&&e.length+1>this.max||(i>-1?e.splice(i,1):e.push(t),this.internalValue=e)},updateSingle:function(t){var a=t===this.internalValue;this.mandatory&&a||(this.internalValue=a?void 0:t)}},render:function(t){return t("div",this.genData(),this.$slots.default)}});o.extend({name:"v-item-group",provide:function(){return{itemGroup:this}}})},"7e58":function(t,a,e){},9296:function(t,a,e){"use strict";var i=function(){var t=this,a=t.$createElement,e=t._self._c||a;return e("div",{staticClass:"col-4 card"},[e("h1",{staticClass:"b__title"},[t._v(" 如何获取金币? ")]),e("div",{staticClass:"rounded-borders mt-3 mb-3"},[t._v(" 关于如何获取金币,这里有详细介绍 "),e("router-link",{staticClass:"font-weight-bold",attrs:{to:"/topic/5f5ed360eb94dc22e5f8b70b"}},[t._v("获取金币的方法")])],1),e("ads_box_list")],1)},n=[],s={name:"rightpanel"},l=s,r=e("2877"),o=Object(r["a"])(l,i,n,!1,null,"937f1c22",null);a["a"]=o.exports},"9f4f":function(t,a,e){"use strict";e.r(a);var i=function(){var t=this,a=t.$createElement,e=t._self._c||a;return e("div",{staticClass:"row m-100"},[e("div",{staticClass:"col-8 card"},[e("h1",{staticClass:"b__title"},[t._v(" 升级VIP ")]),t.vip_configs?e("ul",{staticClass:"product-info"},[e("div",{staticClass:"ccp_four_item_list cl"},t._l(t.vip_configs,(function(a){return e("div",{key:a.id,staticClass:"ccpoil_product col-6",class:{active:t.select_id==a.id},attrs:{"data-code":"0",title:"年度VIP"},on:{click:function(e){return t.select_item(a["id"])}}},[e("div",{staticClass:"ccpoil_product_name"},[t._v(t._s(a["title"]))]),a.day_pay?e("div",{staticClass:"ccpoil_marketing"},[t._v(t._s(a.day_pay)+" 元/天")]):t._e(),a.add_gold?e("div",{staticClass:"ccpoil_marketing "},[t._v(" 赠送 "),e("span",{staticClass:"font-weight-bold mr-1 ml-1 add_gold"},[t._v(t._s(a.add_gold))]),t._v(" 金币 ")]):t._e(),e("div",{staticClass:"ccpoil_price"},[e("div",{staticClass:"ccpoil_currency"},[t._v("¥")]),e("div",{staticClass:"ccpoil_final_price"},[t._v(t._s(a["amount"]))])])])})),0),t.faka?e("div",{staticClass:"vip__code"},[e("p",{staticClass:"tip"},[t._v(" 支持使用微信,支付宝购买卡密,激活。 ")]),e("p",[e("a",{attrs:{href:t.faka,target:"_blank"}},[t._v("点此购买")])]),t._m(0)]):t._e()]):t._e(),e("div",{staticClass:"pay_way mt-4"},[e("p",[t._v("支付方式:")]),e("v-btn-toggle",{staticClass:"flex-wrap",attrs:{group:""},model:{value:t.pay_way,callback:function(a){t.pay_way=a},expression:"pay_way"}},t._l(t.avaliable_payways,(function(a){return e("v-btn",{key:a.pay_way,class:{"v-item--active":a.pay_way==t.pay_way},attrs:{value:a.pay_way}},[t._v(" "+t._s(a.name)+" ")])})),1)],1),e("div",{staticClass:"submit xxbtn mt-3"},[e("v-btn",{staticClass:"pay-button",attrs:{color:"error",loading:t.pay_loading,large:"",dark:"",depressed:""},on:{click:function(a){return t.click_pay()}}},[t._v(" 点击支付 ")])],1)]),e("rightpanel")],1)},n=[function(){var t=this,a=t.$createElement,e=t._self._c||a;return e("p",[e("a",{staticStyle:{"font-size":"1.25rem"},attrs:{href:"/vip/code",target:"_blank"}},[t._v("卡密激活")])])}],s=(e("4160"),e("c975"),e("159b"),e("a026")),l=e("f51c"),r=e("ada0"),o=e("9296"),u={name:"vip",components:{rightpanel:o["a"]},data:function(){return{vip_configs:l["configs"],avaliable_conf:r,pay_way:r.defalut,which_pay:r.defalut,select_id:"1year",pay_url:"",pay_loading:!1,avaliable_payways:[]}},created:function(){window._t=this,this.update_payways(),this.$ga.event({eventCategory:"buy_vip",eventAction:"show",eventLabel:"islogin",eventValue:this.$store.state.hasLogin})},computed:{faka:function(){var t=this.get_pay_item(this.select_id);if(t)return t.faka}},methods:{get_pay_item:function(t){for(var a=0;a<this.vip_configs.length;++a){var e=this.vip_configs[a];if(e["id"]==t)return e}},update_payways:function(){var t=this;this.avaliable_payways=[];var a=this.get_pay_item(this.select_id);this.avaliable_conf.list.forEach((function(e){if(0!=e.avaliable&&(!e["only_mobile"]||t.is_mobile())){var i=e["pay_amounts"];i?(console.log("pay_amounts:",i," this_pay_item['amount']:",a["amount"]),i.indexOf(a["amount"])>=0&&t.avaliable_payways.push(e)):t.avaliable_payways.push(e)}}))},on_id_change:function(){s["a"].nextTick(this.update_payways())},select_item:function(t){this.select_id=t,this.update_payways()},click_pay:function(){var t=this;if("faka"==this.pay_way)return this.navigateToUrl(this.faka);if("crypto"==this.pay_way)return this.$router.push("/pay/crypto?vip_id="+this.select_id);this.pay_url=!1;var a={"pay-way":this.pay_way,"vip-id":this.select_id};this.pay_loading=!0,this.$axios.post("/app/pay/payment",a).then((function(a){t.pay_loading=!1;var e=a.data;t.$messageX("请求支付成功,请稍等 ,正在跳转");var i=e.pay_data.read_url;setTimeout((function(){t.navigateToUrl(i)}),200),t.pay_url=i})).catch((function(a){console.log("error:",a);var e="请求支付失败,请重新尝试或者更换支付方式";t.$messageX(e),t.pay_loading=!1}))}}},c=u,d=(e("1a5c"),e("2877")),p=e("6544"),h=e.n(p),_=e("8336"),y=e("a609"),f=Object(d["a"])(c,i,n,!1,null,"a97e7d78",null);a["default"]=f.exports;h()(f,{VBtn:_["a"],VBtnToggle:y["a"]})},a609:function(t,a,e){"use strict";var i=e("5530"),n=(e("7e58"),e("3860")),s=e("a9ad"),l=e("58df");a["a"]=Object(l["a"])(n["a"],s["a"]).extend({name:"v-btn-toggle",props:{backgroundColor:String,borderless:Boolean,dense:Boolean,group:Boolean,rounded:Boolean,shaped:Boolean,tile:Boolean},computed:{classes:function(){return Object(i["a"])(Object(i["a"])({},n["a"].options.computed.classes.call(this)),{},{"v-btn-toggle":!0,"v-btn-toggle--borderless":this.borderless,"v-btn-toggle--dense":this.dense,"v-btn-toggle--group":this.group,"v-btn-toggle--rounded":this.rounded,"v-btn-toggle--shaped":this.shaped,"v-btn-toggle--tile":this.tile},this.themeClasses)}},methods:{genData:function(){var t=this.setTextColor(this.color,Object(i["a"])({},n["a"].options.methods.genData.call(this)));return this.group?t:this.setBackgroundColor(this.backgroundColor,t)}}})},ada0:function(t){t.exports=JSON.parse('{"list":[{"name":"支付宝2","pay_way":"alipay","which_pay":"jxdonglang","avaliable":true},{"name":"支付宝(荐)","pay_way":"alipay_h5","which_pay":"jxdonglang","avaliable":true},{"name":"支付宝1","pay_way":"ALIPAY2ALIQR","which_pay":"mypay","avaliable":false},{"name":"微信支付","pay_way":"wxwap","which_pay":"hypay","pay_amounts":[100,200],"avaliable":false},{"name":"支付宝","pay_way":"zfbwap","which_pay":"hypay","only_mobile":false,"avaliable":false},{"name":"数字货币(USDT)","pay_way":"crypto","which_pay":"xpay","avaliable":true,"class":"red"}],"tips":"如果碰到支付失败,请尝试更换支付方式,谢谢","defalut":"alipay_h5"}')},f51c:function(t){t.exports=JSON.parse('{"configs":[{"id":"30day","days":30,"amount":69,"title":"一个月VIP","description":"一个月VIP,可不限制下载任何内容","actual_amount":69,"every_month":69,"vip_degree":"vip1","day_pay":"2.1","add_gold":600},{"id":"halfyear","days":90,"amount":99,"title":"三个月VIP","description":"三个月不限制看下载任何内容","actual_amount":99,"vip_degree":"vip2","day_pay":"0.5","add_gold":1000},{"id":"1year","days":365,"amount":199,"title":"一年VIP","description":"一年不限制看下载任何内容","actual_amount":199,"every_month":199,"vip_degree":"vip3","day_pay":"0.2","add_gold":2000},{"id":"threeyear","days":1096,"amount":299,"title":"三年VIP","description":"三年不限制看下载任何内容","actual_amount":299,"vip_degree":"vip4","day_pay":"0.1","add_gold":3000}]}')}}]);
//# sourceMappingURL=chunk-734d7fc7.3c97df21.js.map
|
const fs = require('fs');
const file = 'weka.txt';
const readStream = fs.createReadStream(file);
let progress = 0;
fs.stat(file, (err,data) =>{
const total = data.size;
readStream.on('data', (chunk) => {
progress += chunk.length;
console.log(Math.round((progress * 100)/total));
});
});
readStream.on('end',() => {
console.log('veri okunması tamamlandı..');
});
|
/**
* Listen to all available events and output to the logger
* @param {AddonBase inherited} interface object to register and send events
*/
const functionExampleMonitorAndConfig = (interface) => {
// register all event listeners to log what happens
interface.registerListener('images-loaded', () => interface.logger.warn('images-loaded'));
interface.registerListener('renderer-ready', () => interface.logger.warn('renderer-ready'));
interface.registerListener('deleteImage', index => interface.logger.info('deleteImage', index));
interface.registerListener('imageDeleted', () => interface.logger.info('imageDeleted'));
interface.registerListener('paused', (status) => interface.logger.info('paused', status));
interface.registerListener('muted', (status) => interface.logger.info('muted', status));
interface.registerListener('recordStarted', () => interface.logger.info('recordStarted'));
interface.registerListener('recordStopped', () => interface.logger.info('recordStoppedAddon'));
interface.registerListener('recordError', () => interface.logger.info('recordErrorAddon'));
interface.registerListener('unstarImage', index => interface.logger.info('unstarImage', index));
interface.registerListener('starImage', index => interface.logger.info('starImage', index));
interface.registerListener('changingActiveImage', (index, fadeTime) => interface.logger.info('changingActiveImage', index, fadeTime, interface.images[index].src));
interface.registerListener('changedActiveImage', index => interface.logger.info('changedActiveImage', index, interface.images[index].src));
interface.registerListener('newImage', (sender, type) => {
let unseenCnt = 0;
interface.images.forEach(img => unseenCnt += (img.unseen ? 1 : 0));
interface.logger.info('newImage', sender, type, `Unseen images: ${unseenCnt}`);
});
interface.registerListener('removeImageUnseen', () => interface.logger.info('removeImageUnseen'));
interface.registerListener('imageUnseenRemoved', () => interface.logger.info('imageUnseenRemoved'));
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
module.exports = functionExampleMonitorAndConfig;
}
|
/*!
* Keen UI v1.3.0 (https://github.com/JosephusPaye/keen-ui)
* (c) 2020 Josephus Paye II
* Released under the MIT License.
*/
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.UiTab=t():(e.KeenUI=e.KeenUI||{},e.KeenUI.UiTab=t())}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=258)}({0:function(e,t){e.exports=function(){var e=[];return e.toString=function(){for(var e=[],t=0;t<this.length;t++){var n=this[t];n[2]?e.push("@media "+n[2]+"{"+n[1]+"}"):e.push(n[1])}return e.join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var r={},i=0;i<this.length;i++){var o=this[i][0];"number"==typeof o&&(r[o]=!0)}for(i=0;i<t.length;i++){var a=t[i];"number"==typeof a[0]&&r[a[0]]||(n&&!a[2]?a[2]=n:n&&(a[2]="("+a[2]+") and ("+n+")"),e.push(a))}},e}},1:function(e,t){e.exports=function(e,t,n,r,i){var o,a=e=e||{},s=typeof e.default;"object"!==s&&"function"!==s||(o=e,a=e.default);var u="function"==typeof a?a.options:a;t&&(u.render=t.render,u.staticRenderFns=t.staticRenderFns),r&&(u._scopeId=r);var c;if(i?(c=function(e){e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,e||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),n&&n.call(this,e),e&&e._registeredComponents&&e._registeredComponents.add(i)},u._ssrRegister=c):n&&(c=n),c){var d=u.functional,f=d?u.render:u.beforeCreate;d?u.render=function(e,t){return c.call(t),f(e,t)}:u.beforeCreate=f?[].concat(f,c):[c]}return{esModule:o,exports:a,options:u}}},123:function(e,t,n){"use strict";function r(e){n(222)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(147),o=n(198),a=n(1),s=r,u=null,c=null,d=a(i.a,o.a,s,u,c);t.default=d.exports},147:function(e,t,n){"use strict";var r=n(89);t.a={name:"ui-tab",props:{id:{type:String,default:function(){return r.a.short("ui-tab-")}},title:String,selected:{type:Boolean,default:!1},disabled:{type:Boolean,default:!1}},data:function(){return{isActive:!1}},watch:{disabled:function(){this.$parent.onTabDisabledChange(this)}},created:function(){this.$parent.addTab(this)},beforeDestroy:function(){this.$parent.removeTab(this)},methods:{activate:function(){this.isActive=!0,this.$emit("select",this.id)},deactivate:function(){this.isActive=!1,this.$emit("deselect",this.id)}}}},170:function(e,t,n){t=e.exports=n(0)(),t.push([e.i,".ui-tab{outline:none}",""])},198:function(e,t,n){"use strict";var r=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{directives:[{name:"show",rawName:"v-show",value:e.isActive,expression:"isActive"}],staticClass:"ui-tab",attrs:{role:"tabpanel","aria-hidden":e.isActive?null:"true",id:e.id,tabindex:e.isActive?"0":null}},[e._t("default")],2)},i=[],o={render:r,staticRenderFns:i};t.a=o},2:function(e,t,n){function r(e){for(var t=0;t<e.length;t++){var n=e[t],r=d[n.id];if(r){r.refs++;for(var i=0;i<r.parts.length;i++)r.parts[i](n.parts[i]);for(;i<n.parts.length;i++)r.parts.push(o(n.parts[i]));r.parts.length>n.parts.length&&(r.parts.length=n.parts.length)}else{for(var a=[],i=0;i<n.parts.length;i++)a.push(o(n.parts[i]));d[n.id]={id:n.id,refs:1,parts:a}}}}function i(){var e=document.createElement("style");return e.type="text/css",f.appendChild(e),e}function o(e){var t,n,r=document.querySelector('style[data-vue-ssr-id~="'+e.id+'"]');if(r){if(h)return v;r.parentNode.removeChild(r)}if(m){var o=p++;r=l||(l=i()),t=a.bind(null,r,o,!1),n=a.bind(null,r,o,!0)}else r=i(),t=s.bind(null,r),n=function(){r.parentNode.removeChild(r)};return t(e),function(r){if(r){if(r.css===e.css&&r.media===e.media&&r.sourceMap===e.sourceMap)return;t(e=r)}else n()}}function a(e,t,n,r){var i=n?"":r.css;if(e.styleSheet)e.styleSheet.cssText=g(t,i);else{var o=document.createTextNode(i),a=e.childNodes;a[t]&&e.removeChild(a[t]),a.length?e.insertBefore(o,a[t]):e.appendChild(o)}}function s(e,t){var n=t.css,r=t.media,i=t.sourceMap;if(r&&e.setAttribute("media",r),i&&(n+="\n/*# sourceURL="+i.sources[0]+" */",n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */"),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}var u="undefined"!=typeof document;if("undefined"!=typeof DEBUG&&DEBUG&&!u)throw new Error("vue-style-loader cannot be used in a non-browser environment. Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.");var c=n(3),d={},f=u&&(document.head||document.getElementsByTagName("head")[0]),l=null,p=0,h=!1,v=function(){},m="undefined"!=typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());e.exports=function(e,t,n){h=n;var i=c(e,t);return r(i),function(t){for(var n=[],o=0;o<i.length;o++){var a=i[o],s=d[a.id];s.refs--,n.push(s)}t?(i=c(e,t),r(i)):i=[];for(var o=0;o<n.length;o++){var s=n[o];if(0===s.refs){for(var u=0;u<s.parts.length;u++)s.parts[u]();delete d[s.id]}}}};var g=function(){var e=[];return function(t,n){return e[t]=n,e.filter(Boolean).join("\n")}}()},222:function(e,t,n){var r=n(170);"string"==typeof r&&(r=[[e.i,r,""]]),r.locals&&(e.exports=r.locals);n(2)("40388f68",r,!0)},258:function(e,t,n){e.exports=n(123)},3:function(e,t){e.exports=function(e,t){for(var n=[],r={},i=0;i<t.length;i++){var o=t[i],a=o[0],s=o[1],u=o[2],c=o[3],d={id:e+":"+i,css:s,media:u,sourceMap:c};r[a]?r[a].parts.push(d):n.push(r[a]={id:a,parts:[d]})}return n}},89:function(e,t,n){"use strict";for(var r=[],i=0;i<256;i++)r[i]=(i<16?"0":"")+i.toString(16);var o=function(){var e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return r[255&e]+r[e>>8&255]+r[e>>16&255]+r[e>>24&255]+"-"+r[255&t]+r[t>>8&255]+"-"+r[t>>16&15|64]+r[t>>24&255]+"-"+r[63&n|128]+r[n>>8&255]+"-"+r[n>>16&255]+r[n>>24&255]+r[255&i]+r[i>>8&255]+r[i>>16&255]+r[i>>24&255]},a=function(e){e=e||"";var t=o();return e+t.split("-")[0]};t.a={generate:o,short:a}}})});
|
#!/usr/bin/env python3
from jinja2 import Environment
from jinja2 import FileSystemLoader
organisation_name = input("Enter the company name (e.g. Acme Limited): ")
package_author = input("Your full name (e.g. Joe Smith): ")
github_org = input("The GitHub Organisation (e.g. AcmeLtd): ")
package_repo_url = input("The GitHub URL (e.g. git@github.com:acme/iac.git): ")
package_name = input("The package name (e.g. acme-iac-project): ")
package_description = input("The package description: ")
aws_region = input("The AWS region (e.g. eu-west-2): ")
aws_account_id = input("The AWS Account identifier (e.g. 600123456789): ")
tfstate_bucket_name = input("The Terraform bucket prefix (e.g. acme-tfstate): ")
env = Environment(
loader=FileSystemLoader("."), autoescape=True, keep_trailing_newline=True
)
# Render the README file
template = env.get_template("README.md")
template.stream(organisation_name=organisation_name).dump("README.md")
# Render the README file
template = env.get_template("package.json")
template.stream(
package_name=package_name,
package_description=package_description,
package_repo_url=package_repo_url,
package_author=package_author,
).dump("package.json")
# Render the pyproject.toml file
template = env.get_template("pyproject.toml")
template.stream(
package_name=package_name,
package_author=package_author,
package_description=package_description,
).dump("pyproject.toml")
# Render the .env-config.yaml file
template = env.get_template(".env-config.yaml")
template.stream(aws_account_id=aws_account_id).dump(".env-config.yaml")
# Render the tools/environments/iac.py file
template = env.get_template("tools/environments/iac.py")
template.stream(package_description=package_description).dump(
"tools/environments/iac.py"
)
# Render the tools/environments/test.py file
template = env.get_template("tools/environments/test.py")
template.stream(aws_account_id=aws_account_id).dump("tools/environments/test.py")
# Render the terragrunt.hcl file
template = env.get_template("components/terragrunt.hcl")
template.stream(
aws_region=aws_region,
github_org=github_org,
tfstate_bucket_name=tfstate_bucket_name,
).dump("components/terragrunt.hcl")
|
import appMain from '@cdo/apps/appMain';
import {singleton as studioApp} from '@cdo/apps/StudioApp';
import Dance from '@cdo/apps/dance/Dance';
import blocks from '@cdo/apps/dance/blocks';
export default function loadGamelab(options) {
options.blocksModule = blocks;
const dance = new Dance();
dance.injectStudioApp(studioApp());
appMain(dance, {custom: {}}, options);
return dance;
}
|
# coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# 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.
# Lint as: python3
"""BERT-based LaserTagger runner."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import flags
from termcolor import colored
import tensorflow as tf
import run_lasertagger_utils
import utils
from curLine_file import curLine
FLAGS = flags.FLAGS
## Required parameters
flags.DEFINE_string("training_file", None,
"Path to the TFRecord training file.")
flags.DEFINE_string("eval_file", None, "Path to the the TFRecord dev file.")
flags.DEFINE_string(
"label_map_file", None,
"Path to the label map file. Either a JSON file ending with '.json', that "
"maps each possible tag to an ID, or a text file that has one tag per line.")
flags.DEFINE_string(
'slot_label_map_file', None,
'Path to the label map file. Either a JSON file ending with ".json", that '
'maps each possible tag to an ID, or a text file that has one tag per line.')
flags.DEFINE_string(
"model_config_file", None,
"The config json file specifying the model architecture.")
flags.DEFINE_string(
"output_dir", None,
"The output directory where the model checkpoints will be written. If "
"`init_checkpoint' is not provided when exporting, the latest checkpoint "
"from this directory will be exported.")
## Other parameters
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint, usually from a pre-trained BERT model. In the case of "
"exporting, one can optionally provide path to a particular checkpoint to "
"be exported here.")
flags.DEFINE_integer(
"max_seq_length", 128, # contain CLS and SEP
"The maximum total input sequence length after WordPiece tokenization. "
"Sequences longer than this will be truncated, and sequences shorter than "
"this will be padded.")
flags.DEFINE_bool("do_train", False, "Whether to run training.")
flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
flags.DEFINE_bool("do_export", False, "Whether to export a trained model.")
flags.DEFINE_bool("eval_all_checkpoints", False, "Run through all checkpoints.")
flags.DEFINE_integer(
"eval_timeout", 600,
"The maximum amount of time (in seconds) for eval worker to wait between "
"checkpoints.")
flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
flags.DEFINE_integer("eval_batch_size", 128, "Total batch size for eval.")
flags.DEFINE_integer("predict_batch_size", 8, "Total batch size for predict.")
flags.DEFINE_float("learning_rate", 3e-5, "The initial learning rate for Adam.")
flags.DEFINE_float(
"warmup_proportion", 0.1,
"Proportion of training to perform linear learning rate warmup for. "
"E.g., 0.1 = 10% of training.")
flags.DEFINE_float("num_train_epochs", 3.0,
"Total number of training epochs to perform.")
flags.DEFINE_float("drop_keep_prob", 0.9, "drop_keep_prob")
flags.DEFINE_integer("kernel_size", 2, "kernel_size")
flags.DEFINE_integer("save_checkpoints_steps", 1000,
"How often to save the model checkpoint.")
flags.DEFINE_integer("keep_checkpoint_max", 3,
"How many checkpoints to keep.")
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_integer(
"num_train_examples", None,
"Number of training examples. This is used to determine the number of "
"training steps to respect the `num_train_epochs` flag.")
flags.DEFINE_integer(
"num_eval_examples", None,
"Number of eval examples. This is used to determine the number of "
"eval steps to go through the eval file once.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
flags.DEFINE_string(
"tpu_name", None,
"The Cloud TPU to use for training. This should be either the name "
"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
"url.")
flags.DEFINE_string(
"tpu_zone", None,
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
flags.DEFINE_string("master", None,
"Optional address of the master for the workers.")
flags.DEFINE_string("export_path", None, "Path to save the exported model.")
flags.DEFINE_float("slot_ratio", 0.3, "slot_ratio")
flags.DEFINE_string(
'domain_name', None,
'Whether to lower case the input text. Should be True for uncased '
'models and False for cased models.')
flags.DEFINE_string(
'entity_type_list_file', None, 'path of entity_type_list_file')
def file_based_input_fn_builder(input_file, max_seq_length,
is_training, drop_remainder, entity_type_num):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([max_seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([max_seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([max_seq_length], tf.int64),
"labels": tf.FixedLenFeature([], tf.int64),
"slot_labels": tf.FixedLenFeature([max_seq_length], tf.int64),
"labels_mask": tf.FixedLenFeature([max_seq_length], tf.int64),
"entity_type_ids": tf.FixedLenFeature([max_seq_length*entity_type_num], tf.int64),
"sequence_lengths": tf.FixedLenFeature([], tf.int64),
}
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def input_fn(params):
"""The actual input function."""
d = tf.data.TFRecordDataset(input_file)
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
if is_training:
d = d.repeat() # 每epoch重复使用
d = d.shuffle(buffer_size=100)
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=params["batch_size"],
drop_remainder=drop_remainder))
return d
return input_fn
def _calculate_steps(num_examples, batch_size, num_epochs, warmup_proportion=0):
"""Calculates the number of steps.
Args:
num_examples: Number of examples in the dataset.
batch_size: Batch size.
num_epochs: How many times we should go through the dataset.
warmup_proportion: Proportion of warmup steps.
Returns:
Tuple (number of steps, number of warmup steps).
"""
steps = int(num_examples / batch_size * num_epochs)
warmup_steps = int(warmup_proportion * steps)
return steps, warmup_steps
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
if not (FLAGS.do_train or FLAGS.do_eval or FLAGS.do_export):
raise ValueError("At least one of `do_train`, `do_eval` or `do_export` must be True.")
model_config = run_lasertagger_utils.LaserTaggerConfig.from_json_file(
FLAGS.model_config_file)
if FLAGS.max_seq_length > model_config.max_position_embeddings:
raise ValueError(
"Cannot use sequence length %d because the BERT model "
"was only trained up to sequence length %d" %
(FLAGS.max_seq_length, model_config.max_position_embeddings))
if not FLAGS.do_export and not os.path.exists(FLAGS.output_dir):
os.makedirs(FLAGS.output_dir)
num_tags = len(utils.read_label_map(FLAGS.label_map_file))
num_slot_tags = len(utils.read_label_map(FLAGS.slot_label_map_file))
entity_type_list = utils.read_label_map(FLAGS.entity_type_list_file)[FLAGS.domain_name]
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
keep_checkpoint_max=FLAGS.keep_checkpoint_max) # ,
# tpu_config=tf.contrib.tpu.TPUConfig(
# iterations_per_loop=FLAGS.iterations_per_loop,
# per_host_input_for_training=is_per_host,
# eval_training_input_configuration=tf.contrib.tpu.InputPipelineConfig.SLICED))
if FLAGS.do_train:
num_train_steps, num_warmup_steps = _calculate_steps(
FLAGS.num_train_examples, FLAGS.train_batch_size,
FLAGS.num_train_epochs, FLAGS.warmup_proportion)
else:
num_train_steps, num_warmup_steps = None, None
entity_type_num = len(entity_type_list)
print(curLine(), "num_train_steps=",num_train_steps, "learning_rate=", FLAGS.learning_rate,
",num_warmup_steps=",num_warmup_steps, ",max_seq_length=", FLAGS.max_seq_length)
print(colored("%s restore from init_checkpoint:%s" % (curLine(), FLAGS.init_checkpoint), "red"))
model_fn = run_lasertagger_utils.ModelFnBuilder(
config=model_config,
num_tags=num_tags,
num_slot_tags=num_slot_tags,
init_checkpoint=FLAGS.init_checkpoint,
learning_rate=FLAGS.learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_tpu,
max_seq_length=FLAGS.max_seq_length,
drop_keep_prob=FLAGS.drop_keep_prob,
entity_type_num=entity_type_num,
slot_ratio=FLAGS.slot_ratio).build()
# If TPU is not available, this will fall back to normal Estimator on CPU or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size,
predict_batch_size=FLAGS.predict_batch_size
)
if FLAGS.do_train:
train_input_fn = file_based_input_fn_builder(
input_file=FLAGS.training_file,
max_seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True,
entity_type_num=entity_type_num)
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
if FLAGS.do_export:
tf.logging.info("Exporting the model to %s"% FLAGS.export_path)
def serving_input_fn():
def _input_fn():
features = {
"input_ids": tf.placeholder(tf.int64, [None, None]),
"input_mask": tf.placeholder(tf.int64, [None, None]),
"segment_ids": tf.placeholder(tf.int64, [None, None]),
"entity_type_ids": tf.placeholder(tf.int64, [None, None]),
"sequence_lengths": tf.placeholder(tf.int64, [None]),
}
return tf.estimator.export.ServingInputReceiver(
features=features, receiver_tensors=features)
return _input_fn
if not os.path.exists(FLAGS.export_path):
print(curLine(), "will make dir:%s" % FLAGS.export_path)
os.makedirs(FLAGS.export_path)
estimator.export_saved_model(
FLAGS.export_path,
serving_input_fn(),
checkpoint_path=FLAGS.init_checkpoint)
if __name__ == "__main__":
flags.mark_flag_as_required("model_config_file")
flags.mark_flag_as_required("label_map_file")
flags.mark_flag_as_required("entity_type_list_file")
tf.app.run()
|