text
stringlengths
3
1.05M
from pathlib import Path DATA_DIR = Path(__file__).resolve().parent.parent / "data"
# Copyright 2020, Kay Hayen, mailto:[email protected] # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # 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. # """ Code to generate and interact with compiled function objects. """ from nuitka.PythonVersions import python_version from .CodeHelpers import generateStatementSequenceCode from .Emission import SourceCodeCollector from .FunctionCodes import ( finalizeFunctionLocalVariables, getClosureCopyCode, getFunctionCreationArgs, getFunctionQualnameObj, setupFunctionLocalVariables, ) from .Indentation import indented from .ModuleCodes import getModuleAccessCode from .templates.CodeTemplatesGeneratorFunction import ( template_generator_exception_exit, template_generator_noexception_exit, template_generator_return_exit, template_genfunc_yielder_body_template, template_genfunc_yielder_maker_decl, template_make_empty_generator, template_make_generator, ) from .YieldCodes import getYieldReturnDispatchCode def _getGeneratorMakerIdentifier(function_identifier): return "MAKE_GENERATOR_" + function_identifier def getGeneratorObjectDeclCode(function_identifier, closure_variables): generator_creation_args = getFunctionCreationArgs( defaults_name=None, kw_defaults_name=None, annotations_name=None, closure_variables=closure_variables, ) return template_genfunc_yielder_maker_decl % { "generator_maker_identifier": _getGeneratorMakerIdentifier(function_identifier), "generator_creation_args": ", ".join(generator_creation_args), } def getGeneratorObjectCode( context, function_identifier, closure_variables, user_variables, outline_variables, temp_variables, needs_exception_exit, needs_generator_return, ): # A bit of details going on here, pylint: disable=too-many-locals setupFunctionLocalVariables( context=context, parameters=None, closure_variables=closure_variables, user_variables=user_variables + outline_variables, temp_variables=temp_variables, ) function_codes = SourceCodeCollector() generateStatementSequenceCode( statement_sequence=context.getOwner().subnode_body, allow_none=True, emit=function_codes, context=context, ) function_cleanup = finalizeFunctionLocalVariables(context) if needs_exception_exit: ( exception_type, exception_value, exception_tb, _exception_lineno, ) = context.variable_storage.getExceptionVariableDescriptions() generator_exit = template_generator_exception_exit % { "function_cleanup": indented(function_cleanup), "exception_type": exception_type, "exception_value": exception_value, "exception_tb": exception_tb, } else: generator_exit = template_generator_noexception_exit % { "function_cleanup": indented(function_cleanup) } if needs_generator_return: generator_exit += template_generator_return_exit % { "return_value": context.getReturnValueName() if python_version >= 0x300 else None } function_locals = context.variable_storage.makeCFunctionLevelDeclarations() local_type_decl = context.variable_storage.makeCStructLevelDeclarations() function_locals += context.variable_storage.makeCStructInits() generator_object_body = context.getOwner() if local_type_decl: heap_declaration = """\ struct %(function_identifier)s_locals *generator_heap = \ (struct %(function_identifier)s_locals *)generator->m_heap_storage;""" % { "function_identifier": function_identifier } else: heap_declaration = "" generator_creation_args = getFunctionCreationArgs( defaults_name=None, kw_defaults_name=None, annotations_name=None, closure_variables=closure_variables, ) return template_genfunc_yielder_body_template % { "function_identifier": function_identifier, "function_body": indented(function_codes.codes), "heap_declaration": indented(heap_declaration), "function_local_types": indented(local_type_decl), "function_var_inits": indented(function_locals), "function_dispatch": indented(getYieldReturnDispatchCode(context)), "generator_maker_identifier": _getGeneratorMakerIdentifier(function_identifier), "generator_creation_args": ", ".join(generator_creation_args), "generator_exit": generator_exit, "generator_module": getModuleAccessCode(context), "generator_name_obj": context.getConstantCode( constant=generator_object_body.getFunctionName() ), "generator_qualname_obj": getFunctionQualnameObj( generator_object_body, context ), "code_identifier": context.getCodeObjectHandle( code_object=generator_object_body.getCodeObject() ), "closure_name": "closure" if closure_variables else "NULL", "closure_count": len(closure_variables), } def generateMakeGeneratorObjectCode(to_name, expression, emit, context): generator_object_body = expression.subnode_generator_ref.getFunctionBody() closure_variables = expression.getClosureVariableVersions() closure_name, closure_copy = getClosureCopyCode( closure_variables=closure_variables, context=context ) args = [] if closure_name: args.append(closure_name) # Special case empty generators. if generator_object_body.subnode_body is None: emit( template_make_empty_generator % { "closure_copy": indented(closure_copy, 0, True), "to_name": to_name, "generator_module": getModuleAccessCode(context), "generator_name_obj": context.getConstantCode( constant=generator_object_body.getFunctionName() ), "generator_qualname_obj": getFunctionQualnameObj( generator_object_body, context ), "code_identifier": context.getCodeObjectHandle( code_object=generator_object_body.getCodeObject() ), "closure_name": closure_name if closure_name is not None else "NULL", "closure_count": len(closure_variables), } ) else: emit( template_make_generator % { "generator_maker_identifier": _getGeneratorMakerIdentifier( generator_object_body.getCodeName() ), "to_name": to_name, "args": ", ".join(str(arg) for arg in args), "closure_copy": indented(closure_copy, 0, True), } ) context.addCleanupTempName(to_name)
module.exports = { bracketSpacing: true, jsxBracketSameLine: false, singleQuote: true, trailingComma: 'all', arrowBodyStyle: false, selfClosingComp: false, };
import jinja2 from jingo import register from django.contrib.sites.models import RequestSite from django.utils.http import urlquote from funfactory.helpers import static @register.function @jinja2.contextfunction def abs_static(context, path): """Make sure we always return a FULL absolute URL that starts with 'http'. """ path = static(path) # print "AFTER", path prefix = context['request'].is_secure() and 'https' or 'http' if path.startswith('/') and not path.startswith('//'): # e.g. '/media/foo.png' root_url = '%s://%s' % (prefix, RequestSite(context['request']).domain) path = root_url + path # print "path now", path if path.startswith('//'): path = '%s:%s' % (prefix, path) assert path.startswith('http://') or path.startswith('https://') return path @register.function def show_duration(duration, include_seconds=False): hours = duration / 3600 seconds = duration % 3600 minutes = seconds / 60 seconds = seconds % 60 out = [] if hours > 1: out.append('%d hours' % hours) elif hours: out.append('1 hour') if minutes > 1: out.append('%d minutes' % minutes) elif minutes: out.append('1 minute') if include_seconds or (not hours and not minutes): if seconds > 1: out.append('%d seconds' % seconds) elif seconds: out.append('1 second') return ' '.join(out) @register.function def mozillians_permalink(username): return 'https://mozillians.org/u/%s' % urlquote(username)
var dir_9d16125b5521f63edf675630c8f67983 = [ [ "acl", "dir_963fc05e9365a8e9d159125bf9635cac.html", "dir_963fc05e9365a8e9d159125bf9635cac" ] ];
const glob = require('glob'); module.exports = function listReadmes() { const baseDir = 'src/'; const basename = 'README.md'; return glob.sync(baseDir + '**/' + basename) .map(filename => filename.substring(baseDir.length)) };
const statusCode = require("../module/utils/statusCode"); const userType = require("../module/utils/userStatus"); const responseMessage = require("../module/utils/responseMessage"); const authUtil = require("../module/utils/authUtil"); const pool = require("../module/db/pool"); const moment = require("moment"); require("moment-timezone"); const comment = { getCommentList: ({ user_idx, idx }) => { return new Promise(async (resolve, reject) => { const getCommentListQuery = `SELECT comment.*, user.name as writer FROM comment LEFT JOIN user ON writer_idx = user_idx WHERE board_idx = ? ORDER BY date`; const getCommentListResult = await pool.queryParam_Parse(getCommentListQuery, [idx]); if (getCommentListResult !== undefined) { return resolve({ json: authUtil.successTrue( statusCode.OK, responseMessage.X_READ_ALL_SUCCESS(`${idx} 댓글`), getCommentListResult ), }); } else { return resolve({ json: authUtil.successFalse( statusCode.BAD_REQUEST, responseMessage.X_READ_ALL_FAIL(`${idx} 댓글`) ), }); } }); }, postComment: ({ user_idx, title, contents, board_idx }) => { return new Promise(async (resolve, reject) => { const date = moment().format("YYYY-MM-DD HH:mm:ss"); if (!contents || !board_idx) { return resolve({ json: authUtil.successFalse(statusCode.BAD_REQUEST, responseMessage.NULL_VALUE), }); } const postCommentQuery = `INSERT INTO comment (title, contents, writer_idx, date, board_idx) VALUES (?, ?, ?, ?, ?)`; const postCommentResult = await pool.queryParam_Parse(postCommentQuery, [ title, contents, user_idx, date, board_idx, ]); if (postCommentResult.affectedRows !== 0) { return resolve({ json: authUtil.successTrue(statusCode.CREATED, responseMessage.X_CREATE_SUCCESS("댓글")), }); } else { return resolve({ json: authUtil.successFalse( statusCode.BAD_REQUEST, responseMessage.X_CREATE_FAIL("댓글") ), }); } }); }, putComment: ({ user_idx, commentIdx, title, contents }) => { return new Promise(async (resolve, reject) => { const putCommentQuery = `UPDATE comment SET title = ?, contents = ? WHERE comment_idx = ? AND writer_idx = ?`; const putCommentResult = await pool.queryParam_Parse(putCommentQuery, [ title, contents, commentIdx, user_idx, ]); if (putCommentResult.affectedRows !== 0) { return resolve({ json: authUtil.successTrue(statusCode.OK, responseMessage.X_UPDATE_SUCCESS("댓글")), }); } else { return resolve({ json: authUtil.successFalse( statusCode.BAD_REQUEST, responseMessage.X_UPDATE_FAIL("댓글") ), }); } }); }, deleteComment: ({ user_idx, commentIdx }) => { return new Promise(async (resolve, reject) => { const deleteCommentQuery = `DELETE FROM comment WHERE comment_idx = ? AND writer_idx = ?`; const deleteCommentResult = await pool.queryParam_Parse(deleteCommentQuery, [ commentIdx, user_idx, ]); if (deleteCommentResult.affectedRows !== 0) { return resolve({ json: authUtil.successTrue(statusCode.OK, responseMessage.X_DELETE_SUCCESS("댓글")), }); } else { return resolve({ json: authUtil.successFalse( statusCode.BAD_REQUEST, responseMessage.X_DELETE_FAIL("댓글") ), }); } }); }, }; module.exports = comment;
import struct import math def loadData(fName, sizeLimit=-1): f = open(fName, 'rb') iSize = struct.calcsize('i') dSize = struct.calcsize('d') dataLen = struct.unpack('>i', f.read(iSize))[0] dataSize = struct.unpack('>i', f.read(iSize))[0] if (sizeLimit >= 0): dataSize = sizeLimit print("load Data : len=%d, size=%d"%(dataLen, dataSize)) data = [None]*dataSize; for dIdx in range(dataSize): vList = [None]*dataLen for vIdx in range(dataLen): v = f.read(dSize) vList[vIdx] = struct.unpack('>d', v)[0] data[dIdx] = vList isEnd = (f.read(1) == b'') print("is valid End : %d"%isEnd) f.close() return data def loadListData(fName, sizeLimit=-1): f = open(fName, 'rb') iSize = struct.calcsize('i') dSize = struct.calcsize('d') dataLen = struct.unpack('>i', f.read(iSize))[0] dataSize = struct.unpack('>i', f.read(iSize))[0] if (sizeLimit >= 0): dataSize = sizeLimit print("load Data : len=%d, size=%d"%(dataLen, dataSize)) data = [None]*dataSize; for dIdx in range(dataSize): l = struct.unpack('>i', f.read(iSize))[0] subList = [None]*l for lIdx in range(l): vList = [None]*dataLen for vIdx in range(dataLen): v = f.read(dSize) vList[vIdx] = struct.unpack('>d', v)[0] subList[lIdx] = vList data[dIdx] = subList isEnd = (f.read(1) == b'') print("is valid End : %d"%isEnd) f.close() return data def loadNormalData(fName): f = open(fName, 'rb') iSize = struct.calcsize('i') dSize = struct.calcsize('d') dataSize = struct.unpack('>i', f.read(iSize))[0] mean = [None]*dataSize; std = [None]*dataSize; for dIdx in range(dataSize): v = f.read(dSize) mean[dIdx] = struct.unpack('>d', v)[0] for dIdx in range(dataSize): v = f.read(dSize) std[dIdx] = struct.unpack('>d', v)[0] isEnd = (f.read(1) == b'') print("is valid End : %d"%isEnd) f.close() return mean, std def saveData(fName, data): dataLen = len(data[0]) dataSize = len(data) print("saveData : %d, %d"%(dataLen, dataSize)) f = open(fName, 'wb') f.write(struct.pack('>i', dataLen)) f.write(struct.pack('>i', dataSize)) for dIdx in range(dataSize): for vIdx in range(dataLen): f.write(struct.pack('>d', data[dIdx][vIdx])) f.close() def meanAndStd(data): dataLen = len(data[0]) mean = [0]*dataLen for v in data: for i in range(dataLen): mean[i] += v[i] for i in range(dataLen): mean[i] /= len(data) std = [0]*dataLen for v in data: for i in range(dataLen): diff = v[i] - mean[i] std[i] += diff*diff for i in range(dataLen): std[i] = math.sqrt(std[i]/len(data)) if (std[i] < 0.001): std[i] = 0.001; return [mean, std]
import csv import os import time import tensorflow as tf from tensorflow import app from tensorflow import flags from tensorflow import gfile from tensorflow import logging import numpy as np from scipy.io import wavfile import six import vggish_input import vggish_params import vggish_postprocess import vggish_slim from subprocess import call import eval_util import losses import readers import utils FLAGS = flags.FLAGS if __name__ == '__main__': flags.DEFINE_string('input_wav_file', '', 'input audio file in wav format') # flags.DEFINE_string( 'tfrecord_file', '/mnt/disks/disk-1/data/youtube_video/incident/feature_label_eval.tfrecord', # 'Path to a TFRecord file where embeddings will be written.') flags.DEFINE_string( 'pca_params', 'vggish_pca_params.npz', 'Path to the VGGish PCA parameters file.') flags.DEFINE_string( 'checkpoint', 'vggish_model.ckpt', 'Path to the VGGish checkpoint file.') if __name__ == '__main__': flags.DEFINE_string("train_dir", "/Users/atislam/data/train_dir/temp_model/", "The directory to load the model files from.") flags.DEFINE_string("checkpoint_file", "", "If provided, this specific checkpoint file will be " "used for inference. Otherwise, the latest checkpoint " "from the train_dir' argument will be used instead.") flags.DEFINE_string("output_file", "/Users/atislam/data/test_dir/temp_model/predictions.csv", "The file to save the predictions to.") flags.DEFINE_string( "input_data_pattern", "", "File glob defining the evaluation dataset in tensorflow.SequenceExample " "format. The SequenceExamples are expected to have an 'rgb' byte array " "sequence feature as well as a 'labels' int64 context feature.") # Model flags. flags.DEFINE_bool( "frame_features", True, "If set, then --input_data_pattern must be frame-level features. " "Otherwise, --input_data_pattern must be aggregated video-level " "features. The model must also be set appropriately (i.e. to read 3D " "batches VS 4D batches.") flags.DEFINE_integer( "batch_size", 1, "How many examples to process per batch.") flags.DEFINE_string("feature_names", "audio_embedding", "Name of the feature " "to use for training.") flags.DEFINE_string("feature_sizes", "128", "Length of the feature vectors.") # Other flags. flags.DEFINE_integer("num_readers", 1, "How many threads to use for reading input files.") flags.DEFINE_integer("top_k", 2, "How many predictions to output per video.") flags.DEFINE_string("model", "FrameLevelLogisticModel", "What type of model") def _int64_list_feature(int64_list): return tf.train.Feature(int64_list=tf.train.Int64List(value=int64_list)) def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def _make_bytes(int_array): if bytes == str: # Python2 return ''.join(map(chr, int_array)) else: return bytes(int_array) #return pointer to array of prediction def format_lines(video_ids, predictions, top_k): batch_size = len(video_ids) for video_index in range(batch_size): top_indices = np.argpartition(predictions[video_index], -top_k)[-top_k:] line = [(class_index, predictions[video_index][class_index]) for class_index in top_indices] line = sorted(line, key=lambda p: -p[1]) yield line[0][0] def get_input_data_tensors(reader, data_pattern, batch_size, num_readers=1): """Creates the section of the graph which reads the input data. Args: reader: A class which parses the input data. data_pattern: A 'glob' style path to the data files. batch_size: How many examples to process at a time. num_readers: How many I/O threads to use. Returns: A tuple containing the features tensor, labels tensor, and optionally a tensor containing the number of frames per video. The exact dimensions depend on the reader being used. Raises: IOError: If no files matching the given pattern were found. """ with tf.name_scope("input"): files = gfile.Glob(data_pattern) if not files: raise IOError("Unable to find input files. data_pattern='" + data_pattern + "'") logging.info("number of input files: " + str(len(files))) filename_queue = tf.train.string_input_producer( files, num_epochs=1, shuffle=False) examples_and_labels = [reader.prepare_reader(filename_queue) for _ in range(num_readers)] video_id_batch, video_batch, unused_labels, num_frames_batch = ( tf.train.batch_join(examples_and_labels, batch_size=batch_size, allow_smaller_final_batch=True, enqueue_many=True)) return video_id_batch, video_batch, num_frames_batch def inference(video_batch_val,num_frames_batch_val, checkpoint_file, train_dir,out_file_location, batch_size=1, top_k=2): with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess, gfile.Open(out_file_location, "w+") as out_file: if checkpoint_file: if not gfile.Exists(checkpoint_file + ".meta"): logging.fatal("Unable to find checkpoint file at provided location '%s'" % checkpoint_file) latest_checkpoint = checkpoint_file else: latest_checkpoint = tf.train.latest_checkpoint(train_dir) if latest_checkpoint is None: raise Exception("unable to find a checkpoint at location: %s" % train_dir) else: meta_graph_location = latest_checkpoint + ".meta" logging.info("loading meta-graph: " + meta_graph_location) saver = tf.train.import_meta_graph(meta_graph_location, clear_devices=True) logging.info("restoring variables from " + latest_checkpoint) saver.restore(sess, latest_checkpoint) input_tensor = tf.get_collection("input_batch_raw")[0] num_frames_tensor = tf.get_collection("num_frames")[0] predictions_tensor = tf.get_collection("predictions")[0] # Workaround for num_epochs issue. def set_up_init_ops(variables): init_op_list = [] for variable in list(variables): if "train_input" in variable.name: init_op_list.append(tf.assign(variable, 1)) variables.remove(variable) init_op_list.append(tf.variables_initializer(variables)) return init_op_list sess.run(set_up_init_ops(tf.get_collection_ref( tf.GraphKeys.LOCAL_VARIABLES))) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) print("Number of threads -----------------------------------"+str(len(threads))+"------------------") num_examples_processed = 0 start_time = time.time() #out_file.write("VideoId,LabelConfidencePairs\n") try: #video_id_batch_val, video_batch_val,num_frames_batch_val = sess.run([video_id_batch, video_batch, num_frames_batch]) predictions_val, = sess.run([predictions_tensor], feed_dict={input_tensor: video_batch_val, num_frames_tensor: num_frames_batch_val}) now = time.time() num_examples_processed += len(video_batch_val) num_classes = predictions_val.shape[1] logging.info("num examples processed: " + str(num_examples_processed) + " elapsed seconds: " + "{0:.2f}".format(now-start_time)) print("num examples processed: " + str(num_examples_processed) + " elapsed seconds: " + "{0:.2f}".format(now-start_time)) video_id_batch_val = np.array(['1'], dtype = bytes) ite = format_lines(video_id_batch_val, predictions_val, top_k) #return pointer to array of predicted classes classes = [line for line in ite] return(classes[0]) #returning the prediction of the first sample; ignoring the others assuming there are none except tf.errors.OutOfRangeError: logging.info('Done with inference. The output file was written to ' + out_file_location) finally: coord.request_stop() coord.join(threads) sess.close() def extract_n_predict(input_wav_file, pca_params, checkpoint, checkpoint_file, train_dir, output_file): print("Input file: " +input_wav_file) if (os.path.isfile(input_wav_file)): examples_batch = vggish_input.wavfile_to_examples(input_wav_file) #print(examples_batch) pproc = vggish_postprocess.Postprocessor(pca_params) with tf.Graph().as_default(), tf.Session() as sess: # Define the model in inference mode, load the checkpoint, and # locate input and output tensors. vggish_slim.define_vggish_slim(training=False) vggish_slim.load_vggish_slim_checkpoint(sess, checkpoint) features_tensor = sess.graph.get_tensor_by_name( vggish_params.INPUT_TENSOR_NAME) embedding_tensor = sess.graph.get_tensor_by_name( vggish_params.OUTPUT_TENSOR_NAME) # Run inference and postprocessing. [embedding_batch] = sess.run([embedding_tensor], feed_dict={features_tensor: examples_batch}) #print(embedding_batch) postprocessed_batch = pproc.postprocess(embedding_batch) #print(postprocessed_batch) num_frames_batch_val = np.array([postprocessed_batch.shape[0]],dtype=np.int32) video_batch_val = np.zeros((1, 300, 128), dtype=np.float32) video_batch_val[0,0:postprocessed_batch.shape[0],:] = utils.Dequantize(postprocessed_batch.astype(float),2,-2) # extract_n_predict() predicted_class = inference(video_batch_val ,num_frames_batch_val, checkpoint_file, train_dir, output_file) return(predicted_class) tf.reset_default_graph() def main(unused_argv): predicted_class = extract_n_predict(FLAGS.input_wav_file, FLAGS.pca_params, FLAGS.checkpoint, FLAGS.checkpoint_file, FLAGS.train_dir, FLAGS.output_file) print(predicted_class) if __name__ == '__main__': app.run(main)
var searchData= [ ['arduino_20library_20for_20distance_20sensors',['Arduino library for distance sensors',['../index.html',1,'']]] ];
/* Copyright 2016 OpenMarket Ltd 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 notifications = require('notifications'); var ContentRules = notifications.ContentRules; var PushRuleVectorState = notifications.PushRuleVectorState; var expect = require('expect'); var test_utils = require('../../test-utils'); var NORMAL_RULE = { actions: [ "notify", { set_tweak: "highlight", value: false }, ], enabled: true, pattern: "vdh2", rule_id: "vdh2", }; var LOUD_RULE = { actions: [ "notify", { set_tweak: "highlight" }, { set_tweak: "sound", value: "default" }, ], enabled: true, pattern: "vdh2", rule_id: "vdh2", }; var USERNAME_RULE = { actions: [ "notify", { set_tweak: "sound", value: "default" }, { set_tweak: "highlight" }, ], default: true, enabled: true, pattern: "richvdh", rule_id: ".m.rule.contains_user_name", }; describe("ContentRules", function() { beforeEach(function() { test_utils.beforeEach(this); }); describe("parseContentRules", function() { it("should handle there being no keyword rules", function() { var rules = { 'global': { 'content': [ USERNAME_RULE, ]}}; var parsed = ContentRules.parseContentRules(rules); expect(parsed.rules).toEqual([]); expect(parsed.vectorState).toEqual(PushRuleVectorState.ON); expect(parsed.externalRules).toEqual([]); }); it("should parse regular keyword notifications", function() { var rules = { 'global': { 'content': [ NORMAL_RULE, USERNAME_RULE, ]}}; var parsed = ContentRules.parseContentRules(rules); expect(parsed.rules.length).toEqual(1); expect(parsed.rules[0]).toEqual(NORMAL_RULE); expect(parsed.vectorState).toEqual(PushRuleVectorState.ON); expect(parsed.externalRules).toEqual([]); }); it("should parse loud keyword notifications", function() { var rules = { 'global': { 'content': [ LOUD_RULE, USERNAME_RULE, ]}}; var parsed = ContentRules.parseContentRules(rules); expect(parsed.rules.length).toEqual(1); expect(parsed.rules[0]).toEqual(LOUD_RULE); expect(parsed.vectorState).toEqual(PushRuleVectorState.LOUD); expect(parsed.externalRules).toEqual([]); }); it("should parse mixed keyword notifications", function() { var rules = { 'global': { 'content': [ LOUD_RULE, NORMAL_RULE, USERNAME_RULE, ]}}; var parsed = ContentRules.parseContentRules(rules); expect(parsed.rules.length).toEqual(1); expect(parsed.rules[0]).toEqual(LOUD_RULE); expect(parsed.vectorState).toEqual(PushRuleVectorState.LOUD); expect(parsed.externalRules.length).toEqual(1); expect(parsed.externalRules[0]).toEqual(NORMAL_RULE); }); }); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createIcon = require('../createIcon'); var _createIcon2 = _interopRequireDefault(_createIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var GrinSquintTearsIcon = (0, _createIcon2.default)({ name: 'GrinSquintTearsIcon', height: 512, width: 512, svgPath: 'M409.6 111.9c22.6-3.2 73.5-12 88.3-26.8 19.2-19.2 18.9-50.6-.7-70.2S446-5 426.9 14.2c-14.8 14.8-23.5 65.7-26.8 88.3-.8 5.5 3.9 10.2 9.5 9.4zM102.4 400.1c-22.6 3.2-73.5 12-88.3 26.8-19.1 19.1-18.8 50.6.8 70.2s51 19.9 70.2.7c14.8-14.8 23.5-65.7 26.8-88.3.8-5.5-3.9-10.2-9.5-9.4zm311.7-256.5c-33 3.9-48.6-25.1-45.7-45.7 3.4-24 7.4-42.1 11.5-56.5C285.1-13.4 161.8-.5 80.6 80.6-.5 161.7-13.4 285 41.4 379.9c14.4-4.1 32.4-8 56.5-11.5 33.2-3.9 48.6 25.2 45.7 45.7-3.4 24-7.4 42.1-11.5 56.5 94.8 54.8 218.1 41.9 299.3-39.2s94-204.4 39.2-299.3c-14.4 4.1-32.5 8-56.5 11.5zM255.7 106c3.3-13.2 22.4-11.5 23.6 1.8l4.8 52.3 52.3 4.8c13.4 1.2 14.9 20.3 1.8 23.6l-90.5 22.6c-8.9 2.2-16.7-5.9-14.5-14.5l22.5-90.6zm-90.9 230.3L160 284l-52.3-4.8c-13.4-1.2-14.9-20.3-1.8-23.6l90.5-22.6c8.8-2.2 16.7 5.8 14.5 14.5L188.3 338c-3.1 13.2-22.2 11.7-23.5-1.7zm215.7 44.2c-29.3 29.3-75.7 50.4-116.7 50.4-18.9 0-36.6-4.5-51-14.7-9.8-6.9-8.7-21.8 2-27.2 28.3-14.6 63.9-42.4 97.8-76.3s61.7-69.6 76.3-97.8c5.4-10.5 20.2-11.9 27.3-2 32.3 45.3 7.1 124.7-35.7 167.6z', yOffset: '', xOffset: '', transform: '' }); /* This file is generated by createIcons.js any changes will be lost. */ exports.default = GrinSquintTearsIcon;
# 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 .resource_py3 import Resource class VirtualWAN(Resource): """VirtualWAN Resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param disable_vpn_encryption: Vpn encryption to be disabled or not. :type disable_vpn_encryption: bool :ivar virtual_hubs: List of VirtualHubs in the VirtualWAN. :vartype virtual_hubs: list[~azure.mgmt.network.v2018_12_01.models.SubResource] :ivar vpn_sites: :vartype vpn_sites: list[~azure.mgmt.network.v2018_12_01.models.SubResource] :param security_provider_name: The Security Provider name. :type security_provider_name: str :param allow_branch_to_branch_traffic: True if branch to branch traffic is allowed. :type allow_branch_to_branch_traffic: bool :param allow_vnet_to_vnet_traffic: True if Vnet to Vnet traffic is allowed. :type allow_vnet_to_vnet_traffic: bool :param office365_local_breakout_category: The office local breakout category. Possible values include: 'Optimize', 'OptimizeAndAllow', 'All', 'None' :type office365_local_breakout_category: str or ~azure.mgmt.network.v2018_12_01.models.OfficeTrafficCategory :param p2_svpn_server_configurations: List of all P2SVpnServerConfigurations associated with the virtual wan. :type p2_svpn_server_configurations: list[~azure.mgmt.network.v2018_12_01.models.P2SVpnServerConfiguration] :param provisioning_state: The provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' :type provisioning_state: str or ~azure.mgmt.network.v2018_12_01.models.ProvisioningState :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'virtual_hubs': {'readonly': True}, 'vpn_sites': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'disable_vpn_encryption': {'key': 'properties.disableVpnEncryption', 'type': 'bool'}, 'virtual_hubs': {'key': 'properties.virtualHubs', 'type': '[SubResource]'}, 'vpn_sites': {'key': 'properties.vpnSites', 'type': '[SubResource]'}, 'security_provider_name': {'key': 'properties.securityProviderName', 'type': 'str'}, 'allow_branch_to_branch_traffic': {'key': 'properties.allowBranchToBranchTraffic', 'type': 'bool'}, 'allow_vnet_to_vnet_traffic': {'key': 'properties.allowVnetToVnetTraffic', 'type': 'bool'}, 'office365_local_breakout_category': {'key': 'properties.office365LocalBreakoutCategory', 'type': 'str'}, 'p2_svpn_server_configurations': {'key': 'properties.p2SVpnServerConfigurations', 'type': '[P2SVpnServerConfiguration]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, *, id: str=None, location: str=None, tags=None, disable_vpn_encryption: bool=None, security_provider_name: str=None, allow_branch_to_branch_traffic: bool=None, allow_vnet_to_vnet_traffic: bool=None, office365_local_breakout_category=None, p2_svpn_server_configurations=None, provisioning_state=None, **kwargs) -> None: super(VirtualWAN, self).__init__(id=id, location=location, tags=tags, **kwargs) self.disable_vpn_encryption = disable_vpn_encryption self.virtual_hubs = None self.vpn_sites = None self.security_provider_name = security_provider_name self.allow_branch_to_branch_traffic = allow_branch_to_branch_traffic self.allow_vnet_to_vnet_traffic = allow_vnet_to_vnet_traffic self.office365_local_breakout_category = office365_local_breakout_category self.p2_svpn_server_configurations = p2_svpn_server_configurations self.provisioning_state = provisioning_state self.etag = None
import styled, { css } from "styled-components"; const btn = (light, dark) => css` white-space: nowrap; display: inline-block; border-radius: 5px; padding: 5px 15px; font-size: 16px; color: white; &:visited { color: white; } background-image: linear-gradient(${light}, ${dark}); border: 1px solid ${dark}; &:hover { background-image: linear-gradient(${light}, ${dark}); &[disabled] { background-image: linear-gradient(${light}, ${dark}); } } &:visited { color: black; } &[disabled] { opacity: 0.6; cursor: not-allowed; } `; const btnDefault = css`${btn("#ffffff", "#d5d5d5")} color: #555;`; const btnPrimary = btn("#4f93ce", "#285f8f"); export default styled.div` font-family: sans-serif; h1 { text-align: center; color: #222; } h2 { text-align: center; color: #222; } & > div { text-align: center; } a { display: block; text-align: center; color: #222; } form { max-width: 100%; padding: 20px 5px; background-color: var(--form-bg); & > div { display: flex; flex-flow: row nowrap; line-height: 2em; margin: 5px; & > label { color: #333; width: 110px; font-size: 1em; line-height: 32px; } & > input, & > select, & > textarea { flex: 1; padding: 3px 5px; font-size: 1em; margin-left: 15px; border: 1px solid #ccc; border-radius: 3px; } & > input[type="checkbox"] { margin-top: 7px; } & > div { margin-left: 16px; & > label { display: block; & > input { margin-right: 3px; } } } & > span { line-height: 32px; margin-left: 10px; color: #800; font-weight: bold; } } & > .buttons { display: flex; flex-flow: row nowrap; justify-content: center; margin-top: 15px; } button { margin: 0 10px; &[type="submit"] { ${btnPrimary}; } &[type="button"] { ${btnDefault}; } } pre { border: 1px solid #ccc; background: rgba(0, 0, 0, 0.1); box-shadow: inset 1px 1px 3px rgba(0, 0, 0, 0.2); padding: 20px; } } `;
function executeExercise1(value) { if (value > 10) { writeInDocument("Resposta: valor maior que 10", "exercise_1_result"); } else if (value < 10) { writeInDocument("Resposta: valor menor que 10", "exercise_1_result"); } else if (value == 10) { writeInDocument("Resposta: valor igual a 10", "exercise_1_result"); } else { writeInDocument("Resposta: valor inválido", "exercise_1_result"); } } function executeExercise2(value1, value2) { var floatValue1 = convertToFloatIfPossible(value1) var floatValue2 = convertToFloatIfPossible(value2) if (floatValue1 == null) { return writeInDocument("Resposta: valor 1 inválido", "exercise_2_result"); } if (floatValue2 == null) { return writeInDocument("Resposta: valor 2 inválido", "exercise_2_result"); } var result = floatValue1 + floatValue2 writeInDocument("Resposta: " + result, "exercise_2_result"); } function executeExercise3(value1, value2, operator) { var floatValue1 = convertToFloatIfPossible(value1) var floatValue2 = convertToFloatIfPossible(value2) if (floatValue1 == null) { return writeInDocument("Resposta: valor 1 inválido", "exercise_3_result"); } if (floatValue2 == null) { return writeInDocument("Resposta: valor 2 inválido", "exercise_3_result"); } var result = performOperation(floatValue1, floatValue2, operator) writeInDocument("Resposta: " + result, "exercise_3_result") } function executeExercise4(name, value) { value = convertToIntIfPossible(value) if (value == null) { return writeInDocument("Resposta: valor inválido", "exercise_4_result"); } var result = "Resposta: " for (var i = 0; i < value ; i++) { result = result + " " + name } writeInDocument(result, "exercise_4_result") } function executeExercise5(side1, side2, side3) { var floatValue1 = convertToFloatIfPossible(side1) var floatValue2 = convertToFloatIfPossible(side2) var floatValue3 = convertToFloatIfPossible(side3) if (floatValue1 == null) { return writeInDocument("Resposta: lado 1 inválido", "exercise_5_result"); } if (floatValue2 == null) { return writeInDocument("Resposta: lado 2 inválido", "exercise_5_result"); } if (floatValue3 == null) { return writeInDocument("Resposta: lado 3 inválido", "exercise_5_result"); } if (floatValue1 == floatValue2 && floatValue2 == floatValue3) { writeInDocument("Resposta: triângulo equilátero", "exercise_5_result"); } else if (floatValue1 != floatValue2 && floatValue2 != floatValue3) { writeInDocument("Resposta: triângulo escaleno", "exercise_5_result"); } else { writeInDocument("Resposta: triângulo isósceles", "exercise_5_result"); } } function executeExercise6(kwh, price) { kwh = convertToFloatIfPossible(kwh) price = convertToFloatIfPossible(price) if (kwh == null) { return writeInDocument("Resposta: Quantidade inválida de KWh", "exercise_3_result"); } if (price == null) { return writeInDocument("Resposta: Preço inválido", "exercise_3_result"); } var result = kwh * price if (kwh > 200) { result *= 1.50 } else if (kwh > 100) { result *= 1.25 } writeInDocument(result, "exercise_6_result") } // Private function performOperation(value1, value2, operator) { switch (operator) { case "sum": return value1 + value2 case "subtraction": return value1 - value2 case "multiplication": return value1 * value2 case "division": return value1 / value2 } } // Convenience function writeInDocument(value, document_id) { var element = document.getElementById(document_id); element.innerHTML = value; } function convertToFloatIfPossible(value) { if (isNaN(value)) { return null } return parseFloat(value) } function convertToIntIfPossible(value) { if (isNaN(value)) { return null } return parseInt(value) }
import React from 'react'; import Grid from '../Grid'; import GridItem from '../GridItem'; class SimpleGrid extends React.Component { render() { return ( <Grid> <GridItem span={8}>span = 8</GridItem> <GridItem span={4} rowSpan={2}> span = 4, rowSpan = 2 </GridItem> <GridItem span={2} rowSpan={3}> span = 2, rowSpan = 3 </GridItem> <GridItem span={2}>span = 2</GridItem> <GridItem span={4}>span = 4</GridItem> <GridItem span={2}>span = 2</GridItem> <GridItem span={2}>span = 2</GridItem> <GridItem span={2}>span = 2</GridItem> <GridItem span={4}>span = 4</GridItem> <GridItem span={2}>span = 2</GridItem> <GridItem span={4}>span = 4</GridItem> <GridItem span={4}>span = 4</GridItem> </Grid> ); } } export default SimpleGrid;
--- to: <%= h.src() %>/<%= h.changeCase.lower(name) %>/src/js/init.js --- import { initBreakpointsCssReload } from '@skilld/kaizen-breakpoints'; import config from '../../<%= h.changeCase.lower(name) %>.breakpoints.yml'; <% if(type==='primary'){ -%> import './ui/messages'; import './ui/select'; <% } -%> window.themeBreakpoints = config; initBreakpointsCssReload(config);
systemController = { backup_step:0, restore_step:0, linkSetup:function(obj,setting){ try{ w_url = $(obj).attr('data-url'); if(setting.overlay){ var addOverlay = Overlay.panel({id:'id_overlay_link'}); addOverlay.open({title:setting.title,url:w_url}); return false; if( setting.confirm ){ //$('.dialog-wrapper .dialog-title').empty(); //$('.dialog-wrapper .dialog-title').append('<?php echo __("LBL_CONFIRM-BACKUP")?>'); //$('.backup_message_status').empty(); // //setting.messageConfirm = '<?php echo __("LBL_CONFIRM_BACKUP&RESTORE"); ?>'; //$('.dialog-wrapper .dialog-message').html( setting.messageConfirm ); //$('.dialog-wrapper').css({'display':'block'}); // //$( ".btn-confirm-yes" ).off().bind("click", function() { // Common.closeDialog(); // $('.dialog-backup').css({'display':'block'}); // systemController.updateBackupProgress(2,'<?php echo __("LBL_BACKUP_DATABASE")?>'); // systemController.doBackup(); //}); }else{ addOverlay.open({title:setting.title,url:w_url}); } }else{ if(setting.ajax){ $.ajax({ type: "POST", url: w_url, success: function(data){ Common.closeDialog(); if (typeof(setting.callBack) === 'function') { setting.callBack(data); }else{ try{ var data = $.parseJSON(data); if(data.ok){ if(data.smessage){ Common.showMessage(data.smessage); } if (setting.hide!=null) { $(setting.hide).hide(); } if(setting.callBack!=''){ var form = $(obj).closest('form'); if(setting.callBack == 'reload'){ var urlCallback = setting.url; if(!urlCallback) urlCallback = $(form).find('input[name=loadListUrl]').val(); setting.callBack = form.parent().attr('id'); //load content Common.load(setting.callBack,urlCallback); }else{ eval(setting.callBack); } } }else{ if(data.serror){ Common.showError(data.serror); } } }catch(e){Common.error('JSON Error.')} } } }); }else{ Common.goUrl(w_url); } } }catch(e){ Common.error(e.toString()); } return false; }, performBackup:function(){ var formDeploy = $('#frmSolrRestore'); Common.closeDialog(); $('.dialog-backup').css({'display':'block'}); $.ajax({ url: formDeploy.attr('action'), type: 'POST', data:formDeploy.serialize(), dataType: 'json', success: function(data) { if(data.ok){ systemController.updateBackupProgress(2,'<?php echo __("LBL_BACKUP_DATABASE")?>'); systemController.doBackup(); }else{ $('#warning_restore_close_browser').html(data.serror).show(); } } }); }, verifyRestore:function(){ var formDeploy = $('#frmSolrRestore'); $('#statusRestoreMessage').hide(); $.ajax({ url: formDeploy.attr('action'), type: 'POST', data:formDeploy.serialize(), dataType: 'json', success: function(data) { if(data.ok){ systemController.doRestore(); }else{ $('#statusRestoreMessage').html(data.serror).show(); } } }); }, doRestore:function(){ //initial Common.closeAllOverlay(); $('#btn_backup_restore_retry').hide(); $('#btn_backup_restore_ok').hide(); $('.dialog-backup-restore').css({'display':'block'}); $.ajax({ url: '<?php echo site_url("system/backup/doRestore")?>'+'/'+systemController.restore_step, type: 'POST', dataType: 'json', beforeSend:function(){ $('#backup_restore_message_status').empty(); }, success: function(data) { try{ if(data.ok){ systemController.restore_step++; if( systemController.restore_step <= 5 ){ systemController.doRestore(); systemController.updateRestoreProgress(data.percent,data.smessage); } if(data.percent === 100 ){ systemController.restore_step = 0; systemController.updateRestoreProgress(data.percent,data.smessage); $('#btn_backup_restore_ok').addClass('btn-success').show(); $('.dialog-backup-restore .dialog-title').html('<?php echo __("LBL_COMPLETED")?>'); $('#tooltip-head-deploy').show(); $('#btn_backup_restore_retry').hide(); } }else{ $('#btn_backup_restore_retry').show(); systemController.restore_step = 0; $('#btn_backup_restore_ok').removeClass('btn-success').show(); $('.progress .bar').removeClass().addClass('bar').addClass('bar-danger'); systemController.updateRestoreProgress(data.percent,data.serror,1); } }catch (e){ systemController.restore_step = 0; $('#btn_backup_restore_retry').show(); $('#btn_backup_restore_ok').removeClass('btn-success').show(); $('.progress .bar').removeClass().addClass('bar').addClass('bar-danger'); $('#backup_restore_message_status').removeClass('text_message'); $('#backup_restore_message_status').addClass('text_error'); $('#backup_restore_message_status').html('<?php echo __("ERR_CANNOT_CONNECT")?>'); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { systemController.restore_step = 0; $('#btn_backup_restore_retry').show(); $('#btn_backup_restore_ok').removeClass('btn-success').show(); $('.progress .bar').removeClass().addClass('bar').addClass('bar-danger'); $('#backup_restore_message_status').removeClass('text_message'); $('#backup_restore_message_status').addClass('text_error'); $('#backup_restore_message_status').html('<?php echo __("ERR_CANNOT_CONNECT")?>'); } }); }, doBackup:function(){ //initial Common.closeAllOverlay(); $('#btn_deploy_retry').hide(); $('#btn_deploy_ok').hide(); //$('.dialog-deploy').css({'display':'block'}); $.ajax({ url: '<?php echo site_url("system/backup/doBackup")?>/'+systemController.backup_step, type: 'POST', dataType: 'json', success: function(data) { try { if(data.ok){ if(systemController.backup_step < 5){ systemController.backup_step++; systemController.updateBackupProgress(data.percent,data.smessage); systemController.doBackup(); }else { systemController.backup_step = 0; systemController.updateBackupProgress(data.percent,data.smessage); if( data.urlLoadList && ( parseInt(data.percent) === 100 ) ){ urlLoadList = data.urlLoadList; $('#System_Backup_List').load(urlLoadList); } } $('#btn_backup_retry').hide(); }else{ systemController.backup_step = 0; $('#btn_backup_retry').show(); $('#btn_backup_ok').removeClass('btn-success').show(); $('.progress .bar').removeClass().addClass('bar').addClass('bar-danger'); $('.progress .bar').removeClass('bar-success').addClass('bar-danger'); systemController.updateBackupProgress(data.percent,data.serror,1); } }catch (e){ systemController.backup_step = 0; $('#btn_backup_retry').show(); $('#btn_backup_ok').removeClass('btn-success').hide(); $('.progress .bar').removeClass().addClass('bar').addClass('bar-danger'); $('#backup_message_status').removeClass('text_message'); $('#backup_message_status').addClass('text_error'); $('#backup_message_status').html('<?php echo __("ERR_CANNOT_CONNECT")?>'); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { systemController.backup_step = 0; $('#btn_backup_retry').show(); $('#btn_backup_ok').removeClass('btn-success').hide(); $('.progress .bar').removeClass().addClass('bar').addClass('bar-danger'); $('#backup_message_status').removeClass('text_message'); $('#backup_message_status').addClass('text_error'); $('#backup_message_status').html('<?php echo __("ERR_CANNOT_CONNECT")?>'); } }); }, updateRestoreProgress:function(percent,title,error){ $('.progress').addClass('progress-striped').addClass('active'); $('.progress .bar').removeClass().addClass('bar') .addClass((percent < 40) ? 'bar-danger' : ( (percent < 80) ? 'bar-warning' : 'bar-success' )); if(error){ $('#backup_restore_message_status').removeClass('text_message'); $('#backup_restore_message_status').addClass('text_error'); }else{ if(percent != -1){ $('.progress .bar').width(percent + '%'); $('.progress .bar').text(percent + '%'); } $('#backup_restore_message_status').removeClass('text_error'); $('#backup_restore_message_status').addClass('text_message'); } if(title){ $('#backup_restore_message_status').html(title); } }, updateBackupProgress:function(percent,title,error){ $('.progress').addClass('progress-striped').addClass('active'); $('.progress .bar').removeClass().addClass('bar') .addClass((percent < 40) ? 'bar-danger' : ( (percent < 80) ? 'bar-warning' : 'bar-success' )); if(error){ $('#backup_message_status').removeClass('text_message'); $('#backup_message_status').addClass('text_error'); $('.progress .bar').removeClass('btn-success'); $('.progress .bar').addClass('bar-danger'); }else{ if(percent != -1){ $('.progress .bar').width(percent + '%'); $('.progress .bar').text(percent + '%'); } if( percent == 100 ){ $('.dialog-backup .dialog-title').html( '<?php echo __("LBL_TITLE_BACKUP_COMPLETED") ?>' ); $('#btn_backup_ok').addClass('btn-success').show(); } $('#backup_message_status').removeClass('text_error'); $('#backup_message_status').addClass('text_message'); } if(title){ $('#backup_message_status').html(title); } }, getTableField:function(obj){ val = $(obj).val(); if(!val) return; $.ajax({ type: "POST", url: "<?php echo site_url('system/module/getTableField/')?>", data: 'tableName=' + val, success: function(data){ try{ var data = $.parseJSON(data); if(data.ok){ $('#tableNameError').html(''); $('.primaryKey').val(data.data.primary); $.each(data.data.fields, function (i, item) { $('.tableField').append($('<option>', { value: item.val, text : item.text })); }); }else{ $('#tableNameError').html(data.serror); } }catch(e){ Common.error('JSON Error.') } } }); }, checkControllerName : function(obj,mod){ val = $(obj).val(); $.ajax({ type: "POST", url: "<?php echo site_url('system/module/checkControllerName/')?>", data: 'controllerName=' + val +'&modulePath='+mod, success: function(data){ try{ var data = $.parseJSON(data); if(data.ok){ $('#controllerNameError').html(''); }else{ $('#controllerNameError').html(data.serror); } }catch(e){ Common.error('JSON Error.') } } }); }, moveRightAddEdit : function (obj){ parent = $(obj).closest('fieldset'); $.ajax({ type: "POST", url: "<?php echo site_url('system/module/getConfigAddEdit/')?>", data: parent.serialize(), success: function(data){ $('#tableField1Wrap').html(data); } }); }, moveLeftAddEdit : function (obj){ }, moveRightSearch : function (obj){ parent = $(obj).closest('fieldset'); $.ajax({ type: "POST", url: "<?php echo site_url('system/module/getConfigListSearch/')?>", data: parent.serialize(), success: function(data){ $('#tableField2Wrap').html(data); } }); }, moveLeftSearch : function (obj){ }, removeElement: function(obj){ if(confirm('<?php echo __("Do you want to delete this?");?>')) $(obj).closest("ul").remove(); }, addDropdownItem: function(obj){ var html = '<div class="valueItem">'; html +='<input name="data[dropdown][value][]" value="" placeholder="<?php echo ("Value")?>" rules="required" class="span2" msg="" id="System_Dropdown_Insert_Form_4" type="text">'; html +=' <input name="data[dropdown][text][]" value="" placeholder="<?php echo __("Text"); ?>" rules="required" class="span2" type="text">'; html +=' <span class="pointer action-icon-trash" onclick = "systemController.removeOption(this)"></span></div>'; $('#'+obj).append(html); }, removeOption: function(obj){ $(obj).parent().remove(); }, downloadFile: function (obj) { var w_url = $(obj).attr('href'); $.ajax({ url: w_url, type: 'POST', dataType: 'html', success: function(data) { data = $.parseJSON(data); if( data.ok ){ document.location = data.file; } else{ if( data.serror ){ Common.showError( data.serror ) }else{ var addOverlay = Overlay.panel({id:'id_overlay_link'}); addOverlay.open( {title:'Download', url: w_url } ); } } } }); }, }
import logging from argparse import ArgumentParser from transformers.commands import BaseTransformersCLICommand from transformers.pipelines import SUPPORTED_TASKS, Pipeline, PipelineDataFormat, pipeline logger = logging.getLogger(__name__) # pylint: disable=invalid-name def try_infer_format_from_ext(path: str): if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMATS: if path.endswith(ext): return ext raise Exception( "Unable to determine file format from file extension {}. " "Please provide the format through --format {}".format(path, PipelineDataFormat.SUPPORTED_FORMATS) ) def run_command_factory(args): nlp = pipeline( task=args.task, model=args.model if args.model else None, config=args.config, tokenizer=args.tokenizer, device=args.device, ) format = try_infer_format_from_ext(args.input) if args.format == "infer" else args.format reader = PipelineDataFormat.from_str( format=format, output_path=args.output, input_path=args.input, column=args.column if args.column else nlp.default_input_names, overwrite=args.overwrite, ) return RunCommand(nlp, reader) class RunCommand(BaseTransformersCLICommand): def __init__(self, nlp: Pipeline, reader: PipelineDataFormat): self._nlp = nlp self._reader = reader @staticmethod def register_subcommand(parser: ArgumentParser): run_parser = parser.add_parser("run", help="Run a pipeline through the CLI") run_parser.add_argument("--task", choices=SUPPORTED_TASKS.keys(), help="Task to run") run_parser.add_argument("--input", type=str, help="Path to the file to use for inference") run_parser.add_argument("--output", type=str, help="Path to the file that will be used post to write results.") run_parser.add_argument("--model", type=str, help="Name or path to the model to instantiate.") run_parser.add_argument("--config", type=str, help="Name or path to the model's config to instantiate.") run_parser.add_argument( "--tokenizer", type=str, help="Name of the tokenizer to use. (default: same as the model name)" ) run_parser.add_argument( "--column", type=str, help="Name of the column to use as input. (For multi columns input as QA use column1,columns2)", ) run_parser.add_argument( "--format", type=str, default="infer", choices=PipelineDataFormat.SUPPORTED_FORMATS, help="Input format to read from", ) run_parser.add_argument( "--device", type=int, default=-1, help="Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)", ) run_parser.add_argument("--overwrite", action="store_true", help="Allow overwriting the output file.") run_parser.set_defaults(func=run_command_factory) def run(self): nlp, outputs = self._nlp, [] for entry in self._reader: output = nlp(**entry) if self._reader.is_multi_columns else nlp(entry) if isinstance(output, dict): outputs.append(output) else: outputs += output # Saving data if self._nlp.binary_output: binary_path = self._reader.save_binary(outputs) logger.warning("Current pipeline requires output to be in binary format, saving at {}".format(binary_path)) else: self._reader.save(outputs)
# Owner(s): ["module: onnx"] import unittest import onnxruntime # noqa: F401 import torch from torch.cuda.amp import autocast from test_pytorch_common import disableScriptTest, skipIfUnsupportedMinOpsetVersion from test_pytorch_common import skipIfNoCuda, skipIfNoBFloat16Cuda from test_pytorch_onnx_onnxruntime import TestONNXRuntime class TestONNXRuntime_cuda(unittest.TestCase): from torch.onnx.symbolic_helper import _export_onnx_opset_version opset_version = _export_onnx_opset_version keep_initializers_as_inputs = True onnx_shape_inference = True @skipIfUnsupportedMinOpsetVersion(9) @skipIfNoCuda def test_gelu_fp16(self): class GeluModel(torch.nn.Module): def forward(self, x): return torch.nn.functional.gelu(x) x = torch.randn(2, 4, 5, 6, requires_grad=True, dtype=torch.float16, device=torch.device("cuda")) self.run_test(GeluModel(), x, rtol=1e-3, atol=1e-5) @skipIfUnsupportedMinOpsetVersion(9) @skipIfNoCuda @disableScriptTest() def test_layer_norm_fp16(self): class LayerNormModel(torch.nn.Module): def __init__(self): super(LayerNormModel, self).__init__() self.layer_norm = torch.nn.LayerNorm([10, 10]) @autocast() def forward(self, x): return self.layer_norm(x) x = torch.randn(20, 5, 10, 10, requires_grad=True, dtype=torch.float16, device=torch.device("cuda")) self.run_test(LayerNormModel().cuda(), x, rtol=1e-3, atol=1e-5) @skipIfUnsupportedMinOpsetVersion(12) @skipIfNoCuda @disableScriptTest() def test_softmaxCrossEntropy_fusion_fp16(self): class FusionModel(torch.nn.Module): def __init__(self): super(FusionModel, self).__init__() self.loss = torch.nn.NLLLoss(reduction="none") self.m = torch.nn.LogSoftmax(dim=1) @autocast() def forward(self, input, target): output = self.loss(self.m(2 * input), target) return output N, C = 5, 4 input = torch.randn(N, 16, dtype=torch.float16, device=torch.device("cuda")) target = torch.empty(N, dtype=torch.long, device=torch.device("cuda")).random_(0, C) # using test data containing default ignore_index=-100 target[target == 1] = -100 self.run_test(FusionModel(), (input, target)) @skipIfNoCuda @disableScriptTest() def test_apex_o2(self): class LinearModel(torch.nn.Module): def __init__(self): super(LinearModel, self).__init__() self.linear = torch.nn.Linear(3, 5) def forward(self, x): return self.linear(x) try: from apex import amp except Exception: raise unittest.SkipTest("Apex is not available") input = torch.randn(3, 3, device=torch.device("cuda")) model = amp.initialize(LinearModel(), opt_level="O2") self.run_test(model, input) # ONNX supports bfloat16 for opsets >= 13 # Add, Sub and Mul ops don't support bfloat16 cpu in onnxruntime. @skipIfUnsupportedMinOpsetVersion(13) @skipIfNoBFloat16Cuda def test_arithmetic_bfp16(self): class MyModule(torch.nn.Module): def forward(self, x): y = torch.ones(3, 4, dtype=torch.bfloat16, device=torch.device("cuda")) x = x.type_as(y) return torch.mul(torch.add(x, y), torch.sub(x, y)).to(dtype=torch.float16) x = torch.ones(3, 4, requires_grad=True, dtype=torch.float16, device=torch.device("cuda")) self.run_test(MyModule(), x, rtol=1e-3, atol=1e-5) TestONNXRuntime_cuda.setUp = TestONNXRuntime.setUp TestONNXRuntime_cuda.run_test = TestONNXRuntime.run_test if __name__ == "__main__": unittest.main(TestONNXRuntime_cuda())
/** * DevExtreme (core/class.js) * Version: 18.2.3 * Build date: Wed Nov 07 2018 * * Copyright (c) 2012 - 2018 Developer Express Inc. ALL RIGHTS RESERVED * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/ */ "use strict"; var errors = require("./errors"), typeUtils = require("./utils/type"); var wrapOverridden = function(baseProto, methodName, method) { return function() { var prevCallBase = this.callBase; this.callBase = baseProto[methodName]; try { return method.apply(this, arguments) } finally { this.callBase = prevCallBase } } }; var clonePrototype = function(obj) { var func = function() {}; func.prototype = obj.prototype; return new func }; var redefine = function(members) { var overridden, memberName, member, that = this; if (!members) { return that } for (memberName in members) { member = members[memberName]; overridden = "function" === typeof that.prototype[memberName] && "function" === typeof member; that.prototype[memberName] = overridden ? wrapOverridden(that.parent.prototype, memberName, member) : member } return that }; var include = function() { var argument, name, i, classObj = this; for (i = 0; i < arguments.length; i++) { argument = arguments[i]; if (argument.ctor) { classObj._includedCtors.push(argument.ctor) } if (argument.postCtor) { classObj._includedPostCtors.push(argument.postCtor) } for (name in argument) { if ("ctor" === name || "postCtor" === name) { continue } classObj.prototype[name] = argument[name] } } return classObj }; var subclassOf = function(parentClass) { if (this.parent === parentClass) { return true } if (!this.parent || !this.parent.subclassOf) { return false } return this.parent.subclassOf(parentClass) }; var abstract = function() { throw errors.Error("E0001") }; var copyStatic = function() { var hasOwn = Object.prototype.hasOwnProperty; return function(source, destination) { for (var key in source) { if (!hasOwn.call(source, key)) { return } destination[key] = source[key] } } }(); var classImpl = function() {}; classImpl.inherit = function(members) { var inheritor = function() { if (!this || typeUtils.isWindow(this) || "function" !== typeof this.constructor) { throw errors.Error("E0003") } var i, instance = this, ctor = instance.ctor, includedCtors = instance.constructor._includedCtors, includedPostCtors = instance.constructor._includedPostCtors; for (i = 0; i < includedCtors.length; i++) { includedCtors[i].call(instance) } if (ctor) { ctor.apply(instance, arguments) } for (i = 0; i < includedPostCtors.length; i++) { includedPostCtors[i].call(instance) } }; inheritor.prototype = clonePrototype(this); copyStatic(this, inheritor); inheritor.inherit = this.inherit; inheritor.abstract = abstract; inheritor.redefine = redefine; inheritor.include = include; inheritor.subclassOf = subclassOf; inheritor.parent = this; inheritor._includedCtors = this._includedCtors ? this._includedCtors.slice(0) : []; inheritor._includedPostCtors = this._includedPostCtors ? this._includedPostCtors.slice(0) : []; inheritor.prototype.constructor = inheritor; inheritor.redefine(members); return inheritor }; classImpl.abstract = abstract; module.exports = classImpl;
import keys from 'lodash/keys'; export default /* @ngInject */ ($scope, $q, $translate, Alerter) => { let timeoutObject = null; $scope.data = $scope.currentActionData.ipsList; $scope.loading = { exportCsv: false, }; function printCsv(datas) { let csvContent = ''; let dataString; let link; let headers; let fileName; if (datas && timeoutObject) { // get column name headers = datas.headers; csvContent += `${headers.join(';')}\n`; angular.forEach(datas.ips, (data, index) => { dataString = ''; angular.forEach(headers, (header) => { dataString += `${data[header]};`; }); csvContent += index < datas.ips.length ? `${dataString}\n` : dataString; }); fileName = 'export_ips.csv'; link = document.createElement('a'); if (link.download !== undefined) { link.setAttribute( 'href', `data:text/csv;charset=ISO-8859-1;base64,${btoa(csvContent)}`, ); link.setAttribute('download', fileName); link.style = 'visibility:hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } else { window.open( `data:text/csv;charset=ISO-8859-1;base64,${btoa(csvContent)}`, ); } Alerter.success($translate.instant('ip_export_csv_success')); } else if (!datas) { Alerter.error($translate.instant('ip_export_csv_error')); } timeoutObject = null; $scope.loading.exportCsv = false; $scope.resetAction(); } $scope.exportAccounts = function exportAccounts() { $scope.loading.exportCsv = true; // check timeout if (timeoutObject) { timeoutObject.resolve(); } // init timeout timeoutObject = $q.defer(); // get data for csv const preparedData = []; angular.forEach($scope.data, (value) => { preparedData.push({ ipBlock: value.ipBlock, ipVersion: value.version, type: value.type, country: value.country ? value.country : '', service: value.routedTo ? value.routedTo : '', description: value.description ? value.description : '', }); }); printCsv({ ips: preparedData, headers: keys(preparedData[0]), }); }; $scope.cancelExport = function cancelExport() { timeoutObject = null; $scope.resetAction(); }; };
/* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file iban.js * @author Marek Kotewicz <[email protected]> * @date 2015 */ var BigNumber = require('bignumber.js'); var padLeft = function (string, bytes) { var result = string; while (result.length < bytes * 2) { result = '0' + result; } return result; }; /** * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. * * @method iso13616Prepare * @param {String} iban the IBAN * @returns {String} the prepared IBAN */ var iso13616Prepare = function (iban) { var A = 'A'.charCodeAt(0); var Z = 'Z'.charCodeAt(0); iban = iban.toUpperCase(); iban = iban.substr(4) + iban.substr(0,4); return iban.split('').map(function(n){ var code = n.charCodeAt(0); if (code >= A && code <= Z){ // A = 10, B = 11, ... Z = 35 return code - A + 10; } else { return n; } }).join(''); }; /** * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. * * @method mod9710 * @param {String} iban * @returns {Number} */ var mod9710 = function (iban) { var remainder = iban, block; while (remainder.length > 2){ block = remainder.slice(0, 9); remainder = parseInt(block, 10) % 97 + remainder.slice(block.length); } return parseInt(remainder, 10) % 97; }; /** * This prototype should be used to create iban object from iban correct string * * @param {String} iban */ var Iban = function (iban) { this._iban = iban; }; /** * This method should be used to create iban object from ethereum address * * @method fromAddress * @param {String} address * @return {Iban} the IBAN object */ Iban.fromAddress = function (address) { var asBn = new BigNumber(address, 16); var base36 = asBn.toString(36); var padded = padLeft(base36, 15); return Iban.fromBban(padded.toUpperCase()); }; /** * Convert the passed BBAN to an IBAN for this country specification. * Please note that <i>"generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account"</i>. * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits * * @method fromBban * @param {String} bban the BBAN to convert to IBAN * @returns {Iban} the IBAN object */ Iban.fromBban = function (bban) { var countryCode = 'XE'; var remainder = mod9710(iso13616Prepare(countryCode + '00' + bban)); var checkDigit = ('0' + (98 - remainder)).slice(-2); return new Iban(countryCode + checkDigit + bban); }; /** * Should be used to create IBAN object for given institution and identifier * * @method createIndirect * @param {Object} options, required options are "institution" and "identifier" * @return {Iban} the IBAN object */ Iban.createIndirect = function (options) { return Iban.fromBban('WON' + options.institution + options.identifier); }; /** * Thos method should be used to check if given string is valid iban object * * @method isValid * @param {String} iban string * @return {Boolean} true if it is valid IBAN */ Iban.isValid = function (iban) { var i = new Iban(iban); return i.isValid(); }; /** * Should be called to check if iban is correct * * @method isValid * @returns {Boolean} true if it is, otherwise false */ Iban.prototype.isValid = function () { return /^XE[0-9]{2}(WON[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban) && mod9710(iso13616Prepare(this._iban)) === 1; }; /** * Should be called to check if iban number is direct * * @method isDirect * @returns {Boolean} true if it is, otherwise false */ Iban.prototype.isDirect = function () { return this._iban.length === 34 || this._iban.length === 35; }; /** * Should be called to check if iban number if indirect * * @method isIndirect * @returns {Boolean} true if it is, otherwise false */ Iban.prototype.isIndirect = function () { return this._iban.length === 20; }; /** * Should be called to get iban checksum * Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003) * * @method checksum * @returns {String} checksum */ Iban.prototype.checksum = function () { return this._iban.substr(2, 2); }; /** * Should be called to get institution identifier * eg. XREG * * @method institution * @returns {String} institution identifier */ Iban.prototype.institution = function () { return this.isIndirect() ? this._iban.substr(7, 4) : ''; }; /** * Should be called to get client identifier within institution * eg. GAVOFYORK * * @method client * @returns {String} client identifier */ Iban.prototype.client = function () { return this.isIndirect() ? this._iban.substr(11) : ''; }; /** * Should be called to get client direct address * * @method address * @returns {String} client direct address */ Iban.prototype.address = function () { if (this.isDirect()) { var base36 = this._iban.substr(4); var asBn = new BigNumber(base36, 36); return padLeft(asBn.toString(16), 20); } return ''; }; Iban.prototype.toString = function () { return this._iban; }; module.exports = Iban;
#!/usr/bin/env python3 from xml.etree import ElementTree from xml.etree.ElementTree import Element, tostring as xml_tostring, indent as xml_indent, fromstring as xml_fromstring, ParseError import api_classes import argparse from io import StringIO, BytesIO import re,json,sys,os, subprocess,io,copy,threading,platform,time,serial def recursive_dict(element): return element.tag, dict(map(recursive_dict, element)) or element.text class emu(): obj_type="emu_serial" #this is a list of all tags that are possible in the emu! #list of xml root tags command_root = Element('Command') command_firmware = Element('Firmware') #list of tags that might be nested command_name = Element('Name') #used in set meter attributes multiplier = Element('Multiplier') divisor = Element('Divisor') #used in set_fast_poll frequency = Element('Frequency') duration = Element('Duration') _type = Element('Type') confirm = Element('Confirm') refresh = Element('Refresh') #used for set_current_price trailing_digits = Element('TrailingDigits') currency = Element('Currency') price = Element('Price') #used for set_meter_info nickname = Element('Nickname') account = Element('Account') auth = Element('Auth') host = Element('Host') enabled = Element('Enabled') #billing periods _id = Element('Id') current_day_max_demand = Element('CurrentDayMaxDemand') number_of_periods = Element('NumberOfPeriods') period = Element('Period') start = Element('Start') current_day_maximum_demand = Element('CurrentDayMaximumDemand') #price_blocks device_mac_id = Element('DeviceMacId') meter_mac_id = Element('MeterMacId') time_stamp = Element('TimeStamp') number_of_blocks = Element('NumberOfBlocks') threshold_1 = Element('Threshold1') threshold_2 = Element('Threshold2') threshold3 = Element('Threshold3') threshold4 = Element('Threshold4') threshold = Element('Threshold') interval_channel = Element('IntervalChannel') end_time = Element('EndTime') event = Element('Event') mode = Element('Mode') offset = Element('Offset') blk_size = Element('BlkSize') version = Element('Version') img_type = Element('ImgType') mfg_code = Element('MfgCode') erase = Element('Erase') img_size = Element('ImgSize') blk = Element('Blk') blk_size = Element('BlkSize') block = Element('Block') crc_16 = Element('crc16') new_ver= Element('NewVer') write_buffer='' block_string="" tag_block=False tag="" data = dict() state = dict() responseRoots = ['NetworkInfo','ApsTable','Information', 'TimeCluster','NwkTable','Information','PriceCluster','DeviceInfo','Google','SimpleMeteringCluster','InstantaneousDemand','BlockPriceDetail','ConnectionStatus','BillingPeriodList','MessageCluster','FastPollStatus','CurrentSummationDelivered','NetworkInfo'] #command list (tag Name values) cmd_restart = "restart" cmd_get_restart_info ="get_restart_info" cmd_set_restart_info ="set_restart_info" cmd_factory_reset ="factory_reset" cmd_get_device_info ="get_device_info" cmd_get_network_info ="get_network_info" cmd_get_meter_attributes = "get_meter_attributes" cmd_set_meter_attributes ="set_meter_attributes" cmd_get_fast_poll_status="get_fast_poll_status" cmd_set_fast_poll="set_fast_poll" cmd_restarrt = "restart" cmd_get_current_summation_delivered="get_current_summation_delivered" cmd_get_instantaneous_demand ="get_instantaneous_demand" cmd_get_time ="get_time" cmd_get_current_summation = "get_current_summation" cmd_set_current_price ="set_current_price" cmd_set_meter_info = "set_meter_info" cmd_get_message ="get_message" cmd_confirm_message = "confirm_message" cmd_set_local_attributes="set_local_attributes" cmd_get_local_attributes="get_local_attributes" cmd_get_billing_periods="get_billing_periods" cmd_set_blk_price ="set_blk_price" cmd_set_price_block ="set_price_block" cmd_set_billing_period_list ="set_billing_period_list" cmd_set_billing_period="set_billing_period" cmd_get_price_blocks="get_price_blocks" cmd_set_block_structure ="set_block_structure" cmd_secret = "secret" cmd_get_schedule="get_schedule" cmd_get_profile_data="get_profile_data" cmd_get_schedule="get_schedule" cmd_set_schedule ="set_schedule" cmd_print_network_tables ="print_network_tables" cmd_image_block_dump = "image_block_dump" cmd_image_notify ="image_notify" cmd_image_block ="image_block" cmd_image_block_request ="image_block_request" cmd_image_invalidate_current= "image_invalidate_current" #device management details baud_rate = 115200 port =0 environment ="linux" windows_prefix = "COM" linux_prefix = "/dev/" osx_prefix = "/dev/" parity =serial.PARITY_NONE rtscts=0 dsrdtr=0 timeout=1 bytesize=8 print_string = True read_time = 15 serial_attempt=0 serial_connected = False illegal_xml_re = re.compile(u'[\x00-\x08\x0b-\x1f\x7f-\x84\x86-\x9f\ud800-\udfff\ufdd0-\ufddf\ufffe-\uffff]') original_block = "" history=[] def __init__(self, port): self.port = port if platform.system()=='Windows': self.environment = "windows" elif platform.system()=="Darwin": self.environment= "osx" def restart(self): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_restart self.command.append(self.command_name) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_device_info(self): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_device_info self.command.append(self.command_name) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_network_info(self): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_network_info self.command.append(self.command_name) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def factory_reset(self): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_factory_reset self.command.append(self.command_name) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_restart_info(self): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_restart_info self.command.append(self.command_name) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def set_restart_info(self, _type , confirm): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_set_restart_info self.command.append(self.command_name) self._type= copy.copy(self._type) self._type.text = _type self.confirm.text = confirm self.command.append(self._type) self.command.append(self.confirm) xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_meter_attributes(self): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_meter_attributes self.command.append(self.command_name) def set_meter_attributes(self, multiplier , divisor): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_set_meter_attributes self.multiplier.text = multiplier self.divisor.text = divisor self.command.append(self.command_name) self.command.append(self.multiplier) self.command.append(self.divisor) xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def set_fast_poll(self,frequency, duration): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_set_fast_poll self.frequency.text = frequency self.duration.text=duration self.command.append(self.command_name) self.command.append(self.frequency) self.command.append(self.duration) xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_fast_poll_status(self): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_fast_poll_status self.command.append(self.command_name) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_current_price(self, refresh): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_current_price self.refresh.text = refresh self.command.append(self.command_name) self.command.append(self.refresh) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def set_current_price(price,currency ,trailing_digits): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_set_current_price self.currency.text = currency self.traling_digits.text = trailing_digits self.command.append(self.command_name) self.command.append(self.currency) self.command.append(self.trailing_digits) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_current_summation_delivered(self): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_current_summation_delivered self.command.append(self.command_name) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_instantaneous_demand(self,refresh ): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_instantaneous_demand self.refresh.text = refresh self.command.append(self.command_name) self.command.append(self.refresh) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_time(self,refresh): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_time self.refresh.text = refresh self.command.append(self.command_name) self.command.append(self.refresh) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def set_current_price(self,price ,trailing_digits): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_set_current_price self.price.text = price self.trailing_digits.text = trailing_digits self.command.append(self.command_name) self.command.append(self.price) self.command.append(self.trailing_digits) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def set_meter_info(self,nickname,account,auth,host,enabled): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_set_current_price self.nickname.text = nickname self.account.text = account self.auth.text = auth self.host.text = host self.enabled.text = enabled self.command.append(self.command_name) self.command.append(self.nickname) self.command.append(self.account) self.command.append(self.auth) self.command.append(self.host) self.command.append(self.enabled) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_message(self): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_message self.command.append(self.command_name) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_local_attributes(self): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_local_attributes self.command.append(self.command_name) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def set_local_attributes(self,current_day_max_demand): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_set_local_attributes self.current_day_maximum_demand.text =current_day_max_demand self.command.append(self.command_name) self.command.append(self.current_day_maximum_demand) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_billing_periods(self): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_billing_periods self.command.append(self.command_name) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def set_billing_period_list(self,number_of_billing_period ): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_set_billing_period_list self.number_of_periods.text=number_of_billing_period self.command.append(self.command_name) self.command.append(self.number_of_periods) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def set_billing_period(self, period, start): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_set_billing_period self.period.text=period self.start.text=start self.command.append(self.command_name) self.command.append(self.period) self.command.append(self.start) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_price_blocks(self): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_price_blocks self.command.append(self.command_name) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def set_price_block(self,block,threshold,price ): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_set_price_block self.block.text=block self.threshold.text=threshold self.price.text=price self.command.append(self.command_name) self.command.append(self.block) self.command.append(self.threshold) self.command.append(self.price) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_schedule(self, mode): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_schedule self.mode.text=mode self.command.append(self.command_name) self.command.append(self.mode) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def get_profile_data(self, number_of_periods , interval_channel): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_get_profile_data self.number_of_periods.text=number_of_periods self.interval_channel.text=interval_channel self.command.append(self.command_name) self.command.append(self.interval_channel) self.command.append(self.number_of_periods) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def set_schedule(self,event,mode, frequency, enabled ): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_set_schedule if mode: self.mode.text=mode self.command.append(self.mode) if frequency: self.frequency.text=frequency self.command.append(self.frequency) if enabled: self.enabled.text=enabled self.command.append(self.enabled) self.event.text=event self.mode.text=mode self.event.text=event self.mode.text=mode self.event.text=event self.command.append(self.command_name) self.command.append(self.event) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def print_network_tables(self): self.command = copy.copy(self.command_root) self.command_name.text = self.cmd_print_network_tables self.command.append(self.command_name) #adding in the actual command xml_indent(self.command) self.write_buffer = xml_tostring(self.command) self.debug_command(self.write_buffer) def debug_command(self, msg): #print("debug_command:", msg) pass def create_serial(self): # fix the port/prefix: PREFIXES = { "osx": self.osx_prefix, "linux": self.linux_prefix } prefix = PREFIXES[self.environment] if self.environment in PREFIXES else self.windows_prefix port = str(self.port) port = port if self.port.startswith(prefix) else prefix + port try: self.ser = serial.Serial(port, self.baud_rate, timeout=self.timeout) self.serial_connected =True self.serial_attempt=0 except: print(sys.exc_info()) if self.serial_attempt >3: print("Throwing an error, can't connect to EMU serial") raise else: self.serial_attempt = self.serial_attempt+1 print("having trouble connecting to serial...."+str(self.serial_attempt)) time.sleep(10) def serial_thread(self): self.stop_thread=False #this function is the thread which reads from the serial, writes to the serial and calls parsing functions print("Starting serial process for EMU on "+str(self.port)) #inifinite loop try: self.create_serial() while True: if self.stop_thread is True: self.ser.close() print("Closing serial port for EMU") #in case we was to stop thread self.stop_thread=False self.serial_connected=False return else: text =self.ser.readlines() for line in text: self.serial_reader(line) if self.write_buffer is not None: try: f =open('static/emu-log.txt','a') f.write(self.write_buffer.translate(None, "<>\\")) f.write('\n') f.close() except: pass self.ser.write(self.write_buffer) self.write_history('HOST', self.command_name.text, self.write_buffer, None) self.write_buffer = None time.sleep(0.1) except: raise def start_serial(self): self.thread_handle = threading.Thread(target=self.serial_thread, args=[]) self.thread_handle.start() def stop_serial(self): self.stop_thread= True def parse_response(self,response): self.response = unicode(illegal_xml_re.sub('', response)) self.reponse_root =xml_fromstring(self.response) # TODO: What are the below three lines trying to do? #for child in self.response: # self.tree = objectify.Element(root) #self.tree = etree.fromstring() def look_for_start_tag(self,line): #this reads eachline looking for a start tag start_tag = False #these are thetags that are possible for tag in self.responseRoots: tagToString = '<'+tag+'>' if tagToString in line: start_tag=True self.tag = tag return start_tag def look_for_end_tag(self,line): #this reads eachline looking for a start tag end_tag = False #these are thetags that are possible tagToString = '</'+self.tag+'>' #checking if tag is in line if tagToString in line: end_tag=True return end_tag def serial_reader(self,line): #this function is reads the text self.start_flag=False line = str(line, 'UTF-8') if self.look_for_start_tag(line): self.tag_block=True self.start_flag=True if self.tag_block ==True: self.original_block = self.original_block+line self.block_string = self.block_string+line.rstrip() if self.look_for_end_tag(line): self.tag_block = False try: self.block_to_tree(self.block_string,self.tag) except Exception as e: print("XML ISSUE:", e) obj =dict() # self.block_string self.block_string="" self.original_block = "" self.start_flag=False def block_to_tree(self,block_string,tag): block_string = self.illegal_xml_re.sub('', block_string) if tag in self.responseRoots: try: self.xmlTree = xml_fromstring(block_string) except ParseError as err: print("ERROR parsing XML:", err, block_string) module = __import__('api_classes') class_ = getattr(module, tag) instance = class_(self.xmlTree, self.original_block) setattr(self, tag, instance) self.write_history('EMU', tag, self.original_block, instance) self.state[tag] = dict() for element in self.xmlTree.iter(): self.data[element.tag] = element.text self.state[tag][element.tag]=element.text for tag in self.responseRoots: try: del self.data[tag] except: pass def write_history(self,origin, tag, raw, dict_): history_obj ={ 'origin':origin, 'type':tag, 'obj':dict_, 'raw': raw } self.history.append(history_obj) def readback(self, limit=100): limit_count = 0 for item in reversed(self.history): print("SENT BY :"+str(item['origin'])) print("TYPE OF :"+str(item['type'])) print("RAW DATA:------------------- ") print(str(item['raw'])) #print(str(type(recursive_dict(self.xmlTree.getroot())))) limit_count +=1 if limit_count >limit: break def clear_history(): self.history=[] if __name__ == '__main__': # parse arguments: parser = argparse.ArgumentParser(prog="emu", description="Connect to the EMU-2 Energy Monitoring Unit via serial") parser.add_argument('--port', '-p', help='Serial port of the EMU-2 plugged into USB [tty.usbmodemfd121]', default="tty.usbmodemfd121") args = parser.parse_args() # connect & output emu_instance = emu(vars(args)['port']) emu_instance.start_serial() emu_instance.get_current_summation_delivered() time.sleep(5) emu_instance.stop_serial() print("\n----- CurrentSummationDelivered -----") print(emu_instance.CurrentSummationDelivered) print("\n----- CurrentSummationDelivered.SummationDelivered -----") print(emu_instance.CurrentSummationDelivered.SummationDelivered) print("\n----- History of Responses: ------") for hist in emu_instance.history: print(hist)
import { xRollingAverage } from 'ml-spectra-processing'; /** * * @export * @param {Array<number>} ys * @param {Object} [options={}] * @param {number} [options.window] rolling window size, defaults to 10% of the length of the spectrum * @param {string} [options.padding.size=window-1] none, value, circular, duplicate * @param {string} [options.padding.algorithm='duplicate'] none, value, circular, duplicate * @param {number} [options.padding.value=0] value to use for padding (if algorithm='value') * @returns {BaselineOutput} */ export function rollingAverageBaseline(ys, options = {}) { let window = Math.max(Math.round(ys.length * 0.1), 2); let defaults = { window: window, padding: { size: window - 1, algorithm: 'duplicate', value: 0, }, }; let actualOptions = Object.assign({}, defaults, options); let baseline = xRollingAverage(ys, actualOptions); let corrected = new Float64Array(ys.length); for (let i = 0; i < corrected.length; i++) { corrected[i] = ys[i] - baseline[i]; } return { baseline: baseline, correctedSpectrum: corrected }; }
/* * Globalize Culture ms-MY * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to be fixed in the generator */ (function( window, undefined ) { var Globalize; if ( typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined" ) { // Assume CommonJS Globalize = require( "globalize" ); } else { // Global variable Globalize = window.Globalize; } Globalize.addCultureInfo( "ms-MY", "default", { name: "ms-MY", englishName: "Malay (Malaysia)", nativeName: "Bahasa Melayu (Malaysia)", language: "ms", numberFormat: { currency: { decimals: 0, symbol: "RM" } }, calendars: { standard: { firstDay: 1, days: { names: ["Ahad","Isnin","Selasa","Rabu","Khamis","Jumaat","Sabtu"], namesAbbr: ["Ahad","Isnin","Sel","Rabu","Khamis","Jumaat","Sabtu"], namesShort: ["A","I","S","R","K","J","S"] }, months: { names: ["Januari","Februari","Mac","April","Mei","Jun","Julai","Ogos","September","Oktober","November","Disember",""], namesAbbr: ["Jan","Feb","Mac","Apr","Mei","Jun","Jul","Ogos","Sept","Okt","Nov","Dis",""] }, AM: null, PM: null, patterns: { d: "dd/MM/yyyy", D: "dd MMMM yyyy", t: "H:mm", T: "H:mm:ss", f: "dd MMMM yyyy H:mm", F: "dd MMMM yyyy H:mm:ss", M: "dd MMMM", Y: "MMMM yyyy" } } } }); }( this ));
/*$(document).on("click", '.change_status', function(e) { e.preventDefault(); var thisBtn = this; console.log(this); var status = $(this).attr('data-status'); var id = $(this).attr('data-id'); var token = $('#token').val(); var data = {'id':id, 'status':status, 'token':token }; $.ajax({ url: "/admin/change_tag_status/"+id, data : $('#status_change_form_'+id).serialize(), method: "PUT", success: function(result){ $('#status_'+id).val((($('#status_'+id).val()) == 0)?1:0); $(thisBtn).toggleClass('btn-success btn-danger'); $(thisBtn).text(($(thisBtn).text() == 'Active' )?'Inactive':'Active'); } }); });*/
import React from "react"; import { withStyles } from "material-ui"; // nodejs library to set properties for components import PropTypes from "prop-types"; import typographyStyle from "../../../assets/jss/material-kit-react/components/typographyStyle"; function Quote({ ...props }) { const { classes, text, author } = props; return ( <blockquote className={classes.defaultFontStyle + " " + classes.quote}> <p className={classes.quoteText}>{text}</p> <small className={classes.quoteAuthor}>{author}</small> </blockquote> ); } Quote.propTypes = { classes: PropTypes.object.isRequired, text: PropTypes.node, author: PropTypes.node }; export default withStyles(typographyStyle)(Quote);
import React from 'react'; import DefaultImage from './DefaultImage'; import FullWidthImage from './FullWidthImage'; import { imageCaptionStyles } from 'styles'; /** * Image caption slice component */ const ImageCaption = ({ slice }) => ( <> {slice.slice_label === 'image-full-width' ? ( <FullWidthImage slice={slice} /> ) : ( <DefaultImage slice={slice} /> )} <style jsx global> {imageCaptionStyles} </style> </> ); export default ImageCaption;
// NOTE: Needs specific dates to pass tests describe("Public List by Date Test", function() { it("GIVEN: User navigates to events page", function() { cy.visit("/public/events"); }); it("WHEN: User specifies a specific date range", function() { cy.get("[data-cy=end-date-picker]").click(); cy.get( ".v-date-picker-header > :nth-child(1) > .v-btn__content > .v-icon" ).click(); cy.get(":nth-child(4) > :nth-child(7) > .v-btn") .eq(1) .click(); }); it("THEN: Events that only start in the specified date range appear", function() { cy.get(".container").should("not.contain", "1/20/2019"); cy.get(".container").contains("1/18/2019"); cy.get(".container").contains("1/19/2019"); }); });
# In this script Kth Nearest Neighbor (Knn) machine learning algorithm used on dataset.csv # This dataset consist of 1000 samples with 26 features each # https://scikit-learn.org/stable/modules/neighbors.html import numpy as np from utils import load_analytic_data, save_sklearn_model from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder, StandardScaler from sklearn.neighbors import KNeighborsClassifier dataset = load_analytic_data("dataset.csv") # Encoding the labels genres = dataset.iloc[:, -1] # Last column encoder = LabelEncoder() labels = encoder.fit_transform(genres) # Scaling the features scaler = StandardScaler() # MinMaxScaler() can be also used features = scaler.fit_transform(np.array(dataset.iloc[:, :-1], dtype=float)) # Dividing dataset into training and testing sets # 80to20 split x_train, x_test, y_train, y_test = train_test_split(features, labels, test_size=0.2) # Create knn model model = KNeighborsClassifier(n_neighbors=9, weights="distance") # Training model.fit(x_train, y_train) # Testing accuracy = model.score(x_test, y_test) print(accuracy) # Save model save_sklearn_model(model, "knn.sk")
/** * 寻医问药mip改造 新版广告组件 * @file 脚本支持 * @author [email protected] * @time 2018.05.07 * @version 1.0.7 */ define(function (require) { var $ = require('zepto'); var customElem = require('customElement').create(); var loadAd = function (elem, className, content, token) { var el = document.createElement('div'); var script = document.createElement('script'); var json = null; var arr = []; var res = content.replace(/\[|\,\s*|\]/g, function (matchs) { if (matchs === '[') { return '["'; } else if ($.trim(matchs) === ',') { return '","'; } else if (matchs === ']') { return '"]'; } }); json = JSON.parse(res); if (className.lastIndexOf('exdiv') > -1) { if (typeof window.exAdStore === 'undefined') { window.exAdStore = {}; } arr.push('exAdStore["' + json[0] + '"]'); } else { if (typeof window.adStore === 'undefined') { window.adStore = {}; } arr.push('adStore["' + json[0] + '"]'); } arr.push('='); arr.push('"' + json[1] + '"'); el.className = className; script.type = 'text/javascript'; script.innerHTML = arr.join(''); $(elem).html('').append(el); $(el).append(script); }; // build 方法,元素插入到文档时执行,仅会执行一次 customElem.prototype.build = function () { // this.element 可取到当前实例对应的 dom 元素 var elem = this.element; var elStr = $(elem).attr('el'); var adStr = $(elem).attr('ads'); var domain = document.domain; var url = document.URL; if (domain === '3g.xywy.com') { $('.top-float').hide(); $('.hot-news-panel').addClass('none'); $('.mobile-ad-rnk1-panel').removeClass('none'); $('.mobile-ad-rnk2-panel').removeClass('none'); } if (url.indexOf('3g-xywy-com.mipcdn.com') > -1 && url.indexOf('3g.xywy.com') > -1) { $('mip-fixed[type="bottom"]').hide(); $('.mobile-ad-rnk3-panel').removeClass('none'); } loadAd(elem, elStr, adStr); }; return customElem; });
/** * ProxyStore is a superclass of {@link Ext.data.Store} and {@link Ext.data.BufferedStore}. It's never used directly, * but offers a set of methods used by both of those subclasses. * * We've left it here in the docs for reference purposes, but unless you need to make a whole new type of Store, what * you're probably looking for is {@link Ext.data.Store}. If you're still interested, here's a brief description of what * ProxyStore is and is not. * * ProxyStore provides the basic configuration for anything that can be considered a Store. It expects to be * given a {@link Ext.data.Model Model} that represents the type of data in the Store. It also expects to be given a * {@link Ext.data.proxy.Proxy Proxy} that handles the loading of data into the Store. * * ProxyStore provides a few helpful methods such as {@link #method-load} and {@link #sync}, which load and save data * respectively, passing the requests through the configured {@link #proxy}. * * Built-in Store subclasses add extra behavior to each of these functions. Note also that each ProxyStore subclass * has its own way of storing data - in {@link Ext.data.Store} the data is saved as a flat {@link Ext.util.Collection Collection}, * whereas in {@link Ext.data.BufferedStore BufferedStore} we use a {@link Ext.data.PageMap} to maintain a client side cache of pages of records. * * The store provides filtering and sorting support. This sorting/filtering can happen on the client side * or can be completed on the server. This is controlled by the {@link Ext.data.Store#remoteSort remoteSort} and * {@link Ext.data.Store#remoteFilter remoteFilter} config options. For more information see the {@link #method-sort} and * {@link Ext.data.Store#filter filter} methods. */ Ext.define('Ext.data.ProxyStore', { extend: 'Ext.data.AbstractStore', requires: [ 'Ext.data.Model', 'Ext.data.proxy.Proxy', 'Ext.data.proxy.Memory', 'Ext.data.operation.*' ], config: { // @cmd-auto-dependency {aliasPrefix: "model.", mvc: true, blame: "all"} /** * @cfg {String/Ext.data.Model} model * Name of the {@link Ext.data.Model Model} associated with this store. See * {@link Ext.data.Model#entityName}. * * May also be the actual Model subclass. * * This config is required for the store to be able to read data unless you have defined * the {@link #fields} config which will create an anonymous `Ext.data.Model`. */ model: undefined, // @cmd-auto-dependency {aliasPrefix: "data.field."} /** * @cfg {Object[]/String[]} fields * @inheritdoc Ext.data.Model#cfg-fields * * @localdoc **Note:** In general, this configuration option should only be used * for simple stores like a two-field store of * {@link Ext.form.field.ComboBox ComboBox}. For anything more complicated, such * as specifying a particular id property or associations, a * {@link Ext.data.Model Model} should be defined and specified for the * {@link #model} config. * * @since 2.3.0 */ fields: null, // @cmd-auto-dependency {aliasPrefix : "proxy."} /** * @cfg {String/Ext.data.proxy.Proxy/Object} proxy * The Proxy to use for this Store. This can be either a string, a config object or a Proxy instance - * see {@link #setProxy} for details. * @since 1.1.0 */ proxy: undefined, /** * @cfg {Boolean/Object} autoLoad * If data is not specified, and if autoLoad is true or an Object, this store's load method is automatically called * after creation. If the value of autoLoad is an Object, this Object will be passed to the store's load method. * * It's important to note that {@link Ext.data.TreeStore Tree Stores} will * load regardless of autoLoad's value if expand is set to true on the * {@link Ext.data.TreeStore#root root node}. * * @since 2.3.0 */ autoLoad: undefined, /** * @cfg {Boolean} autoSync * True to automatically sync the Store with its Proxy after every edit to one of its Records. Defaults to false. */ autoSync: false, /** * @cfg {String} batchUpdateMode * Sets the updating behavior based on batch synchronization. 'operation' (the default) will update the Store's * internal representation of the data after each operation of the batch has completed, 'complete' will wait until * the entire batch has been completed before updating the Store's data. 'complete' is a good choice for local * storage proxies, 'operation' is better for remote proxies, where there is a comparatively high latency. */ batchUpdateMode: 'operation', /** * @cfg {Boolean} sortOnLoad * If true, any sorters attached to this Store will be run after loading data, before the datachanged event is fired. * Defaults to true, ignored if {@link Ext.data.Store#remoteSort remoteSort} is true */ sortOnLoad: true, /** * @cfg {Boolean} [trackRemoved=true] * This config controls whether removed records are remembered by this store for * later saving to the server. */ trackRemoved: true, /** * @cfg {Boolean} [asynchronousLoad] * This defaults to `true` when this store's {@link #cfg-proxy} is asynchronous, such as an * {@link Ext.data.proxy.Ajax Ajax proxy}. * * When the proxy is synchronous, such as a {@link Ext.data.proxy.Memory} memory proxy, this * defaults to `false`. * * *NOTE:* This does not cause synchronous Ajax requests if configured `false` when an Ajax proxy * is used. It causes immediate issuing of an Ajax request when {@link #method-load} is called * rather than issuing the request at the end of the current event handler run. * * What this means is that when using an Ajax proxy, calls to * {@link #method-load} do not fire the request to the remote resource * immediately, but schedule a request to be made. This is so that multiple * requests are not fired when mutating a store's remote filters and sorters (as * happens during state restoration). The request is made only once after all * relevant store state is fully set. * * @since 6.0.1 */ asynchronousLoad: undefined }, onClassExtended: function(cls, data, hooks) { var model = data.model, onBeforeClassCreated; if (typeof model === 'string') { onBeforeClassCreated = hooks.onBeforeCreated; hooks.onBeforeCreated = function() { var me = this, args = arguments; Ext.require(model, function() { onBeforeClassCreated.apply(me, args); }); }; } }, /** * @private * @property {Boolean} * The class name of the model that this store uses if no explicit {@link #model} is given */ implicitModel: 'Ext.data.Model', /** * @property {Object} lastOptions * Property to hold the last options from a {@link #method-load} method call. This object is used for the {@link #method-reload} * to reuse the same options. Please see {@link #method-reload} for a simple example on how to use the lastOptions property. */ /** * @property {Number} autoSyncSuspended * A counter to track suspensions. * @private */ autoSyncSuspended: 0, //documented above constructor: function(config) { var me = this; // <debug> var configModel = me.model; // </debug> /** * @event beforeload * Fires before a request is made for a new data object. If the beforeload handler returns false the load * action will be canceled. * @param {Ext.data.Store} store This Store * @param {Ext.data.operation.Operation} operation The Ext.data.operation.Operation object that will be passed to the Proxy to * load the Store * @since 1.1.0 */ /** * @event load * Fires whenever the store reads data from a remote data source. * @param {Ext.data.Store} this * @param {Ext.data.Model[]} records An array of records * @param {Boolean} successful True if the operation was successful. * @param {Ext.data.operation.Read} operation The * {@link Ext.data.operation.Read Operation} object that was used in the data * load call * @since 1.1.0 */ /** * @event write * Fires whenever a successful write has been made via the configured {@link #proxy Proxy} * @param {Ext.data.Store} store This Store * @param {Ext.data.operation.Operation} operation The {@link Ext.data.operation.Operation Operation} object that was used in * the write * @since 3.4.0 */ /** * @event beforesync * Fired before a call to {@link #sync} is executed. Return false from any listener to cancel the sync * @param {Object} options Hash of all records to be synchronized, broken down into create, update and destroy */ /** * @event metachange * Fires when this store's underlying reader (available via the proxy) provides new metadata. * Metadata usually consists of new field definitions, but can include any configuration data * required by an application, and can be processed as needed in the event handler. * This event is currently only fired for JsonReaders. * @param {Ext.data.Store} this * @param {Object} meta The JSON metadata * @since 1.1.0 */ /** * Temporary cache in which removed model instances are kept until successfully * synchronised with a Proxy, at which point this is cleared. * * This cache is maintained unless you set `trackRemoved` to `false`. * * @protected * @property {Ext.data.Model[]} removed */ me.removed = []; me.callParent(arguments); if (me.getAsynchronousLoad() === false) { me.flushLoad(); } // <debug> if (!me.getModel() && me.useModelWarning !== false && me.getStoreId() !== 'ext-empty-store') { // There are a number of ways things could have gone wrong, try to give as much information as possible var logMsg = [ Ext.getClassName(me) || 'Store', ' created with no model.' ]; if (typeof configModel === 'string') { logMsg.push(" The name '", configModel, "'", ' does not correspond to a valid model.'); } Ext.log.warn(logMsg.join('')); } // </debug> }, applyAsynchronousLoad: function(asynchronousLoad) { // Default in an asynchronousLoad setting. // It defaults to false if the proxy is synchronous, and true if the proxy is asynchronous. if (asynchronousLoad == null) { asynchronousLoad = !this.loadsSynchronously(); } return asynchronousLoad; }, updateAutoLoad: function(autoLoad) { // Ensure the data collection is set up this.getData(); if (autoLoad) { // Defer the load until idle, when the store (and probably the view) is fully constructed this.load(Ext.isObject(autoLoad) ? autoLoad : undefined); } }, /** * Returns the total number of {@link Ext.data.Model Model} instances that the {@link Ext.data.proxy.Proxy Proxy} * indicates exist. This will usually differ from {@link #getCount} when using paging - getCount returns the * number of records loaded into the Store at the moment, getTotalCount returns the number of records that * could be loaded into the Store if the Store contained all data * @return {Number} The total number of Model instances available via the Proxy. 0 returned if * no value has been set via the reader. */ getTotalCount: function() { return this.totalCount || 0; }, applyFields: function(fields) { if (fields) { this.createImplicitModel(fields); } }, applyModel: function(model) { if (model) { model = Ext.data.schema.Schema.lookupEntity(model); } else if (!this.destroying) { // If no model, ensure that the fields config is converted to a model. this.getFields(); model = this.getModel() || this.createImplicitModel(); } return model; }, applyProxy: function(proxy) { var model = this.getModel(); if (proxy !== null) { if (proxy) { if (proxy.isProxy) { proxy.setModel(model); } else { if (Ext.isString(proxy)) { proxy = { type: proxy, model: model }; } else if (!proxy.model) { proxy = Ext.apply({ model: model }, proxy); } proxy = Ext.createByAlias('proxy.' + proxy.type, proxy); proxy.autoCreated = true; } } else if (model) { proxy = model.getProxy(); this.useModelProxy = true; } if (!proxy) { proxy = Ext.createByAlias('proxy.memory'); proxy.autoCreated = true; } } return proxy; }, applyState: function (state) { var me = this; me.callParent([state]); // This is called during construction. Sorters and filters might have changed // which require a reload. // If autoLoad is true, it might have loaded synchronously from a memory proxy, so needs to reload. // If it is already loaded, we definitely need to reload to apply the state. if (me.getAutoLoad() || me.isLoaded()) { me.load(); } }, updateProxy: function(proxy, oldProxy) { this.proxyListeners = Ext.destroy(this.proxyListeners); }, updateTrackRemoved: function (track) { this.cleanRemoved(); this.removed = track ? [] : null; }, /** * @private */ onMetaChange: function(proxy, meta) { this.fireEvent('metachange', this, meta); }, //saves any phantom records create: function(data, options) { var me = this, Model = me.getModel(), instance = new Model(data), operation; options = Ext.apply({}, options); if (!options.records) { options.records = [instance]; } options.internalScope = me; options.internalCallback = me.onProxyWrite; operation = me.createOperation('create', options); return operation.execute(); }, read: function() { return this.load.apply(this, arguments); }, update: function(options) { var me = this, operation; options = Ext.apply({}, options); if (!options.records) { options.records = me.getUpdatedRecords(); } options.internalScope = me; options.internalCallback = me.onProxyWrite; operation = me.createOperation('update', options); return operation.execute(); }, /** * @private * Callback for any write Operation over the Proxy. Updates the Store's MixedCollection to reflect * the updates provided by the Proxy */ onProxyWrite: function(operation) { var me = this, success = operation.wasSuccessful(), records = operation.getRecords(); switch (operation.getAction()) { case 'create': me.onCreateRecords(records, operation, success); break; case 'update': me.onUpdateRecords(records, operation, success); break; case 'destroy': me.onDestroyRecords(records, operation, success); break; } if (success) { me.fireEvent('write', me, operation); me.fireEvent('datachanged', me); } }, // may be implemented by store subclasses onCreateRecords: Ext.emptyFn, // may be implemented by store subclasses onUpdateRecords: Ext.emptyFn, /** * Removes any records when a write is returned from the server. * @private * @param {Ext.data.Model[]} records The array of removed records * @param {Ext.data.operation.Operation} operation The operation that just completed * @param {Boolean} success True if the operation was successful */ onDestroyRecords: function(records, operation, success) { if (success) { this.cleanRemoved(); } }, // tells the attached proxy to destroy the given records // @since 3.4.0 erase: function(options) { var me = this, operation; options = Ext.apply({}, options); if (!options.records) { options.records = me.getRemovedRecords(); } options.internalScope = me; options.internalCallback = me.onProxyWrite; operation = me.createOperation('destroy', options); return operation.execute(); }, /** * @private * Attached as the 'operationcomplete' event listener to a proxy's Batch object. By default just calls through * to onProxyWrite. */ onBatchOperationComplete: function(batch, operation) { return this.onProxyWrite(operation); }, /** * @private * Attached as the 'complete' event listener to a proxy's Batch object. Iterates over the batch operations * and updates the Store's internal data MixedCollection. */ onBatchComplete: function(batch, operation) { var me = this, operations = batch.operations, length = operations.length, i; if (me.batchUpdateMode !== 'operation') { me.suspendEvents(); for (i = 0; i < length; i++) { me.onProxyWrite(operations[i]); } me.resumeEvents(); } me.isSyncing = false; me.fireEvent('datachanged', me); }, /** * @private */ onBatchException: function(batch, operation) { // //decide what to do... could continue with the next operation // batch.start(); // // //or retry the last operation // batch.retry(); }, /** * @private * Filter function for new records. */ filterNew: function(item) { // only want phantom records that are valid return item.phantom === true && item.isValid(); }, /** * Returns all `{@link Ext.data.Model#property-phantom phantom}` records in this store. * @return {Ext.data.Model[]} A possibly empty array of `phantom` records. */ getNewRecords: function() { return []; }, /** * Returns all valid, non-phantom Model instances that have been updated in the Store but not yet synchronized with the Proxy. * @return {Ext.data.Model[]} The updated Model instances */ getUpdatedRecords: function() { return []; }, /** * Gets all {@link Ext.data.Model records} added or updated since the last commit. Note that the order of records * returned is not deterministic and does not indicate the order in which records were modified. Note also that * removed records are not included (use {@link #getRemovedRecords} for that). * @return {Ext.data.Model[]} The added and updated Model instances */ getModifiedRecords : function(){ return [].concat(this.getNewRecords(), this.getUpdatedRecords()); }, /** * @private * Filter function for updated records. */ filterUpdated: function(item) { // only want dirty records, not phantoms that are valid return item.dirty === true && item.phantom !== true && item.isValid(); }, /** * Returns any records that have been removed from the store but not yet destroyed on the proxy. * @return {Ext.data.Model[]} The removed Model instances. Note that this is a *copy* of the store's * array, so may be mutated. */ getRemovedRecords: function() { var removed = this.getRawRemovedRecords(); return removed ? Ext.Array.clone(removed) : []; }, /** * Synchronizes the store with its {@link #proxy}. This asks the proxy to batch together any new, updated * and deleted records in the store, updating the store's internal representation of the records * as each operation completes. * * @param {Object} [options] Object containing one or more properties supported by the sync method (these get * passed along to the underlying proxy's {@link Ext.data.Proxy#batch batch} method): * * @param {Ext.data.Batch/Object} [options.batch] A {@link Ext.data.Batch} object (or batch config to apply * to the created batch). If unspecified a default batch will be auto-created as needed. * * @param {Function} [options.callback] The function to be called upon completion of the sync. * The callback is called regardless of success or failure and is passed the following parameters: * @param {Ext.data.Batch} options.callback.batch The {@link Ext.data.Batch batch} that was processed, * containing all operations in their current state after processing * @param {Object} options.callback.options The options argument that was originally passed into sync * * @param {Function} [options.success] The function to be called upon successful completion of the sync. The * success function is called only if no exceptions were reported in any operations. If one or more exceptions * occurred then the failure function will be called instead. The success function is called * with the following parameters: * @param {Ext.data.Batch} options.success.batch The {@link Ext.data.Batch batch} that was processed, * containing all operations in their current state after processing * @param {Object} options.success.options The options argument that was originally passed into sync * * @param {Function} [options.failure] The function to be called upon unsuccessful completion of the sync. The * failure function is called when one or more operations returns an exception during processing (even if some * operations were also successful). In this case you can check the batch's {@link Ext.data.Batch#exceptions * exceptions} array to see exactly which operations had exceptions. The failure function is called with the * following parameters: * @param {Ext.data.Batch} options.failure.batch The {@link Ext.data.Batch} that was processed, containing all * operations in their current state after processing * @param {Object} options.failure.options The options argument that was originally passed into sync * * @param {Object} [options.params] Additional params to send during the sync Operation(s). * * @param {Object} [options.scope] The scope in which to execute any callbacks (i.e. the `this` object inside * the callback, success and/or failure functions). Defaults to the store's proxy. * * @return {Ext.data.Store} this */ sync: function(options) { var me = this, operations = {}, toCreate = me.getNewRecords(), toUpdate = me.getUpdatedRecords(), toDestroy = me.getRemovedRecords(), needsSync = false; //<debug> if (me.isSyncing) { Ext.log.warn('Sync called while a sync operation is in progress. Consider configuring autoSync as false.'); } //</debug> me.needsSync = false; if (toCreate.length > 0) { operations.create = toCreate; needsSync = true; } if (toUpdate.length > 0) { operations.update = toUpdate; needsSync = true; } if (toDestroy.length > 0) { operations.destroy = toDestroy; needsSync = true; } if (needsSync && me.fireEvent('beforesync', operations) !== false) { me.isSyncing = true; options = options || {}; me.proxy.batch(Ext.apply(options, { operations: operations, listeners: me.getBatchListeners() })); } return me; }, /** * @private * Returns an object which is passed in as the listeners argument to proxy.batch inside this.sync. * This is broken out into a separate function to allow for customisation of the listeners * @return {Object} The listeners object */ getBatchListeners: function() { var me = this, listeners = { scope: me, exception: me.onBatchException, complete: me.onBatchComplete }; if (me.batchUpdateMode === 'operation') { listeners.operationcomplete = me.onBatchOperationComplete; } return listeners; }, /** * Saves all pending changes via the configured {@link #proxy}. Use {@link #sync} instead. * @deprecated 4.0.0 Will be removed in the next major version */ save: function() { return this.sync.apply(this, arguments); }, /** * Marks this store as needing a load. When the current executing event handler exits, * this store will send a request to load using its configured {@link #proxy}. * * Upon return of the data from whatever data source the proxy connected to, the retrieved * {@link Ext.data.Model records} will be loaded into this store, and the optional callback will be called. * Example usage: * * store.load({ * scope: this, * callback: function(records, operation, success) { * // the operation object * // contains all of the details of the load operation * console.log(records); * } * }); * * If the callback scope does not need to be set, a function can simply be passed: * * store.load(function(records, operation, success) { * console.log('loaded records'); * }); * * @param {Object} [options] This is passed into the {@link Ext.data.operation.Operation Operation} * object that is created and then sent to the proxy's {@link Ext.data.proxy.Proxy#read} function. * In addition to the options listed below, this object may contain properties to configure the * {@link Ext.data.operation.Operation Operation}. * @param {Function} [options.callback] A function which is called when the response arrives. * @param {Ext.data.Model[]} options.callback.records Array of records. * @param {Ext.data.operation.Operation} options.callback.operation The Operation itself. * @param {Boolean} options.callback.success `true` when operation completed successfully. * @param {Boolean} [options.addRecords=false] Specify as `true` to *add* the incoming records rather than the * default which is to have the incoming records *replace* the existing store contents. * * @return {Ext.data.Store} this * @since 1.1.0 */ load: function(options) { var me = this; // Legacy option. Specifying a function was allowed. if (typeof options === 'function') { options = { callback: options }; } else { // We may mutate the options object in setLoadOptions. options = options ? Ext.Object.chain(options) : {}; } me.pendingLoadOptions = options; // If we are configured to load asynchronously (the default for async proxies) // then schedule a flush, unless one is already scheduled. if (me.getAsynchronousLoad()) { if (!me.loadTimer) { me.loadTimer = Ext.asap(me.flushLoad, me); } } // If we are configured to load synchronously (the default for sync proxies) // then flush the load now. else { me.flushLoad(); } return me; }, /** * Called when the event handler which called the {@link #method-load} method exits. */ flushLoad: function() { var me = this, options = me.pendingLoadOptions, operation; // If it gets called programatically before the timer fired, the listener will need cancelling. me.clearLoadTask(); if (!options) { return; } me.setLoadOptions(options); if (me.getRemoteSort() && options.sorters) { me.fireEvent('beforesort', me, options.sorters); } operation = Ext.apply({ internalScope: me, internalCallback: me.onProxyLoad, scope: me }, options); me.lastOptions = operation; operation = me.createOperation('read', operation); if (me.fireEvent('beforeload', me, operation) !== false) { me.onBeforeLoad(operation); me.loading = true; operation.execute(); } }, /** * Reloads the store using the last options passed to the {@link #method-load} method. You can use the reload method to reload the * store using the parameters from the last load() call. For example: * * store.load({ * params : { * userid : 22216 * } * }); * * //... * * store.reload(); * * The initial {@link #method-load} execution will pass the `userid` parameter in the request. The {@link #reload} execution * will also send the same `userid` parameter in its request as it will reuse the `params` object from the last {@link #method-load} call. * * You can override a param by passing in the config object with the `params` object: * * store.load({ * params : { * userid : 22216, * foo : 'bar' * } * }); * * //... * * store.reload({ * params : { * userid : 1234 * } * }); * * The initial {@link #method-load} execution sends the `userid` and `foo` parameters but in the {@link #reload} it only sends * the `userid` paramter because you are overriding the `params` config not just overriding the one param. To only change a single param * but keep other params, you will have to get the last params from the {@link #lastOptions} property: * * var lastOptions = store.lastOptions, * lastParams = Ext.clone(lastOptions.params); // make a copy of the last params so we don't affect future reload() calls * * lastParams.userid = 1234; * * store.reload({ * params : lastParams * }); * * This will now send the `userid` parameter as `1234` and the `foo` param as `'bar'`. * * @param {Object} [options] A config object which contains options which may override the options passed to the previous load call. See the * {@link #method-load} method for valid configs. */ reload: function(options) { return this.load(Ext.apply({}, options, this.lastOptions)); }, onEndUpdate: function() { var me = this; if (me.needsSync && me.autoSync && !me.autoSyncSuspended) { me.sync(); } }, /** * @private * A model instance should call this method on the Store it has been {@link Ext.data.Model#join joined} to.. * @param {Ext.data.Model} record The model instance that was edited * @since 3.4.0 */ afterReject: function(record) { var me = this; // Must pass the 5th param (modifiedFieldNames) as null, otherwise the // event firing machinery appends the listeners "options" object to the arg list // which may get used as the modified fields array by a handler. // This array is used for selective grid cell updating by Grid View. // Null will be treated as though all cells need updating. if (me.contains(record)) { me.onUpdate(record, Ext.data.Model.REJECT, null); me.fireEvent('update', me, record, Ext.data.Model.REJECT, null); } }, /** * @private * A model instance should call this method on the Store it has been {@link Ext.data.Model#join joined} to. * @param {Ext.data.Model} record The model instance that was edited * @since 3.4.0 */ afterCommit: function(record, modifiedFieldNames) { var me = this; if (!modifiedFieldNames) { modifiedFieldNames = null; } if (me.contains(record)) { me.onUpdate(record, Ext.data.Model.COMMIT, modifiedFieldNames); me.fireEvent('update', me, record, Ext.data.Model.COMMIT, modifiedFieldNames); } }, afterErase: function(record) { this.onErase(record); }, onErase: Ext.emptyFn, onUpdate: Ext.emptyFn, /** * @private */ doDestroy: function() { var me = this, proxy = me.getProxy(); me.clearLoadTask(); me.getData().destroy(); me.data = null; me.setProxy(null); if (proxy.autoCreated) { proxy.destroy(); } me.setModel(null); me.callParent(); }, /** * Returns true if the store has a pending load task. * @return {Boolean} `true` if the store has a pending load task. * @private */ hasPendingLoad: function() { return !!this.pendingLoadOptions || this.isLoading(); }, /** * Returns true if the Store is currently performing a load operation * @return {Boolean} `true` if the Store is currently loading */ isLoading: function() { return !!this.loading; }, /** * Returns `true` if the Store has been loaded. * @return {Boolean} `true` if the Store has been loaded. */ isLoaded: function() { return this.loadCount > 0; }, /** * Suspends automatically syncing the Store with its Proxy. Only applicable if {@link #autoSync} is `true` */ suspendAutoSync: function() { ++this.autoSyncSuspended; }, /** * Resumes automatically syncing the Store with its Proxy. Only applicable if {@link #autoSync} is `true` * @param {Boolean} syncNow Pass `true` to synchronize now. Only synchronizes with the Proxy if the suspension * count has gone to zero (We are not under a higher level of suspension) * */ resumeAutoSync: function(syncNow) { var me = this; //<debug> if (!me.autoSyncSuspended) { Ext.log.warn('Mismatched call to resumeAutoSync - auto synchronization is currently not suspended.'); } //</debug> if (me.autoSyncSuspended && ! --me.autoSyncSuspended) { if (syncNow) { me.sync(); } } }, /** * Removes all records from the store. This method does a "fast remove", * individual remove events are not called. The {@link #clear} event is * fired upon completion. * @method * @since 1.1.0 */ removeAll: Ext.emptyFn, // individual store subclasses should implement a "fast" remove // and fire a clear event afterwards // to be implemented by subclasses clearData: Ext.emptyFn, privates: { /** * @private * Returns the array of records which have been removed since the last time this store was synced. * * This is used internally, when purging removed records after a successful sync. * This is overridden by TreeStore because TreeStore accumulates deleted records on removal * of child nodes from their parent, *not* on removal of records from its collection. The collection * has records added on expand, and removed on collapse. */ getRawRemovedRecords: function() { return this.removed; }, onExtraParamsChanged: function() { }, clearLoadTask: function() { if (this.loadTimer) { Ext.asapCancel(this.loadTimer); } this.pendingLoadOptions = this.loadTimer = null; }, cleanRemoved: function() { // Must use class-specific getRawRemovedRecords. // Regular Stores add to the "removed" property on remove. // TreeStores are having records removed all the time; node collapse removes. // TreeStores add to the "removedNodes" property onNodeRemove var removed = this.getRawRemovedRecords(), len, i; if (removed) { for (i = 0, len = removed.length; i < len; ++i) { removed[i].unjoin(this); } removed.length = 0; } }, createOperation: function(type, options) { var me = this, proxy = me.getProxy(), listeners; if (!me.proxyListeners) { listeners = { scope: me, destroyable: true, beginprocessresponse: me.beginUpdate, endprocessresponse: me.endUpdate }; if (!me.disableMetaChangeEvent) { listeners.metachange = me.onMetaChange; } me.proxyListeners = proxy.on(listeners); } return proxy.createOperation(type, options); }, createImplicitModel: function(fields) { var me = this, modelCfg = { extend: me.implicitModel, statics: { defaultProxy: 'memory' } }, proxy, model; if (fields) { modelCfg.fields = fields; } model = Ext.define(null, modelCfg); me.setModel(model); proxy = me.getProxy(); if (proxy) { model.setProxy(proxy); } else { me.setProxy(model.getProxy()); } }, loadsSynchronously: function() { return this.getProxy().isSynchronous; }, onBeforeLoad: Ext.privateFn, removeFromRemoved: function(record) { // Must use class-specific getRawRemovedRecords. // Regular Stores add to the "removed" property on remove. // TreeStores are having records removed all the time; node collapse removes. // TreeStores add to the "removedNodes" property onNodeRemove var removed = this.getRawRemovedRecords(); if (removed) { Ext.Array.remove(removed, record); record.unjoin(this); } }, setLoadOptions: function(options) { var me = this, filters, sorters; if (me.getRemoteFilter()) { filters = me.getFilters(false); if (filters && filters.getCount()) { options.filters = filters.getRange(); } } if (me.getRemoteSort()) { sorters = me.getSorters(false); if (sorters && sorters.getCount()) { options.sorters = sorters.getRange(); } } } } });
import React, { useState } from 'react'; // JS // const input = document.getElementById('myText'); // const inputValue = input.value // React // value, onChange // dynamic object keys const ControlledInputs = () => { const [person, setPerson] = useState({ firstName: '', email: '', age: '' }); const [people, setPeople] = useState([]); const handleChange = (e) => { const name = e.target.name; const value = e.target.value; setPerson({ ...person, [name]: value }); }; const handleSubmit = (e) => { e.preventDefault(); if (person.firstName && person.email && person.age) { const newPerson = { ...person, id: new Date().getTime().toString() }; setPeople([...people, newPerson]); setPerson({ firstName: '', email: '', age: '' }); } }; return ( <> <article> <form className='form' onSubmit={handleChange}> <div className='form-control'> <label htmlFor='firstName'>Name : </label> <input type='text' id='firstName' name='firstName' value={person.firstName} onChange={handleChange} /> </div> <div className='form-control'> <label htmlFor='text'>age : </label> <input type='text' id='age' name='age' value={person.age} onChange={handleChange} /> </div> <div className='form-control'> <label htmlFor='email'>Email : </label> <input type='email' id='email' name='email' value={person.email} onChange={handleChange} /> </div> <button type='submit' onClick={handleSubmit}>add person</button> </form> {people.map((person) => { const { id, firstName, email, age } = person; return ( <div key={id} className='item'> <h4>{firstName}</h4> <p>{email}</p> <p>{age}</p> </div> ); })} </article> </> ); }; export default ControlledInputs;
function validateEmail(email) { // eslint-disable-next-line no-useless-escape const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } export default validateEmail;
from torch import nn import torch.nn.functional as F from torch import nn, optim from pytorch_lightning import LightningModule class MyAwesomeModel(LightningModule): def __init__(self): ''' Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input layer output_size: integer, size of the output layer hidden_layers: list of integers, the sizes of the hidden layers ''' input_size = 784 output_size = 10 hidden_layers = [512, 256, 128] drop_p = 0.5 super().__init__() # Input to a hidden layer self.hidden_layers = nn.ModuleList([nn.Linear(input_size, hidden_layers[0])]) # Add a variable number of more hidden layers layer_sizes = zip(hidden_layers[:-1], hidden_layers[1:]) self.hidden_layers.extend([nn.Linear(h1, h2) for h1, h2 in layer_sizes]) self.output = nn.Linear(hidden_layers[-1], output_size) self.dropout = nn.Dropout(p=drop_p) self.criterium = nn.CrossEntropyLoss() def forward(self, x): ''' Forward pass through the network, returns the output logits ''' for each in self.hidden_layers: x = F.relu(each(x)) x = self.dropout(x) x = self.output(x) return F.log_softmax(x, dim=1) def training_step(self, batch, batch_idx): data, target = batch data.resize_(data.size()[0], 784) preds = self(data) loss = self.criterium(preds, target) self.log("loss", loss) return loss def configure_optimizers(self): learning_rate = 1e-2 return optim.Adam(self.parameters(), lr=learning_rate)
log_level = 'INFO' load_from = None resume_from = None dist_params = dict(backend='nccl') workflow = [('train', 1)] checkpoint_config = dict(interval=10) evaluation = dict(interval=100, metric='mAP') optimizer = dict( type='Adam', lr=0.0015, ) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[200, 260]) total_epochs = 300 log_config = dict( interval=50, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) channel_cfg = dict( 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 ]) data_cfg = dict( image_size=512, base_size=256, base_sigma=2, heatmap_size=[128, 256], num_joints=channel_cfg['dataset_joints'], dataset_channel=channel_cfg['dataset_channel'], inference_channel=channel_cfg['inference_channel'], num_scales=2, scale_aware_sigma=False, ) # model settings model = dict( type='BottomUp', pretrained='models/pytorch/imagenet/hrnet_w48-8ef0771d.pth', backbone=dict( type='HRNet', in_channels=3, extra=dict( stage1=dict( num_modules=1, num_branches=1, block='BOTTLENECK', num_blocks=(4, ), num_channels=(64, )), stage2=dict( num_modules=1, num_branches=2, block='BASIC', num_blocks=(4, 4), num_channels=(48, 96)), stage3=dict( num_modules=4, num_branches=3, block='BASIC', num_blocks=(4, 4, 4), num_channels=(48, 96, 192)), stage4=dict( num_modules=3, num_branches=4, block='BASIC', num_blocks=(4, 4, 4, 4), num_channels=(48, 96, 192, 384))), ), keypoint_head=dict( type='BottomUpHigherResolutionHead', in_channels=48, num_joints=17, tag_per_joint=True, extra=dict(final_conv_kerne=1, ), num_deconv_layers=1, num_deconv_filters=[48], num_deconv_kernels=[4], num_basic_blocks=4, cat_output=[True], with_ae_loss=[True, False]), train_cfg=dict( num_joints=channel_cfg['dataset_joints'], img_size=data_cfg['image_size']), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, scale_factor=[1], with_heatmaps=[True, True], with_ae=[True, False], project2image=True, nms_kernel=5, nms_padding=2, tag_per_joint=True, detection_threshold=0.1, tag_threshold=1, use_detection_val=True, ignore_too_much=False, adjust=True, refine=True, flip_test=True), loss_pose=dict( type='MultiLossFactory', num_joints=17, num_stages=2, ae_loss_type='exp', with_ae_loss=[True, False], push_loss_factor=[0.001, 0.001], pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0], ), ) train_pipeline = [ dict(type='LoadImageFromFile'), dict( type='BottomUpRandomAffine', rot_factor=30, scale_factor=[0.75, 1.5], scale_type='short', trans_factor=40), dict(type='BottomUpRandomFlip', flip_prob=0.5), dict(type='ToTensor'), dict( type='NormalizeTensor', mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), dict( type='BottomUpGenerateTarget', sigma=2, max_num_people=30, ), dict( type='Collect', keys=['img', 'joints', 'targets', 'masks'], meta_keys=[]), ] val_pipeline = [ dict(type='LoadImageFromFile'), dict(type='BottomUpGetImgSize', test_scale_factor=[1]), # dict(type='BottomUpGetImgSize', test_scale_factor=[0.5, 1, 2]), dict( type='BottomUpResizeAlign', transforms=[ 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', 'aug_data', 'test_scale_factor', 'base_size', 'center', 'scale', 'flip_index' ]), ] test_pipeline = val_pipeline data_root = 'data/coco' data = dict( samples_per_gpu=16, workers_per_gpu=2, train=dict( type='BottomUpCocoDataset', ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', img_prefix=f'{data_root}/train2017/', data_cfg=data_cfg, pipeline=train_pipeline), val=dict( type='BottomUpCocoDataset', ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', img_prefix=f'{data_root}/val2017/', data_cfg=data_cfg, pipeline=val_pipeline), test=dict( type='BottomUpCocoDataset', ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', img_prefix=f'{data_root}/val2017/', data_cfg=data_cfg, pipeline=val_pipeline), ) loss = dict( type='MultiLossFactory', num_stages=2, ae_loss_type='exp', with_ae_loss=[True, False], push_loss_factor=[0.001, 0.001], pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0], )
import OverviewInfo from './OverviewInfo'; export default OverviewInfo;
/* @flow */ import config from '../config' import { initProxy } from './proxy' import { initState } from './state' import { initRender } from './render' import { initEvents } from './events' import { mark, measure } from '../util/perf' import { initLifecycle, callHook } from './lifecycle' import { initProvide, initInjections } from './inject' import { extend, mergeOptions, formatComponentName } from '../util/index' let uid = 0 // 在Vue的原型上添加_init方法 export function initMixin (Vue: Class<Component>) { Vue.prototype._init = function (options?: Object) { // 声明常量,this => Vue const vm: Component = this // a uid // 实例vue的唯一标识 vm._uid = uid++ let startTag, endTag /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { startTag = `vue-perf-start:${vm._uid}` endTag = `vue-perf-end:${vm._uid}` mark(startTag) } // a flag to avoid this being observed // 标记该实例是vue实例 vm._isVue = true // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options) } else { // 用于当前 Vue 实例的初始化选项。需要在选项中包含自定义属性时会有用处: //规范props,inject,directives,合并extends,mixins,挂载合并属性的策略或者直接合并属性 vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), // Vue.options options || {}, // 构造函数传参 el: '#app', data vm // vue实例对象 ) } /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { initProxy(vm) } else { vm._renderProxy = vm } // expose real self vm._self = vm initLifecycle(vm) initEvents(vm) initRender(vm) callHook(vm, 'beforeCreate') initInjections(vm) // resolve injections before data/props initState(vm) initProvide(vm) // resolve provide after data/props callHook(vm, 'created') /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { vm._name = formatComponentName(vm, false) mark(endTag) measure(`vue ${vm._name} init`, startTag, endTag) } if (vm.$options.el) { vm.$mount(vm.$options.el) } } } export function initInternalComponent (vm: Component, options: InternalComponentOptions) { const opts = vm.$options = Object.create(vm.constructor.options) // doing this because it's faster than dynamic enumeration. const parentVnode = options._parentVnode opts.parent = options.parent opts._parentVnode = parentVnode const vnodeComponentOptions = parentVnode.componentOptions opts.propsData = vnodeComponentOptions.propsData opts._parentListeners = vnodeComponentOptions.listeners opts._renderChildren = vnodeComponentOptions.children opts._componentTag = vnodeComponentOptions.tag if (options.render) { opts.render = options.render opts.staticRenderFns = options.staticRenderFns } } // 获取构造函数的options Ctor:构造函数 export function resolveConstructorOptions (Ctor: Class<Component>) { let options = Ctor.options // super是子类构造函数才有的属性 // const Sub = Vue.extend() // console.log(Sub.super) // Vue if (Ctor.super) { const superOptions = resolveConstructorOptions(Ctor.super) const cachedSuperOptions = Ctor.superOptions if (superOptions !== cachedSuperOptions) { // super option changed, // need to resolve new options. Ctor.superOptions = superOptions // check if there are any late-modified/attached options (#4976) const modifiedOptions = resolveModifiedOptions(Ctor) // update base extend options if (modifiedOptions) { extend(Ctor.extendOptions, modifiedOptions) } options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions) if (options.name) { options.components[options.name] = Ctor } } } return options } function resolveModifiedOptions (Ctor: Class<Component>): ?Object { let modified const latest = Ctor.options const sealed = Ctor.sealedOptions for (const key in latest) { if (latest[key] !== sealed[key]) { if (!modified) modified = {} modified[key] = latest[key] } } return modified }
import axios from 'axios'; import { apiAddress } from './config'; export default { async getImports(titleId, rplId) { return await axios.get( `${apiAddress}/api/titles/${titleId}/rpls/${rplId}/imports`, ); }, };
$(function(e){ 'use strict' /* chartjs (#content-overview) */ var ctx = $('#content-overview'); ctx.height(158); var myChart = new Chart(ctx, { type: 'line', data: { labels: ["P1-6", "p1-8", "p2-6", "p2-8", "p3-6", "p3-8", "p4-6", "p4-8", "p5-6", "p5-8", "p6-6", "p6-8"], type: 'line', datasets: [{ label: "Time on site", data: [240, 200, 180, 140, 120, 170, 240, 220, 250, 300, 200, 140], backgroundColor: 'transparent', borderColor: '#4a32d4 ', borderWidth: 3, pointStyle: 'circle', pointRadius: 0, pointBorderColor: 'transparent', pointBackgroundColor: '#4a32d4', }, { label: "Bounce Rate", data: [140, 220, 250, 200, 240, 140, 160, 180, 260, 280, 160, 120], backgroundColor: 'transparent', borderColor: '#00b3ff', borderWidth: 3, pointStyle: 'circle', pointRadius: 0, pointBorderColor: 'transparent', pointBackgroundColor: '#00b3ff', }] }, options: { responsive: true, maintainAspectRatio: false, tooltips: { mode: 'index', titleFontSize: 12, titleFontColor: 'rgba(225,225,225,0.8)', bodyFontColor: 'rgba(225,225,225,0.8)', backgroundColor: 'rgba(0,0,0,0.8)', bodyFontFamily: 'Montserrat', cornerRadius: 3, intersect: false, }, legend: { display: false, labels: { usePointStyle: true, }, }, scales: { xAxes: [{ ticks: { fontColor: "#8e9cad ", }, display: true, gridLines: { color: 'rgb(142, 156, 173,0.2)' }, scaleLabel: { display: false, labelString: '' } }], yAxes: [{ ticks: { fontColor: "#8e9cad ", }, display: true, gridLines: { display: false, drawBorder: true }, scaleLabel: { display: false, labelString: 'Response time In secs' } }] }, title: { display: false, text: 'Normal Legend' } } }); /* chartjs (#content-overview) closed */ /* Chartjs (#total-visits) */ var ctx = document.getElementById("total-visits"); var myChart = new Chart( ctx, { type: 'line', data: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug','Sep','Oct'], type: 'line', datasets: [ { data: [1, 7, 3, 9, 4, 5, 2, 4,1,0], label: 'total-visits', backgroundColor: 'rgba(0, 179, 255,0.6)', borderColor: 'rgba(0, 179, 255,0.9)', borderWidth:2.5, }, ] }, options: { maintainAspectRatio: true, legend: { display: false }, responsive: true, tooltips: { mode: 'index', titleFontSize: 12, titleFontColor: '#000', bodyFontColor: '#000', backgroundColor: '#fff', cornerRadius: 0, intersect: false, }, scales: { xAxes: [ { gridLines: { color: 'transparent', zeroLineColor: 'transparent' }, ticks: { fontSize: 2, fontColor: 'transparent' } } ], yAxes: [ { display:false, ticks: { display: false, } } ] }, title: { display: false, }, elements: { line: { borderWidth: 4 }, point: { radius: 0, hitRadius: 10, hoverRadius: 4 } } } }); /* Chartjs (#total-visits) closed */ /* Chartjs (#pageviews) */ var myCanvas = document.getElementById("pageviews"); myCanvas.height="233"; var myCanvasContext = myCanvas.getContext("2d"); var gradientStroke1 = myCanvasContext.createLinearGradient(0, 90, 0, 180); gradientStroke1.addColorStop(0, '#2575fc'); gradientStroke1.addColorStop(1, '#4a32d4'); var myChart = new Chart(myCanvas, { type: 'bar', data: { labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"], datasets: [{ label: 'pageviews', data: [17, 14, 12, 14, 10, 15, 7, 14,18], backgroundColor: gradientStroke1, hoverBackgroundColor: gradientStroke1, hoverBorderWidth: 2, hoverBorderColor: 'gradientStroke1' } ] }, options: { responsive: true, maintainAspectRatio: false, tooltips: { mode: 'index', titleFontSize: 12, titleFontColor: '#000', bodyFontColor: '#000', backgroundColor: '#fff', cornerRadius: 3, intersect: false, }, legend: { display: false, labels: { usePointStyle: true, }, }, scales: { xAxes: [{ barPercentage: 0.3, ticks: { fontColor: "#8e9cad ", }, display: true, gridLines: { display: false, drawBorder: false }, scaleLabel: { display: false, labelString: 'Month', fontColor: '#8e9cad ' } }], yAxes: [{ ticks: { fontColor: "transparent", }, display: true, gridLines: { display: false, drawBorder: false }, scaleLabel: { display: false, labelString: 'sales', fontColor: 'transparent' } }] }, title: { display: false, text: 'Normal Legend' } } }); /* Chartjs (#pageviews) closed */ /*-----WidgetChart2 CHARTJS-----*/ var ctx = document.getElementById( "widgetChart2" ); var myChart = new Chart( ctx, { type: 'line', data : { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'], type: 'line', datasets: [ { label: "Active Users", backgroundColor: "transparent", data: [0, 30, 10, 120, 50, 63, 102], borderColor: "#4a32d4", borderWidth: 3, pointRadius: 0, pointBorderColor: 'transparent', }, { label: "Contribution", backgroundColor: "transparent", data: [0, 50, 40, 80, 40, 79, 120], borderColor: "#17b9ff", borderWidth: 3, pointRadius: 0, pointBorderColor: 'transparent', } ] }, options: { responsive: true, maintainAspectRatio: false, tooltips: { mode: 'index', titleFontSize: 12, titleFontColor: 'rgba(225,225,225,0.8)', bodyFontColor: 'rgba(225,225,225,0.8)', backgroundColor: 'rgba(0,0,0,0.8)', bodyFontFamily: 'Montserrat', cornerRadius: 3, intersect: false, }, legend: { display: false, labels: { usePointStyle: false, }, }, scales: { xAxes: [{ ticks: { fontColor: "#8e9cad ", }, display: true, gridLines: { color: 'rgb(142, 156, 173,0.2)' }, scaleLabel: { display: false, labelString: '' } }], yAxes: [{ ticks: { fontColor: "#8e9cad ", }, display: true, gridLines: { display: false, drawBorder: true }, scaleLabel: { display: false, labelString: 'Response time In secs' } }] }, title: { display: false, text: 'Normal Legend' } } } ); /*-----WidgetChart2 CHARTJS closed -----*/ });
import sys sys.path.append('../../') import os from data_processor.GOA_simulation.GOA_ECMs_simulation import load_sim_ecm_para_config_dict """ Module Function 本次(第二次)计算Chi-Square 参照ZSimpWin中的最终定义 Tech Note 37: Least Squares Fit Formulation 3. Definition of the chi-squared Eq 10 Modulus weighting 就是在第一次的结果上在除以 v, v为系统的自由度,严格讲 v = N - M - 1,此处为了和ZSimpWIn一样,令 v = N - M N 为测试的阻抗点数,如赖师兄N=30 M 为等效电路中需要拟合的参数数目,CPE元件包含两个参数Y和n 第一此计算Chi-Square计算错误 def cal_w(raw_Z): return 1 / (raw_Z.real ** 2 + raw_Z.imag ** 2) CHi-Square = sum([cal_w(rz) * ((rz.real - sz.real)**2 + (rz.imag - sz.imag)**2) for rz, sz in zip(z_raw_complex_list, z_sim_complex_list)]) Routine 因为20种GOA已分别在9种ECM上按照第一种Chi-Square,CS-1,计算好,正确的Chi-Square,CS2,和CS1差别仅在于v, 所以将之前的结果中的CS1 除以 v即为 CS2 在原先文本的倒数第一列和第二列中间添加CS2 simECM_res folder中是几个测试文本 """ def get_V(ecm_num, file_path): ecm_para_config_dict = load_sim_ecm_para_config_dict(ecm_num, file_path) # N 为测试的阻抗点数,如赖师兄N=30 N = len(ecm_para_config_dict['f']) # M 为等效电路中需要拟合的参数数目,CPE元件包含两个参数Y和n M = len(ecm_para_config_dict['para']) # V为系统的自由度,严格讲 v = N - M - 1,此处为了和ZSimpWIn一样,令 v = N - M v = N - M return v def reCal_Chi_Square(res_fp, sim_EIS_fp): fn_list = os.listdir(res_fp) for i, fn in enumerate(fn_list): print('Processsing {0} file {1}'.format(i, fn)) # 1- txt ? if fn.endswith('.txt'): ecm_num = None # 2- 'bb_bc' ? if fn.split('_')[0] == 'bb': # bb_bc_ecm8_07.txt ecm_num = int(fn.split('.')[0].split('_')[2].split('ecm')[1]) else: # gwo_ecm5_42.txt ecm_num = int(fn.split('.')[0].split('_')[1].split('ecm')[1]) v = get_V(ecm_num, sim_EIS_fp) new_str = '' with open(os.path.join(res_fp, fn), 'r+') as f1: """ Old Line: Iteration, para_list[float, ...], Chi-Square(错误版本), Cumulated Running Time 9984, [0.02012484780316051,0.0001799896579117755, ..., 52972.38087848809], 4.433244077492469e-06, 124.94990979999966 New Line: Iteration, para_list[float, ...], Chi-Square(错误版本), Chi-Square(Right Version), Cumulated Running Time 9984, [0.02012484780316051,0.0001799896579117755, ..., 52972.38087848809], 4.433244077492469e-06, 4.433244077492469e-06 / v, 124.94990979999966 """ for line in f1.readlines(): # 1- Get CS1, Chi-Square(错误版本) line_str_list = line.strip().split(',') cs1 = float(line_str_list[-2]) # 2- Calculate CS2 = CS1 / v, CS2: Chi-Square(Right Version) cs2 = cs1 / v # 3- Create new line line_str_list.insert(-1, str(cs2)) tmp_new_line = ','.join(line_str_list)+'\n' new_str += tmp_new_line # Empty the old content # truncate() 方法用于截断文件,如果指定了可选参数 size,则表示截断文件为 size 个字符。 # 如果没有指定 size,则从当前位置起截断;截断之后 size 后面的所有字符被删除 f1.truncate(0) # Write new content into the same file with open(os.path.join(res_fp, fn), 'w') as f2: f2.write(new_str) # reCal_Chi_Square(res_fp='./simECM_res', sim_EIS_fp='../../datasets/goa_datasets')
/** * Create a new user profile */ const RegisterUser = { method: 'POST', path: '/register', schema: { body: { }, }, async handler(req, reply) { const { body, $storage, $amqp } = req; let profile = { ...body, }; const user = await $storage.users.create(profile); await $amqp.publish('lunamals.user-activity', 'registered', JSON.stringify(profile)); const payload = { id: user.id, username: user.username, permissions: [ ] } return { token: reply.jwtSign(payload), } }, }; const LoginUser = { method: 'POST', path: '/login', schema: { body: { } }, async handler(req, reply) { const { body, $storage } = req; const user = await $storage.users.fetchOne({ username: body.username, password: body.password, }) if (user === null) { res.code(404); return; } const payload = { id: user.id, username: user.username, permissions: [ ] } return { token: reply.jwtSign(payload), } } } module.exports = [ RegisterUser, LoginUser, ];
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); /* * Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. * * This is a generated file powered by the SAP Cloud SDK for JavaScript. */ var core_1 = require("@sap-cloud-sdk/core"); var ExternalTimeSegment_1 = require("./ExternalTimeSegment"); /** * Request builder class for operations supported on the [[ExternalTimeSegment]] entity. */ var ExternalTimeSegmentRequestBuilder = /** @class */ (function (_super) { __extends(ExternalTimeSegmentRequestBuilder, _super); function ExternalTimeSegmentRequestBuilder() { return _super !== null && _super.apply(this, arguments) || this; } /** * Returns a request builder for retrieving one `ExternalTimeSegment` entity based on its keys. * @param externalTimeRecordExternalCode Key property. See [[ExternalTimeSegment.externalTimeRecordExternalCode]]. * @param externalCode Key property. See [[ExternalTimeSegment.externalCode]]. * @returns A request builder for creating requests to retrieve one `ExternalTimeSegment` entity based on its keys. */ ExternalTimeSegmentRequestBuilder.prototype.getByKey = function (externalTimeRecordExternalCode, externalCode) { return new core_1.GetByKeyRequestBuilder(ExternalTimeSegment_1.ExternalTimeSegment, { ExternalTimeRecord_externalCode: externalTimeRecordExternalCode, externalCode: externalCode }); }; /** * Returns a request builder for querying all `ExternalTimeSegment` entities. * @returns A request builder for creating requests to retrieve all `ExternalTimeSegment` entities. */ ExternalTimeSegmentRequestBuilder.prototype.getAll = function () { return new core_1.GetAllRequestBuilder(ExternalTimeSegment_1.ExternalTimeSegment); }; /** * Returns a request builder for creating a `ExternalTimeSegment` entity. * @param entity The entity to be created * @returns A request builder for creating requests that create an entity of type `ExternalTimeSegment`. */ ExternalTimeSegmentRequestBuilder.prototype.create = function (entity) { return new core_1.CreateRequestBuilder(ExternalTimeSegment_1.ExternalTimeSegment, entity); }; /** * Returns a request builder for updating an entity of type `ExternalTimeSegment`. * @param entity The entity to be updated * @returns A request builder for creating requests that update an entity of type `ExternalTimeSegment`. */ ExternalTimeSegmentRequestBuilder.prototype.update = function (entity) { return new core_1.UpdateRequestBuilder(ExternalTimeSegment_1.ExternalTimeSegment, entity); }; ExternalTimeSegmentRequestBuilder.prototype.delete = function (externalTimeRecordExternalCodeOrEntity, externalCode) { return new core_1.DeleteRequestBuilder(ExternalTimeSegment_1.ExternalTimeSegment, externalTimeRecordExternalCodeOrEntity instanceof ExternalTimeSegment_1.ExternalTimeSegment ? externalTimeRecordExternalCodeOrEntity : { ExternalTimeRecord_externalCode: externalTimeRecordExternalCodeOrEntity, externalCode: externalCode }); }; return ExternalTimeSegmentRequestBuilder; }(core_1.RequestBuilder)); exports.ExternalTimeSegmentRequestBuilder = ExternalTimeSegmentRequestBuilder; //# sourceMappingURL=ExternalTimeSegmentRequestBuilder.js.map
"""Discrete uniform probability distribution.""" import numpy import chaospy from ..baseclass import SimpleDistribution from ..operators import J class DiscreteUniform(SimpleDistribution): """ Discrete uniform probability distribution. Examples: >>> distribution = chaospy.DiscreteUniform(2, 4) >>> distribution DiscreteUniform(2, 4) >>> qloc = numpy.linspace(0, 1, 9) >>> qloc.round(2) array([0. , 0.12, 0.25, 0.38, 0.5 , 0.62, 0.75, 0.88, 1. ]) >>> distribution.inv(qloc).round(2) array([1.5 , 1.88, 2.25, 2.62, 3. , 3.38, 3.75, 4.12, 4.5 ]) >>> distribution.fwd(distribution.inv(qloc)).round(2) array([0. , 0.12, 0.25, 0.38, 0.5 , 0.62, 0.75, 0.88, 1. ]) >>> distribution.pdf(distribution.inv(qloc)).round(4) array([0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]) >>> distribution.sample(4) array([3, 2, 4, 3]) >>> distribution.mom(1).round(4) 3.0 """ interpret_as_integer = True def __init__(self, lower, upper): """ Args: lower (float, chaospy.Distribution): Lower threshold of distribution. Must be smaller than ``upper``. Value will be rounded up to closes integer. upper (float, chaospy.Distribution): Upper threshold of distribution. Value will be rounded down to closes integer. """ super(DiscreteUniform, self).__init__(dict(lower=lower, upper=upper)) self._repr_args = [lower, upper] def _cdf(self, x_data, lower, upper): """Cumulative distribution function.""" lower = numpy.round(lower) upper = numpy.round(upper) out = (x_data-lower+0.5)/(upper-lower+1) return out def _lower(self, lower, upper): """Lower bounds.""" return numpy.round(lower)-0.5+1e-10 def _upper(self, lower, upper): """Upper bounds.""" return numpy.round(upper)+0.5-1e-10 def _pdf(self, x_data, lower, upper): """Probability density function.""" return x_data**0/(numpy.round(upper)-numpy.round(lower)) def _ppf(self, q_data, lower, upper): """Point percentile function.""" lower = numpy.round(lower) upper = numpy.rint(upper) return q_data*(upper-lower+1)+lower-0.5 def _mom(self, k_data, lower, upper): """Raw statistical moments.""" return numpy.mean(numpy.arange( numpy.ceil(lower), numpy.floor(upper)+1)**k_data)
from contextlib import contextmanager from errno import EACCES, EAGAIN from fcntl import lockf, LOCK_NB import os import socket def openlock(filename, operation, wait=True): """ Returns a file-like object that gets a fnctl() lock. `operation` should be one of LOCK_SH or LOCK_EX for shared or exclusive locks. If `wait` is False, then openlock() will not block on trying to acquire the lock. """ f = os.fdopen(os.open(filename, os.O_RDWR | os.O_CREAT, 0666), "r+") if not wait: operation |= LOCK_NB try: lockf(f.fileno(), operation) except IOError as err: if not wait and err.errno in (EACCES, EAGAIN): from django.core.management.base import CommandError raise CommandError("Could not acquire lock on '%s' held by %s." % (filename, f.readline().strip())) raise print("%s:%d" % (socket.gethostname(), os.getpid()), file=f) f.truncate() f.flush() return f @contextmanager def lockfile(filename, operation, wait=True): """ Returns a context manager with a file-like object that gets a fnctl() lock. Automatically closes and removes the lock upon completion. `operation` should be one of LOCK_SH or LOCK_EX for shared or exclusive locks. If `wait` is False, then openlock() will not block on trying to acquire the lock. """ path = os.path.abspath(filename) f = openlock(filename=filename, operation=operation, wait=wait) yield f os.unlink(path) f.close()
# -*- coding: utf-8 -*- ################################################################################ # LexaLink Copyright information - do not remove this copyright notice # Copyright (C) 2012 # # Lexalink - a free social network and dating website platform for the Google App Engine. # # Original author: Alexander Marquardt # Documentation and additional information: http://www.LexaLink.com # Git source code repository: https://github.com/alexander-marquardt/lexalink # # Please consider contributing your enhancements and modifications to the LexaLink community, # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ################################################################################ from django.utils.encoding import smart_unicode import settings, error_reporting, logging, utils_top_level, constants def get_pairs_in_current_langauge(tuple_list, lang_idx, do_sort = False): # accepts a list that contains tuples consisting of a key (in position 0) followed by the translation # of the key in the languages that are currently suppored, (in positions 1 through N). # # Generates a list of 2-item tuples, consisting of the tuple key, and the value of the key in the # selected language, and (if do_sort = True) sorted alphabetically in the current language. tmp_key_list = [] tmp_value_list = [] lang_idx_offset = 1 for curr_tuple in tuple_list: tuple_key = curr_tuple[0] tuple_value_in_current_language = curr_tuple[lang_idx + lang_idx_offset] tmp_key_list.append(tuple_key) tmp_value_list.append(tuple_value_in_current_language) list_of_tuples_in_current_language = zip(tmp_key_list, tmp_value_list) # sort the list of tuples so that it is alphabetical in the current language # always sort on location 1, which contains the word in the current language, as opposed to # location 0 which contains the key. if do_sort: list_of_tuples_in_current_language.sort(key=lambda x: x[1]) del tmp_key_list del tmp_value_list return (list_of_tuples_in_current_language) #def transpose_checkbox_rows_into_columns(list_of_sorted_tuples): #""" #This function receives a list of checkbox input choices, and orders them so that they will #displayed vertically instead of horizontally when written out into a table. #Input is a 1-D list containing [A B C D E F G H I J ] which would normally be displayed #as: #[ A B C D ] #[ E F G H ] #[ I J ] #And this function will re-order the list to be [A D G J B E H C F I] which will be displayed #as (notice how data is now sorted in columns instead of horizontally): #[ A D G J] #[ B E H ] #[ C F I ] #""" #try: #import math #cols_per_row = constants.CHECKBOX_INPUT_COLS_PER_ROW #list_len = len(list_of_sorted_tuples) #idx = 0; row = 0; #num_rows = int(math.ceil(float(list_len)/cols_per_row)) #matrix_size = num_rows * cols_per_row #matrix_representation = [] #""" #First, we pull out sections of the list that correspond to the height of the final matrix - #for example, we will pull out sub-lists [A B C], [D E F], [G H I], [J,,] from the input list. #Notice that the length of each of these sub-lists is num_rows. The resulting (temporary) matrix #looks like the following: #[A B C] #[D E F] #[G H I] #[J ] #Notice that the first colum corresponds to the first row of the desired matrix. #""" #start_idx = 0 #end_idx = num_rows #while start_idx <= matrix_size - 1: #row_list = [None,]*num_rows # we use this to pad the list with None in case it is not totally filled #row_ix = 0 #for ix in range(start_idx, end_idx): #if ix <= list_len-1: #row_list[row_ix] = list_of_sorted_tuples[ix] #row_ix += 1 #matrix_representation.append(row_list) #start_idx += num_rows #end_idx += num_rows ## Now, loop over the matrix, and pull out the values, column by column and copy them into new_array. #column = 0 #new_array = [] #while column < num_rows: #for sub_list in matrix_representation: #new_array.append(sub_list[column]) #column += 1 #return new_array #except: #error_reporting.log_exception(logging.critical) #return [] def generate_option_line_based_on_data_struct(fields_data_struct, options_dict): # has two main purposes. # 1) Fills in fields_data_struct[field]['options'] with an # array of strings that can be directly output inside a select dropdown/checkbox statement. # 2) Also, returns an "options_dict". options_dict will hold a # dictionary of values for each field, in which # the principle key specifies the field, second field the language, and the third key specifies the # selection, and the output specifies the selection in the correct language. # ie. options_dict[smoker][english_code][prefer_no_say] = "Non Smoker". This is needed # for printing user settings in the user_main page. # - radio_or_checkbox - valid values are "radio" or "checkbox" -- allows same code to be used for both # convert all of the above lists into language-appropriate options for use in drop-down menus try: for (field, field_dict) in fields_data_struct.items(): options_dict[field]=[] options = [] ordered_choices_tuples = [] choices_tuple_list = field_dict['choices'] input_type = field_dict['input_type'] if 'wrap_choice_with_anchor' in field_dict: wrap_choice_with_anchor_dict = field_dict['wrap_choice_with_anchor'] else: wrap_choice_with_anchor_dict = {} for lang_idx, language_tuple in enumerate(settings.LANGUAGES): lang_code = language_tuple[0] options.append([]) # append sub-array for current language if choices_tuple_list != None: ordered_choices_tuples.append([]) # append sub-array for current language if 'start_sorting_index' in field_dict: # some part of this list should be sorted, starting after the "start_sorting_index" location in the list where_to_start_sort = field_dict['start_sorting_index'] first_unsorted_part = \ get_pairs_in_current_langauge(choices_tuple_list[:where_to_start_sort], lang_idx, do_sort = False) if 'stop_sorting_index' in field_dict: # Leave some part of this list un-sorted where_to_stop_sort = field_dict['stop_sorting_index'] else: # sort to the end of the list where_to_stop_sort = len(choices_tuple_list) part_to_sort = choices_tuple_list[where_to_start_sort:where_to_stop_sort] last_part_to_leave_unsorted = choices_tuple_list[where_to_stop_sort:] sorted_part = \ get_pairs_in_current_langauge(part_to_sort, lang_idx, do_sort = True) last_unsorted_part = \ get_pairs_in_current_langauge(last_part_to_leave_unsorted, lang_idx, do_sort = False) list_of_sorted_tuples = first_unsorted_part + sorted_part + last_unsorted_part else: list_of_sorted_tuples = get_pairs_in_current_langauge(choices_tuple_list, lang_idx, do_sort = False) #if input_type == u'checkbox': #list_of_sorted_tuples = transpose_checkbox_rows_into_columns(list_of_sorted_tuples) ordered_choices_tuples[lang_idx] = list(list_of_sorted_tuples) # copy the list options_dict[field].append({}) for choices_tuple in list_of_sorted_tuples: # make sure the tuple is set to a valid value - due to re-ordering for checkbox display, some tuples # migh be None, which will will interpret to mean that no value should be displayed. # Note, this only could happen if we enable the code to sort checkboxes by column instead of by row. if not choices_tuple: assert(input_type == u'checkbox') options[lang_idx].append(u'') else: choice_key = choices_tuple[0] option_in_current_language = choices_tuple[1] if choice_key in wrap_choice_with_anchor_dict and lang_code in wrap_choice_with_anchor_dict[choice_key]: # This choice should be wrapped with a link (to an advertisement for example) anchor_wrapper = wrap_choice_with_anchor_dict[choice_key][lang_code] options_dict[field][lang_idx][choice_key] = anchor_wrapper.format(option_string=option_in_current_language) else: options_dict[field][lang_idx][choice_key] = option_in_current_language if input_type == u'select': options[lang_idx].append(smart_unicode("<option value='%s'>%s\n" % (choice_key, option_in_current_language))) elif input_type == u'checkbox' or input_type == u'radio': options[lang_idx].append(smart_unicode("<input type = '%s' name='%s' id='id-edit-%s-%s' value='%s'> %s\n" % (input_type, field, field, choice_key, choice_key, option_in_current_language))) else: raise Exception("Unknown input type %s encountered" % input_type) # This is located inside "if choices_tuple_list != None:" so that we don't need special # checks for country, region, sub_region .... they never have choices defined in this data structure fields_data_struct[field]['ordered_choices_tuples'] = ordered_choices_tuples if field != 'country': # note: country is filled in before getting into this function, and should not be over-written # this was done in the populate_country_options function (located in localizations.py at the time # this comment was written). Also, note tht regions and sub_regions never appeared in the signup # fields and so do not have to be explicity excluded here. fields_data_struct[field]['options'] = options except: error_reporting.log_exception(logging.critical)
// This file could contain a whole load of functions and API calls etc... // ... or you may want to create several API files if you have several object types and want to keep everything clean and separated import store from '@/store' export const getTimestamp = (timestamp) => { let date = new Date((parseFloat(timestamp)*1000)) return date.toLocaleString() } export const deepCopy = (object) => { return JSON.parse(JSON.stringify(object)) || false } export const validEmail = (email) => { var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } export const scrollToBottom = () => { window.scrollTo(0, document.body.scrollHeight) } import { Notyf } from 'notyf' const notyf = new Notyf({ duration: 4000, ripple: false, icon: false, types: [ { type: 'primary', className: 'toast-primary', icon: false, }, { type: 'success', className: 'toast-success', icon: false, }, { type: 'danger', className: 'toast-danger', icon: false, }, ], }) export const toast = (message, type = 'primary') => { notyf.open({ type, message, }) } export const debugEnabled = () => { return store.getters['Settings/getField']('settings.debug') && !store.getters['Settings/getField']('settings.disableConsoleLogs') } export const throwError = (msg, payload = false, disableToast = false) => { !disableToast && toast(msg, 'danger') debugEnabled() && console.error(msg || 'error', (payload) ? payload : '') if (payload === 'invalid_grant') { console.warn('the code has expired or already been used') } if (payload === 'invalid parameters josé') { console.warn('wrong params') } } export const getAuthURL = () => { return 'https://www.reddit.com/api/v1/authorize?client_id=' + process.env.VUE_APP_REDDIT_CLIENT_ID + '&response_type=code' + '&state=' + store.getters['Settings/getField']('settings.uid') + '&redirect_uri=' + process.env.VUE_APP_AUTH_URI + '&duration=permanent' + '&scope=submit%20vote' } export default { getTimestamp, deepCopy, validEmail, scrollToBottom, debugEnabled, throwError, toast, getAuthURL }
import throwIfMissing from './util/throwIfMissing' import { addClasses, removeClasses } from './util/dom' // All officially-supported browsers have this, but it's easy to // account for, just in case. var divStyle = document.createElement('div').style const HAS_ANIMATION = typeof document === 'undefined' ? false : 'animation' in divStyle || 'webkitAnimation' in divStyle let __instance = (function() { let instance return newInstance => { if (newInstance) { instance = newInstance } return instance } })() export default class ZoomPane { constructor(options = {}) { this.isShowing = false let { container = null, zoomFactor = throwIfMissing(), inline = throwIfMissing(), namespace = null, showWhitespaceAtEdges = throwIfMissing(), containInline = throwIfMissing(), inlineOffsetX = 0, inlineOffsetY = 0, inlineContainer = document.body } = options this.settings = { container, zoomFactor, inline, namespace, showWhitespaceAtEdges, containInline, inlineOffsetX, inlineOffsetY, inlineContainer } this.openClasses = this._buildClasses('open') this.openingClasses = this._buildClasses('opening') this.closingClasses = this._buildClasses('closing') this.inlineClasses = this._buildClasses('inline') this.loadingClasses = this._buildClasses('loading') this._buildElement() __instance(this) } _buildClasses(suffix) { let classes = [`drift-${suffix}`] let ns = this.settings.namespace if (ns) { classes.push(`${ns}-${suffix}`) } return classes } _buildElement() { this.el = document.createElement('div') addClasses(this.el, this._buildClasses('zoom-pane')) let loaderEl = document.createElement('div') addClasses(loaderEl, this._buildClasses('zoom-pane-loader')) this.el.appendChild(loaderEl) this.imgEl = document.createElement('img') this.el.appendChild(this.imgEl) } _setImageURL(imageURL) { this.imgEl.setAttribute('src', imageURL) } _setImageSize(triggerWidth, triggerHeight) { this.imgEl.style.width = `${triggerWidth * this.settings.zoomFactor}px` this.imgEl.style.height = `${triggerHeight * this.settings.zoomFactor}px` } // `percentageOffsetX` and `percentageOffsetY` must be percentages // expressed as floats between `0' and `1`. setPosition(percentageOffsetX, percentageOffsetY, triggerRect) { let left = -( this.imgEl.clientWidth * percentageOffsetX - this.el.clientWidth / 2 ) let top = -( this.imgEl.clientHeight * percentageOffsetY - this.el.clientHeight / 2 ) let maxLeft = -(this.imgEl.clientWidth - this.el.clientWidth) let maxTop = -(this.imgEl.clientHeight - this.el.clientHeight) if (this.el.parentElement === this.settings.inlineContainer) { // This may be needed in the future to deal with browser event // inconsistencies, but it's difficult to tell for sure. // let scrollX = isTouch ? 0 : window.scrollX; // let scrollY = isTouch ? 0 : window.scrollY; let scrollX = window.pageXOffset let scrollY = window.pageYOffset let inlineLeft = triggerRect.left + percentageOffsetX * triggerRect.width - this.el.clientWidth / 2 + this.settings.inlineOffsetX + scrollX let inlineTop = triggerRect.top + percentageOffsetY * triggerRect.height - this.el.clientHeight / 2 + this.settings.inlineOffsetY + scrollY if (this.settings.containInline) { if (inlineLeft < triggerRect.left + scrollX) { inlineLeft = triggerRect.left + scrollX } else if ( inlineLeft + this.el.clientWidth > triggerRect.left + triggerRect.width + scrollX ) { inlineLeft = triggerRect.left + triggerRect.width - this.el.clientWidth + scrollX } if (inlineTop < triggerRect.top + scrollY) { inlineTop = triggerRect.top + scrollY } else if ( inlineTop + this.el.clientHeight > triggerRect.top + triggerRect.height + scrollY ) { inlineTop = triggerRect.top + triggerRect.height - this.el.clientHeight + scrollY } } this.el.style.left = `${inlineLeft}px` this.el.style.top = `${inlineTop}px` } if (!this.settings.showWhitespaceAtEdges) { if (left > 0) { left = 0 } else if (left < maxLeft) { left = maxLeft } if (top > 0) { top = 0 } else if (top < maxTop) { top = maxTop } } this.imgEl.style.transform = `translate(${left}px, ${top}px)` this.imgEl.style.webkitTransform = `translate(${left}px, ${top}px)` } get _isInline() { let inline = this.settings.inline return ( inline === true || (typeof inline === 'number' && window.innerWidth <= inline) ) } _removeListenersAndResetClasses() { this.el.removeEventListener('animationend', this._completeShow, false) this.el.removeEventListener('animationend', this._completeHide, false) this.el.removeEventListener('webkitAnimationEnd', this._completeShow, false) this.el.removeEventListener('webkitAnimationEnd', this._completeHide, false) removeClasses(this.el, this.openClasses) removeClasses(this.el, this.closingClasses) } show(imageURL, triggerWidth, triggerHeight) { this._removeListenersAndResetClasses() this.isShowing = true addClasses(this.el, this.openClasses) addClasses(this.el, this.loadingClasses) this.imgEl.addEventListener('load', this._handleLoad, false) this._setImageURL(imageURL) this._setImageSize(triggerWidth, triggerHeight) if (this._isInline) { this._showInline() } else { this._showInContainer() } if (HAS_ANIMATION) { this.el.addEventListener('animationend', this._completeShow, false) this.el.addEventListener('webkitAnimationEnd', this._completeShow, false) addClasses(this.el, this.openingClasses) } } _showInline() { this.settings.inlineContainer.appendChild(this.el) addClasses(this.el, this.inlineClasses) } _showInContainer() { this.settings.container.style.display = 'block' this.settings.container.appendChild(this.el) } hide() { this._removeListenersAndResetClasses() this.isShowing = false if (HAS_ANIMATION) { this.el.addEventListener('animationend', this._completeHide, false) this.el.addEventListener('webkitAnimationEnd', this._completeHide, false) addClasses(this.el, this.closingClasses) } else { removeClasses(this.el, this.openClasses) removeClasses(this.el, this.inlineClasses) } } _completeShow = () => { this.el.removeEventListener('animationend', this._completeShow, false) this.el.removeEventListener('webkitAnimationEnd', this._completeShow, false) removeClasses(this.el, this.openingClasses) } _completeHide = () => { this.el.removeEventListener('animationend', this._completeHide, false) this.el.removeEventListener('webkitAnimationEnd', this._completeHide, false) removeClasses(this.el, this.openClasses) removeClasses(this.el, this.closingClasses) removeClasses(this.el, this.inlineClasses) this.el.setAttribute('style', '') // The window could have been resized above or below `inline` // limits since the ZoomPane was shown. Because of this, we // can't rely on `this._isInline` here. if (this.el.parentElement === this.settings.container) { this.settings.container.removeChild(this.el) } else if (this.el.parentElement === this.settings.inlineContainer) { this.settings.inlineContainer.removeChild(this.el) } if (this.settings.inline !== true) { this.settings.container.style.display = 'none' } } _handleLoad = () => { this.imgEl.removeEventListener('load', this._handleLoad, false) removeClasses(this.el, this.loadingClasses) } }
const router = require("express").Router(); const verifyMW = require("../middlewares/auth"); const { createTODO, readTODOs, updateTODO, delTODO, updateTODOText } = require("../models/user") router.post("/", verifyMW, (req, res, next) => { let { text } = req.body; createTODO(req.decodedData.id, text) .then(data => { res.status(201).json(data) }) .catch(next) }) router.get("/", verifyMW, (req, res, next) => { readTODOs(req.decodedData.id) .then(data => { res.json(data) }).catch(next) }) router.put("/", verifyMW, (req, res, next) => { let { is_done } = req.body; if(is_done !== false && is_done !== true) { return res.status(400).json({message: "is_done only accepts false or true boolean"}) } const todo_id = req.query.id; updateTODO(req.decodedData.id, todo_id, is_done) .then(data => { res.json(data) }).catch(next) }) router.delete("/", verifyMW, (req, res, next) => { const todo_id = req.query.id; delTODO(req.decodedData.id, todo_id) .then(data => { res.json(data) }).catch(next) }) router.put("/updatetext", verifyMW, (req, res, next) => { let { text } = req.body; const todo_id = req.query.id; updateTODOText(req.decodedData.id, todo_id, text) .then(data => { res.json(data) }).catch(next) }) module.exports = router;
from django.urls import path from . import views urlpatterns = [ path('', views.all_products, name='products'), path( 'category/<slug:category_slug>/', views.all_products, name='products_by_category'), path( 'category/<slug:category_slug>/<slug:product_slug>/', views.product_detail, name='product_detail'), path('search/', views.search, name='search') ]
var Case = require('Case'); const DOM = require('DOM'); var DocumentIDsMustBeUnique = { run: function (test) { test.get('scope').forEach(function (scope) { var ids = {}; DOM.scry('[id]', scope).forEach(function (element) { var _case = Case({ element: element }); test.add(_case); if (typeof ids[DOM.getAttribute(element, 'id')] === 'undefined' && Object.keys(ids).length === 0) { _case.set({ status: 'inapplicable' }); ids[DOM.getAttribute(element, 'id')] = DOM.getAttribute(element, 'id'); } else if (typeof ids[DOM.getAttribute(element, 'id')] === 'undefined') { _case.set({ status: 'passed' }); ids[DOM.getAttribute(element, 'id')] = DOM.getAttribute(element, 'id'); } else { _case.set({ status: 'failed' }); } }); }); }, meta: { testability: 1, title: { en: 'All element \"id\" attributes must be unique', nl: 'Alle element \"id\"-attributen moeten uniek zijn' }, description: { en: 'Element \"id\" attributes must be unique.', nl: 'Element \"id\"-attributen moeten uniek zijn.' }, guidelines: { wcag: { '4.1.1': { techniques: [ 'F77', 'H93' ] } } }, tags: [ 'document', 'semantics' ] } }; module.exports = DocumentIDsMustBeUnique;
import functools import io import sys import threading import time from tqdm import notebook, tqdm from cogent3.util import parallel as PAR __author__ = "Sheng Han Moses Koh" __copyright__ = "Copyright 2007-2020, The Cogent Project" __credits__ = ["Peter Maxwell", "Sheng Han Moses Koh"] __license__ = "BSD-3" __version__ = "2020.2.7a" __maintainer__ = "Gavin Huttley" __email__ = "[email protected]" __status__ = "Alpha" class LogFileOutput: """A fake progress bar for when progress bars are impossible""" def __init__(self, **kw): self.n = 0 self.message = "" self.t0 = time.time() self.lpad = "" self.output = sys.stdout # sys.stderr def set_description(self, desc="", refresh=False): self.message = desc def close(self): pass def refresh(self): if self.message: delta = "+%s" % int(time.time() - self.t0) progress = int(100 * self.n + 0.5) print( "%s %5s %3i%% %s" % (self.lpad, delta, progress, str(self.message)), file=self.output, ) class ProgressContext: def __init__(self, progress_bar_type=None, depth=-1, message=None, mininterval=1.0): self.progress_bar_type = progress_bar_type self.progress_bar = None self.progress = 0 self.depth = depth self.message = message self.mininterval = mininterval def set_new_progress_bar(self): if self.progress_bar_type: self.progress_bar = self.progress_bar_type( total=1, position=self.depth, leave=True, bar_format="{desc} {percentage:3.0f}%|{bar}|{elapsed}<{remaining}", mininterval=self.mininterval, ) def subcontext(self, *args, **kw): return ProgressContext( progress_bar_type=self.progress_bar_type, depth=self.depth + 1, message=self.message, mininterval=self.mininterval, ) def display(self, msg=None, progress=None): if not self.progress_bar: self.set_new_progress_bar() updated = False if progress is not None: self.progress = min(progress, 1.0) self.progress_bar.n = self.progress updated = True else: self.progress_bar.n = 1 if msg is not None and msg != self.message: self.message = msg self.progress_bar.set_description(self.message, refresh=False) updated = True if updated: self.progress_bar.refresh() def done(self): if self.progress_bar: self.progress_bar.close() self.progress_bar = None def series(self, items, noun="", labels=None, start=None, end=1.0, count=None): """Wrap a looped-over list with a progress bar""" # todo optimise label creation if count is None: if not hasattr(items, "__len__"): items = list(items) count = len(items) if count == 0: # nothing to do return if start is None: start = 0.0 step = (end - start) / count if labels: assert len(labels) == count elif count == 1: labels = [""] else: if noun: noun += " " template = "%s%%%sd/%s" % (noun, len(str(count)), count) labels = [template % (i + 1) for i in range(0, count)] for (i, item) in enumerate(items): self.display(msg=labels[i], progress=start + step * i) yield item self.display(progress=end) def write(self, *args, **kw): if self.progress_bar_type and len(kw) < 3 and not using_notebook(): self.progress_bar_type.write(*args, **kw) else: print(*args, **kw) def imap(self, f, s, mininterval=1.0, parallel=False, par_kw=None, **kw): self.mininterval = mininterval if parallel: # todo document parallel.map arguments par_kw = par_kw or {} results = PAR.imap(f, s, **par_kw) else: results = map(f, s) for result in self.series(results, count=len(s), **kw): yield result def map(self, f, s, **kw): return list(self.imap(f, s, **kw)) class NullContext(ProgressContext): """A UI context which discards all output. Useful on secondary MPI cpus, and other situations where all output is suppressed""" def subcontext(self, *args, **kw): return self def display(self, *args, **kw): pass def done(self): pass NULL_CONTEXT = NullContext() CURRENT = threading.local() CURRENT.context = None def using_notebook(): try: get_ipython() return True except NameError: return False def display_wrap(slow_function): """Decorator which give the function its own UI context. The function will receive an extra argument, 'ui', which is used to report progress etc.""" @functools.wraps(slow_function) def f(*args, **kw): if getattr(CURRENT, "context", None) is None: if sys.stdout.isatty(): klass = tqdm elif using_notebook(): klass = notebook.tqdm elif isinstance(sys.stdout, io.FileIO): klass = LogFileOutput else: klass = None if klass is None: CURRENT.context = NULL_CONTEXT else: CURRENT.context = ProgressContext(klass) parent = CURRENT.context show_progress = kw.pop("show_progress", None) if show_progress is False: subcontext = NULL_CONTEXT else: subcontext = parent.subcontext() kw["ui"] = CURRENT.context = subcontext try: result = slow_function(*args, **kw) finally: CURRENT.context = parent subcontext.done() return result return f @display_wrap def subdemo(ui): for j in ui.series(list(range(10))): time.sleep(0.1) return @display_wrap def demo(ui): ui.write("non-linebuffered output, tricky but look:") for i in ui.series(list(range(10))): time.sleep(0.6) for i in imap(fun, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]): ui.write(str(i)) ui.write(str(i) + ".") ui.write("done") @display_wrap def imap(f, s, ui): for result in ui.imap(f, s): yield result def fun(inp): time.sleep(0.1) return inp if __name__ == "__main__": demo()
import styled from 'styled-components'; import React from 'react'; import PropTypes from 'prop-types'; import { Close as _Close } from '@styled-icons/material/Close'; import { Box, Flex } from '@rebass/grid'; import { FormattedMessage } from 'react-intl'; import { useRouter } from 'next/router'; import StyledButton from '../StyledButton'; import DismissibleMessage from '../DismissibleMessage'; import { BANNER } from '../../lib/constants/dismissable-help-message'; import Container from '../Container'; const SPONSORED_COLLECTIVE = 'SPONSORED_COLLECTIVE'; const Wrapper = styled(Flex)` width: 100%; position: -webkit-sticky; position: sticky; bottom: 0px; z-index: 1000; margin-top: 5em; `; const Banner = styled(Container)` position: relative; overflow: hidden; margin: auto; background: #fff; box-shadow: 0px 0px 10px RGBA(0, 0, 0, 0.1); border-bottom: none; h1, h2 { font-weight: bold; margin: 0px; text-align: left; &:first-child { padding-bottom: 4px; } } h1 { ${props => props.variant === SPONSORED_COLLECTIVE ? `font-size: 24px; line-height: 32px;` : `font-size: 28px; line-height: 36px;`} } h2 { ${props => props.variant === SPONSORED_COLLECTIVE ? `font-size: 16px; line-height: 24px;` : `font-size: 20px; line-height: 28px;`} } @media screen and (max-width: 40em) { h1, h2 &:first-child { padding-bottom: 9px; } h2 { font-size: 15px; line-height: 23px; } h1 { font-size: 20px; line-height: 28px; } } `; const Button = styled(StyledButton)` width: 212px; font-size: 13px; color: #fff; z-index: 100; background: linear-gradient(180deg, #313233 0%, #141414 100%); &:hover { background: linear-gradient(180deg, #4e5052 0%, #313233 100%); } &:visited { color: #fff; outline: none; border: none; } `; const Close = styled(_Close)` position: absolute; color: #dadada; top: 25px; right: 25px; width: 20px; height: 20px; cursor: pointer; &:hover { color: #000; } @media screen and (max-width: 40em) { top: 18px; right: 18px; } `; const Mobile = styled.div` display: none; @media screen and (max-width: 40em) { display: block; } `; const Desktop = styled.div` display: block; @media screen and (max-width: 40em) { display: none; } `; const Virus = styled.div` position: absolute; bottom: 0px; right: 10px; width: 80px; height: 80px; @media screen and (max-width: 40em) { bottom: -20px; } img:nth-child(1) { left: 20px; position: absolute; } img:nth-child(2) { bottom: 15px; position: absolute; } `; const CovidBanner = props => { const router = useRouter(); const dismissAndRedirect = e => { e.preventDefault(); props.dismiss(); router.push('/create'); }; const content = props.variant === SPONSORED_COLLECTIVE ? ( <Box> <h1> <Desktop> <FormattedMessage id="banners.covid.title.sponsored.desktop" defaultMessage="To support this collective's mission we are waiving our platform fees until the end of June." /> </Desktop> <Mobile> <FormattedMessage id="banners.covid.title.sponsored.mobile" defaultMessage="To support this collective's mission we are waiving our platform fees." /> </Mobile> </h1> <Mobile> <h2> <FormattedMessage id="banners.covid.sponsored.description" defaultMessage="Create a COVID-19 a related collective, we'll waive our fees until the end of June." /> </h2> </Mobile> </Box> ) : ( <Box> <h2> <Desktop> <FormattedMessage id="banners.covid.title.desktop" defaultMessage="Let's work together to support each other. We are apart but not alone." /> </Desktop> <Mobile> <FormattedMessage id="banners.covid.title.mobile" defaultMessage="Let's support each other." /> </Mobile> </h2> <h1> <FormattedMessage id="banners.covid.description" defaultMessage="We are waiving our platform fees on COVID-19 related Collectives until the end of June." /> </h1> </Box> ); return ( <Wrapper> <Banner width={[300, 992]} border="1px solid #E6E8EB" borderRadius="16px 16px 0 0" pl={[24, 48]} pr={[24, props.showLink ? 72 : 107]} pt={[24, 16]} pb={24} > <Virus> <img src="/static/images/virus-1.png" width="54px" /> <img src="/static/images/virus-2.png" width="38px" /> </Virus> <Flex flexDirection={['column', 'row']}> {content} {props.showLink && ( <Flex alignItems="center" mt={[16, 0]}> <Button buttonStyle="standard" onClick={dismissAndRedirect}> <FormattedMessage id="banners.covid.button" defaultMessage="Create a COVID-19 Initiative" /> </Button> </Flex> )} </Flex> <Close onClick={props.dismiss} /> </Banner> </Wrapper> ); }; CovidBanner.propTypes = { showLink: PropTypes.bool, dismiss: PropTypes.func, variant: PropTypes.oneOf([SPONSORED_COLLECTIVE]), }; const WrappedBanner = props => ( <DismissibleMessage displayForLoggedOutUser={true} messageId={BANNER.COVID}> {({ dismiss }) => <CovidBanner {...{ dismiss, ...props }} />} </DismissibleMessage> ); export default WrappedBanner;
/** * Module dependencies. */ var should = require('should'), app = require('../../server'), mongoose = require('mongoose'), User = mongoose.model('User'), Article = mongoose.model('Article'); //Globals var user; var article; //The tests describe('<Unit Test>', function() { describe('Model Article:', function() { beforeEach(function(done) { user = new User({ name: 'Full name', email: '[email protected]', username: 'user', password: 'password' }); user.save(function(err) { article = new Article({ title: 'Article Title', content: 'Article Content', user: user }); done(); }); }); describe('Method Save', function() { it('should be able to save whithout problems', function(done) { return article.save(function(err) { should.not.exist(err); done(); }); }); it('should be able to show an error when try to save witout title', function(done) { article.title = ''; return article.save(function(err) { should.exist(err); done(); }); }); }); afterEach(function(done) { done(); }); }); });
'use strict'; const dnscrypt = require('.'); // PTR -> IP(google.com).in-addr.arpa // NAPTR -> digitoffice.ru // CAA -> google.com // SRV -> _sip._udp.sip.voice.google.com dnscrypt.resolve('example.com', 'A', (error, answer) => { if (error) { console.error(error); } else { console.log(answer); } });
version https://git-lfs.github.com/spec/v1 oid sha256:c7b7abf54cc3c6d4c454c090efb0446086b32f4398bd1d17b398116c2f5aec53 size 2098
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("path", { fillOpacity: ".3", d: "M22 8V4.41c0-.89-1.08-1.34-1.71-.71L3.71 20.29c-.63.63-.19 1.71.7 1.71H18V11c0-1.66 1.34-3 3-3h1z" }), h("path", { d: "M18 22V6L3.71 20.29c-.63.63-.19 1.71.7 1.71H18zm2-11v6c0 .55.45 1 1 1s1-.45 1-1v-6c0-.55-.45-1-1-1s-1 .45-1 1zm0 11h2v-2h-2v2z" })), 'SignalCellularConnectedNoInternet3BarRounded');
'use strict'; /* jshint quotmark: double */ window.SwaggerTranslator.learn({ "Warning: Deprecated":"警告:已过时", "Implementation Notes":"实现备注", "Response Class":"响应类", "Status":"状态", "Parameters":"参数", "Parameter":"参数", "Value":"值", "Description":"描述", "Parameter Type":"参数类型", "Data Type":"数据类型", "Response Messages":"响应消息", "HTTP Status Code":"HTTP状态码", "Reason":"原因", "Response Model":"响应模型", "Request URL":"请求URL", "Response Body":"响应体", "Response Code":"响应码", "Response Headers":"响应头", "Hide Response":"隐藏响应", "Headers":"头", "Try it out!":"试一下!", "Show/Hide":"显示/隐藏", "List Operations":"显示操作", "Expand Operations":"展开操作", "Raw":"原始", "can't parse JSON. Raw result":"无法解析JSON. 原始结果", "Example Value":"示例", "Click to set as parameter value":"点击设置参数", "Model Schema":"模型架构", "Model":"模型", "apply":"应用", "Username":"用户名", "Password":"密码", "Terms of service":"服务条款", "Created by":"创建者", "See more at":"查看更多:", "Contact the developer":"联系开发者", "api version":"api版本", "Response Content Type":"响应Content Type", "Parameter content type:":"参数类型:", "fetching resource":"正在获取资源", "fetching resource list":"正在获取资源列表", "Explore":"刷新", "Show Swagger Petstore Example Apis":"显示 Swagger Petstore 示例 Apis", "Can't read from server. It may not have the appropriate access-control-origin settings.":"无法从服务器读取。可能没有正确设置access-control-origin。", "Please specify the protocol for":"请指定协议:", "Can't read swagger JSON from":"无法读取swagger JSON于", "Finished Loading Resource Information. Rendering Swagger UI":"已加载资源信息。正在渲染Swagger UI", "Unable to read api":"无法读取api", "from path":"从路径", "server returned":"服务器返回" });
#!/usr/bin/env python # vim: fdm=indent ''' author: Fabio Zanini date: 01/11/13 content: After the preliminary mapping to reference, plot coverage and allele frequencies to spot major issues. ''' # Modules import os import argparse import numpy as np from Bio import SeqIO import matplotlib.pyplot as plt from matplotlib import cm from hivwholeseq.utils.miseq import read_types from hivwholeseq.sequencing.filenames import get_premapped_filename, get_reference_premap_filename, \ get_fragment_positions_filename from hivwholeseq.utils.one_site_statistics import get_allele_counts_insertions_from_file_unfiltered from hivwholeseq.data.primers import primers_coordinates_HXB2_inner as pcis_HXB2 from hivwholeseq.data.primers import primers_coordinates_HXB2_outer as pcos_HXB2 from hivwholeseq.utils.mapping import get_number_reads from hivwholeseq.sequencing.samples import load_sequencing_run, SampleSeq from hivwholeseq.sequencing.samples import load_samples_sequenced as lss from hivwholeseq.cluster.fork_cluster import fork_premapped_coverage as fork_self # Functions def plot_coverage(counts, offset_x=0, frags_pos=None, frags_pos_out=None, title=None): '''Plot the coverage and the minor allele frequency''' cov = counts.sum(axis=1) cov_tot = cov.sum(axis=0) fig, ax = plt.subplots(1, 1, figsize=(11, 8)) ax.plot(np.arange(len(cov_tot.T)) + offset_x, cov_tot.T, lw=2, c='k', label=read_types) ax.set_xlabel('Position [bases]') ax.set_ylabel('Coverage') ax.grid(True) # If the fragments positions are marked, plot them # Inner primers if frags_pos is not None: for i, frag_pos in enumerate(frags_pos.T): ax.plot(frag_pos + offset_x, 2 * [(0.97 - 0.03 * (i % 2)) * ax.get_ylim()[1]], c=cm.jet(int(255.0 * i / len(frags_pos.T))), lw=2) # Outer primers if frags_pos_out is not None: for i, frag_pos in enumerate(frags_pos_out.T): ax.plot(frag_pos + offset_x, 2 * [(0.96 - 0.03 * (i % 2)) * ax.get_ylim()[1]], c=cm.jet(int(255.0 * i / len(frags_pos_out.T))), lw=2) ax.set_xlim(0, 10000) if title is not None: ax.set_title(title, fontsize=18) plt.tight_layout(rect=(0, 0, 1, 0.95)) def check_premap(data_folder, adaID, fragments, seq_run, samplename, qual_min=30, match_len_min=10, maxreads=-1, VERBOSE=0, savefig=True, title=None): '''Check premap to reference: coverage, etc.''' refseq = SeqIO.read(get_reference_premap_filename(data_folder, adaID), 'fasta') # FIXME: do this possibly better than parsing the description! try: fields = refseq.description.split() refseq_start = int(fields[fields.index('(indices') - 3]) except ValueError: refseq_start = 550 fragpos_filename = get_fragment_positions_filename(data_folder, adaID) if os.path.isfile(fragpos_filename): # Load the fragment positions, considering mixed fragments (e.g. F5a+b) fragtmp = [] postmp = [] with open(fragpos_filename, 'r') as f: f.readline() #HEADER for line in f: fields = line[:-1].split('\t') fragtmp.append(fields[0]) if 'inner' not in fields[1]: postmp.append([fields[1], fields[4]]) else: start = int(fields[1].split(',')[1].split(': ')[1].rstrip('}')) end = int(fields[4].split(',')[1].split(': ')[1].rstrip('}')) postmp.append([start, end]) postmp = np.array(postmp, int) # NOTE: In a lot of old files, it says F3o instead of F3ao if 'F3o' in fragtmp: fragtmp[fragtmp.index('F3o')] = 'F3ao' elif 'F3i' in fragtmp: fragtmp[fragtmp.index('F3i')] = 'F3ai' frags_pos = np.array([postmp[fragtmp.index(fr)] for fr in fragments], int).T else: frags_pos = None frags_pos_out = None # Open BAM and scan reads input_filename = get_premapped_filename(data_folder, adaID, type='bam') if not os.path.isfile(input_filename): if VERBOSE: print 'Premapped BAM file not found' return (None, None) # Count reads if requested n_reads = get_number_reads(input_filename) if VERBOSE: print 'N. of reads:', n_reads # Get counts counts, inserts = get_allele_counts_insertions_from_file_unfiltered(input_filename, len(refseq), qual_min=qual_min, match_len_min=match_len_min, maxreads=maxreads, VERBOSE=VERBOSE) # Plot results if title is None: title=', '.join(['run '+seq_run+' '+adaID, 'sample '+samplename, 'reads '+str(min(maxreads, n_reads))+'/'+str(n_reads), ]) plot_coverage(counts, offset_x=refseq_start, frags_pos=frags_pos, frags_pos_out=frags_pos_out, title=title) if savefig: from hivwholeseq.sequencing.adapter_info import foldername_adapter plt.savefig(data_folder+foldername_adapter(adaID)+'figures/coverage_premapped_'+samplename+'.png') return (counts, inserts) # Script if __name__ == '__main__': # Parse input args parser = argparse.ArgumentParser(description='Check premapped coverage', formatter_class=argparse.ArgumentDefaultsHelpFormatter) runs_or_samples = parser.add_mutually_exclusive_group(required=True) runs_or_samples.add_argument('--runs', nargs='+', help='Seq run to analyze (e.g. Tue28)') runs_or_samples.add_argument('--samples', nargs='+', help='Samples to analyze (e.g. 31440_PCR1') parser.add_argument('--adaIDs', nargs='+', help='Adapter IDs to analyze (e.g. TS2)') parser.add_argument('--maxreads', type=int, default=1000, help='Number of reads analyzed') parser.add_argument('--verbose', type=int, default=0, help='Verbosity level [0-3]') parser.add_argument('--titles', nargs='*', default=None, help='Give a title to the figure') parser.add_argument('--submit', action='store_true', help='Execute the script in parallel on the cluster') parser.add_argument('--noshow', action='store_false', dest='show', help='Do not show the plot, just save it') parser.add_argument('--persist', action='store_true', help='Plot show blocks thread') args = parser.parse_args() samplenames = args.samples seq_runs = args.runs adaIDs = args.adaIDs submit = args.submit maxreads = args.maxreads VERBOSE = args.verbose titles = args.titles show = args.show persist = args.persist if not show: plt.ioff() samples = lss() if samplenames is not None: samples = samples.loc[samples.index.isin(samplenames)] else: ind = np.zeros(len(samples), bool) for seq_run in seq_runs: dataset = load_sequencing_run(seq_run) data_folder = dataset.folder samples_run = dataset.samples # If the script is called with no adaID, iterate over all if adaIDs is not None: samples_run = samples_run.loc[samples_run.adapter.isin(adaIDs)] ind |= samples.index.isin(samples_run.index) samples = samples.loc[ind] for i, (samplename, sample) in enumerate(samples.iterrows()): sample = SampleSeq(sample) seq_run = sample['seq run'] data_folder = sample.sequencing_run.folder adaID = sample.adapter fragments = sample.regions_complete if VERBOSE: print seq_run, adaID if submit: fork_self(samplename, maxreads=maxreads, VERBOSE=VERBOSE) continue if titles is not None: title = titles[i] else: title = None (counts, inserts) = check_premap(data_folder, adaID, fragments, seq_run, samplename, maxreads=maxreads, VERBOSE=VERBOSE, title=title) if show and (not submit) and (counts is not None): plt.ion() plt.show() if persist: plt.waitforbuttonpress(timeout=60)
module.exports = { purge: ["./src/**/*.html", "./src/**/*.js"], darkMode: false, // or 'media' or 'class' theme: { extend: { colors: { one: { lt: "#EF6B81", md: "#E83151", dk: "#B4142F", }, two: { lt: "#0BC2FF", md: "#007EA7", dk: "#005A78", }, three: { lt: "#FFBF49", md: "#FFA400", dk: "#B67600", }, neutral: { lt: "#FFFFFF", dk: "#242424", }, }, }, }, variants: { extend: { backgroundColor: ["active"], textColor: ["active"], }, }, plugins: [], };
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict-local * @format */ 'use strict'; const base62 = require('base62'); // Static ids always end with `:<HASH>` where HASH is an alphanumeric transform // of an auto-incrementing index. A double-colon is used to distinguish between // client ids and static ids that happen to hash to `:client`. const SUFFIX = '::client'; let _nextFragmentID = 0; /** * The "concrete fragment id" uniquely identifies a Relay.QL`fragment ...` * within the source code of an application and will remain the same across * runs of a particular version of an application. * * This function can be used to generate a unique id for fragments constructed * at runtime and is guaranteed not to conflict with statically created ids. */ function generateConcreteFragmentID(): string { return base62(_nextFragmentID++) + SUFFIX; } module.exports = generateConcreteFragmentID;
const authRouter = require('express').Router(); const bcrypt = require('bcryptjs'); const generatePassword = require('../../utils/generatePassword'); const generateToken = require('../../utils/generateToken'); const Users = require('../../../data/models/users.model'); /** * @apiDefine UserNotFound * @apiError UserNotFound Username is not in the system */ /** * @apiDefine NotAuthorized * @apiError NotAuthorized Incorrect Password */ /** * @apiDefine UserNameAlreadyTaken * @apiError UserNameAlreadyTaken Username has already been taken */ /** * @api {post} /api/auth/register Registers a New User * @apiUse UserNameAlreadyTaken * @apiVersion 1.0.0 * @apiName RegisterUser * @apiGroup Auth * @apiPermission none * @apiDescription Registers a New User * @apiParam {String} username The New Users username * @apiParam {String} password The New Users password * * @apiSuccess {Object} user The Newly Created User * @apiSuccessExample {json} Success-Response: * { * "id": 2, * "username": "testuser", * "created_at": "2019-10-19 19:58:08", * "updated_at": "2019-10-19 19:58:08" * } * @apiErrorExample {json} Username-Already-Taken * { * "message": "Username is already taken" * } */ function register (req, res) { Users.findBy({ username: req.body.username }) .then(foundUser => { if (foundUser.length === 0) { const newPassword = generatePassword(req.body.password); Users.add({ username: req.body.username, password: newPassword }) .then(saved => { const newUser = { id : saved[0].id, username : saved[0].username, created_at : saved[0].created_at, updated_at : saved[0].updated_at, }; res.status(201).json(newUser); }) .catch(err => res.status(500).json(err)); } else { res.status(400).json({ message: 'Username is already taken' }); } }) .catch(err => res.status(500).json('register', err)); } /** * @api {post} /api/auth/login Logs an User In * @apiUse UserNotFound * @apiUse NotAuthorized * @apiVersion 1.0.0 * @apiName LoginUser * @apiGroup Auth * @apiPermission none * @apiDescription Logs an User In * @apiParam {String} username Username of the User * @apiParam {String} password Password of the User * @apiSuccess {Object} The Users welcome message, token, and user object * @apiSuccessExample {json} Success-Response: * { * "message": "Welcome back test", * "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJ0ZXN0IiwiaWF0IjoxNTcxNTE0NzcwLCJleHAiOjE1NzE2MDExNzB9.4iEFSx0i7V8cvYgZ0ALRAQG1aUTqqguQ5xDG86sgpjg", * "user": { * "id": 1, * "username": "test", * "created_at": "2019-10-19 18:21:31", * "updated_at": "2019-10-19 18:21:31" * } * } * @apiErrorExample {json} Username-Not-Found-Response * { * "message": "Username is not in the system." * } * @apiErrorExample {json} Incorrect-Password * { * "message": "Incorrect Password" * } */ function login (req, res) { Users.findBy({ username: req.body.username }) .then(user => { if (user) { if (bcrypt.compareSync(req.body.password, user[0].password)) { const token = generateToken(user[0]); const sentUser = { id : user[0].id, username : user[0].username, created_at : user[0].created_at, updated_at : user[0].updated_at, }; res.json({ message : `Welcome back ${sentUser.username}`, token, user : sentUser, }); } else { res.status(401).json({ message: 'Incorrect Password' }); } } else { res.status(404).json({ message: 'Username is not in the system.' }); } }) .catch(err => res.status(500).json('Login', err)); } authRouter.post('/register', register).post('/login', login); module.exports = authRouter;
// Prototypical use case increments loop counter by one on each iteration for (let i = 0; i < 10; i++) { console.log("Iteration #", i); } // Looping through an array let students = ["Johnny", "Tyler", "Bodhi", "Pappas"]; for (let j = 0; j < students.length; j++) { console.log(students[j]); }
var tap = require('../tap'); tap.count(1); var l = [,1]; tap.eq(l[1], 1, 'empty elements allowed');
/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ "./node_modules/alpinejs/dist/module.esm.js": /*!**************************************************!*\ !*** ./node_modules/alpinejs/dist/module.esm.js ***! \**************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ module_default) /* harmony export */ }); var __create = Object.create; var __defProp = Object.defineProperty; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __markAsModule = (target) => __defProp(target, "__esModule", {value: true}); var __commonJS = (callback, module) => () => { if (!module) { module = {exports: {}}; callback(module.exports, module); } return module.exports; }; var __exportStar = (target, module, desc) => { if (module && typeof module === "object" || typeof module === "function") { for (let key of __getOwnPropNames(module)) if (!__hasOwnProp.call(target, key) && key !== "default") __defProp(target, key, {get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable}); } return target; }; var __toModule = (module) => { return __exportStar(__markAsModule(__defProp(module != null ? __create(__getProtoOf(module)) : {}, "default", module && module.__esModule && "default" in module ? {get: () => module.default, enumerable: true} : {value: module, enumerable: true})), module); }; // node_modules/@vue/shared/dist/shared.cjs.js var require_shared_cjs = __commonJS((exports) => { "use strict"; Object.defineProperty(exports, "__esModule", {value: true}); function makeMap(str, expectsLowerCase) { const map = Object.create(null); const list = str.split(","); for (let i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? (val) => !!map[val.toLowerCase()] : (val) => !!map[val]; } var PatchFlagNames = { [1]: `TEXT`, [2]: `CLASS`, [4]: `STYLE`, [8]: `PROPS`, [16]: `FULL_PROPS`, [32]: `HYDRATE_EVENTS`, [64]: `STABLE_FRAGMENT`, [128]: `KEYED_FRAGMENT`, [256]: `UNKEYED_FRAGMENT`, [512]: `NEED_PATCH`, [1024]: `DYNAMIC_SLOTS`, [2048]: `DEV_ROOT_FRAGMENT`, [-1]: `HOISTED`, [-2]: `BAIL` }; var slotFlagsText = { [1]: "STABLE", [2]: "DYNAMIC", [3]: "FORWARDED" }; var GLOBALS_WHITE_LISTED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt"; var isGloballyWhitelisted = /* @__PURE__ */ makeMap(GLOBALS_WHITE_LISTED); var range = 2; function generateCodeFrame(source, start2 = 0, end = source.length) { const lines = source.split(/\r?\n/); let count = 0; const res = []; for (let i = 0; i < lines.length; i++) { count += lines[i].length + 1; if (count >= start2) { for (let j = i - range; j <= i + range || end > count; j++) { if (j < 0 || j >= lines.length) continue; const line = j + 1; res.push(`${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`); const lineLength = lines[j].length; if (j === i) { const pad = start2 - (count - lineLength) + 1; const length = Math.max(1, end > count ? lineLength - pad : end - start2); res.push(` | ` + " ".repeat(pad) + "^".repeat(length)); } else if (j > i) { if (end > count) { const length = Math.max(Math.min(end - count, lineLength), 1); res.push(` | ` + "^".repeat(length)); } count += lineLength + 1; } } break; } } return res.join("\n"); } var specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`; var isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs); var isBooleanAttr2 = /* @__PURE__ */ makeMap(specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`); var unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/; var attrValidationCache = {}; function isSSRSafeAttrName(name) { if (attrValidationCache.hasOwnProperty(name)) { return attrValidationCache[name]; } const isUnsafe = unsafeAttrCharRE.test(name); if (isUnsafe) { console.error(`unsafe attribute name: ${name}`); } return attrValidationCache[name] = !isUnsafe; } var propsToAttrMap = { acceptCharset: "accept-charset", className: "class", htmlFor: "for", httpEquiv: "http-equiv" }; var isNoUnitNumericStyleProp = /* @__PURE__ */ makeMap(`animation-iteration-count,border-image-outset,border-image-slice,border-image-width,box-flex,box-flex-group,box-ordinal-group,column-count,columns,flex,flex-grow,flex-positive,flex-shrink,flex-negative,flex-order,grid-row,grid-row-end,grid-row-span,grid-row-start,grid-column,grid-column-end,grid-column-span,grid-column-start,font-weight,line-clamp,line-height,opacity,order,orphans,tab-size,widows,z-index,zoom,fill-opacity,flood-opacity,stop-opacity,stroke-dasharray,stroke-dashoffset,stroke-miterlimit,stroke-opacity,stroke-width`); var isKnownAttr = /* @__PURE__ */ makeMap(`accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap`); function normalizeStyle(value) { if (isArray(value)) { const res = {}; for (let i = 0; i < value.length; i++) { const item = value[i]; const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item); if (normalized) { for (const key in normalized) { res[key] = normalized[key]; } } } return res; } else if (isObject(value)) { return value; } } var listDelimiterRE = /;(?![^(]*\))/g; var propertyDelimiterRE = /:(.+)/; function parseStringStyle(cssText) { const ret = {}; cssText.split(listDelimiterRE).forEach((item) => { if (item) { const tmp = item.split(propertyDelimiterRE); tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); } }); return ret; } function stringifyStyle(styles) { let ret = ""; if (!styles) { return ret; } for (const key in styles) { const value = styles[key]; const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key); if (isString(value) || typeof value === "number" && isNoUnitNumericStyleProp(normalizedKey)) { ret += `${normalizedKey}:${value};`; } } return ret; } function normalizeClass(value) { let res = ""; if (isString(value)) { res = value; } else if (isArray(value)) { for (let i = 0; i < value.length; i++) { const normalized = normalizeClass(value[i]); if (normalized) { res += normalized + " "; } } } else if (isObject(value)) { for (const name in value) { if (value[name]) { res += name + " "; } } } return res.trim(); } var HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot"; var SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view"; var VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"; var isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS); var isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS); var isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS); var escapeRE = /["'&<>]/; function escapeHtml(string) { const str = "" + string; const match = escapeRE.exec(str); if (!match) { return str; } let html = ""; let escaped; let index; let lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: escaped = "&quot;"; break; case 38: escaped = "&amp;"; break; case 39: escaped = "&#39;"; break; case 60: escaped = "&lt;"; break; case 62: escaped = "&gt;"; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escaped; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; } var commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g; function escapeHtmlComment(src) { return src.replace(commentStripRE, ""); } function looseCompareArrays(a, b) { if (a.length !== b.length) return false; let equal = true; for (let i = 0; equal && i < a.length; i++) { equal = looseEqual(a[i], b[i]); } return equal; } function looseEqual(a, b) { if (a === b) return true; let aValidType = isDate(a); let bValidType = isDate(b); if (aValidType || bValidType) { return aValidType && bValidType ? a.getTime() === b.getTime() : false; } aValidType = isArray(a); bValidType = isArray(b); if (aValidType || bValidType) { return aValidType && bValidType ? looseCompareArrays(a, b) : false; } aValidType = isObject(a); bValidType = isObject(b); if (aValidType || bValidType) { if (!aValidType || !bValidType) { return false; } const aKeysCount = Object.keys(a).length; const bKeysCount = Object.keys(b).length; if (aKeysCount !== bKeysCount) { return false; } for (const key in a) { const aHasKey = a.hasOwnProperty(key); const bHasKey = b.hasOwnProperty(key); if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key])) { return false; } } } return String(a) === String(b); } function looseIndexOf(arr, val) { return arr.findIndex((item) => looseEqual(item, val)); } var toDisplayString = (val) => { return val == null ? "" : isObject(val) ? JSON.stringify(val, replacer, 2) : String(val); }; var replacer = (_key, val) => { if (isMap(val)) { return { [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val2]) => { entries[`${key} =>`] = val2; return entries; }, {}) }; } else if (isSet(val)) { return { [`Set(${val.size})`]: [...val.values()] }; } else if (isObject(val) && !isArray(val) && !isPlainObject(val)) { return String(val); } return val; }; var babelParserDefaultPlugins = [ "bigInt", "optionalChaining", "nullishCoalescingOperator" ]; var EMPTY_OBJ = Object.freeze({}); var EMPTY_ARR = Object.freeze([]); var NOOP = () => { }; var NO = () => false; var onRE = /^on[^a-z]/; var isOn = (key) => onRE.test(key); var isModelListener = (key) => key.startsWith("onUpdate:"); var extend = Object.assign; var remove = (arr, el) => { const i = arr.indexOf(el); if (i > -1) { arr.splice(i, 1); } }; var hasOwnProperty = Object.prototype.hasOwnProperty; var hasOwn = (val, key) => hasOwnProperty.call(val, key); var isArray = Array.isArray; var isMap = (val) => toTypeString(val) === "[object Map]"; var isSet = (val) => toTypeString(val) === "[object Set]"; var isDate = (val) => val instanceof Date; var isFunction = (val) => typeof val === "function"; var isString = (val) => typeof val === "string"; var isSymbol = (val) => typeof val === "symbol"; var isObject = (val) => val !== null && typeof val === "object"; var isPromise = (val) => { return isObject(val) && isFunction(val.then) && isFunction(val.catch); }; var objectToString = Object.prototype.toString; var toTypeString = (value) => objectToString.call(value); var toRawType = (value) => { return toTypeString(value).slice(8, -1); }; var isPlainObject = (val) => toTypeString(val) === "[object Object]"; var isIntegerKey = (key) => isString(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key; var isReservedProp = /* @__PURE__ */ makeMap(",key,ref,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"); var cacheStringFunction = (fn) => { const cache = Object.create(null); return (str) => { const hit = cache[str]; return hit || (cache[str] = fn(str)); }; }; var camelizeRE = /-(\w)/g; var camelize = cacheStringFunction((str) => { return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ""); }); var hyphenateRE = /\B([A-Z])/g; var hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, "-$1").toLowerCase()); var capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1)); var toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``); var hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue); var invokeArrayFns = (fns, arg) => { for (let i = 0; i < fns.length; i++) { fns[i](arg); } }; var def = (obj, key, value) => { Object.defineProperty(obj, key, { configurable: true, enumerable: false, value }); }; var toNumber = (val) => { const n = parseFloat(val); return isNaN(n) ? val : n; }; var _globalThis; var getGlobalThis = () => { return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : {}); }; exports.EMPTY_ARR = EMPTY_ARR; exports.EMPTY_OBJ = EMPTY_OBJ; exports.NO = NO; exports.NOOP = NOOP; exports.PatchFlagNames = PatchFlagNames; exports.babelParserDefaultPlugins = babelParserDefaultPlugins; exports.camelize = camelize; exports.capitalize = capitalize; exports.def = def; exports.escapeHtml = escapeHtml; exports.escapeHtmlComment = escapeHtmlComment; exports.extend = extend; exports.generateCodeFrame = generateCodeFrame; exports.getGlobalThis = getGlobalThis; exports.hasChanged = hasChanged; exports.hasOwn = hasOwn; exports.hyphenate = hyphenate; exports.invokeArrayFns = invokeArrayFns; exports.isArray = isArray; exports.isBooleanAttr = isBooleanAttr2; exports.isDate = isDate; exports.isFunction = isFunction; exports.isGloballyWhitelisted = isGloballyWhitelisted; exports.isHTMLTag = isHTMLTag; exports.isIntegerKey = isIntegerKey; exports.isKnownAttr = isKnownAttr; exports.isMap = isMap; exports.isModelListener = isModelListener; exports.isNoUnitNumericStyleProp = isNoUnitNumericStyleProp; exports.isObject = isObject; exports.isOn = isOn; exports.isPlainObject = isPlainObject; exports.isPromise = isPromise; exports.isReservedProp = isReservedProp; exports.isSSRSafeAttrName = isSSRSafeAttrName; exports.isSVGTag = isSVGTag; exports.isSet = isSet; exports.isSpecialBooleanAttr = isSpecialBooleanAttr; exports.isString = isString; exports.isSymbol = isSymbol; exports.isVoidTag = isVoidTag; exports.looseEqual = looseEqual; exports.looseIndexOf = looseIndexOf; exports.makeMap = makeMap; exports.normalizeClass = normalizeClass; exports.normalizeStyle = normalizeStyle; exports.objectToString = objectToString; exports.parseStringStyle = parseStringStyle; exports.propsToAttrMap = propsToAttrMap; exports.remove = remove; exports.slotFlagsText = slotFlagsText; exports.stringifyStyle = stringifyStyle; exports.toDisplayString = toDisplayString; exports.toHandlerKey = toHandlerKey; exports.toNumber = toNumber; exports.toRawType = toRawType; exports.toTypeString = toTypeString; }); // node_modules/@vue/shared/index.js var require_shared = __commonJS((exports, module) => { "use strict"; if (false) {} else { module.exports = require_shared_cjs(); } }); // node_modules/@vue/reactivity/dist/reactivity.cjs.js var require_reactivity_cjs = __commonJS((exports) => { "use strict"; Object.defineProperty(exports, "__esModule", {value: true}); var shared = require_shared(); var targetMap = new WeakMap(); var effectStack = []; var activeEffect; var ITERATE_KEY = Symbol("iterate"); var MAP_KEY_ITERATE_KEY = Symbol("Map key iterate"); function isEffect(fn) { return fn && fn._isEffect === true; } function effect3(fn, options = shared.EMPTY_OBJ) { if (isEffect(fn)) { fn = fn.raw; } const effect4 = createReactiveEffect(fn, options); if (!options.lazy) { effect4(); } return effect4; } function stop2(effect4) { if (effect4.active) { cleanup(effect4); if (effect4.options.onStop) { effect4.options.onStop(); } effect4.active = false; } } var uid = 0; function createReactiveEffect(fn, options) { const effect4 = function reactiveEffect() { if (!effect4.active) { return fn(); } if (!effectStack.includes(effect4)) { cleanup(effect4); try { enableTracking(); effectStack.push(effect4); activeEffect = effect4; return fn(); } finally { effectStack.pop(); resetTracking(); activeEffect = effectStack[effectStack.length - 1]; } } }; effect4.id = uid++; effect4.allowRecurse = !!options.allowRecurse; effect4._isEffect = true; effect4.active = true; effect4.raw = fn; effect4.deps = []; effect4.options = options; return effect4; } function cleanup(effect4) { const {deps} = effect4; if (deps.length) { for (let i = 0; i < deps.length; i++) { deps[i].delete(effect4); } deps.length = 0; } } var shouldTrack = true; var trackStack = []; function pauseTracking() { trackStack.push(shouldTrack); shouldTrack = false; } function enableTracking() { trackStack.push(shouldTrack); shouldTrack = true; } function resetTracking() { const last = trackStack.pop(); shouldTrack = last === void 0 ? true : last; } function track(target, type, key) { if (!shouldTrack || activeEffect === void 0) { return; } let depsMap = targetMap.get(target); if (!depsMap) { targetMap.set(target, depsMap = new Map()); } let dep = depsMap.get(key); if (!dep) { depsMap.set(key, dep = new Set()); } if (!dep.has(activeEffect)) { dep.add(activeEffect); activeEffect.deps.push(dep); if (activeEffect.options.onTrack) { activeEffect.options.onTrack({ effect: activeEffect, target, type, key }); } } } function trigger(target, type, key, newValue, oldValue, oldTarget) { const depsMap = targetMap.get(target); if (!depsMap) { return; } const effects = new Set(); const add2 = (effectsToAdd) => { if (effectsToAdd) { effectsToAdd.forEach((effect4) => { if (effect4 !== activeEffect || effect4.allowRecurse) { effects.add(effect4); } }); } }; if (type === "clear") { depsMap.forEach(add2); } else if (key === "length" && shared.isArray(target)) { depsMap.forEach((dep, key2) => { if (key2 === "length" || key2 >= newValue) { add2(dep); } }); } else { if (key !== void 0) { add2(depsMap.get(key)); } switch (type) { case "add": if (!shared.isArray(target)) { add2(depsMap.get(ITERATE_KEY)); if (shared.isMap(target)) { add2(depsMap.get(MAP_KEY_ITERATE_KEY)); } } else if (shared.isIntegerKey(key)) { add2(depsMap.get("length")); } break; case "delete": if (!shared.isArray(target)) { add2(depsMap.get(ITERATE_KEY)); if (shared.isMap(target)) { add2(depsMap.get(MAP_KEY_ITERATE_KEY)); } } break; case "set": if (shared.isMap(target)) { add2(depsMap.get(ITERATE_KEY)); } break; } } const run = (effect4) => { if (effect4.options.onTrigger) { effect4.options.onTrigger({ effect: effect4, target, key, type, newValue, oldValue, oldTarget }); } if (effect4.options.scheduler) { effect4.options.scheduler(effect4); } else { effect4(); } }; effects.forEach(run); } var isNonTrackableKeys = /* @__PURE__ */ shared.makeMap(`__proto__,__v_isRef,__isVue`); var builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol).map((key) => Symbol[key]).filter(shared.isSymbol)); var get2 = /* @__PURE__ */ createGetter(); var shallowGet = /* @__PURE__ */ createGetter(false, true); var readonlyGet = /* @__PURE__ */ createGetter(true); var shallowReadonlyGet = /* @__PURE__ */ createGetter(true, true); var arrayInstrumentations = {}; ["includes", "indexOf", "lastIndexOf"].forEach((key) => { const method = Array.prototype[key]; arrayInstrumentations[key] = function(...args) { const arr = toRaw2(this); for (let i = 0, l = this.length; i < l; i++) { track(arr, "get", i + ""); } const res = method.apply(arr, args); if (res === -1 || res === false) { return method.apply(arr, args.map(toRaw2)); } else { return res; } }; }); ["push", "pop", "shift", "unshift", "splice"].forEach((key) => { const method = Array.prototype[key]; arrayInstrumentations[key] = function(...args) { pauseTracking(); const res = method.apply(this, args); resetTracking(); return res; }; }); function createGetter(isReadonly2 = false, shallow = false) { return function get3(target, key, receiver) { if (key === "__v_isReactive") { return !isReadonly2; } else if (key === "__v_isReadonly") { return isReadonly2; } else if (key === "__v_raw" && receiver === (isReadonly2 ? shallow ? shallowReadonlyMap : readonlyMap : shallow ? shallowReactiveMap : reactiveMap).get(target)) { return target; } const targetIsArray = shared.isArray(target); if (!isReadonly2 && targetIsArray && shared.hasOwn(arrayInstrumentations, key)) { return Reflect.get(arrayInstrumentations, key, receiver); } const res = Reflect.get(target, key, receiver); if (shared.isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { return res; } if (!isReadonly2) { track(target, "get", key); } if (shallow) { return res; } if (isRef(res)) { const shouldUnwrap = !targetIsArray || !shared.isIntegerKey(key); return shouldUnwrap ? res.value : res; } if (shared.isObject(res)) { return isReadonly2 ? readonly(res) : reactive3(res); } return res; }; } var set2 = /* @__PURE__ */ createSetter(); var shallowSet = /* @__PURE__ */ createSetter(true); function createSetter(shallow = false) { return function set3(target, key, value, receiver) { let oldValue = target[key]; if (!shallow) { value = toRaw2(value); oldValue = toRaw2(oldValue); if (!shared.isArray(target) && isRef(oldValue) && !isRef(value)) { oldValue.value = value; return true; } } const hadKey = shared.isArray(target) && shared.isIntegerKey(key) ? Number(key) < target.length : shared.hasOwn(target, key); const result = Reflect.set(target, key, value, receiver); if (target === toRaw2(receiver)) { if (!hadKey) { trigger(target, "add", key, value); } else if (shared.hasChanged(value, oldValue)) { trigger(target, "set", key, value, oldValue); } } return result; }; } function deleteProperty(target, key) { const hadKey = shared.hasOwn(target, key); const oldValue = target[key]; const result = Reflect.deleteProperty(target, key); if (result && hadKey) { trigger(target, "delete", key, void 0, oldValue); } return result; } function has(target, key) { const result = Reflect.has(target, key); if (!shared.isSymbol(key) || !builtInSymbols.has(key)) { track(target, "has", key); } return result; } function ownKeys(target) { track(target, "iterate", shared.isArray(target) ? "length" : ITERATE_KEY); return Reflect.ownKeys(target); } var mutableHandlers = { get: get2, set: set2, deleteProperty, has, ownKeys }; var readonlyHandlers = { get: readonlyGet, set(target, key) { { console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target); } return true; }, deleteProperty(target, key) { { console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target); } return true; } }; var shallowReactiveHandlers = shared.extend({}, mutableHandlers, { get: shallowGet, set: shallowSet }); var shallowReadonlyHandlers = shared.extend({}, readonlyHandlers, { get: shallowReadonlyGet }); var toReactive = (value) => shared.isObject(value) ? reactive3(value) : value; var toReadonly = (value) => shared.isObject(value) ? readonly(value) : value; var toShallow = (value) => value; var getProto = (v) => Reflect.getPrototypeOf(v); function get$1(target, key, isReadonly2 = false, isShallow = false) { target = target["__v_raw"]; const rawTarget = toRaw2(target); const rawKey = toRaw2(key); if (key !== rawKey) { !isReadonly2 && track(rawTarget, "get", key); } !isReadonly2 && track(rawTarget, "get", rawKey); const {has: has2} = getProto(rawTarget); const wrap = isShallow ? toShallow : isReadonly2 ? toReadonly : toReactive; if (has2.call(rawTarget, key)) { return wrap(target.get(key)); } else if (has2.call(rawTarget, rawKey)) { return wrap(target.get(rawKey)); } else if (target !== rawTarget) { target.get(key); } } function has$1(key, isReadonly2 = false) { const target = this["__v_raw"]; const rawTarget = toRaw2(target); const rawKey = toRaw2(key); if (key !== rawKey) { !isReadonly2 && track(rawTarget, "has", key); } !isReadonly2 && track(rawTarget, "has", rawKey); return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); } function size(target, isReadonly2 = false) { target = target["__v_raw"]; !isReadonly2 && track(toRaw2(target), "iterate", ITERATE_KEY); return Reflect.get(target, "size", target); } function add(value) { value = toRaw2(value); const target = toRaw2(this); const proto = getProto(target); const hadKey = proto.has.call(target, value); if (!hadKey) { target.add(value); trigger(target, "add", value, value); } return this; } function set$1(key, value) { value = toRaw2(value); const target = toRaw2(this); const {has: has2, get: get3} = getProto(target); let hadKey = has2.call(target, key); if (!hadKey) { key = toRaw2(key); hadKey = has2.call(target, key); } else { checkIdentityKeys(target, has2, key); } const oldValue = get3.call(target, key); target.set(key, value); if (!hadKey) { trigger(target, "add", key, value); } else if (shared.hasChanged(value, oldValue)) { trigger(target, "set", key, value, oldValue); } return this; } function deleteEntry(key) { const target = toRaw2(this); const {has: has2, get: get3} = getProto(target); let hadKey = has2.call(target, key); if (!hadKey) { key = toRaw2(key); hadKey = has2.call(target, key); } else { checkIdentityKeys(target, has2, key); } const oldValue = get3 ? get3.call(target, key) : void 0; const result = target.delete(key); if (hadKey) { trigger(target, "delete", key, void 0, oldValue); } return result; } function clear() { const target = toRaw2(this); const hadItems = target.size !== 0; const oldTarget = shared.isMap(target) ? new Map(target) : new Set(target); const result = target.clear(); if (hadItems) { trigger(target, "clear", void 0, void 0, oldTarget); } return result; } function createForEach(isReadonly2, isShallow) { return function forEach(callback, thisArg) { const observed = this; const target = observed["__v_raw"]; const rawTarget = toRaw2(target); const wrap = isShallow ? toShallow : isReadonly2 ? toReadonly : toReactive; !isReadonly2 && track(rawTarget, "iterate", ITERATE_KEY); return target.forEach((value, key) => { return callback.call(thisArg, wrap(value), wrap(key), observed); }); }; } function createIterableMethod(method, isReadonly2, isShallow) { return function(...args) { const target = this["__v_raw"]; const rawTarget = toRaw2(target); const targetIsMap = shared.isMap(rawTarget); const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; const isKeyOnly = method === "keys" && targetIsMap; const innerIterator = target[method](...args); const wrap = isShallow ? toShallow : isReadonly2 ? toReadonly : toReactive; !isReadonly2 && track(rawTarget, "iterate", isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY); return { next() { const {value, done} = innerIterator.next(); return done ? {value, done} : { value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), done }; }, [Symbol.iterator]() { return this; } }; }; } function createReadonlyMethod(type) { return function(...args) { { const key = args[0] ? `on key "${args[0]}" ` : ``; console.warn(`${shared.capitalize(type)} operation ${key}failed: target is readonly.`, toRaw2(this)); } return type === "delete" ? false : this; }; } var mutableInstrumentations = { get(key) { return get$1(this, key); }, get size() { return size(this); }, has: has$1, add, set: set$1, delete: deleteEntry, clear, forEach: createForEach(false, false) }; var shallowInstrumentations = { get(key) { return get$1(this, key, false, true); }, get size() { return size(this); }, has: has$1, add, set: set$1, delete: deleteEntry, clear, forEach: createForEach(false, true) }; var readonlyInstrumentations = { get(key) { return get$1(this, key, true); }, get size() { return size(this, true); }, has(key) { return has$1.call(this, key, true); }, add: createReadonlyMethod("add"), set: createReadonlyMethod("set"), delete: createReadonlyMethod("delete"), clear: createReadonlyMethod("clear"), forEach: createForEach(true, false) }; var shallowReadonlyInstrumentations = { get(key) { return get$1(this, key, true, true); }, get size() { return size(this, true); }, has(key) { return has$1.call(this, key, true); }, add: createReadonlyMethod("add"), set: createReadonlyMethod("set"), delete: createReadonlyMethod("delete"), clear: createReadonlyMethod("clear"), forEach: createForEach(true, true) }; var iteratorMethods = ["keys", "values", "entries", Symbol.iterator]; iteratorMethods.forEach((method) => { mutableInstrumentations[method] = createIterableMethod(method, false, false); readonlyInstrumentations[method] = createIterableMethod(method, true, false); shallowInstrumentations[method] = createIterableMethod(method, false, true); shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true); }); function createInstrumentationGetter(isReadonly2, shallow) { const instrumentations = shallow ? isReadonly2 ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly2 ? readonlyInstrumentations : mutableInstrumentations; return (target, key, receiver) => { if (key === "__v_isReactive") { return !isReadonly2; } else if (key === "__v_isReadonly") { return isReadonly2; } else if (key === "__v_raw") { return target; } return Reflect.get(shared.hasOwn(instrumentations, key) && key in target ? instrumentations : target, key, receiver); }; } var mutableCollectionHandlers = { get: createInstrumentationGetter(false, false) }; var shallowCollectionHandlers = { get: createInstrumentationGetter(false, true) }; var readonlyCollectionHandlers = { get: createInstrumentationGetter(true, false) }; var shallowReadonlyCollectionHandlers = { get: createInstrumentationGetter(true, true) }; function checkIdentityKeys(target, has2, key) { const rawKey = toRaw2(key); if (rawKey !== key && has2.call(target, rawKey)) { const type = shared.toRawType(target); console.warn(`Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? ` as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.`); } } var reactiveMap = new WeakMap(); var shallowReactiveMap = new WeakMap(); var readonlyMap = new WeakMap(); var shallowReadonlyMap = new WeakMap(); function targetTypeMap(rawType) { switch (rawType) { case "Object": case "Array": return 1; case "Map": case "Set": case "WeakMap": case "WeakSet": return 2; default: return 0; } } function getTargetType(value) { return value["__v_skip"] || !Object.isExtensible(value) ? 0 : targetTypeMap(shared.toRawType(value)); } function reactive3(target) { if (target && target["__v_isReadonly"]) { return target; } return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap); } function shallowReactive(target) { return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap); } function readonly(target) { return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap); } function shallowReadonly(target) { return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap); } function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) { if (!shared.isObject(target)) { { console.warn(`value cannot be made reactive: ${String(target)}`); } return target; } if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) { return target; } const existingProxy = proxyMap.get(target); if (existingProxy) { return existingProxy; } const targetType = getTargetType(target); if (targetType === 0) { return target; } const proxy = new Proxy(target, targetType === 2 ? collectionHandlers : baseHandlers); proxyMap.set(target, proxy); return proxy; } function isReactive2(value) { if (isReadonly(value)) { return isReactive2(value["__v_raw"]); } return !!(value && value["__v_isReactive"]); } function isReadonly(value) { return !!(value && value["__v_isReadonly"]); } function isProxy(value) { return isReactive2(value) || isReadonly(value); } function toRaw2(observed) { return observed && toRaw2(observed["__v_raw"]) || observed; } function markRaw(value) { shared.def(value, "__v_skip", true); return value; } var convert = (val) => shared.isObject(val) ? reactive3(val) : val; function isRef(r) { return Boolean(r && r.__v_isRef === true); } function ref(value) { return createRef(value); } function shallowRef(value) { return createRef(value, true); } var RefImpl = class { constructor(_rawValue, _shallow = false) { this._rawValue = _rawValue; this._shallow = _shallow; this.__v_isRef = true; this._value = _shallow ? _rawValue : convert(_rawValue); } get value() { track(toRaw2(this), "get", "value"); return this._value; } set value(newVal) { if (shared.hasChanged(toRaw2(newVal), this._rawValue)) { this._rawValue = newVal; this._value = this._shallow ? newVal : convert(newVal); trigger(toRaw2(this), "set", "value", newVal); } } }; function createRef(rawValue, shallow = false) { if (isRef(rawValue)) { return rawValue; } return new RefImpl(rawValue, shallow); } function triggerRef(ref2) { trigger(toRaw2(ref2), "set", "value", ref2.value); } function unref(ref2) { return isRef(ref2) ? ref2.value : ref2; } var shallowUnwrapHandlers = { get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)), set: (target, key, value, receiver) => { const oldValue = target[key]; if (isRef(oldValue) && !isRef(value)) { oldValue.value = value; return true; } else { return Reflect.set(target, key, value, receiver); } } }; function proxyRefs(objectWithRefs) { return isReactive2(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); } var CustomRefImpl = class { constructor(factory) { this.__v_isRef = true; const {get: get3, set: set3} = factory(() => track(this, "get", "value"), () => trigger(this, "set", "value")); this._get = get3; this._set = set3; } get value() { return this._get(); } set value(newVal) { this._set(newVal); } }; function customRef(factory) { return new CustomRefImpl(factory); } function toRefs(object) { if (!isProxy(object)) { console.warn(`toRefs() expects a reactive object but received a plain one.`); } const ret = shared.isArray(object) ? new Array(object.length) : {}; for (const key in object) { ret[key] = toRef(object, key); } return ret; } var ObjectRefImpl = class { constructor(_object, _key) { this._object = _object; this._key = _key; this.__v_isRef = true; } get value() { return this._object[this._key]; } set value(newVal) { this._object[this._key] = newVal; } }; function toRef(object, key) { return isRef(object[key]) ? object[key] : new ObjectRefImpl(object, key); } var ComputedRefImpl = class { constructor(getter, _setter, isReadonly2) { this._setter = _setter; this._dirty = true; this.__v_isRef = true; this.effect = effect3(getter, { lazy: true, scheduler: () => { if (!this._dirty) { this._dirty = true; trigger(toRaw2(this), "set", "value"); } } }); this["__v_isReadonly"] = isReadonly2; } get value() { const self2 = toRaw2(this); if (self2._dirty) { self2._value = this.effect(); self2._dirty = false; } track(self2, "get", "value"); return self2._value; } set value(newValue) { this._setter(newValue); } }; function computed(getterOrOptions) { let getter; let setter; if (shared.isFunction(getterOrOptions)) { getter = getterOrOptions; setter = () => { console.warn("Write operation failed: computed value is readonly"); }; } else { getter = getterOrOptions.get; setter = getterOrOptions.set; } return new ComputedRefImpl(getter, setter, shared.isFunction(getterOrOptions) || !getterOrOptions.set); } exports.ITERATE_KEY = ITERATE_KEY; exports.computed = computed; exports.customRef = customRef; exports.effect = effect3; exports.enableTracking = enableTracking; exports.isProxy = isProxy; exports.isReactive = isReactive2; exports.isReadonly = isReadonly; exports.isRef = isRef; exports.markRaw = markRaw; exports.pauseTracking = pauseTracking; exports.proxyRefs = proxyRefs; exports.reactive = reactive3; exports.readonly = readonly; exports.ref = ref; exports.resetTracking = resetTracking; exports.shallowReactive = shallowReactive; exports.shallowReadonly = shallowReadonly; exports.shallowRef = shallowRef; exports.stop = stop2; exports.toRaw = toRaw2; exports.toRef = toRef; exports.toRefs = toRefs; exports.track = track; exports.trigger = trigger; exports.triggerRef = triggerRef; exports.unref = unref; }); // node_modules/@vue/reactivity/index.js var require_reactivity = __commonJS((exports, module) => { "use strict"; if (false) {} else { module.exports = require_reactivity_cjs(); } }); // packages/alpinejs/src/scheduler.js var flushPending = false; var flushing = false; var queue = []; function scheduler(callback) { queueJob(callback); } function queueJob(job) { if (!queue.includes(job)) queue.push(job); queueFlush(); } function queueFlush() { if (!flushing && !flushPending) { flushPending = true; queueMicrotask(flushJobs); } } function flushJobs() { flushPending = false; flushing = true; for (let i = 0; i < queue.length; i++) { queue[i](); } queue.length = 0; flushing = false; } // packages/alpinejs/src/reactivity.js var reactive; var effect; var release; var raw; var shouldSchedule = true; function disableEffectScheduling(callback) { shouldSchedule = false; callback(); shouldSchedule = true; } function setReactivityEngine(engine) { reactive = engine.reactive; release = engine.release; effect = (callback) => engine.effect(callback, {scheduler: (task) => { if (shouldSchedule) { scheduler(task); } else { task(); } }}); raw = engine.raw; } function overrideEffect(override) { effect = override; } function elementBoundEffect(el) { let cleanup = () => { }; let wrappedEffect = (callback) => { let effectReference = effect(callback); if (!el._x_effects) { el._x_effects = new Set(); el._x_runEffects = () => { el._x_effects.forEach((i) => i()); }; } el._x_effects.add(effectReference); cleanup = () => { if (effectReference === void 0) return; el._x_effects.delete(effectReference); release(effectReference); }; }; return [wrappedEffect, () => { cleanup(); }]; } // packages/alpinejs/src/mutation.js var onAttributeAddeds = []; var onElRemoveds = []; var onElAddeds = []; function onElAdded(callback) { onElAddeds.push(callback); } function onElRemoved(callback) { onElRemoveds.push(callback); } function onAttributesAdded(callback) { onAttributeAddeds.push(callback); } function onAttributeRemoved(el, name, callback) { if (!el._x_attributeCleanups) el._x_attributeCleanups = {}; if (!el._x_attributeCleanups[name]) el._x_attributeCleanups[name] = []; el._x_attributeCleanups[name].push(callback); } function cleanupAttributes(el, names) { if (!el._x_attributeCleanups) return; Object.entries(el._x_attributeCleanups).forEach(([name, value]) => { (names === void 0 || names.includes(name)) && value.forEach((i) => i()); delete el._x_attributeCleanups[name]; }); } var observer = new MutationObserver(onMutate); var currentlyObserving = false; function startObservingMutations() { observer.observe(document, {subtree: true, childList: true, attributes: true, attributeOldValue: true}); currentlyObserving = true; } function stopObservingMutations() { observer.disconnect(); currentlyObserving = false; } var recordQueue = []; var willProcessRecordQueue = false; function flushObserver() { recordQueue = recordQueue.concat(observer.takeRecords()); if (recordQueue.length && !willProcessRecordQueue) { willProcessRecordQueue = true; queueMicrotask(() => { processRecordQueue(); willProcessRecordQueue = false; }); } } function processRecordQueue() { onMutate(recordQueue); recordQueue.length = 0; } function mutateDom(callback) { if (!currentlyObserving) return callback(); flushObserver(); stopObservingMutations(); let result = callback(); startObservingMutations(); return result; } function onMutate(mutations) { let addedNodes = []; let removedNodes = []; let addedAttributes = new Map(); let removedAttributes = new Map(); for (let i = 0; i < mutations.length; i++) { if (mutations[i].target._x_ignoreMutationObserver) continue; if (mutations[i].type === "childList") { mutations[i].addedNodes.forEach((node) => node.nodeType === 1 && addedNodes.push(node)); mutations[i].removedNodes.forEach((node) => node.nodeType === 1 && removedNodes.push(node)); } if (mutations[i].type === "attributes") { let el = mutations[i].target; let name = mutations[i].attributeName; let oldValue = mutations[i].oldValue; let add = () => { if (!addedAttributes.has(el)) addedAttributes.set(el, []); addedAttributes.get(el).push({name, value: el.getAttribute(name)}); }; let remove = () => { if (!removedAttributes.has(el)) removedAttributes.set(el, []); removedAttributes.get(el).push(name); }; if (el.hasAttribute(name) && oldValue === null) { add(); } else if (el.hasAttribute(name)) { remove(); add(); } else { remove(); } } } removedAttributes.forEach((attrs, el) => { cleanupAttributes(el, attrs); }); addedAttributes.forEach((attrs, el) => { onAttributeAddeds.forEach((i) => i(el, attrs)); }); for (let node of addedNodes) { if (removedNodes.includes(node)) continue; onElAddeds.forEach((i) => i(node)); } for (let node of removedNodes) { if (addedNodes.includes(node)) continue; onElRemoveds.forEach((i) => i(node)); } addedNodes = null; removedNodes = null; addedAttributes = null; removedAttributes = null; } // packages/alpinejs/src/scope.js function addScopeToNode(node, data2, referenceNode) { node._x_dataStack = [data2, ...closestDataStack(referenceNode || node)]; return () => { node._x_dataStack = node._x_dataStack.filter((i) => i !== data2); }; } function refreshScope(element, scope) { let existingScope = element._x_dataStack[0]; Object.entries(scope).forEach(([key, value]) => { existingScope[key] = value; }); } function closestDataStack(node) { if (node._x_dataStack) return node._x_dataStack; if (node instanceof ShadowRoot) { return closestDataStack(node.host); } if (!node.parentNode) { return []; } return closestDataStack(node.parentNode); } function mergeProxies(objects) { return new Proxy({}, { ownKeys: () => { return Array.from(new Set(objects.flatMap((i) => Object.keys(i)))); }, has: (target, name) => { return objects.some((obj) => obj.hasOwnProperty(name)); }, get: (target, name) => { return (objects.find((obj) => obj.hasOwnProperty(name)) || {})[name]; }, set: (target, name, value) => { let closestObjectWithKey = objects.find((obj) => obj.hasOwnProperty(name)); if (closestObjectWithKey) { closestObjectWithKey[name] = value; } else { objects[objects.length - 1][name] = value; } return true; } }); } // packages/alpinejs/src/interceptor.js function initInterceptors(data2) { let isObject = (val) => typeof val === "object" && !Array.isArray(val) && val !== null; let recurse = (obj, basePath = "") => { Object.entries(obj).forEach(([key, value]) => { let path = basePath === "" ? key : `${basePath}.${key}`; if (typeof value === "object" && value !== null && value._x_interceptor) { obj[key] = value.initialize(data2, path, key); } else { if (isObject(value) && value !== obj && !(value instanceof Element)) { recurse(value, path); } } }); }; return recurse(data2); } function interceptor(callback, mutateObj = () => { }) { let obj = { initialValue: void 0, _x_interceptor: true, initialize(data2, path, key) { return callback(this.initialValue, () => get(data2, path), (value) => set(data2, path, value), path, key); } }; mutateObj(obj); return (initialValue) => { if (typeof initialValue === "object" && initialValue !== null && initialValue._x_interceptor) { let initialize = obj.initialize.bind(obj); obj.initialize = (data2, path, key) => { let innerValue = initialValue.initialize(data2, path, key); obj.initialValue = innerValue; return initialize(data2, path, key); }; } else { obj.initialValue = initialValue; } return obj; }; } function get(obj, path) { return path.split(".").reduce((carry, segment) => carry[segment], obj); } function set(obj, path, value) { if (typeof path === "string") path = path.split("."); if (path.length === 1) obj[path[0]] = value; else if (path.length === 0) throw error; else { if (obj[path[0]]) return set(obj[path[0]], path.slice(1), value); else { obj[path[0]] = {}; return set(obj[path[0]], path.slice(1), value); } } } // packages/alpinejs/src/magics.js var magics = {}; function magic(name, callback) { magics[name] = callback; } function injectMagics(obj, el) { Object.entries(magics).forEach(([name, callback]) => { Object.defineProperty(obj, `$${name}`, { get() { return callback(el, {Alpine: alpine_default, interceptor}); }, enumerable: false }); }); return obj; } // packages/alpinejs/src/evaluator.js function evaluate(el, expression, extras = {}) { let result; evaluateLater(el, expression)((value) => result = value, extras); return result; } function evaluateLater(...args) { return theEvaluatorFunction(...args); } var theEvaluatorFunction = normalEvaluator; function setEvaluator(newEvaluator) { theEvaluatorFunction = newEvaluator; } function normalEvaluator(el, expression) { let overriddenMagics = {}; injectMagics(overriddenMagics, el); let dataStack = [overriddenMagics, ...closestDataStack(el)]; if (typeof expression === "function") { return generateEvaluatorFromFunction(dataStack, expression); } let evaluator = generateEvaluatorFromString(dataStack, expression); return tryCatch.bind(null, el, expression, evaluator); } function generateEvaluatorFromFunction(dataStack, func) { return (receiver = () => { }, {scope = {}, params = []} = {}) => { let result = func.apply(mergeProxies([scope, ...dataStack]), params); runIfTypeOfFunction(receiver, result); }; } var evaluatorMemo = {}; function generateFunctionFromString(expression) { if (evaluatorMemo[expression]) { return evaluatorMemo[expression]; } let AsyncFunction = Object.getPrototypeOf(async function() { }).constructor; let rightSideSafeExpression = /^[\n\s]*if.*\(.*\)/.test(expression) || /^(let|const)/.test(expression) ? `(() => { ${expression} })()` : expression; let func = new AsyncFunction(["__self", "scope"], `with (scope) { __self.result = ${rightSideSafeExpression} }; __self.finished = true; return __self.result;`); evaluatorMemo[expression] = func; return func; } function generateEvaluatorFromString(dataStack, expression) { let func = generateFunctionFromString(expression); return (receiver = () => { }, {scope = {}, params = []} = {}) => { func.result = void 0; func.finished = false; let completeScope = mergeProxies([scope, ...dataStack]); let promise = func(func, completeScope); if (func.finished) { runIfTypeOfFunction(receiver, func.result, completeScope, params); } else { promise.then((result) => { runIfTypeOfFunction(receiver, result, completeScope, params); }); } }; } function runIfTypeOfFunction(receiver, value, scope, params) { if (typeof value === "function") { let result = value.apply(scope, params); if (result instanceof Promise) { result.then((i) => runIfTypeOfFunction(receiver, i, scope, params)); } else { receiver(result); } } else { receiver(value); } } function tryCatch(el, expression, callback, ...args) { try { return callback(...args); } catch (e) { console.warn(`Alpine Expression Error: ${e.message} Expression: "${expression}" `, el); throw e; } } // packages/alpinejs/src/directives.js var prefixAsString = "x-"; function prefix(subject = "") { return prefixAsString + subject; } function setPrefix(newPrefix) { prefixAsString = newPrefix; } var directiveHandlers = {}; function directive(name, callback) { directiveHandlers[name] = callback; } function directives(el, attributes, originalAttributeOverride) { let transformedAttributeMap = {}; let directives2 = Array.from(attributes).map(toTransformedAttributes((newName, oldName) => transformedAttributeMap[newName] = oldName)).filter(outNonAlpineAttributes).map(toParsedDirectives(transformedAttributeMap, originalAttributeOverride)).sort(byPriority); return directives2.map((directive2) => { return getDirectiveHandler(el, directive2); }); } var isDeferringHandlers = false; var directiveHandlerStacks = new Map(); var currentHandlerStackKey = Symbol(); function deferHandlingDirectives(callback) { isDeferringHandlers = true; let key = Symbol(); currentHandlerStackKey = key; directiveHandlerStacks.set(key, []); let flushHandlers = () => { while (directiveHandlerStacks.get(key).length) directiveHandlerStacks.get(key).shift()(); directiveHandlerStacks.delete(key); }; let stopDeferring = () => { isDeferringHandlers = false; flushHandlers(); }; callback(flushHandlers); stopDeferring(); } function getDirectiveHandler(el, directive2) { let noop = () => { }; let handler3 = directiveHandlers[directive2.type] || noop; let cleanups = []; let cleanup = (callback) => cleanups.push(callback); let [effect3, cleanupEffect] = elementBoundEffect(el); cleanups.push(cleanupEffect); let utilities = { Alpine: alpine_default, effect: effect3, cleanup, evaluateLater: evaluateLater.bind(evaluateLater, el), evaluate: evaluate.bind(evaluate, el) }; let doCleanup = () => cleanups.forEach((i) => i()); onAttributeRemoved(el, directive2.original, doCleanup); let fullHandler = () => { if (el._x_ignore || el._x_ignoreSelf) return; handler3.inline && handler3.inline(el, directive2, utilities); handler3 = handler3.bind(handler3, el, directive2, utilities); isDeferringHandlers ? directiveHandlerStacks.get(currentHandlerStackKey).push(handler3) : handler3(); }; fullHandler.runCleanups = doCleanup; return fullHandler; } var startingWith = (subject, replacement) => ({name, value}) => { if (name.startsWith(subject)) name = name.replace(subject, replacement); return {name, value}; }; var into = (i) => i; function toTransformedAttributes(callback) { return ({name, value}) => { let {name: newName, value: newValue} = attributeTransformers.reduce((carry, transform) => { return transform(carry); }, {name, value}); if (newName !== name) callback(newName, name); return {name: newName, value: newValue}; }; } var attributeTransformers = []; function mapAttributes(callback) { attributeTransformers.push(callback); } function outNonAlpineAttributes({name}) { return alpineAttributeRegex().test(name); } var alpineAttributeRegex = () => new RegExp(`^${prefixAsString}([^:^.]+)\\b`); function toParsedDirectives(transformedAttributeMap, originalAttributeOverride) { return ({name, value}) => { let typeMatch = name.match(alpineAttributeRegex()); let valueMatch = name.match(/:([a-zA-Z0-9\-:]+)/); let modifiers = name.match(/\.[^.\]]+(?=[^\]]*$)/g) || []; let original = originalAttributeOverride || transformedAttributeMap[name] || name; return { type: typeMatch ? typeMatch[1] : null, value: valueMatch ? valueMatch[1] : null, modifiers: modifiers.map((i) => i.replace(".", "")), expression: value, original }; }; } var DEFAULT = "DEFAULT"; var directiveOrder = [ "ignore", "ref", "data", "bind", "init", "for", "model", "transition", "show", "if", DEFAULT, "element" ]; function byPriority(a, b) { let typeA = directiveOrder.indexOf(a.type) === -1 ? DEFAULT : a.type; let typeB = directiveOrder.indexOf(b.type) === -1 ? DEFAULT : b.type; return directiveOrder.indexOf(typeA) - directiveOrder.indexOf(typeB); } // packages/alpinejs/src/utils/dispatch.js function dispatch(el, name, detail = {}) { el.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true, cancelable: true })); } // packages/alpinejs/src/nextTick.js var tickStack = []; var isHolding = false; function nextTick(callback) { tickStack.push(callback); queueMicrotask(() => { isHolding || setTimeout(() => { releaseNextTicks(); }); }); } function releaseNextTicks() { isHolding = false; while (tickStack.length) tickStack.shift()(); } function holdNextTicks() { isHolding = true; } // packages/alpinejs/src/utils/walk.js function walk(el, callback) { if (el instanceof ShadowRoot) { Array.from(el.children).forEach((el2) => walk(el2, callback)); return; } let skip = false; callback(el, () => skip = true); if (skip) return; let node = el.firstElementChild; while (node) { walk(node, callback, false); node = node.nextElementSibling; } } // packages/alpinejs/src/utils/warn.js function warn(message, ...args) { console.warn(`Alpine Warning: ${message}`, ...args); } // packages/alpinejs/src/lifecycle.js function start() { if (!document.body) warn("Unable to initialize. Trying to load Alpine before `<body>` is available. Did you forget to add `defer` in Alpine's `<script>` tag?"); dispatch(document, "alpine:init"); dispatch(document, "alpine:initializing"); startObservingMutations(); onElAdded((el) => initTree(el, walk)); onElRemoved((el) => nextTick(() => destroyTree(el))); onAttributesAdded((el, attrs) => { directives(el, attrs).forEach((handle) => handle()); }); let outNestedComponents = (el) => !closestRoot(el.parentElement); Array.from(document.querySelectorAll(allSelectors())).filter(outNestedComponents).forEach((el) => { initTree(el); }); dispatch(document, "alpine:initialized"); } var rootSelectorCallbacks = []; var initSelectorCallbacks = []; function rootSelectors() { return rootSelectorCallbacks.map((fn) => fn()); } function allSelectors() { return rootSelectorCallbacks.concat(initSelectorCallbacks).map((fn) => fn()); } function addRootSelector(selectorCallback) { rootSelectorCallbacks.push(selectorCallback); } function addInitSelector(selectorCallback) { initSelectorCallbacks.push(selectorCallback); } function closestRoot(el) { if (!el) return; if (rootSelectors().some((selector) => el.matches(selector))) return el; if (!el.parentElement) return; return closestRoot(el.parentElement); } function isRoot(el) { return rootSelectors().some((selector) => el.matches(selector)); } function initTree(el, walker = walk) { deferHandlingDirectives(() => { walker(el, (el2, skip) => { directives(el2, el2.attributes).forEach((handle) => handle()); el2._x_ignore && skip(); }); }); } function destroyTree(root) { walk(root, (el) => cleanupAttributes(el)); } // packages/alpinejs/src/plugin.js function plugin(callback) { callback(alpine_default); } // packages/alpinejs/src/store.js var stores = {}; var isReactive = false; function store(name, value) { if (!isReactive) { stores = reactive(stores); isReactive = true; } if (value === void 0) { return stores[name]; } stores[name] = value; if (typeof value === "object" && value !== null && value.hasOwnProperty("init") && typeof value.init === "function") { stores[name].init(); } } function getStores() { return stores; } // packages/alpinejs/src/clone.js var isCloning = false; function skipDuringClone(callback) { return (...args) => isCloning || callback(...args); } function clone(oldEl, newEl) { newEl._x_dataStack = oldEl._x_dataStack; isCloning = true; dontRegisterReactiveSideEffects(() => { cloneTree(newEl); }); isCloning = false; } function cloneTree(el) { let hasRunThroughFirstEl = false; let shallowWalker = (el2, callback) => { walk(el2, (el3, skip) => { if (hasRunThroughFirstEl && isRoot(el3)) return skip(); hasRunThroughFirstEl = true; callback(el3, skip); }); }; initTree(el, shallowWalker); } function dontRegisterReactiveSideEffects(callback) { let cache = effect; overrideEffect((callback2, el) => { let storedEffect = cache(callback2); release(storedEffect); return () => { }; }); callback(); overrideEffect(cache); } // packages/alpinejs/src/datas.js var datas = {}; function data(name, callback) { datas[name] = callback; } function injectDataProviders(obj, context) { Object.entries(datas).forEach(([name, callback]) => { Object.defineProperty(obj, name, { get() { return (...args) => { return callback.bind(context)(...args); }; }, enumerable: false }); }); return obj; } // packages/alpinejs/src/alpine.js var Alpine = { get reactive() { return reactive; }, get release() { return release; }, get effect() { return effect; }, get raw() { return raw; }, version: "3.3.1", disableEffectScheduling, setReactivityEngine, addRootSelector, mapAttributes, evaluateLater, setEvaluator, closestRoot, interceptor, mutateDom, directive, evaluate, initTree, nextTick, prefix: setPrefix, plugin, magic, store, start, clone, data }; var alpine_default = Alpine; // packages/alpinejs/src/index.js var import_reactivity9 = __toModule(require_reactivity()); // packages/alpinejs/src/magics/$nextTick.js magic("nextTick", () => nextTick); // packages/alpinejs/src/magics/$dispatch.js magic("dispatch", (el) => dispatch.bind(dispatch, el)); // packages/alpinejs/src/magics/$watch.js magic("watch", (el) => (key, callback) => { let evaluate2 = evaluateLater(el, key); let firstTime = true; let oldValue; effect(() => evaluate2((value) => { let div = document.createElement("div"); div.dataset.throwAway = value; if (!firstTime) { queueMicrotask(() => { callback(value, oldValue); oldValue = value; }); } else { oldValue = value; } firstTime = false; })); }); // packages/alpinejs/src/magics/$store.js magic("store", getStores); // packages/alpinejs/src/magics/$root.js magic("root", (el) => closestRoot(el)); // packages/alpinejs/src/magics/$refs.js magic("refs", (el) => closestRoot(el)._x_refs || {}); // packages/alpinejs/src/magics/$el.js magic("el", (el) => el); // packages/alpinejs/src/utils/classes.js function setClasses(el, value) { if (Array.isArray(value)) { return setClassesFromString(el, value.join(" ")); } else if (typeof value === "object" && value !== null) { return setClassesFromObject(el, value); } else if (typeof value === "function") { return setClasses(el, value()); } return setClassesFromString(el, value); } function setClassesFromString(el, classString) { let split = (classString2) => classString2.split(" ").filter(Boolean); let missingClasses = (classString2) => classString2.split(" ").filter((i) => !el.classList.contains(i)).filter(Boolean); let addClassesAndReturnUndo = (classes) => { el.classList.add(...classes); return () => { el.classList.remove(...classes); }; }; classString = classString === true ? classString = "" : classString || ""; return addClassesAndReturnUndo(missingClasses(classString)); } function setClassesFromObject(el, classObject) { let split = (classString) => classString.split(" ").filter(Boolean); let forAdd = Object.entries(classObject).flatMap(([classString, bool]) => bool ? split(classString) : false).filter(Boolean); let forRemove = Object.entries(classObject).flatMap(([classString, bool]) => !bool ? split(classString) : false).filter(Boolean); let added = []; let removed = []; forRemove.forEach((i) => { if (el.classList.contains(i)) { el.classList.remove(i); removed.push(i); } }); forAdd.forEach((i) => { if (!el.classList.contains(i)) { el.classList.add(i); added.push(i); } }); return () => { removed.forEach((i) => el.classList.add(i)); added.forEach((i) => el.classList.remove(i)); }; } // packages/alpinejs/src/utils/styles.js function setStyles(el, value) { if (typeof value === "object" && value !== null) { return setStylesFromObject(el, value); } return setStylesFromString(el, value); } function setStylesFromObject(el, value) { let previousStyles = {}; Object.entries(value).forEach(([key, value2]) => { previousStyles[key] = el.style[key]; el.style.setProperty(kebabCase(key), value2); }); setTimeout(() => { if (el.style.length === 0) { el.removeAttribute("style"); } }); return () => { setStyles(el, previousStyles); }; } function setStylesFromString(el, value) { let cache = el.getAttribute("style", value); el.setAttribute("style", value); return () => { el.setAttribute("style", cache); }; } function kebabCase(subject) { return subject.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(); } // packages/alpinejs/src/utils/once.js function once(callback, fallback = () => { }) { let called = false; return function() { if (!called) { called = true; callback.apply(this, arguments); } else { fallback.apply(this, arguments); } }; } // packages/alpinejs/src/directives/x-transition.js directive("transition", (el, {value, modifiers, expression}, {evaluate: evaluate2}) => { if (typeof expression === "function") expression = evaluate2(expression); if (!expression) { registerTransitionsFromHelper(el, modifiers, value); } else { registerTransitionsFromClassString(el, expression, value); } }); function registerTransitionsFromClassString(el, classString, stage) { registerTransitionObject(el, setClasses, ""); let directiveStorageMap = { enter: (classes) => { el._x_transition.enter.during = classes; }, "enter-start": (classes) => { el._x_transition.enter.start = classes; }, "enter-end": (classes) => { el._x_transition.enter.end = classes; }, leave: (classes) => { el._x_transition.leave.during = classes; }, "leave-start": (classes) => { el._x_transition.leave.start = classes; }, "leave-end": (classes) => { el._x_transition.leave.end = classes; } }; directiveStorageMap[stage](classString); } function registerTransitionsFromHelper(el, modifiers, stage) { registerTransitionObject(el, setStyles); let doesntSpecify = !modifiers.includes("in") && !modifiers.includes("out") && !stage; let transitioningIn = doesntSpecify || modifiers.includes("in") || ["enter"].includes(stage); let transitioningOut = doesntSpecify || modifiers.includes("out") || ["leave"].includes(stage); if (modifiers.includes("in") && !doesntSpecify) { modifiers = modifiers.filter((i, index) => index < modifiers.indexOf("out")); } if (modifiers.includes("out") && !doesntSpecify) { modifiers = modifiers.filter((i, index) => index > modifiers.indexOf("out")); } let wantsAll = !modifiers.includes("opacity") && !modifiers.includes("scale"); let wantsOpacity = wantsAll || modifiers.includes("opacity"); let wantsScale = wantsAll || modifiers.includes("scale"); let opacityValue = wantsOpacity ? 0 : 1; let scaleValue = wantsScale ? modifierValue(modifiers, "scale", 95) / 100 : 1; let delay = modifierValue(modifiers, "delay", 0); let origin = modifierValue(modifiers, "origin", "center"); let property = "opacity, transform"; let durationIn = modifierValue(modifiers, "duration", 150) / 1e3; let durationOut = modifierValue(modifiers, "duration", 75) / 1e3; let easing = `cubic-bezier(0.4, 0.0, 0.2, 1)`; if (transitioningIn) { el._x_transition.enter.during = { transformOrigin: origin, transitionDelay: delay, transitionProperty: property, transitionDuration: `${durationIn}s`, transitionTimingFunction: easing }; el._x_transition.enter.start = { opacity: opacityValue, transform: `scale(${scaleValue})` }; el._x_transition.enter.end = { opacity: 1, transform: `scale(1)` }; } if (transitioningOut) { el._x_transition.leave.during = { transformOrigin: origin, transitionDelay: delay, transitionProperty: property, transitionDuration: `${durationOut}s`, transitionTimingFunction: easing }; el._x_transition.leave.start = { opacity: 1, transform: `scale(1)` }; el._x_transition.leave.end = { opacity: opacityValue, transform: `scale(${scaleValue})` }; } } function registerTransitionObject(el, setFunction, defaultValue = {}) { if (!el._x_transition) el._x_transition = { enter: {during: defaultValue, start: defaultValue, end: defaultValue}, leave: {during: defaultValue, start: defaultValue, end: defaultValue}, in(before = () => { }, after = () => { }) { transition(el, setFunction, { during: this.enter.during, start: this.enter.start, end: this.enter.end, entering: true }, before, after); }, out(before = () => { }, after = () => { }) { transition(el, setFunction, { during: this.leave.during, start: this.leave.start, end: this.leave.end, entering: false }, before, after); } }; } window.Element.prototype._x_toggleAndCascadeWithTransitions = function(el, value, show, hide) { let clickAwayCompatibleShow = () => requestAnimationFrame(show); if (value) { el._x_transition ? el._x_transition.in(show) : clickAwayCompatibleShow(); return; } el._x_hidePromise = el._x_transition ? new Promise((resolve, reject) => { el._x_transition.out(() => { }, () => resolve(hide)); el._x_transitioning.beforeCancel(() => reject({isFromCancelledTransition: true})); }) : Promise.resolve(hide); queueMicrotask(() => { let closest = closestHide(el); if (closest) { if (!closest._x_hideChildren) closest._x_hideChildren = []; closest._x_hideChildren.push(el); } else { queueMicrotask(() => { let hideAfterChildren = (el2) => { let carry = Promise.all([ el2._x_hidePromise, ...(el2._x_hideChildren || []).map(hideAfterChildren) ]).then(([i]) => i()); delete el2._x_hidePromise; delete el2._x_hideChildren; return carry; }; hideAfterChildren(el).catch((e) => { if (!e.isFromCancelledTransition) throw e; }); }); } }); }; function closestHide(el) { let parent = el.parentNode; if (!parent) return; return parent._x_hidePromise ? parent : closestHide(parent); } function transition(el, setFunction, {during, start: start2, end, entering} = {}, before = () => { }, after = () => { }) { if (el._x_transitioning) el._x_transitioning.cancel(); if (Object.keys(during).length === 0 && Object.keys(start2).length === 0 && Object.keys(end).length === 0) { before(); after(); return; } let undoStart, undoDuring, undoEnd; performTransition(el, { start() { undoStart = setFunction(el, start2); }, during() { undoDuring = setFunction(el, during); }, before, end() { undoStart(); undoEnd = setFunction(el, end); }, after, cleanup() { undoDuring(); undoEnd(); } }, entering); } function performTransition(el, stages, entering) { let interrupted, reachedBefore, reachedEnd; let finish = once(() => { mutateDom(() => { interrupted = true; if (!reachedBefore) stages.before(); if (!reachedEnd) { stages.end(); releaseNextTicks(); } stages.after(); if (el.isConnected) stages.cleanup(); delete el._x_transitioning; }); }); el._x_transitioning = { beforeCancels: [], beforeCancel(callback) { this.beforeCancels.push(callback); }, cancel: once(function() { while (this.beforeCancels.length) { this.beforeCancels.shift()(); } ; finish(); }), finish, entering }; mutateDom(() => { stages.start(); stages.during(); }); holdNextTicks(); requestAnimationFrame(() => { if (interrupted) return; let duration = Number(getComputedStyle(el).transitionDuration.replace(/,.*/, "").replace("s", "")) * 1e3; let delay = Number(getComputedStyle(el).transitionDelay.replace(/,.*/, "").replace("s", "")) * 1e3; if (duration === 0) duration = Number(getComputedStyle(el).animationDuration.replace("s", "")) * 1e3; mutateDom(() => { stages.before(); }); reachedBefore = true; requestAnimationFrame(() => { if (interrupted) return; mutateDom(() => { stages.end(); }); releaseNextTicks(); setTimeout(el._x_transitioning.finish, duration + delay); reachedEnd = true; }); }); } function modifierValue(modifiers, key, fallback) { if (modifiers.indexOf(key) === -1) return fallback; const rawValue = modifiers[modifiers.indexOf(key) + 1]; if (!rawValue) return fallback; if (key === "scale") { if (isNaN(rawValue)) return fallback; } if (key === "duration") { let match = rawValue.match(/([0-9]+)ms/); if (match) return match[1]; } if (key === "origin") { if (["top", "right", "left", "center", "bottom"].includes(modifiers[modifiers.indexOf(key) + 2])) { return [rawValue, modifiers[modifiers.indexOf(key) + 2]].join(" "); } } return rawValue; } // packages/alpinejs/src/directives/x-ignore.js var handler = () => { }; handler.inline = (el, {modifiers}, {cleanup}) => { modifiers.includes("self") ? el._x_ignoreSelf = true : el._x_ignore = true; cleanup(() => { modifiers.includes("self") ? delete el._x_ignoreSelf : delete el._x_ignore; }); }; directive("ignore", handler); // packages/alpinejs/src/directives/x-effect.js directive("effect", (el, {expression}, {effect: effect3}) => effect3(evaluateLater(el, expression))); // packages/alpinejs/src/utils/bind.js function bind(el, name, value, modifiers = []) { if (!el._x_bindings) el._x_bindings = reactive({}); el._x_bindings[name] = value; name = modifiers.includes("camel") ? camelCase(name) : name; switch (name) { case "value": bindInputValue(el, value); break; case "style": bindStyles(el, value); break; case "class": bindClasses(el, value); break; default: bindAttribute(el, name, value); break; } } function bindInputValue(el, value) { if (el.type === "radio") { if (el.attributes.value === void 0) { el.value = value; } if (window.fromModel) { el.checked = checkedAttrLooseCompare(el.value, value); } } else if (el.type === "checkbox") { if (Number.isInteger(value)) { el.value = value; } else if (!Number.isInteger(value) && !Array.isArray(value) && typeof value !== "boolean" && ![null, void 0].includes(value)) { el.value = String(value); } else { if (Array.isArray(value)) { el.checked = value.some((val) => checkedAttrLooseCompare(val, el.value)); } else { el.checked = !!value; } } } else if (el.tagName === "SELECT") { updateSelect(el, value); } else { if (el.value === value) return; el.value = value; } } function bindClasses(el, value) { if (el._x_undoAddedClasses) el._x_undoAddedClasses(); el._x_undoAddedClasses = setClasses(el, value); } function bindStyles(el, value) { if (el._x_undoAddedStyles) el._x_undoAddedStyles(); el._x_undoAddedStyles = setStyles(el, value); } function bindAttribute(el, name, value) { if ([null, void 0, false].includes(value) && attributeShouldntBePreservedIfFalsy(name)) { el.removeAttribute(name); } else { if (isBooleanAttr(name)) value = name; setIfChanged(el, name, value); } } function setIfChanged(el, attrName, value) { if (el.getAttribute(attrName) != value) { el.setAttribute(attrName, value); } } function updateSelect(el, value) { const arrayWrappedValue = [].concat(value).map((value2) => { return value2 + ""; }); Array.from(el.options).forEach((option) => { option.selected = arrayWrappedValue.includes(option.value); }); } function camelCase(subject) { return subject.toLowerCase().replace(/-(\w)/g, (match, char) => char.toUpperCase()); } function checkedAttrLooseCompare(valueA, valueB) { return valueA == valueB; } function isBooleanAttr(attrName) { const booleanAttributes = [ "disabled", "checked", "required", "readonly", "hidden", "open", "selected", "autofocus", "itemscope", "multiple", "novalidate", "allowfullscreen", "allowpaymentrequest", "formnovalidate", "autoplay", "controls", "loop", "muted", "playsinline", "default", "ismap", "reversed", "async", "defer", "nomodule" ]; return booleanAttributes.includes(attrName); } function attributeShouldntBePreservedIfFalsy(name) { return !["aria-pressed", "aria-checked"].includes(name); } // packages/alpinejs/src/utils/on.js function on(el, event, modifiers, callback) { let listenerTarget = el; let handler3 = (e) => callback(e); let options = {}; let wrapHandler = (callback2, wrapper) => (e) => wrapper(callback2, e); if (modifiers.includes("dot")) event = dotSyntax(event); if (modifiers.includes("camel")) event = camelCase2(event); if (modifiers.includes("passive")) options.passive = true; if (modifiers.includes("window")) listenerTarget = window; if (modifiers.includes("document")) listenerTarget = document; if (modifiers.includes("prevent")) handler3 = wrapHandler(handler3, (next, e) => { e.preventDefault(); next(e); }); if (modifiers.includes("stop")) handler3 = wrapHandler(handler3, (next, e) => { e.stopPropagation(); next(e); }); if (modifiers.includes("self")) handler3 = wrapHandler(handler3, (next, e) => { e.target === el && next(e); }); if (modifiers.includes("away") || modifiers.includes("outside")) { listenerTarget = document; handler3 = wrapHandler(handler3, (next, e) => { if (el.contains(e.target)) return; if (el.offsetWidth < 1 && el.offsetHeight < 1) return; next(e); }); } handler3 = wrapHandler(handler3, (next, e) => { if (isKeyEvent(event)) { if (isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers)) { return; } } next(e); }); if (modifiers.includes("debounce")) { let nextModifier = modifiers[modifiers.indexOf("debounce") + 1] || "invalid-wait"; let wait = isNumeric(nextModifier.split("ms")[0]) ? Number(nextModifier.split("ms")[0]) : 250; handler3 = debounce(handler3, wait, this); } if (modifiers.includes("throttle")) { let nextModifier = modifiers[modifiers.indexOf("throttle") + 1] || "invalid-wait"; let wait = isNumeric(nextModifier.split("ms")[0]) ? Number(nextModifier.split("ms")[0]) : 250; handler3 = throttle(handler3, wait, this); } if (modifiers.includes("once")) { handler3 = wrapHandler(handler3, (next, e) => { next(e); listenerTarget.removeEventListener(event, handler3, options); }); } listenerTarget.addEventListener(event, handler3, options); return () => { listenerTarget.removeEventListener(event, handler3, options); }; } function dotSyntax(subject) { return subject.replace(/-/g, "."); } function camelCase2(subject) { return subject.toLowerCase().replace(/-(\w)/g, (match, char) => char.toUpperCase()); } function debounce(func, wait) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; func.apply(context, args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; } function throttle(func, limit) { let inThrottle; return function() { let context = this, args = arguments; if (!inThrottle) { func.apply(context, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } }; } function isNumeric(subject) { return !Array.isArray(subject) && !isNaN(subject); } function kebabCase2(subject) { return subject.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[_\s]/, "-").toLowerCase(); } function isKeyEvent(event) { return ["keydown", "keyup"].includes(event); } function isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers) { let keyModifiers = modifiers.filter((i) => { return !["window", "document", "prevent", "stop", "once"].includes(i); }); if (keyModifiers.includes("debounce")) { let debounceIndex = keyModifiers.indexOf("debounce"); keyModifiers.splice(debounceIndex, isNumeric((keyModifiers[debounceIndex + 1] || "invalid-wait").split("ms")[0]) ? 2 : 1); } if (keyModifiers.length === 0) return false; if (keyModifiers.length === 1 && keyToModifiers(e.key).includes(keyModifiers[0])) return false; const systemKeyModifiers = ["ctrl", "shift", "alt", "meta", "cmd", "super"]; const selectedSystemKeyModifiers = systemKeyModifiers.filter((modifier) => keyModifiers.includes(modifier)); keyModifiers = keyModifiers.filter((i) => !selectedSystemKeyModifiers.includes(i)); if (selectedSystemKeyModifiers.length > 0) { const activelyPressedKeyModifiers = selectedSystemKeyModifiers.filter((modifier) => { if (modifier === "cmd" || modifier === "super") modifier = "meta"; return e[`${modifier}Key`]; }); if (activelyPressedKeyModifiers.length === selectedSystemKeyModifiers.length) { if (keyToModifiers(e.key).includes(keyModifiers[0])) return false; } } return true; } function keyToModifiers(key) { if (!key) return []; key = kebabCase2(key); let modifierToKeyMap = { ctrl: "control", slash: "/", space: "-", spacebar: "-", cmd: "meta", esc: "escape", up: "arrow-up", down: "arrow-down", left: "arrow-left", right: "arrow-right", period: ".", equal: "=" }; modifierToKeyMap[key] = key; return Object.keys(modifierToKeyMap).map((modifier) => { if (modifierToKeyMap[modifier] === key) return modifier; }).filter((modifier) => modifier); } // packages/alpinejs/src/directives/x-model.js directive("model", (el, {modifiers, expression}, {effect: effect3, cleanup}) => { let evaluate2 = evaluateLater(el, expression); let assignmentExpression = `${expression} = rightSideOfExpression($event, ${expression})`; let evaluateAssignment = evaluateLater(el, assignmentExpression); var event = el.tagName.toLowerCase() === "select" || ["checkbox", "radio"].includes(el.type) || modifiers.includes("lazy") ? "change" : "input"; let assigmentFunction = generateAssignmentFunction(el, modifiers, expression); let removeListener = on(el, event, modifiers, (e) => { evaluateAssignment(() => { }, {scope: { $event: e, rightSideOfExpression: assigmentFunction }}); }); cleanup(() => removeListener()); el._x_forceModelUpdate = () => { evaluate2((value) => { if (value === void 0 && expression.match(/\./)) value = ""; window.fromModel = true; mutateDom(() => bind(el, "value", value)); delete window.fromModel; }); }; effect3(() => { if (modifiers.includes("unintrusive") && document.activeElement.isSameNode(el)) return; el._x_forceModelUpdate(); }); }); function generateAssignmentFunction(el, modifiers, expression) { if (el.type === "radio") { mutateDom(() => { if (!el.hasAttribute("name")) el.setAttribute("name", expression); }); } return (event, currentValue) => { return mutateDom(() => { if (event instanceof CustomEvent && event.detail !== void 0) { return event.detail || event.target.value; } else if (el.type === "checkbox") { if (Array.isArray(currentValue)) { let newValue = modifiers.includes("number") ? safeParseNumber(event.target.value) : event.target.value; return event.target.checked ? currentValue.concat([newValue]) : currentValue.filter((el2) => !checkedAttrLooseCompare2(el2, newValue)); } else { return event.target.checked; } } else if (el.tagName.toLowerCase() === "select" && el.multiple) { return modifiers.includes("number") ? Array.from(event.target.selectedOptions).map((option) => { let rawValue = option.value || option.text; return safeParseNumber(rawValue); }) : Array.from(event.target.selectedOptions).map((option) => { return option.value || option.text; }); } else { let rawValue = event.target.value; return modifiers.includes("number") ? safeParseNumber(rawValue) : modifiers.includes("trim") ? rawValue.trim() : rawValue; } }); }; } function safeParseNumber(rawValue) { let number = rawValue ? parseFloat(rawValue) : null; return isNumeric2(number) ? number : rawValue; } function checkedAttrLooseCompare2(valueA, valueB) { return valueA == valueB; } function isNumeric2(subject) { return !Array.isArray(subject) && !isNaN(subject); } // packages/alpinejs/src/directives/x-cloak.js directive("cloak", (el) => queueMicrotask(() => mutateDom(() => el.removeAttribute(prefix("cloak"))))); // packages/alpinejs/src/directives/x-init.js addInitSelector(() => `[${prefix("init")}]`); directive("init", skipDuringClone((el, {expression}) => !!expression.trim() && evaluate(el, expression, {}, false))); // packages/alpinejs/src/directives/x-text.js directive("text", (el, {expression}, {effect: effect3, evaluateLater: evaluateLater2}) => { let evaluate2 = evaluateLater2(expression); effect3(() => { evaluate2((value) => { mutateDom(() => { el.textContent = value; }); }); }); }); // packages/alpinejs/src/directives/x-html.js directive("html", (el, {expression}, {effect: effect3, evaluateLater: evaluateLater2}) => { let evaluate2 = evaluateLater2(expression); effect3(() => { evaluate2((value) => { el.innerHTML = value; }); }); }); // packages/alpinejs/src/directives/x-bind.js mapAttributes(startingWith(":", into(prefix("bind:")))); directive("bind", (el, {value, modifiers, expression, original}, {effect: effect3}) => { if (!value) return applyBindingsObject(el, expression, original, effect3); if (value === "key") return storeKeyForXFor(el, expression); let evaluate2 = evaluateLater(el, expression); effect3(() => evaluate2((result) => { if (result === void 0 && expression.match(/\./)) result = ""; mutateDom(() => bind(el, value, result, modifiers)); })); }); function applyBindingsObject(el, expression, original, effect3) { let getBindings = evaluateLater(el, expression); let cleanupRunners = []; effect3(() => { while (cleanupRunners.length) cleanupRunners.pop()(); getBindings((bindings) => { let attributes = Object.entries(bindings).map(([name, value]) => ({name, value})); directives(el, attributes, original).map((handle) => { cleanupRunners.push(handle.runCleanups); handle(); }); }); }); } function storeKeyForXFor(el, expression) { el._x_keyExpression = expression; } // packages/alpinejs/src/directives/x-data.js addRootSelector(() => `[${prefix("data")}]`); directive("data", skipDuringClone((el, {expression}, {cleanup}) => { expression = expression === "" ? "{}" : expression; let magicContext = {}; injectMagics(magicContext, el); let dataProviderContext = {}; injectDataProviders(dataProviderContext, magicContext); let data2 = evaluate(el, expression, {scope: dataProviderContext}); injectMagics(data2, el); let reactiveData = reactive(data2); initInterceptors(reactiveData); let undo = addScopeToNode(el, reactiveData); reactiveData["init"] && evaluate(el, reactiveData["init"]); cleanup(() => { undo(); reactiveData["destroy"] && evaluate(el, reactiveData["destroy"]); }); })); // packages/alpinejs/src/directives/x-show.js directive("show", (el, {modifiers, expression}, {effect: effect3}) => { let evaluate2 = evaluateLater(el, expression); let hide = () => mutateDom(() => { el.style.display = "none"; el._x_isShown = false; }); let show = () => mutateDom(() => { if (el.style.length === 1 && el.style.display === "none") { el.removeAttribute("style"); } else { el.style.removeProperty("display"); } el._x_isShown = true; }); let clickAwayCompatibleShow = () => setTimeout(show); let toggle = once((value) => value ? show() : hide(), (value) => { if (typeof el._x_toggleAndCascadeWithTransitions === "function") { el._x_toggleAndCascadeWithTransitions(el, value, show, hide); } else { value ? clickAwayCompatibleShow() : hide(); } }); let oldValue; let firstTime = true; effect3(() => evaluate2((value) => { if (!firstTime && value === oldValue) return; if (modifiers.includes("immediate")) value ? clickAwayCompatibleShow() : hide(); toggle(value); oldValue = value; firstTime = false; })); }); // packages/alpinejs/src/directives/x-for.js directive("for", (el, {expression}, {effect: effect3, cleanup}) => { let iteratorNames = parseForExpression(expression); let evaluateItems = evaluateLater(el, iteratorNames.items); let evaluateKey = evaluateLater(el, el._x_keyExpression || "index"); el._x_prevKeys = []; el._x_lookup = {}; effect3(() => loop(el, iteratorNames, evaluateItems, evaluateKey)); cleanup(() => { Object.values(el._x_lookup).forEach((el2) => el2.remove()); delete el._x_prevKeys; delete el._x_lookup; }); }); function loop(el, iteratorNames, evaluateItems, evaluateKey) { let isObject = (i) => typeof i === "object" && !Array.isArray(i); let templateEl = el; evaluateItems((items) => { if (isNumeric3(items) && items >= 0) { items = Array.from(Array(items).keys(), (i) => i + 1); } if (items === void 0) items = []; let lookup = el._x_lookup; let prevKeys = el._x_prevKeys; let scopes = []; let keys = []; if (isObject(items)) { items = Object.entries(items).map(([key, value]) => { let scope = getIterationScopeVariables(iteratorNames, value, key, items); evaluateKey((value2) => keys.push(value2), {scope: {index: key, ...scope}}); scopes.push(scope); }); } else { for (let i = 0; i < items.length; i++) { let scope = getIterationScopeVariables(iteratorNames, items[i], i, items); evaluateKey((value) => keys.push(value), {scope: {index: i, ...scope}}); scopes.push(scope); } } let adds = []; let moves = []; let removes = []; let sames = []; for (let i = 0; i < prevKeys.length; i++) { let key = prevKeys[i]; if (keys.indexOf(key) === -1) removes.push(key); } prevKeys = prevKeys.filter((key) => !removes.includes(key)); let lastKey = "template"; for (let i = 0; i < keys.length; i++) { let key = keys[i]; let prevIndex = prevKeys.indexOf(key); if (prevIndex === -1) { prevKeys.splice(i, 0, key); adds.push([lastKey, i]); } else if (prevIndex !== i) { let keyInSpot = prevKeys.splice(i, 1)[0]; let keyForSpot = prevKeys.splice(prevIndex - 1, 1)[0]; prevKeys.splice(i, 0, keyForSpot); prevKeys.splice(prevIndex, 0, keyInSpot); moves.push([keyInSpot, keyForSpot]); } else { sames.push(key); } lastKey = key; } for (let i = 0; i < removes.length; i++) { let key = removes[i]; lookup[key].remove(); lookup[key] = null; delete lookup[key]; } for (let i = 0; i < moves.length; i++) { let [keyInSpot, keyForSpot] = moves[i]; let elInSpot = lookup[keyInSpot]; let elForSpot = lookup[keyForSpot]; let marker = document.createElement("div"); mutateDom(() => { elForSpot.after(marker); elInSpot.after(elForSpot); marker.before(elInSpot); marker.remove(); }); refreshScope(elForSpot, scopes[keys.indexOf(keyForSpot)]); } for (let i = 0; i < adds.length; i++) { let [lastKey2, index] = adds[i]; let lastEl = lastKey2 === "template" ? templateEl : lookup[lastKey2]; let scope = scopes[index]; let key = keys[index]; let clone2 = document.importNode(templateEl.content, true).firstElementChild; addScopeToNode(clone2, reactive(scope), templateEl); mutateDom(() => { lastEl.after(clone2); initTree(clone2); }); if (typeof key === "object") { warn("x-for key cannot be an object, it must be a string or an integer", templateEl); } lookup[key] = clone2; } for (let i = 0; i < sames.length; i++) { refreshScope(lookup[sames[i]], scopes[keys.indexOf(sames[i])]); } templateEl._x_prevKeys = keys; }); } function parseForExpression(expression) { let forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/; let stripParensRE = /^\s*\(|\)\s*$/g; let forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/; let inMatch = expression.match(forAliasRE); if (!inMatch) return; let res = {}; res.items = inMatch[2].trim(); let item = inMatch[1].replace(stripParensRE, "").trim(); let iteratorMatch = item.match(forIteratorRE); if (iteratorMatch) { res.item = item.replace(forIteratorRE, "").trim(); res.index = iteratorMatch[1].trim(); if (iteratorMatch[2]) { res.collection = iteratorMatch[2].trim(); } } else { res.item = item; } return res; } function getIterationScopeVariables(iteratorNames, item, index, items) { let scopeVariables = {}; if (/^\[.*\]$/.test(iteratorNames.item) && Array.isArray(item)) { let names = iteratorNames.item.replace("[", "").replace("]", "").split(",").map((i) => i.trim()); names.forEach((name, i) => { scopeVariables[name] = item[i]; }); } else if (/^\{.*\}$/.test(iteratorNames.item) && !Array.isArray(item) && typeof item === "object") { let names = iteratorNames.item.replace("{", "").replace("}", "").split(",").map((i) => i.trim()); names.forEach((name) => { scopeVariables[name] = item[name]; }); } else { scopeVariables[iteratorNames.item] = item; } if (iteratorNames.index) scopeVariables[iteratorNames.index] = index; if (iteratorNames.collection) scopeVariables[iteratorNames.collection] = items; return scopeVariables; } function isNumeric3(subject) { return !Array.isArray(subject) && !isNaN(subject); } // packages/alpinejs/src/directives/x-ref.js function handler2() { } handler2.inline = (el, {expression}, {cleanup}) => { let root = closestRoot(el); if (!root._x_refs) root._x_refs = {}; root._x_refs[expression] = el; cleanup(() => delete root._x_refs[expression]); }; directive("ref", handler2); // packages/alpinejs/src/directives/x-if.js directive("if", (el, {expression}, {effect: effect3, cleanup}) => { let evaluate2 = evaluateLater(el, expression); let show = () => { if (el._x_currentIfEl) return el._x_currentIfEl; let clone2 = el.content.cloneNode(true).firstElementChild; addScopeToNode(clone2, {}, el); mutateDom(() => { el.after(clone2); initTree(clone2); }); el._x_currentIfEl = clone2; el._x_undoIf = () => { clone2.remove(); delete el._x_currentIfEl; }; return clone2; }; let hide = () => { if (!el._x_undoIf) return; el._x_undoIf(); delete el._x_undoIf; }; effect3(() => evaluate2((value) => { value ? show() : hide(); })); cleanup(() => el._x_undoIf && el._x_undoIf()); }); // packages/alpinejs/src/directives/x-on.js mapAttributes(startingWith("@", into(prefix("on:")))); directive("on", skipDuringClone((el, {value, modifiers, expression}, {cleanup}) => { let evaluate2 = expression ? evaluateLater(el, expression) : () => { }; let removeListener = on(el, value, modifiers, (e) => { evaluate2(() => { }, {scope: {$event: e}, params: [e]}); }); cleanup(() => removeListener()); })); // packages/alpinejs/src/index.js alpine_default.setEvaluator(normalEvaluator); alpine_default.setReactivityEngine({reactive: import_reactivity9.reactive, effect: import_reactivity9.effect, release: import_reactivity9.stop, raw: import_reactivity9.toRaw}); var src_default = alpine_default; // packages/alpinejs/builds/module.js var module_default = src_default; /***/ }), /***/ "./node_modules/axios/index.js": /*!*************************************!*\ !*** ./node_modules/axios/index.js ***! \*************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = __webpack_require__(/*! ./lib/axios */ "./node_modules/axios/lib/axios.js"); /***/ }), /***/ "./node_modules/axios/lib/adapters/xhr.js": /*!************************************************!*\ !*** ./node_modules/axios/lib/adapters/xhr.js ***! \************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var settle = __webpack_require__(/*! ./../core/settle */ "./node_modules/axios/lib/core/settle.js"); var cookies = __webpack_require__(/*! ./../helpers/cookies */ "./node_modules/axios/lib/helpers/cookies.js"); var buildURL = __webpack_require__(/*! ./../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js"); var buildFullPath = __webpack_require__(/*! ../core/buildFullPath */ "./node_modules/axios/lib/core/buildFullPath.js"); var parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ "./node_modules/axios/lib/helpers/parseHeaders.js"); var isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ "./node_modules/axios/lib/helpers/isURLSameOrigin.js"); var createError = __webpack_require__(/*! ../core/createError */ "./node_modules/axios/lib/core/createError.js"); module.exports = function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { var requestData = config.data; var requestHeaders = config.headers; var responseType = config.responseType; if (utils.isFormData(requestData)) { delete requestHeaders['Content-Type']; // Let the browser set it } var request = new XMLHttpRequest(); // HTTP basic authentication if (config.auth) { var username = config.auth.username || ''; var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); } var fullPath = buildFullPath(config.baseURL, config.url); request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); // Set the request timeout in MS request.timeout = config.timeout; function onloadend() { if (!request) { return; } // Prepare the response var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; var responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response; var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // Clean up request request = null; } if ('onloadend' in request) { // Use onloadend if available request.onloadend = onloadend; } else { // Listen for ready state to emulate onloadend request.onreadystatechange = function handleLoad() { if (!request || request.readyState !== 4) { return; } // The request errored out and we didn't get a response, this will be // handled by onerror instead // With one exception: request that using file: protocol, most browsers // will return status as 0 even though it's a successful request if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { return; } // readystate handler is calling before onerror or ontimeout handlers, // so we should call onloadend on the next 'tick' setTimeout(onloadend); }; } // Handle browser request cancellation (as opposed to a manual cancellation) request.onabort = function handleAbort() { if (!request) { return; } reject(createError('Request aborted', config, 'ECONNABORTED', request)); // Clean up request request = null; }; // Handle low level network errors request.onerror = function handleError() { // Real errors are hidden from us by the browser // onerror should only fire if it's a network error reject(createError('Network Error', config, null, request)); // Clean up request request = null; }; // Handle timeout request.ontimeout = function handleTimeout() { var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; if (config.timeoutErrorMessage) { timeoutErrorMessage = config.timeoutErrorMessage; } reject(createError( timeoutErrorMessage, config, config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', request)); // Clean up request request = null; }; // Add xsrf header // This is only done if running in a standard browser environment. // Specifically not if we're in a web worker, or react-native. if (utils.isStandardBrowserEnv()) { // Add xsrf header var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName] = xsrfValue; } } // Add headers to the request if ('setRequestHeader' in request) { utils.forEach(requestHeaders, function setRequestHeader(val, key) { if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { // Remove Content-Type if data is undefined delete requestHeaders[key]; } else { // Otherwise add header to the request request.setRequestHeader(key, val); } }); } // Add withCredentials to request if needed if (!utils.isUndefined(config.withCredentials)) { request.withCredentials = !!config.withCredentials; } // Add responseType to request if needed if (responseType && responseType !== 'json') { request.responseType = config.responseType; } // Handle progress if needed if (typeof config.onDownloadProgress === 'function') { request.addEventListener('progress', config.onDownloadProgress); } // Not all browsers support upload events if (typeof config.onUploadProgress === 'function' && request.upload) { request.upload.addEventListener('progress', config.onUploadProgress); } if (config.cancelToken) { // Handle cancellation config.cancelToken.promise.then(function onCanceled(cancel) { if (!request) { return; } request.abort(); reject(cancel); // Clean up request request = null; }); } if (!requestData) { requestData = null; } // Send the request request.send(requestData); }); }; /***/ }), /***/ "./node_modules/axios/lib/axios.js": /*!*****************************************!*\ !*** ./node_modules/axios/lib/axios.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js"); var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js"); var Axios = __webpack_require__(/*! ./core/Axios */ "./node_modules/axios/lib/core/Axios.js"); var mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js"); var defaults = __webpack_require__(/*! ./defaults */ "./node_modules/axios/lib/defaults.js"); /** * Create an instance of Axios * * @param {Object} defaultConfig The default config for the instance * @return {Axios} A new instance of Axios */ function createInstance(defaultConfig) { var context = new Axios(defaultConfig); var instance = bind(Axios.prototype.request, context); // Copy axios.prototype to instance utils.extend(instance, Axios.prototype, context); // Copy context to instance utils.extend(instance, context); return instance; } // Create the default instance to be exported var axios = createInstance(defaults); // Expose Axios class to allow class inheritance axios.Axios = Axios; // Factory for creating new instances axios.create = function create(instanceConfig) { return createInstance(mergeConfig(axios.defaults, instanceConfig)); }; // Expose Cancel & CancelToken axios.Cancel = __webpack_require__(/*! ./cancel/Cancel */ "./node_modules/axios/lib/cancel/Cancel.js"); axios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ "./node_modules/axios/lib/cancel/CancelToken.js"); axios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js"); // Expose all/spread axios.all = function all(promises) { return Promise.all(promises); }; axios.spread = __webpack_require__(/*! ./helpers/spread */ "./node_modules/axios/lib/helpers/spread.js"); // Expose isAxiosError axios.isAxiosError = __webpack_require__(/*! ./helpers/isAxiosError */ "./node_modules/axios/lib/helpers/isAxiosError.js"); module.exports = axios; // Allow use of default import syntax in TypeScript module.exports["default"] = axios; /***/ }), /***/ "./node_modules/axios/lib/cancel/Cancel.js": /*!*************************************************!*\ !*** ./node_modules/axios/lib/cancel/Cancel.js ***! \*************************************************/ /***/ ((module) => { "use strict"; /** * A `Cancel` is an object that is thrown when an operation is canceled. * * @class * @param {string=} message The message. */ function Cancel(message) { this.message = message; } Cancel.prototype.toString = function toString() { return 'Cancel' + (this.message ? ': ' + this.message : ''); }; Cancel.prototype.__CANCEL__ = true; module.exports = Cancel; /***/ }), /***/ "./node_modules/axios/lib/cancel/CancelToken.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/cancel/CancelToken.js ***! \******************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Cancel = __webpack_require__(/*! ./Cancel */ "./node_modules/axios/lib/cancel/Cancel.js"); /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * * @class * @param {Function} executor The executor function. */ function CancelToken(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); } var resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); var token = this; executor(function cancel(message) { if (token.reason) { // Cancellation has already been requested return; } token.reason = new Cancel(message); resolvePromise(token.reason); }); } /** * Throws a `Cancel` if cancellation has been requested. */ CancelToken.prototype.throwIfRequested = function throwIfRequested() { if (this.reason) { throw this.reason; } }; /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. */ CancelToken.source = function source() { var cancel; var token = new CancelToken(function executor(c) { cancel = c; }); return { token: token, cancel: cancel }; }; module.exports = CancelToken; /***/ }), /***/ "./node_modules/axios/lib/cancel/isCancel.js": /*!***************************************************!*\ !*** ./node_modules/axios/lib/cancel/isCancel.js ***! \***************************************************/ /***/ ((module) => { "use strict"; module.exports = function isCancel(value) { return !!(value && value.__CANCEL__); }; /***/ }), /***/ "./node_modules/axios/lib/core/Axios.js": /*!**********************************************!*\ !*** ./node_modules/axios/lib/core/Axios.js ***! \**********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var buildURL = __webpack_require__(/*! ../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js"); var InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ "./node_modules/axios/lib/core/InterceptorManager.js"); var dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ "./node_modules/axios/lib/core/dispatchRequest.js"); var mergeConfig = __webpack_require__(/*! ./mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js"); var validator = __webpack_require__(/*! ../helpers/validator */ "./node_modules/axios/lib/helpers/validator.js"); var validators = validator.validators; /** * Create a new instance of Axios * * @param {Object} instanceConfig The default config for the instance */ function Axios(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; } /** * Dispatch a request * * @param {Object} config The config specific for this request (merged with this.defaults) */ Axios.prototype.request = function request(config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof config === 'string') { config = arguments[1] || {}; config.url = arguments[0]; } else { config = config || {}; } config = mergeConfig(this.defaults, config); // Set config.method if (config.method) { config.method = config.method.toLowerCase(); } else if (this.defaults.method) { config.method = this.defaults.method.toLowerCase(); } else { config.method = 'get'; } var transitional = config.transitional; if (transitional !== undefined) { validator.assertOptions(transitional, { silentJSONParsing: validators.transitional(validators.boolean, '1.0.0'), forcedJSONParsing: validators.transitional(validators.boolean, '1.0.0'), clarifyTimeoutError: validators.transitional(validators.boolean, '1.0.0') }, false); } // filter out skipped interceptors var requestInterceptorChain = []; var synchronousRequestInterceptors = true; this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { return; } synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); }); var responseInterceptorChain = []; this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); }); var promise; if (!synchronousRequestInterceptors) { var chain = [dispatchRequest, undefined]; Array.prototype.unshift.apply(chain, requestInterceptorChain); chain = chain.concat(responseInterceptorChain); promise = Promise.resolve(config); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; } var newConfig = config; while (requestInterceptorChain.length) { var onFulfilled = requestInterceptorChain.shift(); var onRejected = requestInterceptorChain.shift(); try { newConfig = onFulfilled(newConfig); } catch (error) { onRejected(error); break; } } try { promise = dispatchRequest(newConfig); } catch (error) { return Promise.reject(error); } while (responseInterceptorChain.length) { promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); } return promise; }; Axios.prototype.getUri = function getUri(config) { config = mergeConfig(this.defaults, config); return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); }; // Provide aliases for supported request methods utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { return this.request(mergeConfig(config || {}, { method: method, url: url, data: (config || {}).data })); }; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, data, config) { return this.request(mergeConfig(config || {}, { method: method, url: url, data: data })); }; }); module.exports = Axios; /***/ }), /***/ "./node_modules/axios/lib/core/InterceptorManager.js": /*!***********************************************************!*\ !*** ./node_modules/axios/lib/core/InterceptorManager.js ***! \***********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); function InterceptorManager() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ InterceptorManager.prototype.use = function use(fulfilled, rejected, options) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected, synchronous: options ? options.synchronous : false, runWhen: options ? options.runWhen : null }); return this.handlers.length - 1; }; /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` */ InterceptorManager.prototype.eject = function eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } }; /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `eject`. * * @param {Function} fn The function to call for each interceptor */ InterceptorManager.prototype.forEach = function forEach(fn) { utils.forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } }); }; module.exports = InterceptorManager; /***/ }), /***/ "./node_modules/axios/lib/core/buildFullPath.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/core/buildFullPath.js ***! \******************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isAbsoluteURL = __webpack_require__(/*! ../helpers/isAbsoluteURL */ "./node_modules/axios/lib/helpers/isAbsoluteURL.js"); var combineURLs = __webpack_require__(/*! ../helpers/combineURLs */ "./node_modules/axios/lib/helpers/combineURLs.js"); /** * Creates a new URL by combining the baseURL with the requestedURL, * only when the requestedURL is not already an absolute URL. * If the requestURL is absolute, this function returns the requestedURL untouched. * * @param {string} baseURL The base URL * @param {string} requestedURL Absolute or relative URL to combine * @returns {string} The combined full path */ module.exports = function buildFullPath(baseURL, requestedURL) { if (baseURL && !isAbsoluteURL(requestedURL)) { return combineURLs(baseURL, requestedURL); } return requestedURL; }; /***/ }), /***/ "./node_modules/axios/lib/core/createError.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/core/createError.js ***! \****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var enhanceError = __webpack_require__(/*! ./enhanceError */ "./node_modules/axios/lib/core/enhanceError.js"); /** * Create an Error with the specified message, config, error code, request and response. * * @param {string} message The error message. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The created error. */ module.exports = function createError(message, config, code, request, response) { var error = new Error(message); return enhanceError(error, config, code, request, response); }; /***/ }), /***/ "./node_modules/axios/lib/core/dispatchRequest.js": /*!********************************************************!*\ !*** ./node_modules/axios/lib/core/dispatchRequest.js ***! \********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var transformData = __webpack_require__(/*! ./transformData */ "./node_modules/axios/lib/core/transformData.js"); var isCancel = __webpack_require__(/*! ../cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js"); var defaults = __webpack_require__(/*! ../defaults */ "./node_modules/axios/lib/defaults.js"); /** * Throws a `Cancel` if cancellation has been requested. */ function throwIfCancellationRequested(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } } /** * Dispatch a request to the server using the configured adapter. * * @param {object} config The config that is to be used for the request * @returns {Promise} The Promise to be fulfilled */ module.exports = function dispatchRequest(config) { throwIfCancellationRequested(config); // Ensure headers exist config.headers = config.headers || {}; // Transform request data config.data = transformData.call( config, config.data, config.headers, config.transformRequest ); // Flatten headers config.headers = utils.merge( config.headers.common || {}, config.headers[config.method] || {}, config.headers ); utils.forEach( ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { delete config.headers[method]; } ); var adapter = config.adapter || defaults.adapter; return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); // Transform response data response.data = transformData.call( config, response.data, response.headers, config.transformResponse ); return response; }, function onAdapterRejection(reason) { if (!isCancel(reason)) { throwIfCancellationRequested(config); // Transform response data if (reason && reason.response) { reason.response.data = transformData.call( config, reason.response.data, reason.response.headers, config.transformResponse ); } } return Promise.reject(reason); }); }; /***/ }), /***/ "./node_modules/axios/lib/core/enhanceError.js": /*!*****************************************************!*\ !*** ./node_modules/axios/lib/core/enhanceError.js ***! \*****************************************************/ /***/ ((module) => { "use strict"; /** * Update an Error with the specified config, error code, and response. * * @param {Error} error The error to update. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The error. */ module.exports = function enhanceError(error, config, code, request, response) { error.config = config; if (code) { error.code = code; } error.request = request; error.response = response; error.isAxiosError = true; error.toJSON = function toJSON() { return { // Standard message: this.message, name: this.name, // Microsoft description: this.description, number: this.number, // Mozilla fileName: this.fileName, lineNumber: this.lineNumber, columnNumber: this.columnNumber, stack: this.stack, // Axios config: this.config, code: this.code }; }; return error; }; /***/ }), /***/ "./node_modules/axios/lib/core/mergeConfig.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/core/mergeConfig.js ***! \****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js"); /** * Config-specific merge-function which creates a new config-object * by merging two configuration objects together. * * @param {Object} config1 * @param {Object} config2 * @returns {Object} New object resulting from merging config2 to config1 */ module.exports = function mergeConfig(config1, config2) { // eslint-disable-next-line no-param-reassign config2 = config2 || {}; var config = {}; var valueFromConfig2Keys = ['url', 'method', 'data']; var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; var defaultToConfig2Keys = [ 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' ]; var directMergeKeys = ['validateStatus']; function getMergedValue(target, source) { if (utils.isPlainObject(target) && utils.isPlainObject(source)) { return utils.merge(target, source); } else if (utils.isPlainObject(source)) { return utils.merge({}, source); } else if (utils.isArray(source)) { return source.slice(); } return source; } function mergeDeepProperties(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(config1[prop], config2[prop]); } else if (!utils.isUndefined(config1[prop])) { config[prop] = getMergedValue(undefined, config1[prop]); } } utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(undefined, config2[prop]); } }); utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(undefined, config2[prop]); } else if (!utils.isUndefined(config1[prop])) { config[prop] = getMergedValue(undefined, config1[prop]); } }); utils.forEach(directMergeKeys, function merge(prop) { if (prop in config2) { config[prop] = getMergedValue(config1[prop], config2[prop]); } else if (prop in config1) { config[prop] = getMergedValue(undefined, config1[prop]); } }); var axiosKeys = valueFromConfig2Keys .concat(mergeDeepPropertiesKeys) .concat(defaultToConfig2Keys) .concat(directMergeKeys); var otherKeys = Object .keys(config1) .concat(Object.keys(config2)) .filter(function filterAxiosKeys(key) { return axiosKeys.indexOf(key) === -1; }); utils.forEach(otherKeys, mergeDeepProperties); return config; }; /***/ }), /***/ "./node_modules/axios/lib/core/settle.js": /*!***********************************************!*\ !*** ./node_modules/axios/lib/core/settle.js ***! \***********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var createError = __webpack_require__(/*! ./createError */ "./node_modules/axios/lib/core/createError.js"); /** * Resolve or reject a Promise based on response status. * * @param {Function} resolve A function that resolves the promise. * @param {Function} reject A function that rejects the promise. * @param {object} response The response. */ module.exports = function settle(resolve, reject, response) { var validateStatus = response.config.validateStatus; if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { reject(createError( 'Request failed with status code ' + response.status, response.config, null, response.request, response )); } }; /***/ }), /***/ "./node_modules/axios/lib/core/transformData.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/core/transformData.js ***! \******************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var defaults = __webpack_require__(/*! ./../defaults */ "./node_modules/axios/lib/defaults.js"); /** * Transform the data for a request or a response * * @param {Object|String} data The data to be transformed * @param {Array} headers The headers for the request or response * @param {Array|Function} fns A single function or Array of functions * @returns {*} The resulting transformed data */ module.exports = function transformData(data, headers, fns) { var context = this || defaults; /*eslint no-param-reassign:0*/ utils.forEach(fns, function transform(fn) { data = fn.call(context, data, headers); }); return data; }; /***/ }), /***/ "./node_modules/axios/lib/defaults.js": /*!********************************************!*\ !*** ./node_modules/axios/lib/defaults.js ***! \********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var process = __webpack_require__(/*! process/browser */ "./node_modules/process/browser.js"); var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js"); var normalizeHeaderName = __webpack_require__(/*! ./helpers/normalizeHeaderName */ "./node_modules/axios/lib/helpers/normalizeHeaderName.js"); var enhanceError = __webpack_require__(/*! ./core/enhanceError */ "./node_modules/axios/lib/core/enhanceError.js"); var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } function getDefaultAdapter() { var adapter; if (typeof XMLHttpRequest !== 'undefined') { // For browsers use XHR adapter adapter = __webpack_require__(/*! ./adapters/xhr */ "./node_modules/axios/lib/adapters/xhr.js"); } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { // For node use HTTP adapter adapter = __webpack_require__(/*! ./adapters/http */ "./node_modules/axios/lib/adapters/xhr.js"); } return adapter; } var defaults = { transitional: { silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false }, adapter: getDefaultAdapter(), transformRequest: [function transformRequest(data, headers) { normalizeHeaderName(headers, 'Accept'); normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) { setContentTypeIfUnset(headers, 'application/json'); return JSON.stringify(data); } return data; }], transformResponse: [function transformResponse(data) { var transitional = this.transitional; var silentJSONParsing = transitional && transitional.silentJSONParsing; var forcedJSONParsing = transitional && transitional.forcedJSONParsing; var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { try { return JSON.parse(data); } catch (e) { if (strictJSONParsing) { if (e.name === 'SyntaxError') { throw enhanceError(e, this, 'E_JSON_PARSE'); } throw e; } } } return data; }], /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, maxBodyLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; } }; defaults.headers = { common: { 'Accept': 'application/json, text/plain, */*' } }; utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { defaults.headers[method] = {}; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); }); module.exports = defaults; /***/ }), /***/ "./node_modules/axios/lib/helpers/bind.js": /*!************************************************!*\ !*** ./node_modules/axios/lib/helpers/bind.js ***! \************************************************/ /***/ ((module) => { "use strict"; module.exports = function bind(fn, thisArg) { return function wrap() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/buildURL.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/helpers/buildURL.js ***! \****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); function encode(val) { return encodeURIComponent(val). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, '+'). replace(/%5B/gi, '['). replace(/%5D/gi, ']'); } /** * Build a URL by appending params to the end * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended * @returns {string} The formatted url */ module.exports = function buildURL(url, params, paramsSerializer) { /*eslint no-param-reassign:0*/ if (!params) { return url; } var serializedParams; if (paramsSerializer) { serializedParams = paramsSerializer(params); } else if (utils.isURLSearchParams(params)) { serializedParams = params.toString(); } else { var parts = []; utils.forEach(params, function serialize(val, key) { if (val === null || typeof val === 'undefined') { return; } if (utils.isArray(val)) { key = key + '[]'; } else { val = [val]; } utils.forEach(val, function parseValue(v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); } parts.push(encode(key) + '=' + encode(v)); }); }); serializedParams = parts.join('&'); } if (serializedParams) { var hashmarkIndex = url.indexOf('#'); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } return url; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/combineURLs.js": /*!*******************************************************!*\ !*** ./node_modules/axios/lib/helpers/combineURLs.js ***! \*******************************************************/ /***/ ((module) => { "use strict"; /** * Creates a new URL by combining the specified URLs * * @param {string} baseURL The base URL * @param {string} relativeURL The relative URL * @returns {string} The combined URL */ module.exports = function combineURLs(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/cookies.js": /*!***************************************************!*\ !*** ./node_modules/axios/lib/helpers/cookies.js ***! \***************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs support document.cookie (function standardBrowserEnv() { return { write: function write(name, value, expires, path, domain, secure) { var cookie = []; cookie.push(name + '=' + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push('expires=' + new Date(expires).toGMTString()); } if (utils.isString(path)) { cookie.push('path=' + path); } if (utils.isString(domain)) { cookie.push('domain=' + domain); } if (secure === true) { cookie.push('secure'); } document.cookie = cookie.join('; '); }, read: function read(name) { var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); return (match ? decodeURIComponent(match[3]) : null); }, remove: function remove(name) { this.write(name, '', Date.now() - 86400000); } }; })() : // Non standard browser env (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return { write: function write() {}, read: function read() { return null; }, remove: function remove() {} }; })() ); /***/ }), /***/ "./node_modules/axios/lib/helpers/isAbsoluteURL.js": /*!*********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isAbsoluteURL.js ***! \*********************************************************/ /***/ ((module) => { "use strict"; /** * Determines whether the specified URL is absolute * * @param {string} url The URL to test * @returns {boolean} True if the specified URL is absolute, otherwise false */ module.exports = function isAbsoluteURL(url) { // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL). // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed // by any combination of letters, digits, plus, period, or hyphen. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); }; /***/ }), /***/ "./node_modules/axios/lib/helpers/isAxiosError.js": /*!********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isAxiosError.js ***! \********************************************************/ /***/ ((module) => { "use strict"; /** * Determines whether the payload is an error thrown by Axios * * @param {*} payload The value to test * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false */ module.exports = function isAxiosError(payload) { return (typeof payload === 'object') && (payload.isAxiosError === true); }; /***/ }), /***/ "./node_modules/axios/lib/helpers/isURLSameOrigin.js": /*!***********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isURLSameOrigin.js ***! \***********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. (function standardBrowserEnv() { var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement('a'); var originURL; /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ function resolveURL(url) { var href = url; if (msie) { // IE needs attribute set twice to normalize properties urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); /** * Determine if a URL shares the same origin as the current location * * @param {String} requestURL The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ return function isURLSameOrigin(requestURL) { var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); }; })() : // Non standard browser envs (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return function isURLSameOrigin() { return true; }; })() ); /***/ }), /***/ "./node_modules/axios/lib/helpers/normalizeHeaderName.js": /*!***************************************************************!*\ !*** ./node_modules/axios/lib/helpers/normalizeHeaderName.js ***! \***************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js"); module.exports = function normalizeHeaderName(headers, normalizedName) { utils.forEach(headers, function processHeader(value, name) { if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { headers[normalizedName] = value; delete headers[name]; } }); }; /***/ }), /***/ "./node_modules/axios/lib/helpers/parseHeaders.js": /*!********************************************************!*\ !*** ./node_modules/axios/lib/helpers/parseHeaders.js ***! \********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); // Headers whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers var ignoreDuplicateOf = [ 'age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent' ]; /** * Parse headers into an object * * ``` * Date: Wed, 27 Aug 2014 08:58:49 GMT * Content-Type: application/json * Connection: keep-alive * Transfer-Encoding: chunked * ``` * * @param {String} headers Headers needing to be parsed * @returns {Object} Headers parsed into an object */ module.exports = function parseHeaders(headers) { var parsed = {}; var key; var val; var i; if (!headers) { return parsed; } utils.forEach(headers.split('\n'), function parser(line) { i = line.indexOf(':'); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { return; } if (key === 'set-cookie') { parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); } else { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } } }); return parsed; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/spread.js": /*!**************************************************!*\ !*** ./node_modules/axios/lib/helpers/spread.js ***! \**************************************************/ /***/ ((module) => { "use strict"; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ module.exports = function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/validator.js": /*!*****************************************************!*\ !*** ./node_modules/axios/lib/helpers/validator.js ***! \*****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var pkg = __webpack_require__(/*! ./../../package.json */ "./node_modules/axios/package.json"); var validators = {}; // eslint-disable-next-line func-names ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { validators[type] = function validator(thing) { return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; }; }); var deprecatedWarnings = {}; var currentVerArr = pkg.version.split('.'); /** * Compare package versions * @param {string} version * @param {string?} thanVersion * @returns {boolean} */ function isOlderVersion(version, thanVersion) { var pkgVersionArr = thanVersion ? thanVersion.split('.') : currentVerArr; var destVer = version.split('.'); for (var i = 0; i < 3; i++) { if (pkgVersionArr[i] > destVer[i]) { return true; } else if (pkgVersionArr[i] < destVer[i]) { return false; } } return false; } /** * Transitional option validator * @param {function|boolean?} validator * @param {string?} version * @param {string} message * @returns {function} */ validators.transitional = function transitional(validator, version, message) { var isDeprecated = version && isOlderVersion(version); function formatMessage(opt, desc) { return '[Axios v' + pkg.version + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); } // eslint-disable-next-line func-names return function(value, opt, opts) { if (validator === false) { throw new Error(formatMessage(opt, ' has been removed in ' + version)); } if (isDeprecated && !deprecatedWarnings[opt]) { deprecatedWarnings[opt] = true; // eslint-disable-next-line no-console console.warn( formatMessage( opt, ' has been deprecated since v' + version + ' and will be removed in the near future' ) ); } return validator ? validator(value, opt, opts) : true; }; }; /** * Assert object's properties type * @param {object} options * @param {object} schema * @param {boolean?} allowUnknown */ function assertOptions(options, schema, allowUnknown) { if (typeof options !== 'object') { throw new TypeError('options must be an object'); } var keys = Object.keys(options); var i = keys.length; while (i-- > 0) { var opt = keys[i]; var validator = schema[opt]; if (validator) { var value = options[opt]; var result = value === undefined || validator(value, opt, options); if (result !== true) { throw new TypeError('option ' + opt + ' must be ' + result); } continue; } if (allowUnknown !== true) { throw Error('Unknown option ' + opt); } } } module.exports = { isOlderVersion: isOlderVersion, assertOptions: assertOptions, validators: validators }; /***/ }), /***/ "./node_modules/axios/lib/utils.js": /*!*****************************************!*\ !*** ./node_modules/axios/lib/utils.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js"); // utils is a library of generic helper functions non-specific to axios var toString = Object.prototype.toString; /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray(val) { return toString.call(val) === '[object Array]'; } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined(val) { return typeof val === 'undefined'; } /** * Determine if a value is a Buffer * * @param {Object} val The value to test * @returns {boolean} True if value is a Buffer, otherwise false */ function isBuffer(val) { return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); } /** * Determine if a value is an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ function isArrayBuffer(val) { return toString.call(val) === '[object ArrayBuffer]'; } /** * Determine if a value is a FormData * * @param {Object} val The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(val) { return (typeof FormData !== 'undefined') && (val instanceof FormData); } /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { var result; if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { result = ArrayBuffer.isView(val); } else { result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); } return result; } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber(val) { return typeof val === 'number'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a plain Object * * @param {Object} val The value to test * @return {boolean} True if value is a plain Object, otherwise false */ function isPlainObject(val) { if (toString.call(val) !== '[object Object]') { return false; } var prototype = Object.getPrototypeOf(val); return prototype === null || prototype === Object.prototype; } /** * Determine if a value is a Date * * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ function isDate(val) { return toString.call(val) === '[object Date]'; } /** * Determine if a value is a File * * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ function isFile(val) { return toString.call(val) === '[object File]'; } /** * Determine if a value is a Blob * * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ function isBlob(val) { return toString.call(val) === '[object Blob]'; } /** * Determine if a value is a Function * * @param {Object} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ function isFunction(val) { return toString.call(val) === '[object Function]'; } /** * Determine if a value is a Stream * * @param {Object} val The value to test * @returns {boolean} True if value is a Stream, otherwise false */ function isStream(val) { return isObject(val) && isFunction(val.pipe); } /** * Determine if a value is a URLSearchParams object * * @param {Object} val The value to test * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ function isURLSearchParams(val) { return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; } /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim(str) { return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); } /** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: * typeof window -> undefined * typeof document -> undefined * * react-native: * navigator.product -> 'ReactNative' * nativescript * navigator.product -> 'NativeScript' or 'NS' */ function isStandardBrowserEnv() { if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { return false; } return ( typeof window !== 'undefined' && typeof document !== 'undefined' ); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object') { /*eslint no-param-reassign:0*/ obj = [obj]; } if (isArray(obj)) { // Iterate over array values for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (isPlainObject(result[key]) && isPlainObject(val)) { result[key] = merge(result[key], val); } else if (isPlainObject(val)) { result[key] = merge({}, val); } else if (isArray(val)) { result[key] = val.slice(); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } /** * Extends object a by mutably adding to it the properties of object b. * * @param {Object} a The object to be extended * @param {Object} b The object to copy properties from * @param {Object} thisArg The object to bind function to * @return {Object} The resulting value of object a */ function extend(a, b, thisArg) { forEach(b, function assignValue(val, key) { if (thisArg && typeof val === 'function') { a[key] = bind(val, thisArg); } else { a[key] = val; } }); return a; } /** * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) * * @param {string} content with BOM * @return {string} content value without BOM */ function stripBOM(content) { if (content.charCodeAt(0) === 0xFEFF) { content = content.slice(1); } return content; } module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, isBuffer: isBuffer, isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString, isNumber: isNumber, isObject: isObject, isPlainObject: isPlainObject, isUndefined: isUndefined, isDate: isDate, isFile: isFile, isBlob: isBlob, isFunction: isFunction, isStream: isStream, isURLSearchParams: isURLSearchParams, isStandardBrowserEnv: isStandardBrowserEnv, forEach: forEach, merge: merge, extend: extend, trim: trim, stripBOM: stripBOM }; /***/ }), /***/ "./resources/js/app.js": /*!*****************************!*\ !*** ./resources/js/app.js ***! \*****************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var alpinejs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! alpinejs */ "./node_modules/alpinejs/dist/module.esm.js"); __webpack_require__(/*! ./bootstrap */ "./resources/js/bootstrap.js"); window.Alpine = alpinejs__WEBPACK_IMPORTED_MODULE_0__["default"]; alpinejs__WEBPACK_IMPORTED_MODULE_0__["default"].start(); /***/ }), /***/ "./resources/js/bootstrap.js": /*!***********************************!*\ !*** ./resources/js/bootstrap.js ***! \***********************************/ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { window._ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); /** * We'll load the axios HTTP library which allows us to easily issue requests * to our Laravel back-end. This library automatically handles sending the * CSRF token as a header based on the value of the "XSRF" token cookie. */ window.axios = __webpack_require__(/*! axios */ "./node_modules/axios/index.js"); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from 'laravel-echo'; // window.Pusher = require('pusher-js'); // window.Echo = new Echo({ // broadcaster: 'pusher', // key: process.env.MIX_PUSHER_APP_KEY, // cluster: process.env.MIX_PUSHER_APP_CLUSTER, // forceTLS: true // }); /***/ }), /***/ "./node_modules/lodash/lodash.js": /*!***************************************!*\ !*** ./node_modules/lodash/lodash.js ***! \***************************************/ /***/ (function(module, exports, __webpack_require__) { /* module decorator */ module = __webpack_require__.nmd(module); var __WEBPACK_AMD_DEFINE_RESULT__;/** * @license * Lodash <https://lodash.com/> * Copyright OpenJS Foundation and other contributors <https://openjsf.org/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '4.17.21'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Error message constants. */ var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', FUNC_ERROR_TEXT = 'Expected a function', INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', domExcTag = '[object DOMException]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading whitespace. */ var reTrimStart = /^\s+/; /** Used to match a single whitespace character. */ var reWhitespace = /\s/; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; /** * Used to validate the `validate` option in `_.template` variable. * * Forbids characters which could potentially change the meaning of the function argument definition: * - "()," (modification of function parameters) * - "=" (default value) * - "[]{}" (destructuring of function parameters) * - "/" (beginning of a comment) * - whitespace */ var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([ rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, rsUpper + '+' + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { // Latin-1 Supplement block. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss', // Latin Extended-A block. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', '\u0134': 'J', '\u0135': 'j', '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', '\u0163': 't', '\u0165': 't', '\u0167': 't', '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', '\u0174': 'W', '\u0175': 'w', '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', '\u0132': 'IJ', '\u0133': 'ij', '\u0152': 'Oe', '\u0153': 'oe', '\u0149': "'n", '\u017f': 's' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'" }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = true && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /*--------------------------------------------------------------------------*/ /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * Gets the size of an ASCII `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ var asciiSize = baseProperty('length'); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Splits an ASCII `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function asciiWords(string) { return string.match(reAsciiWord) || []; } /** * The base implementation of methods like `_.findKey` and `_.findLastKey`, * without support for iteratee shorthands, which iterates over `collection` * using `eachFunc`. * * @private * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array == null ? 0 : array.length; return length ? (baseSum(array, iteratee) / length) : NAN; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.propertyOf` without support for deep paths. * * @private * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { return function(key) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * The base implementation of `_.trim`. * * @private * @param {string} string The string to trim. * @returns {string} Returns the trimmed string. */ function baseTrim(string) { return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string; } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } /** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ var deburrLetter = basePropertyOf(deburredLetters); /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ var escapeHtmlChar = basePropertyOf(htmlEscapes); /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * A specialized version of `_.lastIndexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { if (array[index] === value) { return index; } } return index; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace * character of `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the index of the last non-whitespace character. */ function trimmedEndIndex(string) { var index = string.length; while (index-- && reWhitespace.test(string.charAt(index))) {} return index; } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); /** * Gets the size of a Unicode `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { ++result; } return result; } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** * Splits a Unicode `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ var runInContext = (function runInContext(context) { context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = context['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined; var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB) as well as ES2015 template strings. Change the * following template settings to use alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || (!isRight && arrLength == length && takeCount == length)) { return baseWrapperValue(array, this.__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * A specialized version of `_.sample` for arrays. * * @private * @param {Array} array The array to sample. * @returns {*} Returns the random element. */ function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined; } /** * A specialized version of `_.sampleSize` for arrays. * * @private * @param {Array} array The array to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** * A specialized version of `_.shuffle` for arrays. * * @private * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. */ function arrayShuffle(array) { return shuffleSelf(copyArray(array)); } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, length = paths.length, result = Array(length), skip = object == null; while (++index < length) { result[index] = skip ? undefined : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); } else if (isMap(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); } var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; } /** * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if ((value === undefined && !(key in object)) || !predicate(value)) { return false; } } return true; } /** * The base implementation of `_.delay` and `_.defer` which accepts `args` * to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Array} args The arguments to provide to `func`. * @returns {number|Object} Returns the timer id or timeout object. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? (current === current && !isSymbol(current)) : comparator(current, computed) )) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.gt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { path = castPath(path, object); object = parent(object, path); var func = object == null ? object : object[toKey(last(path))]; return func == null ? undefined : apply(func, object, args); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ function baseIsArrayBuffer(value) { return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** * The base implementation of `_.isDate` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ function baseIsDate(value) { return isObjectLike(value) && baseGetTag(value) == dateTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The base implementation of `_.lt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { stack || (stack = new Stack); if (isObject(srcValue)) { baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || isFunction(objValue)) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce arguments. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { if (iteratees.length) { iteratees = arrayMap(iteratees, function(iteratee) { if (isArray(iteratee)) { return function(value) { return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); } } return iteratee; }); } else { iteratees = [identity]; } var index = -1; iteratees = arrayMap(iteratees, baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values); } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else { baseUnset(array, index); } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } /** * The base implementation of `_.sample`. * * @private * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. */ function baseSample(collection) { return arraySample(values(collection)); } /** * The base implementation of `_.sampleSize` without param guards. * * @private * @param {Array|Object} collection The collection to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function baseSampleSize(collection, n) { var array = values(collection); return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (key === '__proto__' || key === 'constructor' || key === 'prototype') { return object; } if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; /** * The base implementation of `_.shuffle`. * * @private * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. */ function baseShuffle(collection) { return shuffleSelf(values(collection)); } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array == null ? low : array.length; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? (computed <= value) : (computed < value))) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { var low = 0, high = array == null ? 0 : array.length; if (high === 0) { return 0; } value = iteratee(value); var valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** * A `baseRest` alias which can be replaced with `identity` by module * replacement plugins. * * @private * @type {Function} * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ var castRest = baseRest; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private * @param {number|Object} id The timer id or timeout object of the timer to clear. */ var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id); }; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return flatRest(function(funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value)) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined && other === undefined) { return defaultValue; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return flatRest(function(iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); return baseRest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); if (precision && nativeIsFinite(number)) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source * objects into destination objects that are passed thru. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); stack['delete'](srcValue); } return objValue; } /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined : value; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Check that cyclic values are equal. var arrStacked = stack.get(array); var othStacked = stack.get(other); if (arrStacked && othStacked) { return arrStacked == other && othStacked == array; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Check that cyclic values are equal. var objStacked = stack.get(object); var othStacked = stack.get(other); if (objStacked && othStacked) { return objStacked == other && othStacked == object; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return new Ctor; case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return new Ctor; case symbolTag: return cloneSymbol(object); } } /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `func` is capable of being masked. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ var isMaskable = coreJsData ? isFunction : stubFalse; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Gets the value at `key`, unless `key` is "__proto__" or "constructor". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { if (key === 'constructor' && typeof object[key] === 'function') { return; } if (key == '__proto__') { return; } return object[key]; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); /** * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @returns {number|Object} Returns the timer id or timeout object. */ var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait); }; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } /** * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * * @private * @param {Array} array The array to shuffle. * @param {number} [size=array.length] The size of `array`. * @returns {Array} Returns `array`. */ function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length; if (!length) { return []; } var args = Array(length - 1), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. The order and * references of result values are determined by the first array. The comparator * is invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, getIteratee(predicate, 3), index); } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length - 1; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array == null ? 0 : array.length; if (!length) { return []; } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 0, -1) : []; } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. The order and references * of result values are determined by the first array. The comparator is * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); comparator = typeof comparator == 'function' ? comparator : undefined; if (comparator) { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, undefined, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array == null ? '' : nativeJoin.call(array, separator); } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); } /** * Gets the element at index `n` of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pull(array, 'a', 'c'); * console.log(array); * // => ['b', 'b'] */ var pull = baseRest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pullAll(array, ['a', 'c']); * console.log(array); * // => ['b', 'b'] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return (array && array.length && values && values.length) ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return (array && array.length && values && values.length) ? basePullAll(array, values, undefined, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = ['a', 'b', 'c', 'd']; * var pulled = _.pullAt(array, [1, 3]); * * console.log(array); * // => ['a', 'c'] * * console.log(pulled); * // => ['b', 'd'] */ var pullAt = flatRest(function(array, indexes) { var length = array == null ? 0 : array.length, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array == null ? array : nativeReverse.call(array); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 0 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([4, 5, 5, 5, 6], 5); * // => 1 */ function sortedIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5, 5, 5, 6], 5); * // => 4 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return (array && array.length) ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return (array && array.length) ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 1, length) : []; } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. Result values are chosen from the first * array in which the value occurs. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1], [1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. Result values are chosen from * the first array in which the value occurs. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each element * is kept. The order of result values is determined by the order they occur * in the array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return (array && array.length) ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The order of result values is determined by the * order they occur in the array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The order of result values is * determined by the order they occur in the array.The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { comparator = typeof comparator == 'function' ? comparator : undefined; return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] * * _.unzip(zipped); * // => [['a', 'b'], [1, 2], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The order of result values is determined * by the order they occur in the arrays. The iteratee is invoked with one * argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2, 3.4] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The order of result values is * determined by the order they occur in the arrays. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] */ var zip = baseRest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine * grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ var wrapperAt = flatRest(function(paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()); } var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined }); return new LodashWrapper(wrapped, this.__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * // The `_.property` iteratee shorthand. * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; } else { baseAssignValue(result, key, 1); } }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * **Note:** This method returns `true` for * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] * * // Combining several predicates using `_.overEvery` or `_.overSome`. * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); * // => objects for ['fred', 'barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(findLastIndex); /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `path` is a function, it's invoked * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function(result, value, key) { baseAssignValue(result, key, value); }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var func = isArray(collection) ? arraySample : baseSample; return func(collection); } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } var func = isArray(collection) ? arraySampleSize : baseSampleSize; return func(collection, n); } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { var func = isArray(collection) ? arrayShuffle : baseShuffle; return func(collection); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 30 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = ctxNow || function() { return root.Date.now(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = (func && n == null) ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = baseRest(function(object, key, partials) { var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. clearTimeout(timerId); timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one millisecond. */ var defer = baseRest(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrap(func, WRAP_FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with its arguments transformed. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Function|Function[])} [transforms=[_.identity]] * The argument transforms. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, [square, doubled]); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = castRest(function(func, transforms) { transforms = (transforms.length == 1 && isArray(transforms[0])) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = flatRest(function(func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? start : toInteger(start); return baseRest(func, start); } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start == null ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to `wrapper` as its first * argument. Any additional arguments provided to the function are appended * to those provided to the `wrapper`. The wrapper is invoked with the `this` * binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('fred, barney, & pebbles'); * // => '<p>fred, barney, &amp; pebbles</p>' */ function wrap(value, wrapper) { return partial(castFunction(wrapper), value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); } /** * Checks if `object` conforms to `source` by invoking the predicate * properties of `source` with the corresponding property values of `object`. * * **Note:** This method is equivalent to `_.conforms` when `source` is * partially applied. * * @static * @memberOf _ * @since 4.14.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); * // => true * * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); * // => false */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && baseGetTag(value) == boolTag); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement('<body>'); * // => false */ function isElement(value) { return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. * * **Note:** This method is equivalent to `_.matches` when `source` is * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.isMatch(object, { 'b': 2 }); * // => true * * _.isMatch(object, { 'b': 1 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a pristine native function. * * **Note:** This method can't reliably detect native functions in the presence * of the core-js package because core-js circumvents this kind of detection. * Despite multiple requests, the core-js maintainer has made it clear: any * attempt to fix the detection will be obstructed. As a result, we're left * with little choice but to throw an error. Unfortunately, this also affects * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (isMaskable(value)) { throw new Error(CORE_ERROR_TEXT); } return baseIsNative(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && baseGetTag(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = baseTrim(value); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : (value === 0 ? value : 0); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ var assign = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object); }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] */ var at = flatRest(baseAt); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties == null ? result : baseAssign(result, properties); } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined || (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { object[key] = source[key]; } } } return object; }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ var defaultsDeep = baseRest(function(args) { args.push(undefined, customDefaultsMerge); return apply(mergeWith, undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = baseRest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with six arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { 'a': [1], 'b': [2] }; * var other = { 'a': [3], 'b': [4] }; * * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = getIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = castPath(path, object); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { length = 1; object = undefined; } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. If `accumulator` is not * provided, a new object with the same `[[Prototype]]` will be used. The * iteratee is invoked with four arguments: (accumulator, value, key, object). * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor : []; } else if (isObject(object)) { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; } } (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined; } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; } if (floating === undefined) { if (typeof upper == 'boolean') { floating = upper; upper = undefined; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1; } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; lower = 0; } else { upper = toFinite(upper); } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) * letters to basic Latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search up to. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; } /** * Converts the characters "&", "<", ">", '"', and "'" in `string` to their * corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, &amp; pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return ( createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) ); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (string + createPadding(length - strLength, chars)) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (createPadding(length - strLength, chars) + string) : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined; } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && ( typeof separator == 'string' || (separator != null && !isRegExp(separator)) )) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit); } } return string.split(separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<b><%- value %></b>'); * compiled({ 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // Use the "evaluate" delimiter to execute JavaScript and generate HTML. * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the internal `print` function in "evaluate" delimiters. * var compiled = _.template('<% print("hello " + user); %>!'); * compiled({ 'user': 'barney' }); * // => 'hello barney!' * * // Use the ES template literal delimiter as an "interpolate" delimiter. * // Disable support by replacing the "interpolate" delimiter. * var compiled = _.template('hello ${ user }!'); * compiled({ 'user': 'pebbles' }); * // => 'hello pebbles!' * * // Use backslashes to treat delimiters as plain text. * var compiled = _.template('<%= "\\<%- value %\\>" %>'); * compiled({ 'value': 'ignored' }); * // => '<%- value %>' * * // Use the `imports` option to import `jQuery` as `jq`. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the `sourceURL` option to specify a custom sourceURL for the template. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. * * // Use the `variable` option to ensure a with-statement isn't used in the compiled template. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); * compiled.source; * // => function(data) { * // var __t, __p = ''; * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; * // return __p; * // } * * // Use custom template delimiters. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; * var compiled = _.template('hello {{ user }}!'); * compiled({ 'user': 'mustache' }); * // => 'hello mustache!' * * // Use the `source` property to inline compiled templates for meaningful * // line numbers in error messages and stack traces. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(string, options, guard) { // Based on John Resig's `tmpl` implementation // (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined; } string = toString(string); options = assignInWith({}, options, settings, customDefaultsAssignIn); var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. // The sourceURL gets injected into the source that's eval-ed, so be careful // to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in // and escape the comment, thus injecting code that gets evaled. var sourceURL = '//# sourceURL=' + (hasOwnProperty.call(options, 'sourceURL') ? (options.sourceURL + '').replace(/\s/g, ' ') : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products needs `match` returned in // order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. var variable = hasOwnProperty.call(options, 'variable') && options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Throw an error if a forbidden character was found in `variable`, to prevent // potential command injection attacks. else if (reForbiddenIdentifierChars.test(variable)) { throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT); } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source) .apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; } /** * Converts `string`, as a whole, to lower case just like * [String#toLowerCase](https://mdn.io/toLowerCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.toLower('--Foo-Bar--'); * // => '--foo-bar--' * * _.toLower('fooBar'); * // => 'foobar' * * _.toLower('__FOO_BAR__'); * // => '__foo_bar__' */ function toLower(value) { return toString(value).toLowerCase(); } /** * Converts `string`, as a whole, to upper case just like * [String#toUpperCase](https://mdn.io/toUpperCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.toUpper('--foo-bar--'); * // => '--FOO-BAR--' * * _.toUpper('fooBar'); * // => 'FOOBAR' * * _.toUpper('__foo_bar__'); * // => '__FOO_BAR__' */ function toUpper(value) { return toString(value).toUpperCase(); } /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return baseTrim(string); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } /** * Removes trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimEnd(' abc '); * // => ' abc' * * _.trimEnd('-_-abc-_-', '_-'); * // => '-_-abc' */ function trimEnd(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.slice(0, trimmedEndIndex(string) + 1); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; return castSlice(strSymbols, 0, end).join(''); } /** * Removes leading whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimStart(' abc '); * // => 'abc ' * * _.trimStart('-_-abc-_-', '_-'); * // => 'abc-_-' */ function trimStart(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimStart, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); return castSlice(strSymbols, start).join(''); } /** * Truncates `string` if it's longer than the given maximum string length. * The last characters of the truncated string are replaced with the omission * string which defaults to "...". * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to truncate. * @param {Object} [options={}] The options object. * @param {number} [options.length=30] The maximum string length. * @param {string} [options.omission='...'] The string to indicate text is omitted. * @param {RegExp|string} [options.separator] The separator pattern to truncate to. * @returns {string} Returns the truncated string. * @example * * _.truncate('hi-diddly-ho there, neighborino'); * // => 'hi-diddly-ho there, neighbo...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': ' ' * }); * // => 'hi-diddly-ho there,...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': /,? +/ * }); * // => 'hi-diddly-ho there...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'omission': ' [...]' * }); * // => 'hi-diddly-ho there, neig [...]' */ function truncate(string, options) { var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (isObject(options)) { var separator = 'separator' in options ? options.separator : separator; length = 'length' in options ? toInteger(options.length) : length; omission = 'omission' in options ? baseToString(options.omission) : omission; } string = toString(string); var strLength = string.length; if (hasUnicode(string)) { var strSymbols = stringToArray(string); strLength = strSymbols.length; } if (length >= strLength) { return string; } var end = length - stringSize(omission); if (end < 1) { return omission; } var result = strSymbols ? castSlice(strSymbols, 0, end).join('') : string.slice(0, end); if (separator === undefined) { return result + omission; } if (strSymbols) { end += (result.length - end); } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, substring = result; if (!separator.global) { separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); } separator.lastIndex = 0; while ((match = separator.exec(substring))) { var newEnd = match.index; } result = result.slice(0, newEnd === undefined ? end : newEnd); } } else if (string.indexOf(baseToString(separator), end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } /** * The inverse of `_.escape`; this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to * their corresponding characters. * * **Note:** No other HTML entities are unescaped. To unescape additional * HTML entities use a third-party library like [_he_](https://mths.be/he). * * @static * @memberOf _ * @since 0.6.0 * @category String * @param {string} [string=''] The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('fred, barney, &amp; pebbles'); * // => 'fred, barney, & pebbles' */ function unescape(string) { string = toString(string); return (string && reHasEscapedHtml.test(string)) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; } /** * Converts `string`, as space separated words, to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.upperCase('--foo-bar'); * // => 'FOO BAR' * * _.upperCase('fooBar'); * // => 'FOO BAR' * * _.upperCase('__foo_bar__'); * // => 'FOO BAR' */ var upperCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toUpperCase(); }); /** * Converts the first character of `string` to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.upperFirst('fred'); * // => 'Fred' * * _.upperFirst('FRED'); * // => 'FRED' */ var upperFirst = createCaseFirst('toUpperCase'); /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); } return string.match(pattern) || []; } /*------------------------------------------------------------------------*/ /** * Attempts to invoke `func`, returning either the result or the caught error * object. Any additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Function} func The function to attempt. * @param {...*} [args] The arguments to invoke `func` with. * @returns {*} Returns the `func` result or error object. * @example * * // Avoid throwing errors for invalid selectors. * var elements = _.attempt(function(selector) { * return document.querySelectorAll(selector); * }, '>_>'); * * if (_.isError(elements)) { * elements = []; * } */ var attempt = baseRest(function(func, args) { try { return apply(func, undefined, args); } catch (e) { return isError(e) ? e : new Error(e); } }); /** * Binds methods of an object to the object itself, overwriting the existing * method. * * **Note:** This method doesn't set the "length" property of bound functions. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Object} object The object to bind and assign the bound methods to. * @param {...(string|string[])} methodNames The object method names to bind. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'click': function() { * console.log('clicked ' + this.label); * } * }; * * _.bindAll(view, ['click']); * jQuery(element).on('click', view.click); * // => Logs 'clicked docs' when clicked. */ var bindAll = flatRest(function(object, methodNames) { arrayEach(methodNames, function(key) { key = toKey(key); baseAssignValue(object, key, bind(object[key], object)); }); return object; }); /** * Creates a function that iterates over `pairs` and invokes the corresponding * function of the first predicate to return truthy. The predicate-function * pairs are invoked with the `this` binding and arguments of the created * function. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Array} pairs The predicate-function pairs. * @returns {Function} Returns the new composite function. * @example * * var func = _.cond([ * [_.matches({ 'a': 1 }), _.constant('matches A')], * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], * [_.stubTrue, _.constant('no match')] * ]); * * func({ 'a': 1, 'b': 2 }); * // => 'matches A' * * func({ 'a': 0, 'b': 1 }); * // => 'matches B' * * func({ 'a': '1', 'b': '2' }); * // => 'no match' */ function cond(pairs) { var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); pairs = !length ? [] : arrayMap(pairs, function(pair) { if (typeof pair[1] != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return [toIteratee(pair[0]), pair[1]]; }); return baseRest(function(args) { var index = -1; while (++index < length) { var pair = pairs[index]; if (apply(pair[0], this, args)) { return apply(pair[1], this, args); } } }); } /** * Creates a function that invokes the predicate properties of `source` with * the corresponding property values of a given object, returning `true` if * all predicates return truthy, else `false`. * * **Note:** The created function is equivalent to `_.conformsTo` with * `source` partially applied. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 2, 'b': 1 }, * { 'a': 1, 'b': 2 } * ]; * * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); * // => [{ 'a': 1, 'b': 2 }] */ function conforms(source) { return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } /** * Checks `value` to determine whether a default value should be returned in * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, * or `undefined`. * * @static * @memberOf _ * @since 4.14.0 * @category Util * @param {*} value The value to check. * @param {*} defaultValue The default value. * @returns {*} Returns the resolved value. * @example * * _.defaultTo(1, 10); * // => 1 * * _.defaultTo(undefined, 10); * // => 10 */ function defaultTo(value, defaultValue) { return (value == null || value !== value) ? defaultValue : value; } /** * Creates a function that returns the result of invoking the given functions * with the `this` binding of the created function, where each successive * invocation is supplied the return value of the previous. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flowRight * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flow([_.add, square]); * addSquare(1, 2); * // => 9 */ var flow = createFlow(); /** * This method is like `_.flow` except that it creates a function that * invokes the given functions from right to left. * * @static * @since 3.0.0 * @memberOf _ * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flow * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flowRight([square, _.add]); * addSquare(1, 2); * // => 9 */ var flowRight = createFlow(true); /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } /** * Creates a function that invokes `func` with the arguments of the created * function. If `func` is a property name, the created function returns the * property value for a given element. If `func` is an array or object, the * created function returns `true` for elements that contain the equivalent * source properties, otherwise it returns `false`. * * @static * @since 4.0.0 * @memberOf _ * @category Util * @param {*} [func=_.identity] The value to convert to a callback. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); * // => [{ 'user': 'barney', 'age': 36, 'active': true }] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, _.iteratee(['user', 'fred'])); * // => [{ 'user': 'fred', 'age': 40 }] * * // The `_.property` iteratee shorthand. * _.map(users, _.iteratee('user')); * // => ['barney', 'fred'] * * // Create custom iteratee shorthands. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { * return !_.isRegExp(func) ? iteratee(func) : function(string) { * return func.test(string); * }; * }); * * _.filter(['abc', 'def'], /ef/); * // => ['def'] */ function iteratee(func) { return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between a given * object and `source`, returning `true` if the given object has equivalent * property values, else `false`. * * **Note:** The created function is equivalent to `_.isMatch` with `source` * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * **Note:** Multiple values can be checked by combining several matchers * using `_.overSome` * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); * // => [{ 'a': 4, 'b': 5, 'c': 6 }] * * // Checking for several possible values * _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })])); * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }] */ function matches(source) { return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between the * value at `path` of a given object to `srcValue`, returning `true` if the * object value is equivalent, else `false`. * * **Note:** Partial comparisons will match empty array and empty object * `srcValue` values against any array or object value, respectively. See * `_.isEqual` for a list of supported value comparisons. * * **Note:** Multiple values can be checked by combining several matchers * using `_.overSome` * * @static * @memberOf _ * @since 3.2.0 * @category Util * @param {Array|string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.find(objects, _.matchesProperty('a', 4)); * // => { 'a': 4, 'b': 5, 'c': 6 } * * // Checking for several possible values * _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)])); * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }] */ function matchesProperty(path, srcValue) { return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); } /** * Creates a function that invokes the method at `path` of a given object. * Any additional arguments are provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var objects = [ * { 'a': { 'b': _.constant(2) } }, * { 'a': { 'b': _.constant(1) } } * ]; * * _.map(objects, _.method('a.b')); * // => [2, 1] * * _.map(objects, _.method(['a', 'b'])); * // => [2, 1] */ var method = baseRest(function(path, args) { return function(object) { return baseInvoke(object, path, args); }; }); /** * The opposite of `_.method`; this method creates a function that invokes * the method at a given path of `object`. Any additional arguments are * provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Object} object The object to query. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var array = _.times(3, _.constant), * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.methodOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); * // => [2, 0] */ var methodOf = baseRest(function(object, args) { return function(path) { return baseInvoke(object, path, args); }; }); /** * Adds all own enumerable string keyed function properties of a source * object to the destination object. If `object` is a function, then methods * are added to its prototype as well. * * **Note:** Use `_.runInContext` to create a pristine `lodash` function to * avoid conflicts caused by modifying the original. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Function|Object} [object=lodash] The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options={}] The options object. * @param {boolean} [options.chain=true] Specify whether mixins are chainable. * @returns {Function|Object} Returns `object`. * @example * * function vowels(string) { * return _.filter(string, function(v) { * return /[aeiou]/i.test(v); * }); * } * * _.mixin({ 'vowels': vowels }); * _.vowels('fred'); * // => ['e'] * * _('fred').vowels().value(); * // => ['e'] * * _.mixin({ 'vowels': vowels }, { 'chain': false }); * _('fred').vowels(); * // => ['e'] */ function mixin(object, source, options) { var props = keys(source), methodNames = baseFunctions(source, props); if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { options = source; source = object; object = this; methodNames = baseFunctions(source, keys(source)); } var chain = !(isObject(options) && 'chain' in options) || !!options.chain, isFunc = isFunction(object); arrayEach(methodNames, function(methodName) { var func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = function() { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), actions = result.__actions__ = copyArray(this.__actions__); actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); result.__chain__ = chainAll; return result; } return func.apply(object, arrayPush([this.value()], arguments)); }; } }); return object; } /** * Reverts the `_` variable to its previous value and returns a reference to * the `lodash` function. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { if (root._ === this) { root._ = oldDash; } return this; } /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } /** * Creates a function that gets the argument at index `n`. If `n` is negative, * the nth argument from the end is returned. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [n=0] The index of the argument to return. * @returns {Function} Returns the new pass-thru function. * @example * * var func = _.nthArg(1); * func('a', 'b', 'c', 'd'); * // => 'b' * * var func = _.nthArg(-2); * func('a', 'b', 'c', 'd'); * // => 'c' */ function nthArg(n) { n = toInteger(n); return baseRest(function(args) { return baseNth(args, n); }); } /** * Creates a function that invokes `iteratees` with the arguments it receives * and returns their results. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to invoke. * @returns {Function} Returns the new function. * @example * * var func = _.over([Math.max, Math.min]); * * func(1, 2, 3, 4); * // => [4, 1] */ var over = createOver(arrayMap); /** * Creates a function that checks if **all** of the `predicates` return * truthy when invoked with the arguments it receives. * * Following shorthands are possible for providing predicates. * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overEvery([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => false * * func(NaN); * // => false */ var overEvery = createOver(arrayEvery); /** * Creates a function that checks if **any** of the `predicates` return * truthy when invoked with the arguments it receives. * * Following shorthands are possible for providing predicates. * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overSome([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => true * * func(NaN); * // => false * * var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }]) * var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]]) */ var overSome = createOver(arraySome); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } /** * The opposite of `_.property`; this method creates a function that returns * the value at a given path of `object`. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. * @example * * var array = [0, 1, 2], * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); * // => [2, 0] */ function propertyOf(object) { return function(path) { return object == null ? undefined : baseGet(object, path); }; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = createRange(); /** * This method is like `_.range` except that it populates values in * descending order. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.range * @example * * _.rangeRight(4); * // => [3, 2, 1, 0] * * _.rangeRight(-4); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 5); * // => [4, 3, 2, 1] * * _.rangeRight(0, 20, 5); * // => [15, 10, 5, 0] * * _.rangeRight(0, -4, -1); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 4, 0); * // => [1, 1, 1] * * _.rangeRight(0); * // => [] */ var rangeRight = createRange(true); /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } /** * This method returns a new empty object. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Object} Returns the new empty object. * @example * * var objects = _.times(2, _.stubObject); * * console.log(objects); * // => [{}, {}] * * console.log(objects[0] === objects[1]); * // => false */ function stubObject() { return {}; } /** * This method returns an empty string. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {string} Returns the empty string. * @example * * _.times(2, _.stubString); * // => ['', ''] */ function stubString() { return ''; } /** * This method returns `true`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `true`. * @example * * _.times(2, _.stubTrue); * // => [true, true] */ function stubTrue() { return true; } /** * Invokes the iteratee `n` times, returning an array of the results of * each invocation. The iteratee is invoked with one argument; (index). * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} n The number of times to invoke `iteratee`. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of results. * @example * * _.times(3, String); * // => ['0', '1', '2'] * * _.times(4, _.constant(0)); * // => [0, 0, 0, 0] */ function times(n, iteratee) { n = toInteger(n); if (n < 1 || n > MAX_SAFE_INTEGER) { return []; } var index = MAX_ARRAY_LENGTH, length = nativeMin(n, MAX_ARRAY_LENGTH); iteratee = getIteratee(iteratee); n -= MAX_ARRAY_LENGTH; var result = baseTimes(length, iteratee); while (++index < n) { iteratee(index); } return result; } /** * Converts `value` to a property path array. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {*} value The value to convert. * @returns {Array} Returns the new property path array. * @example * * _.toPath('a.b.c'); * // => ['a', 'b', 'c'] * * _.toPath('a[0].b.c'); * // => ['a', '0', 'b', 'c'] */ function toPath(value) { if (isArray(value)) { return arrayMap(value, toKey); } return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); } /** * Generates a unique ID. If `prefix` is given, the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } /*------------------------------------------------------------------------*/ /** * Adds two numbers. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {number} augend The first number in an addition. * @param {number} addend The second number in an addition. * @returns {number} Returns the total. * @example * * _.add(6, 4); * // => 10 */ var add = createMathOperation(function(augend, addend) { return augend + addend; }, 0); /** * Computes `number` rounded up to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round up. * @param {number} [precision=0] The precision to round up to. * @returns {number} Returns the rounded up number. * @example * * _.ceil(4.006); * // => 5 * * _.ceil(6.004, 2); * // => 6.01 * * _.ceil(6040, -2); * // => 6100 */ var ceil = createRound('ceil'); /** * Divide two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} dividend The first number in a division. * @param {number} divisor The second number in a division. * @returns {number} Returns the quotient. * @example * * _.divide(6, 4); * // => 1.5 */ var divide = createMathOperation(function(dividend, divisor) { return dividend / divisor; }, 1); /** * Computes `number` rounded down to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round down. * @param {number} [precision=0] The precision to round down to. * @returns {number} Returns the rounded down number. * @example * * _.floor(4.006); * // => 4 * * _.floor(0.046, 2); * // => 0.04 * * _.floor(4060, -2); * // => 4000 */ var floor = createRound('floor'); /** * Computes the maximum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * _.max([]); * // => undefined */ function max(array) { return (array && array.length) ? baseExtremum(array, identity, baseGt) : undefined; } /** * This method is like `_.max` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the maximum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.maxBy(objects, function(o) { return o.n; }); * // => { 'n': 2 } * * // The `_.property` iteratee shorthand. * _.maxBy(objects, 'n'); * // => { 'n': 2 } */ function maxBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) : undefined; } /** * Computes the mean of the values in `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the mean. * @example * * _.mean([4, 2, 8, 6]); * // => 5 */ function mean(array) { return baseMean(array, identity); } /** * This method is like `_.mean` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be averaged. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the mean. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.meanBy(objects, function(o) { return o.n; }); * // => 5 * * // The `_.property` iteratee shorthand. * _.meanBy(objects, 'n'); * // => 5 */ function meanBy(array, iteratee) { return baseMean(array, getIteratee(iteratee, 2)); } /** * Computes the minimum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * _.min([]); * // => undefined */ function min(array) { return (array && array.length) ? baseExtremum(array, identity, baseLt) : undefined; } /** * This method is like `_.min` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the minimum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.minBy(objects, function(o) { return o.n; }); * // => { 'n': 1 } * * // The `_.property` iteratee shorthand. * _.minBy(objects, 'n'); * // => { 'n': 1 } */ function minBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) : undefined; } /** * Multiply two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} multiplier The first number in a multiplication. * @param {number} multiplicand The second number in a multiplication. * @returns {number} Returns the product. * @example * * _.multiply(6, 4); * // => 24 */ var multiply = createMathOperation(function(multiplier, multiplicand) { return multiplier * multiplicand; }, 1); /** * Computes `number` rounded to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round. * @param {number} [precision=0] The precision to round to. * @returns {number} Returns the rounded number. * @example * * _.round(4.006); * // => 4 * * _.round(4.006, 2); * // => 4.01 * * _.round(4060, -2); * // => 4100 */ var round = createRound('round'); /** * Subtract two numbers. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {number} minuend The first number in a subtraction. * @param {number} subtrahend The second number in a subtraction. * @returns {number} Returns the difference. * @example * * _.subtract(6, 4); * // => 2 */ var subtract = createMathOperation(function(minuend, subtrahend) { return minuend - subtrahend; }, 0); /** * Computes the sum of the values in `array`. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. * @example * * _.sum([4, 2, 8, 6]); * // => 20 */ function sum(array) { return (array && array.length) ? baseSum(array, identity) : 0; } /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? baseSum(array, getIteratee(iteratee, 2)) : 0; } /*------------------------------------------------------------------------*/ // Add methods that return wrapped values in chain sequences. lodash.after = after; lodash.ary = ary; lodash.assign = assign; lodash.assignIn = assignIn; lodash.assignInWith = assignInWith; lodash.assignWith = assignWith; lodash.at = at; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.castArray = castArray; lodash.chain = chain; lodash.chunk = chunk; lodash.compact = compact; lodash.concat = concat; lodash.cond = cond; lodash.conforms = conforms; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.curry = curry; lodash.curryRight = curryRight; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defaultsDeep = defaultsDeep; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.differenceBy = differenceBy; lodash.differenceWith = differenceWith; lodash.drop = drop; lodash.dropRight = dropRight; lodash.dropRightWhile = dropRightWhile; lodash.dropWhile = dropWhile; lodash.fill = fill; lodash.filter = filter; lodash.flatMap = flatMap; lodash.flatMapDeep = flatMapDeep; lodash.flatMapDepth = flatMapDepth; lodash.flatten = flatten; lodash.flattenDeep = flattenDeep; lodash.flattenDepth = flattenDepth; lodash.flip = flip; lodash.flow = flow; lodash.flowRight = flowRight; lodash.fromPairs = fromPairs; lodash.functions = functions; lodash.functionsIn = functionsIn; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; lodash.intersectionBy = intersectionBy; lodash.intersectionWith = intersectionWith; lodash.invert = invert; lodash.invertBy = invertBy; lodash.invokeMap = invokeMap; lodash.iteratee = iteratee; lodash.keyBy = keyBy; lodash.keys = keys; lodash.keysIn = keysIn; lodash.map = map; lodash.mapKeys = mapKeys; lodash.mapValues = mapValues; lodash.matches = matches; lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; lodash.mergeWith = mergeWith; lodash.method = method; lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.nthArg = nthArg; lodash.omit = omit; lodash.omitBy = omitBy; lodash.once = once; lodash.orderBy = orderBy; lodash.over = over; lodash.overArgs = overArgs; lodash.overEvery = overEvery; lodash.overSome = overSome; lodash.partial = partial; lodash.partialRight = partialRight; lodash.partition = partition; lodash.pick = pick; lodash.pickBy = pickBy; lodash.property = property; lodash.propertyOf = propertyOf; lodash.pull = pull; lodash.pullAll = pullAll; lodash.pullAllBy = pullAllBy; lodash.pullAllWith = pullAllWith; lodash.pullAt = pullAt; lodash.range = range; lodash.rangeRight = rangeRight; lodash.rearg = rearg; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.reverse = reverse; lodash.sampleSize = sampleSize; lodash.set = set; lodash.setWith = setWith; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; lodash.sortedUniq = sortedUniq; lodash.sortedUniqBy = sortedUniqBy; lodash.split = split; lodash.spread = spread; lodash.tail = tail; lodash.take = take; lodash.takeRight = takeRight; lodash.takeRightWhile = takeRightWhile; lodash.takeWhile = takeWhile; lodash.tap = tap; lodash.throttle = throttle; lodash.thru = thru; lodash.toArray = toArray; lodash.toPairs = toPairs; lodash.toPairsIn = toPairsIn; lodash.toPath = toPath; lodash.toPlainObject = toPlainObject; lodash.transform = transform; lodash.unary = unary; lodash.union = union; lodash.unionBy = unionBy; lodash.unionWith = unionWith; lodash.uniq = uniq; lodash.uniqBy = uniqBy; lodash.uniqWith = uniqWith; lodash.unset = unset; lodash.unzip = unzip; lodash.unzipWith = unzipWith; lodash.update = update; lodash.updateWith = updateWith; lodash.values = values; lodash.valuesIn = valuesIn; lodash.without = without; lodash.words = words; lodash.wrap = wrap; lodash.xor = xor; lodash.xorBy = xorBy; lodash.xorWith = xorWith; lodash.zip = zip; lodash.zipObject = zipObject; lodash.zipObjectDeep = zipObjectDeep; lodash.zipWith = zipWith; // Add aliases. lodash.entries = toPairs; lodash.entriesIn = toPairsIn; lodash.extend = assignIn; lodash.extendWith = assignInWith; // Add methods to `lodash.prototype`. mixin(lodash, lodash); /*------------------------------------------------------------------------*/ // Add methods that return unwrapped values in chain sequences. lodash.add = add; lodash.attempt = attempt; lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.ceil = ceil; lodash.clamp = clamp; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.cloneDeepWith = cloneDeepWith; lodash.cloneWith = cloneWith; lodash.conformsTo = conformsTo; lodash.deburr = deburr; lodash.defaultTo = defaultTo; lodash.divide = divide; lodash.endsWith = endsWith; lodash.eq = eq; lodash.escape = escape; lodash.escapeRegExp = escapeRegExp; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.floor = floor; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.get = get; lodash.gt = gt; lodash.gte = gte; lodash.has = has; lodash.hasIn = hasIn; lodash.head = head; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.inRange = inRange; lodash.invoke = invoke; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isArrayBuffer = isArrayBuffer; lodash.isArrayLike = isArrayLike; lodash.isArrayLikeObject = isArrayLikeObject; lodash.isBoolean = isBoolean; lodash.isBuffer = isBuffer; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isEqualWith = isEqualWith; lodash.isError = isError; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isInteger = isInteger; lodash.isLength = isLength; lodash.isMap = isMap; lodash.isMatch = isMatch; lodash.isMatchWith = isMatchWith; lodash.isNaN = isNaN; lodash.isNative = isNative; lodash.isNil = isNil; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isObjectLike = isObjectLike; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isSafeInteger = isSafeInteger; lodash.isSet = isSet; lodash.isString = isString; lodash.isSymbol = isSymbol; lodash.isTypedArray = isTypedArray; lodash.isUndefined = isUndefined; lodash.isWeakMap = isWeakMap; lodash.isWeakSet = isWeakSet; lodash.join = join; lodash.kebabCase = kebabCase; lodash.last = last; lodash.lastIndexOf = lastIndexOf; lodash.lowerCase = lowerCase; lodash.lowerFirst = lowerFirst; lodash.lt = lt; lodash.lte = lte; lodash.max = max; lodash.maxBy = maxBy; lodash.mean = mean; lodash.meanBy = meanBy; lodash.min = min; lodash.minBy = minBy; lodash.stubArray = stubArray; lodash.stubFalse = stubFalse; lodash.stubObject = stubObject; lodash.stubString = stubString; lodash.stubTrue = stubTrue; lodash.multiply = multiply; lodash.nth = nth; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.pad = pad; lodash.padEnd = padEnd; lodash.padStart = padStart; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.repeat = repeat; lodash.replace = replace; lodash.result = result; lodash.round = round; lodash.runInContext = runInContext; lodash.sample = sample; lodash.size = size; lodash.snakeCase = snakeCase; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.sortedIndexBy = sortedIndexBy; lodash.sortedIndexOf = sortedIndexOf; lodash.sortedLastIndex = sortedLastIndex; lodash.sortedLastIndexBy = sortedLastIndexBy; lodash.sortedLastIndexOf = sortedLastIndexOf; lodash.startCase = startCase; lodash.startsWith = startsWith; lodash.subtract = subtract; lodash.sum = sum; lodash.sumBy = sumBy; lodash.template = template; lodash.times = times; lodash.toFinite = toFinite; lodash.toInteger = toInteger; lodash.toLength = toLength; lodash.toLower = toLower; lodash.toNumber = toNumber; lodash.toSafeInteger = toSafeInteger; lodash.toString = toString; lodash.toUpper = toUpper; lodash.trim = trim; lodash.trimEnd = trimEnd; lodash.trimStart = trimStart; lodash.truncate = truncate; lodash.unescape = unescape; lodash.uniqueId = uniqueId; lodash.upperCase = upperCase; lodash.upperFirst = upperFirst; // Add aliases. lodash.each = forEach; lodash.eachRight = forEachRight; lodash.first = head; mixin(lodash, (function() { var source = {}; baseForOwn(lodash, function(func, methodName) { if (!hasOwnProperty.call(lodash.prototype, methodName)) { source[methodName] = func; } }); return source; }()), { 'chain': false }); /*------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type {string} */ lodash.VERSION = VERSION; // Assign default placeholders. arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { lodash[methodName].placeholder = lodash; }); // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. arrayEach(['drop', 'take'], function(methodName, index) { LazyWrapper.prototype[methodName] = function(n) { n = n === undefined ? 1 : nativeMax(toInteger(n), 0); var result = (this.__filtered__ && !index) ? new LazyWrapper(this) : this.clone(); if (result.__filtered__) { result.__takeCount__ = nativeMin(n, result.__takeCount__); } else { result.__views__.push({ 'size': nativeMin(n, MAX_ARRAY_LENGTH), 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') }); } return result; }; LazyWrapper.prototype[methodName + 'Right'] = function(n) { return this.reverse()[methodName](n).reverse(); }; }); // Add `LazyWrapper` methods that accept an `iteratee` value. arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; LazyWrapper.prototype[methodName] = function(iteratee) { var result = this.clone(); result.__iteratees__.push({ 'iteratee': getIteratee(iteratee, 3), 'type': type }); result.__filtered__ = result.__filtered__ || isFilter; return result; }; }); // Add `LazyWrapper` methods for `_.head` and `_.last`. arrayEach(['head', 'last'], function(methodName, index) { var takeName = 'take' + (index ? 'Right' : ''); LazyWrapper.prototype[methodName] = function() { return this[takeName](1).value()[0]; }; }); // Add `LazyWrapper` methods for `_.initial` and `_.tail`. arrayEach(['initial', 'tail'], function(methodName, index) { var dropName = 'drop' + (index ? '' : 'Right'); LazyWrapper.prototype[methodName] = function() { return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); }; }); LazyWrapper.prototype.compact = function() { return this.filter(identity); }; LazyWrapper.prototype.find = function(predicate) { return this.filter(predicate).head(); }; LazyWrapper.prototype.findLast = function(predicate) { return this.reverse().find(predicate); }; LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { if (typeof path == 'function') { return new LazyWrapper(this); } return this.map(function(value) { return baseInvoke(value, path, args); }); }); LazyWrapper.prototype.reject = function(predicate) { return this.filter(negate(getIteratee(predicate))); }; LazyWrapper.prototype.slice = function(start, end) { start = toInteger(start); var result = this; if (result.__filtered__ && (start > 0 || end < 0)) { return new LazyWrapper(result); } if (start < 0) { result = result.takeRight(-start); } else if (start) { result = result.drop(start); } if (end !== undefined) { end = toInteger(end); result = end < 0 ? result.dropRight(-end) : result.take(end - start); } return result; }; LazyWrapper.prototype.takeRightWhile = function(predicate) { return this.reverse().takeWhile(predicate).reverse(); }; LazyWrapper.prototype.toArray = function() { return this.take(MAX_ARRAY_LENGTH); }; // Add `LazyWrapper` methods to `lodash.prototype`. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], retUnwrapped = isTaker || /^find/.test(methodName); if (!lodashFunc) { return; } lodash.prototype[methodName] = function() { var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); var interceptor = function(value) { var result = lodashFunc.apply(lodash, arrayPush([value], args)); return (isTaker && chainAll) ? result[0] : result; }; if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { // Avoid lazy use if the iteratee has a "length" value other than `1`. isLazy = useLazy = false; } var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; if (!retUnwrapped && useLazy) { value = onlyLazy ? value : new LazyWrapper(this); var result = func.apply(value, args); result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(result, chainAll); } if (isUnwrapped && onlyLazy) { return func.apply(this, args); } result = this.thru(interceptor); return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; }; }); // Add `Array` methods to `lodash.prototype`. arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:pop|shift)$/.test(methodName); lodash.prototype[methodName] = function() { var args = arguments; if (retUnwrapped && !this.__chain__) { var value = this.value(); return func.apply(isArray(value) ? value : [], args); } return this[chainName](function(value) { return func.apply(isArray(value) ? value : [], args); }); }; }); // Map minified method names to their real names. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = lodashFunc.name + ''; if (!hasOwnProperty.call(realNames, key)) { realNames[key] = []; } realNames[key].push({ 'name': methodName, 'func': lodashFunc }); } }); realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }]; // Add methods to `LazyWrapper`. LazyWrapper.prototype.clone = lazyClone; LazyWrapper.prototype.reverse = lazyReverse; LazyWrapper.prototype.value = lazyValue; // Add chain sequence methods to the `lodash` wrapper. lodash.prototype.at = wrapperAt; lodash.prototype.chain = wrapperChain; lodash.prototype.commit = wrapperCommit; lodash.prototype.next = wrapperNext; lodash.prototype.plant = wrapperPlant; lodash.prototype.reverse = wrapperReverse; lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; // Add lazy aliases. lodash.prototype.first = lodash.prototype.head; if (symIterator) { lodash.prototype[symIterator] = wrapperToIterator; } return lodash; }); /*--------------------------------------------------------------------------*/ // Export lodash. var _ = runInContext(); // Some AMD build optimizers, like r.js, check for condition patterns like: if (true) { // Expose Lodash on the global object to prevent errors when Lodash is // loaded by a script tag in the presence of an AMD loader. // See http://requirejs.org/docs/errors.html#mismatch for more details. // Use `_.noConflict` to remove Lodash from the global object. root._ = _; // Define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module. !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return _; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } // Check for `exports` after `define` in case a build optimizer adds it. else {} }.call(this)); /***/ }), /***/ "./resources/css/app.css": /*!*******************************!*\ !*** ./resources/css/app.css ***! \*******************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); // extracted by mini-css-extract-plugin /***/ }), /***/ "./node_modules/process/browser.js": /*!*****************************************!*\ !*** ./node_modules/process/browser.js ***! \*****************************************/ /***/ ((module) => { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /***/ "./node_modules/axios/package.json": /*!*****************************************!*\ !*** ./node_modules/axios/package.json ***! \*****************************************/ /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"_from":"axios@^0.21","_id":"[email protected]","_inBundle":false,"_integrity":"sha512-JtoZ3Ndke/+Iwt5n+BgSli/3idTvpt5OjKyoCmz4LX5+lPiY5l7C1colYezhlxThjNa/NhngCUWZSZFypIFuaA==","_location":"/axios","_phantomChildren":{},"_requested":{"type":"range","registry":true,"raw":"axios@^0.21","name":"axios","escapedName":"axios","rawSpec":"^0.21","saveSpec":null,"fetchSpec":"^0.21"},"_requiredBy":["#DEV:/"],"_resolved":"https://registry.npmjs.org/axios/-/axios-0.21.3.tgz","_shasum":"f85d9b747f9b66d59ca463605cedf1844872b82e","_spec":"axios@^0.21","_where":"C:\\\\Users\\\\pc\\\\Desktop\\\\Restaurant","author":{"name":"Matt Zabriskie"},"browser":{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},"bugs":{"url":"https://github.com/axios/axios/issues"},"bundleDependencies":false,"bundlesize":[{"path":"./dist/axios.min.js","threshold":"5kB"}],"dependencies":{"follow-redirects":"^1.14.0"},"deprecated":false,"description":"Promise based HTTP client for the browser and node.js","devDependencies":{"coveralls":"^3.0.0","es6-promise":"^4.2.4","grunt":"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1","karma":"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2","minimist":"^1.2.0","mocha":"^8.2.1","sinon":"^4.5.0","terser-webpack-plugin":"^4.2.3","typescript":"^4.0.5","url-search-params":"^0.10.0","webpack":"^4.44.2","webpack-dev-server":"^3.11.0"},"homepage":"https://axios-http.com","jsdelivr":"dist/axios.min.js","keywords":["xhr","http","ajax","promise","node"],"license":"MIT","main":"index.js","name":"axios","repository":{"type":"git","url":"git+https://github.com/axios/axios.git"},"scripts":{"build":"NODE_ENV=production grunt build","coveralls":"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js","examples":"node ./examples/server.js","fix":"eslint --fix lib/**/*.js","postversion":"git push && git push --tags","preversion":"npm test","start":"node ./sandbox/server.js","test":"grunt test","version":"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json"},"typings":"./index.d.ts","unpkg":"dist/axios.min.js","version":"0.21.3"}'); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ id: moduleId, /******/ loaded: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = __webpack_modules__; /******/ /************************************************************************/ /******/ /* webpack/runtime/chunk loaded */ /******/ (() => { /******/ var deferred = []; /******/ __webpack_require__.O = (result, chunkIds, fn, priority) => { /******/ if(chunkIds) { /******/ priority = priority || 0; /******/ for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1]; /******/ deferred[i] = [chunkIds, fn, priority]; /******/ return; /******/ } /******/ var notFulfilled = Infinity; /******/ for (var i = 0; i < deferred.length; i++) { /******/ var [chunkIds, fn, priority] = deferred[i]; /******/ var fulfilled = true; /******/ for (var j = 0; j < chunkIds.length; j++) { /******/ if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) { /******/ chunkIds.splice(j--, 1); /******/ } else { /******/ fulfilled = false; /******/ if(priority < notFulfilled) notFulfilled = priority; /******/ } /******/ } /******/ if(fulfilled) { /******/ deferred.splice(i--, 1) /******/ var r = fn(); /******/ if (r !== undefined) result = r; /******/ } /******/ } /******/ return result; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/global */ /******/ (() => { /******/ __webpack_require__.g = (function() { /******/ if (typeof globalThis === 'object') return globalThis; /******/ try { /******/ return this || new Function('return this')(); /******/ } catch (e) { /******/ if (typeof window === 'object') return window; /******/ } /******/ })(); /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/node module decorator */ /******/ (() => { /******/ __webpack_require__.nmd = (module) => { /******/ module.paths = []; /******/ if (!module.children) module.children = []; /******/ return module; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/jsonp chunk loading */ /******/ (() => { /******/ // no baseURI /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ "/js/app": 0, /******/ "css/app": 0 /******/ }; /******/ /******/ // no chunk on demand loading /******/ /******/ // no prefetching /******/ /******/ // no preloaded /******/ /******/ // no HMR /******/ /******/ // no HMR manifest /******/ /******/ __webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0); /******/ /******/ // install a JSONP callback for chunk loading /******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => { /******/ var [chunkIds, moreModules, runtime] = data; /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0; /******/ if(chunkIds.some((id) => (installedChunks[id] !== 0))) { /******/ for(moduleId in moreModules) { /******/ if(__webpack_require__.o(moreModules, moduleId)) { /******/ __webpack_require__.m[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(runtime) var result = runtime(__webpack_require__); /******/ } /******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data); /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { /******/ installedChunks[chunkId][0](); /******/ } /******/ installedChunks[chunkIds[i]] = 0; /******/ } /******/ return __webpack_require__.O(result); /******/ } /******/ /******/ var chunkLoadingGlobal = self["webpackChunk"] = self["webpackChunk"] || []; /******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0)); /******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal)); /******/ })(); /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module depends on other loaded chunks and execution need to be delayed /******/ __webpack_require__.O(undefined, ["css/app"], () => (__webpack_require__("./resources/js/app.js"))) /******/ var __webpack_exports__ = __webpack_require__.O(undefined, ["css/app"], () => (__webpack_require__("./resources/css/app.css"))) /******/ __webpack_exports__ = __webpack_require__.O(__webpack_exports__); /******/ /******/ })() ;
/* eslint-env jest */ import React from 'react' import CloseButton from '../CloseButton' import { mockIntl } from '../../../../test/__mocks__/react-intl' import { mountWithIntl } from '../../../../test/helpers/intl-enzyme-test-helper.js' import { initIcons } from '../../ui/icons' const onClick = jest.fn() describe('CloseButton', () => { beforeAll(() => { initIcons() }) it('should renders without crashing', () => { const wrapper = mountWithIntl(<CloseButton onClick={onClick} />) expect(wrapper.find('button').length).toEqual(1) }) it('should set title attribute', () => { const wrapper = mountWithIntl(<CloseButton onClick={onClick} title={mockIntl.formatMessage({ id: 'gallery.delete-street-tooltip', defaultMessage: 'Delete street' })} />) expect(wrapper.find('button').instance().getAttribute('title')).toEqual('Delete street') }) it('should set className', () => { const wrapper = mountWithIntl(<CloseButton onClick={onClick} className="hide-btn" />) expect(wrapper.find('button').hasClass('hide-btn')).toEqual(true) }) it('should call onClick function when button is clicked', () => { const wrapper = mountWithIntl(<CloseButton onClick={onClick} />) wrapper.find('button').simulate('click') expect(onClick).toBeCalled() }) })
import React from 'react'; export default function Map(){ return( <div className="col-lg-6 map"> <iframe src="https://www.google.com/maps/embed?pb=!1m23!1m12!1m3!1d127052.55163192659!2d-0.27637432927504807!3d5.6562688855568135!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!4m8!3e6!4m0!4m5!1s0xfdf9f753c779a8f%3A0x714bb4bd8453e233!2sGreater%20Accra%20Region!3m2!1d5.6860408!2d-0.2816745!5e0!3m2!1sen!2sgh!4v1592427265627!5m2!1sen!2sgh" className="w-100 h-100" frameBorder="0" style={{border:0}} allowFullScreen="" aria-hidden="false" title="map"></iframe> </div> ); }
'use strict'; var ByteBuffer = require('bytebuffer'); var constants = require('../helpers/constants.js'); // Private fields var modules, library; // Constructor function Signature () {} Signature.prototype.bind = function (scope) { modules = scope.modules; library = scope.library; }; Signature.prototype.create = function (data, trs) { trs.recipientId = null; trs.amount = 0; trs.asset.signature = { publicKey: data.secondKeypair.publicKey.toString('hex') }; return trs; }; Signature.prototype.calculateFee = function (trs, sender) { return constants.fees.secondsignature; }; Signature.prototype.verify = function (trs, sender, cb) { if (!trs.asset || !trs.asset.signature) { return setImmediate(cb, 'Invalid transaction asset'); } if (trs.amount !== 0) { return setImmediate(cb, 'Invalid transaction amount'); } try { if (!trs.asset.signature.publicKey || new Buffer(trs.asset.signature.publicKey, 'hex').length !== 32) { return setImmediate(cb, 'Invalid public key'); } } catch (e) { library.logger.error(e.stack); return setImmediate(cb, 'Invalid public key'); } return setImmediate(cb, null, trs); }; Signature.prototype.process = function (trs, sender, cb) { return setImmediate(cb, null, trs); }; Signature.prototype.getBytes = function (trs) { var bb; try { bb = new ByteBuffer(32, true); var publicKeyBuffer = new Buffer(trs.asset.signature.publicKey, 'hex'); for (var i = 0; i < publicKeyBuffer.length; i++) { bb.writeByte(publicKeyBuffer[i]); } bb.flip(); } catch (e) { throw e; } return bb.toBuffer(); }; Signature.prototype.apply = function (trs, block, sender, cb) { modules.accounts.setAccountAndGet({ address: sender.address, secondSignature: 1, u_secondSignature: 0, secondPublicKey: trs.asset.signature.publicKey }, cb); }; Signature.prototype.undo = function (trs, block, sender, cb) { modules.accounts.setAccountAndGet({ address: sender.address, secondSignature: 0, u_secondSignature: 1, secondPublicKey: null }, cb); }; Signature.prototype.applyUnconfirmed = function (trs, sender, cb) { if (sender.u_secondSignature || sender.secondSignature) { return setImmediate(cb, 'Second signature already enabled'); } modules.accounts.setAccountAndGet({address: sender.address, u_secondSignature: 1}, cb); }; Signature.prototype.undoUnconfirmed = function (trs, sender, cb) { modules.accounts.setAccountAndGet({address: sender.address, u_secondSignature: 0}, cb); }; Signature.prototype.schema = { id: 'Signature', object: true, properties: { publicKey: { type: 'string', format: 'publicKey' } }, required: ['publicKey'] }; Signature.prototype.objectNormalize = function (trs) { var report = library.schema.validate(trs.asset.signature, Signature.prototype.schema); if (!report) { throw 'Failed to validate signature schema: ' + this.scope.schema.getLastErrors().map(function (err) { return err.message; }).join(', '); } return trs; }; Signature.prototype.dbRead = function (raw) { if (!raw.s_publicKey) { return null; } else { var signature = { transactionId: raw.t_id, publicKey: raw.s_publicKey }; return {signature: signature}; } }; Signature.prototype.dbTable = 'signatures'; Signature.prototype.dbFields = [ 'transactionId', 'publicKey' ]; Signature.prototype.dbSave = function (trs) { var publicKey; try { publicKey = new Buffer(trs.asset.signature.publicKey, 'hex'); } catch (e) { throw e; } return { table: this.dbTable, fields: this.dbFields, values: { transactionId: trs.id, publicKey: publicKey } }; }; Signature.prototype.ready = function (trs, sender) { if (Array.isArray(sender.multisignatures) && sender.multisignatures.length) { if (!Array.isArray(trs.signatures)) { return false; } return trs.signatures.length >= sender.multimin; } else { return true; } }; // Export module.exports = Signature;
import datetime as dt start = dt.datetime(2016, 12, 8, 0) end = dt.datetime(2016, 12, 18, 0) valid = dt.datetime(2016, 12, 18, 0) # FIXME: set an appropriate output path (target parameter) request = """ retrieve, class=od, stream=enfo, expver=1, type=pf, grid=1.0/1.0, number=1/TO/50, area=90/-180/0/180, levtype=pl, levelist=10/50/100/200/250/300/400/500/700/850/925/1000, param=130.128/131/132, date={init:%Y-%m-%d}, time={init:%H}:00:00, step={step}, target="FIXME/ENS-DEC18-EVAL-{init:%Y-%m-%dT%HZ}.grb" """.format init = start while init <= end: # Only need data for specified valid time step = int((valid-init).total_seconds() / 60 / 60) # Write MARS request with open("request-eval-{:%Y-%m-%dT%HZ}".format(init), "w") as f: f.write(request(init=init, step=step).lstrip()) # Next forecast init = init + dt.timedelta(hours=12)
(function(d){ const l = d['th'] = d['th'] || {}; l.dictionary=Object.assign( l.dictionary||{}, {"%0 of %1":"","Align cell text to the bottom":"","Align cell text to the center":"","Align cell text to the left":"","Align cell text to the middle":"","Align cell text to the right":"","Align cell text to the top":"","Align table to the left":"","Align table to the right":"",Alignment:"",Aquamarine:"พลอยสีฟ้า",Background:"",Big:"ใหญ่",Black:"สีดำ","Block quote":"คำพูดบล็อก",Blue:"สีน้ำเงิน",Border:"",Cancel:"ยกเลิก","Cannot upload file:":"ไม่สามารถอัปโหลดไฟล์ได้:","Cell properties":"","Center table":"","Centered image":"จัดแนวรูปกึ่งกลาง","Change image text alternative":"เปลี่ยนข้อความเมื่อไม่พบรูป","Choose heading":"เลือกขนาดหัวข้อ",Color:"","Color picker":"",Column:"คอลัมน์",Dashed:"","Decrease indent":"ลดการเยื้อง",Default:"ค่าเริ่มต้น","Delete column":"ลบคอลัมน์","Delete row":"ลบแถว","Dim grey":"สีเทาเข้ม",Dimensions:"","Document colors":"สีเอกสาร",Dotted:"",Double:"","Dropdown toolbar":"","Editor toolbar":"","Enter image caption":"ระบุคำอธิบายภาพ","Font Background Color":"สีพื้นหลังข้อความ","Font Color":"สีข้อความ","Font Family":"แบบอักษร","Font Size":"ขนาดข้อความ","Full size image":"รูปขนาดเต็ม",Green:"สีเขียว",Grey:"สีเทา",Groove:"","Header column":"หัวข้อคอลัมน์","Header row":"ส่วนหัวแถว",Heading:"หัวข้อ","Heading 1":"หัวข้อขนาด 1","Heading 2":"","Heading 3":"","Heading 4":"","Heading 5":"","Heading 6":"",Height:"","Horizontal line":"เส้นแนวนอน","Horizontal text alignment toolbar":"",Huge:"ใหญ่มาก","Image toolbar":"เครื่องมือรูปภาพ","image widget":"วิดเจ็ตรูปภาพ","Increase indent":"เพิ่มการเยื้อง","Insert column left":"แทรกคอลัมน์ทางซ้าย","Insert column right":"แทรกคอลัมน์ทางขวา","Insert image":"แทรกรูป","Insert paragraph after block":"","Insert paragraph before block":"","Insert row above":"แทรกส่วนหัวด้านบน","Insert row below":"แทรกส่วนหัวด้านล่าง","Insert table":"แทรกตาราง",Inset:"","Justify cell text":"","Left aligned image":"จัดแนวภาพซ้าย","Light blue":"สีฟ้า","Light green":"สีเขียวอ่อน","Light grey":"สีเทาอ่อน","Merge cell down":"ผสานเซลล์ด้านล่าง","Merge cell left":"ผสานเซลล์ด้านซ้าย","Merge cell right":"ผสานเซลล์ด้านขวา","Merge cell up":"ผสานเซลล์ด้านบน","Merge cells":"ผสานเซลล์",Next:"",None:"",Orange:"สีส้ม",Outset:"",Padding:"","Page break":"ตัวแบ่งหน้า",Paragraph:"ย่อหน้า",Previous:"",Purple:"สีม่วง",Red:"สีแดง",Redo:"ทำซ้ำ","Remove color":"ลบสี","Remove Format":"ลบรูปแบบ","Rich Text Editor":"","Rich Text Editor, %0":"",Ridge:"","Right aligned image":"จัดแนวภาพขวา",Row:"แถว",Save:"บันทึก","Saving changes":"บันทึกการเปลี่ยนแปลง<br>","Select column":"","Select row":"","Show more items":"","Side image":"รูปด้านข้าง",Small:"เล็ก",Solid:"","Split cell horizontally":"แยกเซลล์แนวนอน","Split cell vertically":"แยกเซลล์แนวตั้ง",Style:"","Table alignment toolbar":"","Table cell text alignment":"","Table properties":"","Table toolbar":"เครื่องมือตาราง","Text alternative":"ข้อความเมื่อไม่พบรูป","The color is invalid. Try \"#FF0000\" or \"rgb(255,0,0)\" or \"red\".":"","The value is invalid. Try \"10px\" or \"2em\" or simply \"2\".":"",Tiny:"เล็กมาก",Turquoise:"สีเขียวขุ่น",Undo:"ย้อนกลับ","Upload failed":"อัปโหลดไม่สำเร็จ","Upload in progress":"กำลังดำเนินการอัปโหลด","Vertical text alignment toolbar":"",White:"สีขาว","Widget toolbar":"แถมเครื่องมือวิดเจ็ต",Width:"",Yellow:"สีเหลือง"} );l.getPluralForm=function(n){return 0;;};})(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
# coding=utf-8 # Copyright 2020 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. """An implementation of Prioritized Experience Replay (PER). This implementation is based on the paper "Prioritized Experience Replay" by Tom Schaul et al. (2015). Many thanks to Tom Schaul, John Quan, and Matteo Hessel for providing useful pointers on the algorithm and its implementation. """ from dopamine.replay_memory import sum_tree import gin import numpy as np import tensorflow.compat.v1 as tf from experience_replay.replay_memory import circular_replay_buffer from experience_replay.replay_memory.circular_replay_buffer import ReplayElement class OutOfGraphPrioritizedReplayBuffer( circular_replay_buffer.OutOfGraphReplayBuffer): """An out-of-graph Replay Buffer for Prioritized Experience Replay. See circular_replay_buffer.py for details. """ def __init__(self, observation_shape, stack_size, replay_capacity, batch_size, update_horizon=1, gamma=0.99, max_sample_attempts=1000, extra_storage_types=None, observation_dtype=np.uint8, terminal_dtype=np.uint8, action_shape=(), action_dtype=np.int32, reward_shape=(), reward_dtype=np.float32, replay_forgetting='default', sample_newest_immediately=False): """Initializes OutOfGraphPrioritizedReplayBuffer. Args: observation_shape: tuple of ints. stack_size: int, number of frames to use in state stack. replay_capacity: int, number of transitions to keep in memory. batch_size: int. update_horizon: int, length of update ('n' in n-step update). gamma: int, the discount factor. max_sample_attempts: int, the maximum number of attempts allowed to get a sample. extra_storage_types: list of ReplayElements defining the type of the extra contents that will be stored and returned by sample_transition_batch. observation_dtype: np.dtype, type of the observations. Defaults to np.uint8 for Atari 2600. terminal_dtype: np.dtype, type of the terminals. Defaults to np.uint8 for Atari 2600. action_shape: tuple of ints, the shape for the action vector. Empty tuple means the action is a scalar. action_dtype: np.dtype, type of elements in the action. reward_shape: tuple of ints, the shape of the reward vector. Empty tuple means the reward is a scalar. reward_dtype: np.dtype, type of elements in the reward. replay_forgetting: str, What strategy to employ for forgetting old trajectories. One of ['default', 'elephant']. sample_newest_immediately: bool, when True, immediately trains on the newest transition instead of using the max_priority hack. """ super(OutOfGraphPrioritizedReplayBuffer, self).__init__( observation_shape=observation_shape, stack_size=stack_size, replay_capacity=replay_capacity, batch_size=batch_size, update_horizon=update_horizon, gamma=gamma, max_sample_attempts=max_sample_attempts, extra_storage_types=extra_storage_types, observation_dtype=observation_dtype, terminal_dtype=terminal_dtype, action_shape=action_shape, action_dtype=action_dtype, reward_shape=reward_shape, reward_dtype=reward_dtype, replay_forgetting=replay_forgetting) tf.logging.info('\t replay_forgetting: %s', replay_forgetting) self.sum_tree = sum_tree.SumTree(replay_capacity) self._sample_newest_immediately = sample_newest_immediately def get_add_args_signature(self): """The signature of the add function. The signature is the same as the one for OutOfGraphReplayBuffer, with an added priority. Returns: list of ReplayElements defining the type of the argument signature needed by the add function. """ parent_add_signature = super(OutOfGraphPrioritizedReplayBuffer, self).get_add_args_signature() add_signature = parent_add_signature + [ ReplayElement('priority', (), np.float32) ] return add_signature def _add(self, *args): """Internal add method to add to the underlying memory arrays. The arguments need to match add_arg_signature. If priority is none, it is set to the maximum priority ever seen. Args: *args: All the elements in a transition. """ self._check_args_length(*args) # Use Schaul et al.'s (2015) scheme of setting the priority of new elements # to the maximum priority so far. # Picks out 'priority' from arguments and adds it to the sum_tree. transition = {} for i, element in enumerate(self.get_add_args_signature()): if element.name == 'priority': if (self._sample_newest_immediately and self.add_count > self._stack_size): # add_count needs to be above stack_size because otherwise the first # transition added to the buffer has priority 0, which means the # sum_tree has a total_priority of 0, and thus it cannot sample. priority = 0.0 else: priority = args[i] else: transition[element.name] = args[i] self.sum_tree.set(self.cursor(), priority) super(OutOfGraphPrioritizedReplayBuffer, self)._add_transition(transition) def sample_index_batch(self, batch_size): """Returns a batch of valid indices sampled as in Schaul et al. (2015). Args: batch_size: int, number of indices returned. Returns: list of ints, a batch of valid indices sampled uniformly. Raises: Exception: If the batch was not constructed after maximum number of tries. """ manually_sample_newest = False if self._sample_newest_immediately: # self.cursor() points to the next hole to fill, so need to back up to the # the transition that has now accumulated enough data in terms of n-step # horizon for the purpose of training. newest_transition_index = self.cursor() - (self._update_horizon + 1) # Cannot sample newest if either there are not enough transitions in the # buffer or these are empty frames used for context at the start of the # episode. if self.is_valid_transition(newest_transition_index): # Sample N - 1 indices and append the newest transition. manually_sample_newest = True batch_size -= 1 # Sample stratified indices. Some of them might be invalid. indices = self.sum_tree.stratified_sample(batch_size) allowed_attempts = self._max_sample_attempts for i in range(len(indices)): if not self.is_valid_transition(indices[i]): if allowed_attempts == 0: raise RuntimeError( 'Max sample attempts: Tried {} times but only sampled {}' ' valid indices. Batch size is {}'. format(self._max_sample_attempts, i, batch_size)) index = indices[i] while not self.is_valid_transition(index) and allowed_attempts > 0: # If index i is not valid keep sampling others. Note that this # is not stratified. index = self.sum_tree.sample() allowed_attempts -= 1 indices[i] = index if manually_sample_newest: indices.append(newest_transition_index) return indices def sample_transition_batch(self, batch_size=None, indices=None): """Returns a batch of transitions with extra storage and the priorities. The extra storage are defined through the extra_storage_types constructor argument. When the transition is terminal next_state_batch has undefined contents. Args: batch_size: int, number of transitions returned. If None, the default batch_size will be used. indices: None or list of ints, the indices of every transition in the batch. If None, sample the indices uniformly. Returns: transition_batch: tuple of np.arrays with the shape and type as in get_transition_elements(). """ transition = (super(OutOfGraphPrioritizedReplayBuffer, self). sample_transition_batch(batch_size, indices)) transition_elements = self.get_transition_elements(batch_size) transition_names = [e.name for e in transition_elements] probabilities_index = transition_names.index('sampling_probabilities') indices_index = transition_names.index('indices') indices = transition[indices_index] # The parent returned an empty array for the probabilities. Fill it with the # contents of the sum tree. transition[probabilities_index][:] = self.get_priority(indices) return transition def set_priority(self, indices, priorities): """Sets the priority of the given elements according to Schaul et al. Args: indices: np.array with dtype int32, of indices in range [0, replay_capacity). priorities: float, the corresponding priorities. """ assert indices.dtype == np.int32, ('Indices must be integers, ' 'given: {}'.format(indices.dtype)) for index, priority in zip(indices, priorities): self.sum_tree.set(index, priority) def get_priority(self, indices): """Fetches the priorities correspond to a batch of memory indices. For any memory location not yet used, the corresponding priority is 0. Args: indices: np.array with dtype int32, of indices in range [0, replay_capacity). Returns: priorities: float, the corresponding priorities. """ assert indices.shape, 'Indices must be an array.' assert indices.dtype == np.int32, ('Indices must be int32s, ' 'given: {}'.format(indices.dtype)) batch_size = len(indices) priority_batch = np.empty((batch_size), dtype=np.float32) for i, memory_index in enumerate(indices): priority_batch[i] = self.sum_tree.get(memory_index) return priority_batch def get_transition_elements(self, batch_size=None): """Returns a 'type signature' for sample_transition_batch. Args: batch_size: int, number of transitions returned. If None, the default batch_size will be used. Returns: signature: A namedtuple describing the method's return type signature. """ parent_transition_type = ( super(OutOfGraphPrioritizedReplayBuffer, self).get_transition_elements(batch_size)) probablilities_type = [ ReplayElement('sampling_probabilities', (batch_size,), np.float32) ] return parent_transition_type + probablilities_type @gin.configurable(blacklist=['observation_shape', 'stack_size', 'update_horizon', 'gamma']) class WrappedPrioritizedReplayBuffer( circular_replay_buffer.WrappedReplayBuffer): """Wrapper of OutOfGraphPrioritizedReplayBuffer with in-graph sampling. Usage: * To add a transition: Call the add function. * To sample a batch: Query any of the tensors in the transition dictionary. Every sess.run that requires any of these tensors will sample a new transition. """ def __init__(self, observation_shape, stack_size, use_staging=True, replay_capacity=1000000, batch_size=32, update_horizon=1, gamma=0.99, max_sample_attempts=1000, extra_storage_types=None, observation_dtype=np.uint8, terminal_dtype=np.uint8, action_shape=(), action_dtype=np.int32, reward_shape=(), reward_dtype=np.float32, replay_forgetting='default', sample_newest_immediately=False): """Initializes WrappedPrioritizedReplayBuffer. Args: observation_shape: tuple of ints. stack_size: int, number of frames to use in state stack. use_staging: bool, when True it would use a staging area to prefetch the next sampling batch. replay_capacity: int, number of transitions to keep in memory. batch_size: int. update_horizon: int, length of update ('n' in n-step update). gamma: int, the discount factor. max_sample_attempts: int, the maximum number of attempts allowed to get a sample. extra_storage_types: list of ReplayElements defining the type of the extra contents that will be stored and returned by sample_transition_batch. observation_dtype: np.dtype, type of the observations. Defaults to np.uint8 for Atari 2600. terminal_dtype: np.dtype, type of the terminals. Defaults to np.uint8 for Atari 2600. action_shape: tuple of ints, the shape for the action vector. Empty tuple means the action is a scalar. action_dtype: np.dtype, type of elements in the action. reward_shape: tuple of ints, the shape of the reward vector. Empty tuple means the reward is a scalar. reward_dtype: np.dtype, type of elements in the reward. replay_forgetting: str, What strategy to employ for forgetting old trajectories. One of ['default', 'elephant']. sample_newest_immediately: bool, whether to sample a new transition immediately for training. Raises: ValueError: If update_horizon is not positive. ValueError: If discount factor is not in [0, 1]. """ memory = OutOfGraphPrioritizedReplayBuffer( observation_shape, stack_size, replay_capacity, batch_size, update_horizon, gamma, max_sample_attempts, extra_storage_types=extra_storage_types, observation_dtype=observation_dtype, replay_forgetting=replay_forgetting, sample_newest_immediately=sample_newest_immediately) super(WrappedPrioritizedReplayBuffer, self).__init__( observation_shape, stack_size, use_staging, replay_capacity, batch_size, update_horizon, gamma, wrapped_memory=memory, extra_storage_types=extra_storage_types, observation_dtype=observation_dtype, terminal_dtype=terminal_dtype, action_shape=action_shape, action_dtype=action_dtype, reward_shape=reward_shape, reward_dtype=reward_dtype, replay_forgetting=replay_forgetting) tf.logging.info('\t replay_forgetting: %s', replay_forgetting) def tf_set_priority(self, indices, priorities): """Sets the priorities for the given indices. Args: indices: tf.Tensor with dtype int32 and shape [n]. priorities: tf.Tensor with dtype float and shape [n]. Returns: A tf op setting the priorities for prioritized sampling. """ return tf.py_func( self.memory.set_priority, [indices, priorities], [], name='prioritized_replay_set_priority_py_func') def tf_get_priority(self, indices): """Gets the priorities for the given indices. Args: indices: tf.Tensor with dtype int32 and shape [n]. Returns: priorities: tf.Tensor with dtype float and shape [n], the priorities at the indices. """ return tf.py_func( self.memory.get_priority, [indices], tf.float32, name='prioritized_replay_get_priority_py_func')
console.log("mod3.js");
# -*- coding: utf-8 -*- from setuptools import setup, find_packages, Extension from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='socketextra', version='0.0.3', description='sendmsg etc. for Python2 (not needed for Py3)', long_description=long_description, url='https://github.com/Bluehorn/socketextra', author='Torsten Landschoff', author_email='[email protected]', license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: System :: Networking', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], keywords='socket sendmsg recvmsg', packages=find_packages(exclude=['contrib', 'docs', 'tests*']), install_requires=[], extras_require={}, ext_modules=[Extension('socketextra._socketextra', ["socketextra/_socketextra.c"])], )
/* ************************************************************************************************* * * * Plese read the following tutorial before implementing tasks: * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration * * * ************************************************************************************************ */ /** * Returns the 'Fizz','Buzz' or an original number using the following rules: * 1) return original number * 2) but if number multiples of three return 'Fizz' * 3) for the multiples of five return 'Buzz' * 4) for numbers which are multiples of both three and five return 'FizzBuzz' * * @param {number} num * @return {any} * * @example * 2 => 2 * 3 => 'Fizz' * 5 => 'Buzz' * 4 => 4 * 15 => 'FizzBuzz' * 20 => 'Buzz' * 21 => 'Fizz' * */ function getFizzBuzz(/* num */) { throw new Error('Not implemented'); } /** * Returns the factorial of the specified integer n. * * @param {number} n * @return {number} * * @example: * 1 => 1 * 5 => 120 * 10 => 3628800 */ function getFactorial(n) { let res = 1; for (let i = 1; i <= n; i += 1) { res *= i; } return res; } /** * Returns the sum of integer numbers between n1 and n2 (inclusive). * * @param {number} n1 * @param {number} n2 * @return {number} * * @example: * 1,2 => 3 ( = 1+2 ) * 5,10 => 45 ( = 5+6+7+8+9+10 ) * -1,1 => 0 ( = -1 + 0 + 1 ) */ function getSumBetweenNumbers(n1, n2) { let res = 0; for (let i = n1; i <= n2; i += 1) { res += i; } return res; } /** * Returns true, if a triangle can be built with the specified sides a, b, c * and false in any other ways. * * @param {number} a * @param {number} b * @param {number} c * @return {bool} * * @example: * 1,2,3 => false * 3,4,5 => true * 10,1,1 => false * 10,10,10 => true */ function isTriangle(a, b, c) { if (a + b > c && a + c > b && c + b > a) { return true; } return false; } /** * Returns true, if two specified axis-aligned rectangles overlap, otherwise false. * Each rectangle representing by object * { * top: 5, * left: 5, * width: 20, * height: 10 * } * * (5;5) * ------------- * | | * | | height = 10 * ------------- * width=20 * * NOTE: Please use canvas coordinate space (https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes#The_grid), * it differs from Cartesian coordinate system. * * @param {object} rect1 * @param {object} rect2 * @return {bool} * * @example: * { top: 0, left: 0, width: 10, height: 10 }, * { top: 5, left: 5, width: 20, height: 20 } => true * * { top: 0, left: 0, width: 10, height: 10 }, * { top:20, left:20, width: 20, height: 20 } => false * */ function doRectanglesOverlap(/* rect1, rect2 */) { throw new Error('Not implemented'); } /** * Returns true, if point lies inside the circle, otherwise false. * Circle is an object of * { * center: { * x: 5, * y: 5 * }, * radius: 20 * } * * Point is object of * { * x: 5, * y: 5 * } * * @param {object} circle * @param {object} point * @return {bool} * * @example: * { center: { x:0, y:0 }, radius:10 }, { x:0, y:0 } => true * { center: { x:0, y:0 }, radius:10 }, { x:10, y:10 } => false * */ function isInsideCircle(/* circle, point */) { throw new Error('Not implemented'); } /** * Returns the first non repeated char in the specified strings otherwise returns null. * * @param {string} str * @return {string} * * @example: * 'The quick brown fox jumps over the lazy dog' => 'T' * 'abracadabra' => 'c' * 'entente' => null */ function findFirstSingleChar(str) { let string = str; for (let i = 0; i < string.length; i += 1) { for (let j = i + 1; j < string.length; j += 1) { if (string[i] === string[j]) { const arr = string.split(''); const letter = string[i]; const arrWithoutDuplicetes = arr.filter((item) => item !== letter); string = arrWithoutDuplicetes.join(''); i = -1; break; } } } if (string.length === 0) { return null; } return string[0]; } /** * Returns the string representation of math interval, * specified by two points and include / exclude flags. * See the details: https://en.wikipedia.org/wiki/Interval_(mathematics) * * Please take attention, that the smaller number should be the first in the notation * * @param {number} a * @param {number} b * @param {bool} isStartIncluded * @param {bool} isEndIncluded * @return {string} * * @example * 0, 1, true, true => '[0, 1]' * 0, 1, true, false => '[0, 1)' * 0, 1, false, true => '(0, 1]' * 0, 1, false, false => '(0, 1)' * Smaller number has to be first : * 5, 3, true, true => '[3, 5]' * */ function getIntervalString(a, b, isStartIncluded, isEndIncluded) { let firstNumber; let secondNumber; let leftBracket = '('; let rightBracket = ')'; if (a < b) { firstNumber = a; secondNumber = b; } else { firstNumber = b; secondNumber = a; } if (isStartIncluded) { leftBracket = '['; } if (isEndIncluded) { rightBracket = ']'; } return `${leftBracket}${firstNumber}, ${secondNumber}${rightBracket}`; } /** * Reverse the specified string (put all chars in reverse order) * * @param {string} str * @return {string} * * @example: * 'The quick brown fox jumps over the lazy dog' => 'god yzal eht revo spmuj xof nworb kciuq ehT' * 'abracadabra' => 'arbadacarba' * 'rotator' => 'rotator' * 'noon' => 'noon' */ function reverseString(str) { return str.split('').reverse().join(''); } /** * Reverse the specified integer number (put all digits in reverse order) * * @param {number} num * @return {number} * * @example: * 12345 => 54321 * 1111 => 1111 * 87354 => 45378 * 34143 => 34143 */ function reverseInteger(num) { return String(num).split('').reverse().join(''); } /** * Validates the CCN (credit card number) and return true if CCN is valid * and false otherwise. * * See algorithm here : https://en.wikipedia.org/wiki/Luhn_algorithm * * @param {number} cnn * @return {boolean} * * @example: * 79927398713 => true * 4012888888881881 => true * 5123456789012346 => true * 378282246310005 => true * 371449635398431 => true * * 4571234567890111 => false * 5436468789016589 => false * 4916123456789012 => false */ function isCreditCardNumber(/* ccn */) { throw new Error('Not implemented'); } /** * Returns the digital root of integer: * step1 : find sum of all digits * step2 : if sum > 9 then goto step1 otherwise return the sum * * @param {number} n * @return {number} * * @example: * 12345 ( 1+2+3+4+5 = 15, 1+5 = 6) => 6 * 23456 ( 2+3+4+5+6 = 20, 2+0 = 2) => 2 * 10000 ( 1+0+0+0+0 = 1 ) => 1 * 165536 (1+6+5+5+3+6 = 26, 2+6 = 8) => 8 */ function getDigitalRoot(num) { let arr = String(num).split(''); while (arr.length !== 1) { const sum = arr.reduce((acc, item) => acc + Number(item), 0); arr = String(sum).split(''); } return arr[0]; } /** * Returns true if the specified string has the balanced brackets and false otherwise. * Balanced means that is, whether it consists entirely of pairs of opening/closing brackets * (in that order), none of which mis-nest. * Brackets include [],(),{},<> * * @param {string} str * @return {boolean} * * @example: * '' => true * '[]' => true * '{}' => true * '() => true * '[[]' => false * '][' => false * '[[][][[]]]' => true * '[[][]][' => false * '{)' = false * '{[(<{[]}>)]}' = true */ function isBracketsBalanced(/* str */) { throw new Error('Not implemented'); } /** * Returns the string with n-ary (binary, ternary, etc, where n <= 10) * representation of specified number. * See more about * https://en.wikipedia.org/wiki/Binary_number * https://en.wikipedia.org/wiki/Ternary_numeral_system * https://en.wikipedia.org/wiki/Radix * * @param {number} num * @param {number} n, radix of the result * @return {string} * * @example: * 1024, 2 => '10000000000' * 6561, 3 => '100000000' * 365, 2 => '101101101' * 365, 3 => '111112' * 365, 4 => '11231' * 365, 10 => '365' */ function toNaryString(num, n) { const res = num.toString(n); return res; } /** * Returns the commom directory path for specified array of full filenames. * * @param {array} pathes * @return {string} * * @example: * ['/web/images/image1.png', '/web/images/image2.png'] => '/web/images/' * ['/web/assets/style.css', '/web/scripts/app.js', 'home/setting.conf'] => '' * ['/web/assets/style.css', '/.bin/mocha', '/read.me'] => '/' * ['/web/favicon.ico', '/web-scripts/dump', '/webalizer/logs'] => '/' */ function getCommonDirectoryPath(/* pathes */) { throw new Error('Not implemented'); } /** * Returns the product of two specified matrixes. * See details: https://en.wikipedia.org/wiki/Matrix_multiplication * * @param {array} m1 * @param {array} m2 * @return {array} * * @example: * [[ 1, 0, 0 ], [[ 1, 2, 3 ], [[ 1, 2, 3 ], * [ 0, 1, 0 ], X [ 4, 5, 6 ], => [ 4, 5, 6 ], * [ 0, 0, 1 ]] [ 7, 8, 9 ]] [ 7, 8, 9 ]] * * [[ 4 ], * [[ 1, 2, 3]] X [ 5 ], => [[ 32 ]] * [ 6 ]] * */ function getMatrixProduct(/* m1, m2 */) { throw new Error('Not implemented'); } /** * Returns the evaluation of the specified tic-tac-toe position. * See the details: https://en.wikipedia.org/wiki/Tic-tac-toe * * Position is provides as 3x3 array with the following values: 'X','0', undefined * Function should return who is winner in the current position according to the game rules. * The result can be: 'X','0',undefined * * @param {array} position * @return {string} * * @example * * [[ 'X', ,'0' ], * [ ,'X','0' ], => 'X' * [ , ,'X' ]] * * [[ '0','0','0' ], * [ ,'X', ], => '0' * [ 'X', ,'X' ]] * * [[ '0','X','0' ], * [ ,'X', ], => undefined * [ 'X','0','X' ]] * * [[ , , ], * [ , , ], => undefined * [ , , ]] * */ function evaluateTicTacToePosition(/* position */) { throw new Error('Not implemented'); } module.exports = { getFizzBuzz, getFactorial, getSumBetweenNumbers, isTriangle, doRectanglesOverlap, isInsideCircle, findFirstSingleChar, getIntervalString, reverseString, reverseInteger, isCreditCardNumber, getDigitalRoot, isBracketsBalanced, toNaryString, getCommonDirectoryPath, getMatrixProduct, evaluateTicTacToePosition, };
import React, { useEffect, useRef } from 'react'; import { useRouteMatch } from 'react-router-dom'; import * as Yup from 'yup'; import { toast } from 'react-toastify'; import * as HV from '~/components/HeaderView'; import { SelectAsync } from '~/components/Form/Selects'; import api from '~/services/api'; import history from '~/services/history'; import { atLeastTwoNames, validCep } from '~/util/regex'; import ufConversor from '~/util/ufConversor'; import { options } from './selectContent'; import * as S from './styles'; export default function Form() { const formRef = useRef(null); const match = useRouteMatch(); const addRequest = async (data, reset) => { try { await api.post('/recipients', data); reset(); toast.success('Destinatário cadastrado com sucesso !'); } catch (err) { const { error } = err.response.data; toast.error(error); } }; const editRequest = async data => { const { params } = match; try { await api.put(`/recipients/${params.id}`, data); toast.success('Destinatário editado com sucesso !'); history.push('/recipients'); } catch (err) { const { error } = err.response.data; history.push('/recipients'); toast.error(error); } }; const validation = async (data, { reset }) => { formRef.current.setErrors({}); const { path } = match; try { const schema = Yup.object().shape({ name: Yup.string() .matches(atLeastTwoNames, 'Passe nome e sobrenome no minimo !') .required(), email: Yup.string() .email() .required(), street: Yup.string().required(), number: Yup.string().required(), complement: Yup.string().max(40), city: Yup.string().required(), state: Yup.string().required(), zip_code: Yup.string() .matches(validCep, 'Passe um cep válido !') .required(), }); await schema.validate(data, { abortEarly: false, }); if (path === '/recipients/add') { addRequest(data, reset); return; } editRequest(data); } catch (err) { const validationErrors = {}; if (err instanceof Yup.ValidationError) { err.inner.forEach(error => { validationErrors[error.path] = error.message; }); formRef.current.setErrors(validationErrors); } } }; const loadStateOptions = (query, callback) => { callback( options .filter(o => o.label.toLowerCase().includes(query.toLowerCase())) .slice(0, 5) ); }; useEffect(() => { const { url, params } = match; if (url === '/recipients/add') return; const loadDeliveryman = async () => { try { const { data } = await api.get(`/recipients/${params.id}`); formRef.current.setData(data); formRef.current.setFieldValue('state', { label: ufConversor(data.state), value: data.state, }); } catch (err) { const { error } = err.response.data; history.push('/recipients'); toast.error(error); } }; loadDeliveryman(); }, [match]); return ( <S.Container> <HV.Container title={ match.path === '/recipients/add' ? 'Cadastro de destinatários' : 'Edição de destinatários' } isToForm > <HV.BackButton /> <HV.SaveButton onClick={() => formRef.current.submitForm()} /> </HV.Container> <S.UnForm ref={formRef} onSubmit={validation}> <S.Wrapper columns={2}> <S.Input name="name" label="Nome" placeholder="Nome ..." /> <S.Input name="email" label="Email" placeholder="[email protected]" /> </S.Wrapper> <S.Wrapper> <S.Input name="street" label="Rua" placeholder="Rua ..." /> <S.Input name="number" type="number" label="Número" placeholder="0000" /> <S.Input name="complement" label="Complemento" placeholder="Complemento ..." /> </S.Wrapper> <S.Wrapper> <S.Input name="city" label="Cidade" placeholder="Cidade ..." /> <SelectAsync name="state" label="Estado" placeholder="Selecione o estado" loadOptions={loadStateOptions} defaultOptions noOptionsMessage={() => 'Nenhum estado foi encontrado !'} /> <S.InputMask name="zip_code" label="CEP" placeholder="CEP ..." mask="99999-999" /> </S.Wrapper> <button type="submit"> * </button> </S.UnForm> </S.Container> ); }
import { WS_INSERT_PROCESS, WS_UPDATE_PROCESS, LIST_PROCESSES, GET_PROCESS } from "../../app/actionTypes"; import reducer, { initialState as reducerInitialState } from "../reducer"; describe("Processes Reducer", () => { it("should return the initial state on first pass", () => { const result = reducer(undefined, {}); expect(result).toEqual(reducerInitialState); }); it("should return the given state on other action types", () => { const action = { type: "UNHANDLED_ACTION" }; const result = reducer(reducerInitialState, action); expect(result).toEqual(reducerInitialState); }); it("should handle WS_INSERT_PROCESS", () => { const state = { documents: [] }; const action = { type: WS_INSERT_PROCESS, data: { id: "test" } }; const result = reducer(state, action); expect(result).toEqual({ documents: [{ id: "test" }] }); }); it("should handle WS_UPDATE_PROCESS", () => { const state = { documents: [{ id: "test", foo: "bar" }] }; const action = { type: WS_UPDATE_PROCESS, data: { id: "test", foo: "baz" } }; const result = reducer(state, action); expect(result).toEqual({ documents: [{ id: "test", foo: "baz" }] }); }); it("should handle LIST_PROCESSES_SUCCEEDED", () => { const state = { documents: [] }; const action = { type: LIST_PROCESSES.SUCCEEDED, data: [{ id: "test1" }, { id: "test2" }, { id: "test3" }] }; const result = reducer(state, action); expect(result).toEqual({ documents: [...action.data] }); }); it("should handle GET_PROCESS_REQUESTED", () => { const state = { detail: { foo: "bar" } }; const action = { type: GET_PROCESS.REQUESTED }; const result = reducer(state, action); expect(result).toEqual({ detail: null }); }); it("should handle GET_PROCESS_SUCCEEDED", () => { const state = { detail: null }; const action = { type: GET_PROCESS.SUCCEEDED, data: { foo: "bar" } }; const result = reducer(state, action); expect(result).toEqual({ detail: { foo: "bar" } }); }); });
// THIS FILE IS AUTO GENERATED var GenIcon = require('../lib').GenIcon module.exports.SiParseDotLy = function SiParseDotLy (props) { return GenIcon({"tag":"svg","attr":{"role":"img","viewBox":"0 0 24 24"},"child":[{"tag":"title","attr":{},"child":[]},{"tag":"path","attr":{"d":"M9.623,19.131c0-0.064,0-0.123-0.023-0.191c-0.103-0.741-0.375-1.449-0.796-2.07c-0.268-0.34-0.577-0.646-0.92-0.912 c-0.101-0.078-0.189-0.041-0.193,0.082l-0.087,1.281c0,0.123-0.147,0.128-0.184,0L6.849,15.52c-0.026-0.065-0.066-0.125-0.115-0.175 c-0.05-0.05-0.109-0.09-0.175-0.117c-0.382-0.131-0.773-0.236-1.169-0.315c-0.525-0.091-1.284-0.141-1.284-0.141 c-0.129,0-0.17,0.077-0.097,0.178l0.782,1.409c0.074,0.105,0,0.205-0.11,0.123l-1.703-1.368c-0.159-0.103-0.337-0.172-0.524-0.203 c-0.187-0.031-0.378-0.024-0.562,0.021c-0.377,0.059-0.92,0.173-0.92,0.173c-0.059,0.013-0.112,0.047-0.147,0.096 c-0.037,0.047-0.055,0.105-0.051,0.164c0,0,0.041,0.547,0.087,0.912c0.005,0.186,0.049,0.369,0.128,0.537 c0.079,0.168,0.192,0.319,0.332,0.443l1.772,1.254c0.11,0.073,0.032,0.182-0.087,0.137l-1.578-0.351 c-0.12-0.046-0.189,0-0.152,0.137c0,0,0.262,0.711,0.492,1.181c0.195,0.368,0.416,0.721,0.663,1.058 c0.044,0.055,0.098,0.1,0.16,0.133c0.062,0.034,0.129,0.055,0.199,0.063l1.905,0.046c0.124,0,0.156,0.141,0.041,0.178l-1.219,0.456 c-0.12,0.036-0.129,0.128-0.028,0.205c0.357,0.252,0.743,0.461,1.15,0.62c0.72,0.231,1.483,0.295,2.232,0.187 c0.557-0.078,1.106-0.208,1.638-0.388c-0.02-0.151-0.031-0.303-0.032-0.456c0.002-0.488,0.106-0.97,0.307-1.416 c0.2-0.446,0.493-0.845,0.858-1.173 M23.217,15.388c0.002-0.059-0.016-0.117-0.051-0.164c-0.036-0.049-0.088-0.083-0.147-0.096 c0,0-0.543-0.114-0.92-0.169c-0.183-0.045-0.373-0.053-0.559-0.022c-0.186,0.031-0.364,0.099-0.522,0.2l-1.703,1.368 c-0.101,0.082-0.184,0-0.11-0.123l0.778-1.409c0.078-0.1,0.037-0.182-0.092-0.178c0,0-0.759,0.05-1.284,0.141 c-0.396,0.079-0.787,0.184-1.169,0.315c-0.065,0.027-0.125,0.067-0.175,0.117c-0.05,0.05-0.089,0.109-0.115,0.175l-0.571,1.796 c-0.037,0.119-0.179,0.114-0.184,0l-0.092-1.281c0-0.123-0.087-0.16-0.189-0.082c-0.343,0.266-0.652,0.572-0.92,0.912 c-0.42,0.615-0.693,1.316-0.796,2.052c0,0.068,0,0.128,0,0.191c0.365,0.327,0.657,0.727,0.857,1.173 c0.2,0.446,0.303,0.929,0.303,1.417c-0.001,0.152-0.012,0.305-0.032,0.456c0.534,0.179,1.084,0.309,1.643,0.388 c0.749,0.108,1.512,0.044,2.232-0.187c0.408-0.16,0.794-0.368,1.15-0.62c0.101-0.077,0.092-0.169-0.028-0.205l-1.219-0.456 c-0.115-0.036-0.083-0.173,0.041-0.178l1.901-0.046c0.071-0.006,0.14-0.027,0.203-0.06c0.063-0.034,0.117-0.08,0.161-0.136 c0.227-0.328,0.431-0.671,0.612-1.026c0.235-0.456,0.497-1.181,0.497-1.181c0.037-0.118-0.032-0.182-0.152-0.137l-1.578,0.351 c-0.124,0.046-0.198-0.064-0.092-0.137l1.785-1.254c0.14-0.124,0.253-0.275,0.332-0.443c0.079-0.169,0.123-0.351,0.128-0.537 c0.046-0.378,0.087-0.912,0.087-0.912 M18.229,9.429c0-0.196-0.129-0.269-0.304-0.16l-1.841,0.994c-0.17,0.109-0.207-0.1-0.083-0.26 l1.758-2.325c0.064-0.091,0.107-0.195,0.126-0.305c0.018-0.11,0.012-0.222-0.02-0.329c-0.23-0.627-0.505-1.236-0.824-1.824 c-0.321-0.516-0.678-1.01-1.068-1.477c-0.124-0.155-0.276-0.128-0.341,0.059l-0.86,2.129c-0.064,0.187-0.226,0.182-0.221,0 l0.101-3.342c-0.002-0.237-0.094-0.465-0.258-0.638c0,0-0.511-0.511-0.92-0.884c-0.409-0.374-1.173-0.966-1.173-0.966 C12.22,0.036,12.117,0,12.012,0c-0.106,0-0.208,0.036-0.29,0.102c0,0-0.722,0.561-1.192,0.966c-0.469,0.406-0.92,0.88-0.92,0.88 c-0.166,0.166-0.264,0.387-0.276,0.62L9.439,5.91c0,0.201-0.156,0.205-0.226,0l-0.86-2.106c-0.06-0.187-0.216-0.214-0.341-0.055 C7.601,4.245,7.227,4.771,6.895,5.322C6.592,5.877,6.33,6.453,6.112,7.045C6.083,7.15,6.076,7.261,6.094,7.368 c0.017,0.108,0.058,0.211,0.12,0.301l1.767,2.334c0.124,0.16,0.087,0.369-0.087,0.26L6.052,9.27C5.882,9.16,5.74,9.233,5.744,9.429 c0.015,0.645,0.12,1.285,0.313,1.901c0.435,1.115,1.13,2.111,2.029,2.909c1.182,1.209,2.14,2.615,2.83,4.153 c0.702-0.225,1.457-0.225,2.158,0c0.688-1.534,1.639-2.938,2.812-4.149c0.823-0.731,1.479-1.628,1.924-2.63 c0.253-0.701,0.394-1.436,0.419-2.179 M14.308,21.721c0,0.451-0.135,0.892-0.388,1.266c-0.253,0.375-0.612,0.667-1.033,0.84 c-0.42,0.173-0.883,0.218-1.329,0.13c-0.446-0.088-0.856-0.305-1.178-0.624c-0.322-0.319-0.541-0.725-0.63-1.167 c-0.089-0.442-0.043-0.9,0.131-1.317c0.174-0.417,0.469-0.773,0.847-1.023c0.378-0.25,0.823-0.384,1.278-0.384 c0.61,0,1.195,0.24,1.627,0.668C14.066,20.536,14.308,21.116,14.308,21.721z"}}]})(props); };
import React from 'react'; import { withRouter } from 'react-router-dom'; import { useSelector } from 'react-redux'; import useDocumentTitle from 'hooks/useDocumentTitle'; import useScrollTop from 'hooks/useScrollTop'; import { ADD_PRODUCT } from 'constants/routes'; import ProductAppliedFilters from 'components/product/ProductAppliedFilters'; import { selectFilter } from 'selectors/selector'; import ProductList from 'components/product/ProductList'; import Boundary from 'components/ui/Boundary'; import SearchBar from 'components/ui/SearchBar'; import FiltersToggle from 'components/ui/FiltersToggle'; import ProductItem from '../components/ProductItem'; const Products = ({ history }) => { useDocumentTitle('Product List | Salinaka Admin'); useScrollTop(); const store = useSelector(state => ({ filter: state.filter, basket: state.basket, filteredProducts: selectFilter(state.products.items, state.filter), requestStatus: state.app.requestStatus, isLoading: state.app.loading, products: state.products.items, productsCount: state.products.items.length, totalProductsCount: state.products.total, })); const onClickAddProduct = () => { history.push(ADD_PRODUCT); }; // TODO insufficient permission // TODO fix filters modal return ( <Boundary> <div className="product-admin-header"> <h3 className="product-admin-header-title"> Products &nbsp; ({`${store.productsCount} / ${store.totalProductsCount}`}) </h3> <SearchBar filter={store.filter} isLoading={store.isLoading} productsCount={store.productsCount} /> &nbsp; <FiltersToggle filter={store.filter} isLoading={store.isLoading} products={store.products} productsCount={store.productsCount} > <button className="button-muted button-small"> More Filters &nbsp;<i className="fa fa-chevron-right" /> </button> </FiltersToggle> <button className="button button-small" onClick={onClickAddProduct} > Добавить продукт </button> </div> <div className="product-admin-items"> <ProductList {...store}> {() => ( <> <ProductAppliedFilters filter={store.filter} /> {store.filteredProducts.length > 0 && ( <div className="grid grid-product grid-count-6"> <div className="grid-col" /> <div className="grid-col"> <h5>Name</h5> </div> <div className="grid-col"> <h5>Brand</h5> </div> <div className="grid-col"> <h5>Price</h5> </div> <div className="grid-col"> <h5>Date Added</h5> </div> <div className="grid-col"> <h5>Qty</h5> </div> </div> )} {store.filteredProducts.length === 0 ? new Array(10).fill({}).map((product, index) => ( <ProductItem key={`product-skeleton ${index}`} product={product} /> )) : store.filteredProducts.map(product => ( <ProductItem key={product.id} product={product} /> ))} </> )} </ProductList> </div> </Boundary> ); }; export default withRouter(Products);
# -*- coding: utf-8 -*- """ GIS Module @requires: U{B{I{gluon}} <http://web2py.com>} @requires: U{B{I{shapely}} <http://trac.gispython.org/lab/wiki/Shapely>} @copyright: (c) 2010-2019 Sahana Software Foundation @license: MIT 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 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. @status: partially fixed for Py3, needs more work """ __all__ = ("GIS", "MAP2", "S3Map", "S3ExportPOI", "S3ImportPOI", ) import datetime # Needed for Feed Refresh checks & web2py version check import json import os import re import sys #import logging from collections import OrderedDict try: from lxml import etree # Needed to follow NetworkLinks except ImportError: sys.stderr.write("ERROR: lxml module needed for XML handling\n") raise KML_NAMESPACE = "http://earth.google.com/kml/2.2" from gluon import * # Here are dependencies listed for reference: #from gluon import current, redirect #from gluon.html import * #from gluon.http import HTTP from gluon.fileutils import parse_version from gluon.languages import lazyT, regex_translate from gluon.settings import global_settings from gluon.storage import Storage from s3compat import Cookie, HTTPError, StringIO, URLError, basestring, urllib_quote from s3dal import Rows from .s3datetime import s3_format_datetime, s3_parse_datetime from .s3fields import s3_all_meta_field_names from .s3rest import S3Method from .s3track import S3Trackable from .s3utils import s3_include_ext, s3_include_underscore, s3_str # Map WKT types to db types GEOM_TYPES = {"point": 1, "linestring": 2, "polygon": 3, "multipoint": 4, "multilinestring": 5, "multipolygon": 6, "geometrycollection": 7, } # km RADIUS_EARTH = 6371.01 # Compact JSON encoding SEPARATORS = (",", ":") # Map Defaults # Also in static/S3/s3.gis.js # http://dev.openlayers.org/docs/files/OpenLayers/Strategy/Cluster-js.html CLUSTER_ATTRIBUTE = "colour" CLUSTER_DISTANCE = 20 # pixels CLUSTER_THRESHOLD = 2 # minimum # of features to form a cluster # Garmin GPS Symbols GPS_SYMBOLS = ("Airport", "Amusement Park" "Ball Park", "Bank", "Bar", "Beach", "Bell", "Boat Ramp", "Bowling", "Bridge", "Building", "Campground", "Car", "Car Rental", "Car Repair", "Cemetery", "Church", "Circle with X", "City (Capitol)", "City (Large)", "City (Medium)", "City (Small)", "Civil", "Contact, Dreadlocks", "Controlled Area", "Convenience Store", "Crossing", "Dam", "Danger Area", "Department Store", "Diver Down Flag 1", "Diver Down Flag 2", "Drinking Water", "Exit", "Fast Food", "Fishing Area", "Fitness Center", "Flag", "Forest", "Gas Station", "Geocache", "Geocache Found", "Ghost Town", "Glider Area", "Golf Course", "Green Diamond", "Green Square", "Heliport", "Horn", "Hunting Area", "Information", "Levee", "Light", "Live Theater", "Lodging", "Man Overboard", "Marina", "Medical Facility", "Mile Marker", "Military", "Mine", "Movie Theater", "Museum", "Navaid, Amber", "Navaid, Black", "Navaid, Blue", "Navaid, Green", "Navaid, Green/Red", "Navaid, Green/White", "Navaid, Orange", "Navaid, Red", "Navaid, Red/Green", "Navaid, Red/White", "Navaid, Violet", "Navaid, White", "Navaid, White/Green", "Navaid, White/Red", "Oil Field", "Parachute Area", "Park", "Parking Area", "Pharmacy", "Picnic Area", "Pizza", "Police Station", "Post Office", "Private Field", "Radio Beacon", "Red Diamond", "Red Square", "Residence", "Restaurant", "Restricted Area", "Restroom", "RV Park", "Scales", "Scenic Area", "School", "Seaplane Base", "Shipwreck", "Shopping Center", "Short Tower", "Shower", "Skiing Area", "Skull and Crossbones", "Soft Field", "Stadium", "Summit", "Swimming Area", "Tall Tower", "Telephone", "Toll Booth", "TracBack Point", "Trail Head", "Truck Stop", "Tunnel", "Ultralight Area", "Water Hydrant", "Waypoint", "White Buoy", "White Dot", "Zoo" ) # ----------------------------------------------------------------------------- class GIS(object): """ GeoSpatial functions """ # Used to disable location tree updates during prepopulate. # It is not appropriate to use auth.override for this, as there are times # (e.g. during tests) when auth.override is turned on, but location tree # updates should still be enabled. disable_update_location_tree = False def __init__(self): messages = current.messages #messages.centroid_error = str(A("Shapely", _href="http://pypi.python.org/pypi/Shapely/", _target="_blank")) + " library not found, so can't find centroid!" messages.centroid_error = "Shapely library not functional, so can't find centroid! Install Geos & Shapely for Line/Polygon support" messages.unknown_type = "Unknown Type!" messages.invalid_wkt_point = "Invalid WKT: must be like POINT(3 4)" messages.invalid_wkt = "Invalid WKT: see http://en.wikipedia.org/wiki/Well-known_text" messages.lon_empty = "Invalid: Longitude can't be empty if Latitude specified!" messages.lat_empty = "Invalid: Latitude can't be empty if Longitude specified!" messages.unknown_parent = "Invalid: %(parent_id)s is not a known Location" self.DEFAULT_SYMBOL = "White Dot" self.hierarchy_level_keys = ("L0", "L1", "L2", "L3", "L4", "L5") self.hierarchy_levels = {} self.max_allowed_level_num = 4 self.relevant_hierarchy_levels = None #self.google_geocode_retry = True # ------------------------------------------------------------------------- @staticmethod def gps_symbols(): return GPS_SYMBOLS # ------------------------------------------------------------------------- def download_kml(self, record_id, filename, session_id_name, session_id): """ Download a KML file: - unzip it if-required - follow NetworkLinks recursively if-required Save the file to the /uploads folder Designed to be called asynchronously using: current.s3task.run_async("download_kml", [record_id, filename]) @param record_id: id of the record in db.gis_layer_kml @param filename: name to save the file as @param session_id_name: name of the session @param session_id: id of the session @ToDo: Pass error messages to Result & have JavaScript listen for these """ table = current.s3db.gis_layer_kml record = current.db(table.id == record_id).select(table.url, limitby=(0, 1) ).first() url = record.url filepath = os.path.join(global_settings.applications_parent, current.request.folder, "uploads", "gis_cache", filename) warning = self.fetch_kml(url, filepath, session_id_name, session_id) # @ToDo: Handle errors #query = (cachetable.name == name) if "URLError" in warning or "HTTPError" in warning: # URL inaccessible if os.access(filepath, os.R_OK): statinfo = os.stat(filepath) if statinfo.st_size: # Use cached version #date = db(query).select(cachetable.modified_on, # limitby=(0, 1)).first().modified_on #response.warning += "%s %s %s\n" % (url, # T("not accessible - using cached version from"), # str(date)) #url = URL(c="default", f="download", # args=[filename]) pass else: # 0k file is all that is available #response.warning += "%s %s\n" % (url, # T("not accessible - no cached version available!")) # skip layer return else: # No cached version available #response.warning += "%s %s\n" % (url, # T("not accessible - no cached version available!")) # skip layer return else: # Download was succesful #db(query).update(modified_on=request.utcnow) if "ParseError" in warning: # @ToDo Parse detail #response.warning += "%s: %s %s\n" % (T("Layer"), # name, # T("couldn't be parsed so NetworkLinks not followed.")) pass if "GroundOverlay" in warning or "ScreenOverlay" in warning: #response.warning += "%s: %s %s\n" % (T("Layer"), # name, # T("includes a GroundOverlay or ScreenOverlay which aren't supported in OpenLayers yet, so it may not work properly.")) # Code to support GroundOverlay: # https://github.com/openlayers/openlayers/pull/759 pass # ------------------------------------------------------------------------- def fetch_kml(self, url, filepath, session_id_name, session_id): """ Fetch a KML file: - unzip it if-required - follow NetworkLinks recursively if-required Returns a file object Designed as a helper function for download_kml() """ from gluon.tools import fetch response = current.response public_url = current.deployment_settings.get_base_public_url() warning = "" local = False if not url.startswith("http"): local = True url = "%s%s" % (public_url, url) elif len(url) > len(public_url) and url[:len(public_url)] == public_url: local = True if local: # Keep Session for local URLs cookie = Cookie.SimpleCookie() cookie[session_id_name] = session_id # For sync connections current.session._unlock(response) try: file = fetch(url, cookie=cookie) except HTTPError: warning = "HTTPError" return warning except URLError: warning = "URLError" return warning else: try: file = fetch(url) except HTTPError: warning = "HTTPError" return warning except URLError: warning = "URLError" return warning filenames = [] if file[:2] == "PK": # Unzip fp = StringIO(file) import zipfile myfile = zipfile.ZipFile(fp) files = myfile.infolist() main = None candidates = [] for _file in files: filename = _file.filename if filename == "doc.kml": main = filename elif filename[-4:] == ".kml": candidates.append(filename) if not main: if candidates: # Any better way than this to guess which KML file is the main one? main = candidates[0] else: response.error = "KMZ contains no KML Files!" return "" # Write files to cache (other than the main one) request = current.request path = os.path.join(request.folder, "static", "cache", "kml") if not os.path.exists(path): os.makedirs(path) for _file in files: filename = _file.filename if filename != main: if "/" in filename: _filename = filename.split("/") dir = os.path.join(path, _filename[0]) if not os.path.exists(dir): os.mkdir(dir) _filepath = os.path.join(path, *_filename) else: _filepath = os.path.join(path, filename) try: f = open(_filepath, "wb") except: # Trying to write the Folder pass else: filenames.append(filename) __file = myfile.read(filename) f.write(__file) f.close() # Now read the main one (to parse) file = myfile.read(main) myfile.close() # Check for NetworkLink if "<NetworkLink>" in file: try: # Remove extraneous whitespace parser = etree.XMLParser(recover=True, remove_blank_text=True) tree = etree.XML(file, parser) # Find contents of href tag (must be a better way?) url = "" for element in tree.iter(): if element.tag == "{%s}href" % KML_NAMESPACE: url = element.text if url: # Follow NetworkLink (synchronously) warning2 = self.fetch_kml(url, filepath) warning += warning2 except (etree.XMLSyntaxError,): e = sys.exc_info()[1] warning += "<ParseError>%s %s</ParseError>" % (e.line, e.errormsg) # Check for Overlays if "<GroundOverlay>" in file: warning += "GroundOverlay" if "<ScreenOverlay>" in file: warning += "ScreenOverlay" for filename in filenames: replace = "%s/%s" % (URL(c="static", f="cache", args=["kml"]), filename) # Rewrite all references to point to the correct place # need to catch <Icon><href> (which could be done via lxml) # & also <description><![CDATA[<img src=" (which can't) file = file.replace(filename, replace) # Write main file to cache f = open(filepath, "w") f.write(file) f.close() return warning # ------------------------------------------------------------------------- @staticmethod def geocode(address, postcode=None, Lx_ids=None, geocoder=None): """ Geocode an Address - used by S3LocationSelector settings.get_gis_geocode_imported_addresses @param address: street address @param postcode: postcode @param Lx_ids: list of ancestor IDs @param geocoder: which geocoder service to use """ try: from geopy import geocoders except ImportError: current.log.error("S3GIS unresolved dependency: geopy required for Geocoder support") return "S3GIS unresolved dependency: geopy required for Geocoder support" settings = current.deployment_settings if geocoder is None: geocoder = settings.get_gis_geocode_service() if geocoder == "nominatim": g = geocoders.Nominatim(user_agent = "Sahana Eden") geocode_ = lambda names, g=g, **kwargs: g.geocode(names, **kwargs) elif geocoder == "google": api_key = settings.get_gis_api_google() if not api_key: current.log.error("Geocoder: No API Key") return "No API Key" g = geocoders.GoogleV3(api_key = api_key) #if current.gis.google_geocode_retry: # # Retry when reaching maximum requests per second # import time # from geopy.geocoders.googlev3 import GTooManyQueriesError # def geocode_(names, g=g, **kwargs): # attempts = 0 # while attempts < 3: # try: # result = g.geocode(names, **kwargs) # except GTooManyQueriesError: # if attempts == 2: # # Daily limit reached # current.gis.google_geocode_retry = False # raise # time.sleep(1) # else: # break # attempts += 1 # return result #else: geocode_ = lambda names, g=g, **kwargs: g.geocode(names, **kwargs) else: # @ToDo raise NotImplementedError location = address if postcode: location = "%s,%s" % (location, postcode) Lx = L5 = L4 = L3 = L2 = L1 = L0 = None if Lx_ids: # Convert Lx IDs to Names table = current.s3db.gis_location limit = len(Lx_ids) if limit > 1: query = (table.id.belongs(Lx_ids)) else: query = (table.id == Lx_ids[0]) db = current.db Lx = db(query).select(table.id, table.name, table.level, table.gis_feature_type, # Better as separate query #table.lon_min, #table.lat_min, #table.lon_max, #table.lat_max, # Better as separate query #table.wkt, limitby=(0, limit), orderby=~table.level ) if Lx: Lx_names = ",".join([l.name for l in Lx]) location = "%s,%s" % (location, Lx_names) for l in Lx: if l.level == "L0": L0 = l.id continue elif l.level == "L1": L1 = l.id continue elif l.level == "L2": L2 = l.id continue elif l.level == "L3": L3 = l.id continue elif l.level == "L4": L4 = l.id continue elif l.level == "L5": L5 = l.id Lx = Lx.as_dict() try: results = geocode_(location, exactly_one=False) except: error = sys.exc_info()[1] output = str(error) else: if results is None: output = "No results found" elif len(results) > 1: output = "Multiple results found" # @ToDo: Iterate through the results to see if just 1 is within the right bounds else: place, (lat, lon) = results[0] if Lx: output = None # Check Results are for a specific address & not just that for the City results = geocode_(Lx_names, exactly_one=False) if not results: output = "Can't check that these results are specific enough" for result in results: place2, (lat2, lon2) = result if place == place2: output = "We can only geocode to the Lx" break if not output: # Check Results are within relevant bounds L0_row = None wkt = None if L5 and Lx[L5]["gis_feature_type"] != 1: wkt = db(table.id == L5).select(table.wkt, limitby=(0, 1) ).first().wkt used_Lx = L5 elif L4 and Lx[L4]["gis_feature_type"] != 1: wkt = db(table.id == L4).select(table.wkt, limitby=(0, 1) ).first().wkt used_Lx = L4 elif L3 and Lx[L3]["gis_feature_type"] != 1: wkt = db(table.id == L3).select(table.wkt, limitby=(0, 1) ).first().wkt used_Lx = L3 elif L2 and Lx[L2]["gis_feature_type"] != 1: wkt = db(table.id == L2).select(table.wkt, limitby=(0, 1) ).first().wkt used_Lx = L2 elif L1 and Lx[L1]["gis_feature_type"] != 1: wkt = db(table.id == L1).select(table.wkt, limitby=(0, 1) ).first().wkt used_Lx = L1 elif L0: L0_row = db(table.id == L0).select(table.wkt, table.lon_min, table.lat_min, table.lon_max, table.lat_max, limitby=(0, 1) ).first() if not L0_row.wkt.startswith("POI"): # Point wkt = L0_row.wkt used_Lx = L0 if wkt: from shapely.geometry import point from shapely.wkt import loads as wkt_loads try: # Enable C-based speedups available from 1.2.10+ from shapely import speedups speedups.enable() except: current.log.info("S3GIS", "Upgrade Shapely for Performance enhancements") test = point.Point(lon, lat) shape = wkt_loads(wkt) ok = test.intersects(shape) if not ok: output = "Returned value not within %s" % Lx[used_Lx]["name"] elif L0: # Check within country at least if not L0_row: L0_row = db(table.id == L0).select(table.lon_min, table.lat_min, table.lon_max, table.lat_max, limitby=(0, 1) ).first() if lat < L0_row["lat_max"] and \ lat > L0_row["lat_min"] and \ lon < L0_row["lon_max"] and \ lon > L0_row["lon_min"]: ok = True else: ok = False output = "Returned value not within %s" % Lx["name"] else: # We'll just have to trust it! ok = True if ok: output = {"lat": lat, "lon": lon, } else: # We'll just have to trust it! output = {"lat": lat, "lon": lon, } return output # ------------------------------------------------------------------------- @staticmethod def geocode_r(lat, lon): """ Reverse Geocode a Lat/Lon - used by S3LocationSelector """ if not lat or not lon: return "Need Lat & Lon" results = "" # Check vaguely valid try: lat = float(lat) except ValueError: results = "Latitude is Invalid!" try: lon = float(lon) except ValueError: results += "Longitude is Invalid!" if not results: if lon > 180 or lon < -180: results = "Longitude must be between -180 & 180!" elif lat > 90 or lat < -90: results = "Latitude must be between -90 & 90!" else: table = current.s3db.gis_location query = (table.level != None) & \ (table.deleted != True) if current.deployment_settings.get_gis_spatialdb(): point = "POINT(%s %s)" % (lon, lat) query &= (table.the_geom.st_intersects(point)) rows = current.db(query).select(table.id, table.level, ) results = {} for row in rows: results[row.level] = row.id else: # Oh dear, this is going to be slow :/ # Filter to the BBOX initially query &= (table.lat_min < lat) & \ (table.lat_max > lat) & \ (table.lon_min < lon) & \ (table.lon_max > lon) rows = current.db(query).select(table.id, table.level, table.wkt, ) from shapely.geometry import point from shapely.wkt import loads as wkt_loads test = point.Point(lon, lat) results = {} for row in rows: shape = wkt_loads(row.wkt) ok = test.intersects(shape) if ok: #sys.stderr.write("Level: %s, id: %s\n" % (row.level, row.id)) results[row.level] = row.id return results # ------------------------------------------------------------------------- @staticmethod def get_bearing(lat_start, lon_start, lat_end, lon_end): """ Given a Start & End set of Coordinates, return a Bearing Formula from: http://www.movable-type.co.uk/scripts/latlong.html """ import math # shortcuts cos = math.cos sin = math.sin delta_lon = lon_start - lon_end bearing = math.atan2(sin(delta_lon) * cos(lat_end), (cos(lat_start) * sin(lat_end)) - \ (sin(lat_start) * cos(lat_end) * cos(delta_lon)) ) # Convert to a compass bearing bearing = (bearing + 360) % 360 return bearing # ------------------------------------------------------------------------- def get_bounds(self, features = None, bbox_min_size = None, bbox_inset = None): """ Calculate the Bounds of a list of Point Features, suitable for setting map bounds. If no features are supplied, the current map configuration bounds will be returned. e.g. When a map is displayed that focuses on a collection of points, the map is zoomed to show just the region bounding the points. e.g. To use in GPX export for correct zooming ` Ensure a minimum size of bounding box, and that the points are inset from the border. @param features: A list of point features @param bbox_min_size: Minimum bounding box - gives a minimum width and height in degrees for the region shown. Without this, a map showing a single point would not show any extent around that point. @param bbox_inset: Bounding box insets - adds a small amount of distance outside the points. Without this, the outermost points would be on the bounding box, and might not be visible. @return: An appropriate map bounding box, as a dict: dict(lon_min=lon_min, lat_min=lat_min, lon_max=lon_max, lat_max=lat_max) @ToDo: Support Polygons (separate function?) """ if features: lon_min = 180 lat_min = 90 lon_max = -180 lat_max = -90 # Is this a simple feature set or the result of a join? try: lon = features[0].lon simple = True except (AttributeError, KeyError): simple = False # @ToDo: Optimised Geospatial routines rather than this crude hack for feature in features: try: if simple: lon = feature.lon lat = feature.lat else: # A Join lon = feature.gis_location.lon lat = feature.gis_location.lat except AttributeError: # Skip any rows without the necessary lat/lon fields continue # Also skip those set to None. Note must use explicit test, # as zero is a legal value. if lon is None or lat is None: continue lon_min = min(lon, lon_min) lat_min = min(lat, lat_min) lon_max = max(lon, lon_max) lat_max = max(lat, lat_max) # Assure a reasonable-sized box. settings = current.deployment_settings bbox_min_size = bbox_min_size or settings.get_gis_bbox_inset() delta_lon = (bbox_min_size - (lon_max - lon_min)) / 2.0 if delta_lon > 0: lon_min -= delta_lon lon_max += delta_lon delta_lat = (bbox_min_size - (lat_max - lat_min)) / 2.0 if delta_lat > 0: lat_min -= delta_lat lat_max += delta_lat # Move bounds outward by specified inset. bbox_inset = bbox_inset or settings.get_gis_bbox_inset() lon_min -= bbox_inset lon_max += bbox_inset lat_min -= bbox_inset lat_max += bbox_inset else: # no features config = GIS.get_config() if config.lat_min is not None: lat_min = config.lat_min else: lat_min = -90 if config.lon_min is not None: lon_min = config.lon_min else: lon_min = -180 if config.lat_max is not None: lat_max = config.lat_max else: lat_max = 90 if config.lon_max is not None: lon_max = config.lon_max else: lon_max = 180 return {"lon_min": lon_min, "lat_min": lat_min, "lon_max": lon_max, "lat_max": lat_max, } # ------------------------------------------------------------------------- def get_parent_bounds(self, parent=None): """ Get bounds from the specified (parent) location and its ancestors. This is used to validate lat, lon, and bounds for child locations. Caution: This calls update_location_tree if the parent bounds are not set. During prepopulate, update_location_tree is disabled, so unless the parent contains its own bounds (i.e. they do not need to be propagated down from its ancestors), this will not provide a check on location nesting. Prepopulate data should be prepared to be correct. A set of candidate prepopulate data can be tested by importing after prepopulate is run. @param parent: A location_id to provide bounds suitable for validating child locations @return: bounding box and parent location name, as a list: [lat_min, lon_min, lat_max, lon_max, parent_name] @ToDo: Support Polygons (separate function?) """ table = current.s3db.gis_location db = current.db parent = db(table.id == parent).select(table.id, table.level, table.name, table.parent, table.path, table.lon, table.lat, table.lon_min, table.lat_min, table.lon_max, table.lat_max).first() if parent.lon_min is None or \ parent.lon_max is None or \ parent.lat_min is None or \ parent.lat_max is None or \ parent.lon_min == parent.lon_max or \ parent.lat_min == parent.lat_max: # This is unsuitable - try higher parent if parent.level == "L1": if parent.parent: # We can trust that L0 should have the data from prepop L0 = db(table.id == parent.parent).select(table.name, table.lon_min, table.lat_min, table.lon_max, table.lat_max).first() return L0.lat_min, L0.lon_min, L0.lat_max, L0.lon_max, L0.name if parent.path: path = parent.path else: # This will return None during prepopulate. path = GIS.update_location_tree({"id": parent.id, "level": parent.level, }) if path: path_list = [int(item) for item in path.split("/")] rows = db(table.id.belongs(path_list)).select(table.level, table.name, table.lat, table.lon, table.lon_min, table.lat_min, table.lon_max, table.lat_max, orderby=table.level) row_list = rows.as_list() row_list.reverse() ok = False for row in row_list: if row["lon_min"] is not None and row["lon_max"] is not None and \ row["lat_min"] is not None and row["lat_max"] is not None and \ row["lon"] != row["lon_min"] != row["lon_max"] and \ row["lat"] != row["lat_min"] != row["lat_max"]: ok = True break if ok: # This level is suitable return row["lat_min"], row["lon_min"], row["lat_max"], row["lon_max"], row["name"] else: # This level is suitable return parent.lat_min, parent.lon_min, parent.lat_max, parent.lon_max, parent.name # No ancestor bounds available -- use the active gis_config. config = GIS.get_config() if config: return config.lat_min, config.lon_min, config.lat_max, config.lon_max, None # Last resort -- fall back to no restriction. return -90, -180, 90, 180, None # ------------------------------------------------------------------------- @staticmethod def _lookup_parent_path(feature_id): """ Helper that gets parent and path for a location. """ db = current.db table = db.gis_location feature = db(table.id == feature_id).select(table.id, table.name, table.level, table.path, table.parent, limitby=(0, 1)).first() return feature # ------------------------------------------------------------------------- @staticmethod def get_children(id, level=None): """ Return a list of IDs of all GIS Features which are children of the requested feature, using Materialized path for retrieving the children This has been chosen over Modified Preorder Tree Traversal for greater efficiency: http://eden.sahanafoundation.org/wiki/HaitiGISToDo#HierarchicalTrees @param: level - optionally filter by level @return: Rows object containing IDs & Names Note: This does NOT include the parent location itself """ db = current.db try: table = db.gis_location except: # Being run from CLI for debugging table = current.s3db.gis_location query = (table.deleted == False) if level: query &= (table.level == level) term = str(id) path = table.path query &= ((path.like(term + "/%")) | \ (path.like("%/" + term + "/%"))) children = db(query).select(table.id, table.name) return children # ------------------------------------------------------------------------- @staticmethod def get_parents(feature_id, feature=None, ids_only=False): """ Returns a list containing ancestors of the requested feature. If the caller already has the location row, including path and parent fields, they can supply it via feature to avoid a db lookup. If ids_only is false, each element in the list is a gluon.sql.Row containing the gis_location record of an ancestor of the specified location. If ids_only is true, just returns a list of ids of the parents. This avoids a db lookup for the parents if the specified feature has a path. List elements are in the opposite order as the location path and exclude the specified location itself, i.e. element 0 is the parent and the last element is the most distant ancestor. Assists lazy update of a database without location paths by calling update_location_tree to get the path. Note that during prepopulate, update_location_tree is disabled, in which case this will only return the immediate parent. """ if not feature or "path" not in feature or "parent" not in feature: feature = GIS._lookup_parent_path(feature_id) if feature and (feature.path or feature.parent): if feature.path: path = feature.path else: path = GIS.update_location_tree(feature) if path: path_list = [int(item) for item in path.split("/")] if len(path_list) == 1: # No parents - path contains only this feature. return None # Get only ancestors path_list = path_list[:-1] # Get path in the desired -- reversed -- order. path_list.reverse() elif feature.parent: path_list = [feature.parent] else: return None # If only ids are wanted, stop here. if ids_only: return path_list # Retrieve parents - order in which they're returned is arbitrary. s3db = current.s3db table = s3db.gis_location query = (table.id.belongs(path_list)) fields = [table.id, table.name, table.level, table.lat, table.lon] unordered_parents = current.db(query).select(cache=s3db.cache, *fields) # Reorder parents in order of reversed path. unordered_ids = [row.id for row in unordered_parents] parents = [unordered_parents[unordered_ids.index(path_id)] for path_id in path_list if path_id in unordered_ids] return parents else: return None # ------------------------------------------------------------------------- def get_parent_per_level(self, results, feature_id, feature=None, ids=True, names=True): """ Adds ancestor of requested feature for each level to supplied dict. If the caller already has the location row, including path and parent fields, they can supply it via feature to avoid a db lookup. If a dict is not supplied in results, one is created. The results dict is returned in either case. If ids=True and names=False (used by old S3LocationSelectorWidget): For each ancestor, an entry is added to results, like ancestor.level : ancestor.id If ids=False and names=True (used by address_onvalidation): For each ancestor, an entry is added to results, like ancestor.level : ancestor.name If ids=True and names=True (used by new S3LocationSelectorWidget): For each ancestor, an entry is added to results, like ancestor.level : {name : ancestor.name, id: ancestor.id} """ if not results: results = {} _id = feature_id # if we don't have a feature or a feature ID return the dict as-is if not feature_id and not feature: return results if not feature_id and "path" not in feature and "parent" in feature: # gis_location_onvalidation on a Create => no ID yet # Read the Parent's path instead feature = self._lookup_parent_path(feature.parent) _id = feature.id elif not feature or "path" not in feature or "parent" not in feature: feature = self._lookup_parent_path(feature_id) if feature and (feature.path or feature.parent): if feature.path: path = feature.path else: path = self.update_location_tree(feature) # Get ids of ancestors at each level. if feature.parent: strict = self.get_strict_hierarchy(feature.parent) else: strict = self.get_strict_hierarchy(_id) if path and strict and not names: # No need to do a db lookup for parents in this case -- we # know the levels of the parents from their position in path. # Note ids returned from db are ints, not strings, so be # consistent with that. path_ids = [int(item) for item in path.split("/")] # This skips the last path element, which is the supplied # location. for (i, _id) in enumerate(path_ids[:-1]): results["L%i" % i] = _id elif path: ancestors = self.get_parents(_id, feature=feature) if ancestors: for ancestor in ancestors: if ancestor.level and ancestor.level in self.hierarchy_level_keys: if names and ids: results[ancestor.level] = Storage() results[ancestor.level].name = ancestor.name results[ancestor.level].id = ancestor.id elif names: results[ancestor.level] = ancestor.name else: results[ancestor.level] = ancestor.id if not feature_id: # Add the Parent in (we only need the version required for gis_location onvalidation here) results[feature.level] = feature.name if names: # We need to have entries for all levels # (both for address onvalidation & new LocationSelector) hierarchy_level_keys = self.hierarchy_level_keys for key in hierarchy_level_keys: if key not in results: results[key] = None return results # ------------------------------------------------------------------------- def update_table_hierarchy_labels(self, tablename=None): """ Re-set table options that depend on location_hierarchy Only update tables which are already defined """ levels = ("L1", "L2", "L3", "L4", "L5") labels = self.get_location_hierarchy() db = current.db if tablename and tablename in db: # Update the specific table which has just been defined table = db[tablename] if tablename == "gis_location": labels["L0"] = current.messages.COUNTRY table.level.requires = \ IS_EMPTY_OR(IS_IN_SET(labels)) else: for level in levels: table[level].label = labels[level] else: # Do all Tables which are already defined # gis_location if "gis_location" in db: table = db.gis_location table.level.requires = \ IS_EMPTY_OR(IS_IN_SET(labels)) # These tables store location hierarchy info for XSLT export. # Labels are used for PDF & XLS Reports tables = ["org_office", #"pr_person", "pr_address", "cr_shelter", "asset_asset", #"hms_hospital", ] for tablename in tables: if tablename in db: table = db[tablename] for level in levels: table[level].label = labels[level] # ------------------------------------------------------------------------- @staticmethod def set_config(config_id=None, force_update_cache=False): """ Reads the specified GIS config from the DB, caches it in response. Passing in a false or non-existent id will cause the personal config, if any, to be used, else the site config (uuid SITE_DEFAULT), else their fallback values defined in this class. If force_update_cache is true, the config will be read and cached in response even if the specified config is the same as what's already cached. Used when the config was just written. The config itself will be available in response.s3.gis.config. Scalar fields from the gis_config record and its linked gis_projection record have the same names as the fields in their tables and can be accessed as response.s3.gis.<fieldname>. Returns the id of the config it actually used, if any. @param: config_id. use '0' to set the SITE_DEFAULT @ToDo: Merge configs for Event """ _gis = current.response.s3.gis # If an id has been supplied, try it first. If it matches what's in # response, there's no work to do. if config_id and not force_update_cache and \ _gis.config and \ _gis.config.id == config_id: return db = current.db s3db = current.s3db ctable = s3db.gis_config mtable = s3db.gis_marker ptable = s3db.gis_projection stable = s3db.gis_style fields = (ctable.id, ctable.default_location_id, ctable.region_location_id, ctable.geocoder, ctable.lat_min, ctable.lat_max, ctable.lon_min, ctable.lon_max, ctable.zoom, ctable.lat, ctable.lon, ctable.pe_id, ctable.wmsbrowser_url, ctable.wmsbrowser_name, ctable.zoom_levels, ctable.merge, mtable.image, mtable.height, mtable.width, ptable.epsg, ptable.proj4js, ptable.maxExtent, ptable.units, ) cache = Storage() row = None rows = None if config_id: # Merge this one with the Site Default query = (ctable.id == config_id) | \ (ctable.uuid == "SITE_DEFAULT") # May well not be complete, so Left Join left = (ptable.on(ptable.id == ctable.projection_id), stable.on((stable.config_id == ctable.id) & \ (stable.layer_id == None)), mtable.on(mtable.id == stable.marker_id), ) rows = db(query).select(*fields, left=left, orderby=ctable.pe_type, limitby=(0, 2)) if len(rows) == 1: # The requested config must be invalid, so just use site default row = rows.first() elif config_id is 0: # Use site default query = (ctable.uuid == "SITE_DEFAULT") # May well not be complete, so Left Join left = (ptable.on(ptable.id == ctable.projection_id), stable.on((stable.config_id == ctable.id) & \ (stable.layer_id == None)), mtable.on(mtable.id == stable.marker_id), ) row = db(query).select(*fields, left=left, limitby=(0, 1)).first() if not row: # No configs found at all _gis.config = cache return cache # If no id supplied, extend the site config with any personal or OU configs if not rows and not row: auth = current.auth if auth.is_logged_in(): # Read personalised config, if available. user = auth.user pe_id = user.get("pe_id") if pe_id: # Also look for OU configs pes = [] if user.organisation_id: # Add the user account's Org to the list # (Will take lower-priority than Personal) otable = s3db.org_organisation org = db(otable.id == user.organisation_id).select(otable.pe_id, limitby=(0, 1) ).first() try: pes.append(org.pe_id) except: current.log.warning("Unable to find Org %s" % user.organisation_id) if current.deployment_settings.get_org_branches(): # Also look for Parent Orgs ancestors = s3db.pr_get_ancestors(org.pe_id) pes += ancestors if user.site_id: # Add the user account's Site to the list # (Will take lower-priority than Org/Personal) site_pe_id = s3db.pr_get_pe_id("org_site", user.site_id) if site_pe_id: pes.append(site_pe_id) if user.org_group_id: # Add the user account's Org Group to the list # (Will take lower-priority than Site/Org/Personal) ogtable = s3db.org_group ogroup = db(ogtable.id == user.org_group_id).select(ogtable.pe_id, limitby=(0, 1) ).first() pes = list(pes) try: pes.append(ogroup.pe_id) except: current.log.warning("Unable to find Org Group %s" % user.org_group_id) query = (ctable.uuid == "SITE_DEFAULT") | \ ((ctable.pe_id == pe_id) & \ (ctable.pe_default != False)) if len(pes) == 1: query |= (ctable.pe_id == pes[0]) else: query |= (ctable.pe_id.belongs(pes)) # Personal/OU may well not be complete, so Left Join left = (ptable.on(ptable.id == ctable.projection_id), stable.on((stable.config_id == ctable.id) & \ (stable.layer_id == None)), mtable.on(mtable.id == stable.marker_id), ) # Order by pe_type (defined in gis_config) # @ToDo: Sort orgs from the hierarchy? # (Currently we just have branch > non-branch in pe_type) rows = db(query).select(*fields, left=left, orderby=ctable.pe_type) if len(rows) == 1: row = rows.first() if rows and not row: # Merge Configs merge = True cache["ids"] = [] for row in rows: if not merge: break config = row["gis_config"] if config.merge is False: # Backwards-compatibility merge = False if not config_id: config_id = config.id cache["ids"].append(config.id) for key in config: if key in ("delete_record", "gis_layer_config", "gis_menu", "update_record", "merge"): continue if key not in cache or cache[key] is None: cache[key] = config[key] if "epsg" not in cache or cache["epsg"] is None: projection = row["gis_projection"] for key in ["epsg", "units", "maxExtent", "proj4js"]: cache[key] = projection[key] if key in projection \ else None if "marker_image" not in cache or \ cache["marker_image"] is None: marker = row["gis_marker"] for key in ("image", "height", "width"): cache["marker_%s" % key] = marker[key] if key in marker \ else None # Add NULL values for any that aren't defined, to avoid KeyErrors for key in ("epsg", "units", "proj4js", "maxExtent", "marker_image", "marker_height", "marker_width", ): if key not in cache: cache[key] = None if not row: # No personal config or not logged in. Use site default. query = (ctable.uuid == "SITE_DEFAULT") & \ (mtable.id == stable.marker_id) & \ (stable.config_id == ctable.id) & \ (stable.layer_id == None) & \ (ptable.id == ctable.projection_id) row = db(query).select(*fields, limitby=(0, 1)).first() if not row: # No configs found at all _gis.config = cache return cache if not cache: # We had a single row config = row["gis_config"] config_id = config.id cache["ids"] = [config_id] projection = row["gis_projection"] marker = row["gis_marker"] for key in config: cache[key] = config[key] for key in ("epsg", "maxExtent", "proj4js", "units"): cache[key] = projection[key] if key in projection else None for key in ("image", "height", "width"): cache["marker_%s" % key] = marker[key] if key in marker \ else None # Store the values _gis.config = cache return cache # ------------------------------------------------------------------------- @staticmethod def get_config(): """ Returns the current GIS config structure. @ToDo: Config() class """ _gis = current.response.s3.gis if not _gis.config: # Ask set_config to put the appropriate config in response. if current.session.s3.gis_config_id: GIS.set_config(current.session.s3.gis_config_id) else: GIS.set_config() return _gis.config # ------------------------------------------------------------------------- def get_location_hierarchy(self, level=None, location=None): """ Returns the location hierarchy and it's labels @param: level - a specific level for which to lookup the label @param: location - the location_id to lookup the location for currently only the actual location is supported @ToDo: Do a search of parents to allow this lookup for any location """ _levels = self.hierarchy_levels _location = location if not location and _levels: # Use cached value if level: if level in _levels: return _levels[level] else: return level else: return _levels COUNTRY = current.messages.COUNTRY if level == "L0": return COUNTRY db = current.db s3db = current.s3db table = s3db.gis_hierarchy fields = (table.uuid, table.L1, table.L2, table.L3, table.L4, table.L5, ) query = (table.uuid == "SITE_DEFAULT") if not location: config = GIS.get_config() location = config.region_location_id if location: # Try the Region, but ensure we have the fallback available in a single query query = query | (table.location_id == location) rows = db(query).select(cache=s3db.cache, *fields) if len(rows) > 1: # Remove the Site Default _filter = lambda row: row.uuid == "SITE_DEFAULT" rows.exclude(_filter) elif not rows: # prepop hasn't run yet if level: return level levels = OrderedDict() hierarchy_level_keys = self.hierarchy_level_keys for key in hierarchy_level_keys: if key == "L0": levels[key] = COUNTRY else: levels[key] = key return levels T = current.T row = rows.first() if level: try: return T(row[level]) except: return level else: levels = OrderedDict() hierarchy_level_keys = self.hierarchy_level_keys for key in hierarchy_level_keys: if key == "L0": levels[key] = COUNTRY elif key in row and row[key]: # Only include rows with values levels[key] = str(T(row[key])) if not _location: # Cache the value self.hierarchy_levels = levels if level: return levels[level] else: return levels # ------------------------------------------------------------------------- def get_strict_hierarchy(self, location=None): """ Returns the strict hierarchy value from the current config. @param: location - the location_id of the record to check """ s3db = current.s3db table = s3db.gis_hierarchy # Read the system default # @ToDo: Check for an active gis_config region? query = (table.uuid == "SITE_DEFAULT") if location: # Try the Location's Country, but ensure we have the fallback available in a single query query = query | (table.location_id == self.get_parent_country(location)) rows = current.db(query).select(table.uuid, table.strict_hierarchy, cache=s3db.cache) if len(rows) > 1: # Remove the Site Default _filter = lambda row: row.uuid == "SITE_DEFAULT" rows.exclude(_filter) row = rows.first() if row: strict = row.strict_hierarchy else: # Pre-pop hasn't run yet return False return strict # ------------------------------------------------------------------------- def get_max_hierarchy_level(self): """ Returns the deepest level key (i.e. Ln) in the current hierarchy. - used by gis_location_onvalidation() """ location_hierarchy = self.get_location_hierarchy() return max(location_hierarchy) # ------------------------------------------------------------------------- def get_all_current_levels(self, level=None): """ Get the current hierarchy levels plus non-hierarchy levels. """ all_levels = OrderedDict() all_levels.update(self.get_location_hierarchy()) #T = current.T #all_levels["GR"] = T("Location Group") #all_levels["XX"] = T("Imported") if level: try: return all_levels[level] except Exception: return level else: return all_levels # ------------------------------------------------------------------------- def get_relevant_hierarchy_levels(self, as_dict=False): """ Get current location hierarchy levels relevant for the user """ levels = self.relevant_hierarchy_levels if not levels: levels = OrderedDict(self.get_location_hierarchy()) if len(current.deployment_settings.get_gis_countries()) == 1 or \ current.response.s3.gis.config.region_location_id: levels.pop("L0", None) self.relevant_hierarchy_levels = levels if not as_dict: return list(levels.keys()) else: return levels # ------------------------------------------------------------------------- @staticmethod def get_countries(key_type="id"): """ Returns country code or L0 location id versus name for all countries. The lookup is cached in the session If key_type is "code", these are returned as an OrderedDict with country code as the key. If key_type is "id", then the location id is the key. In all cases, the value is the name. """ session = current.session if "gis" not in session: session.gis = Storage() gis = session.gis if gis.countries_by_id: cached = True else: cached = False if not cached: s3db = current.s3db table = s3db.gis_location ttable = s3db.gis_location_tag query = (table.level == "L0") & \ (ttable.tag == "ISO2") & \ (ttable.location_id == table.id) countries = current.db(query).select(table.id, table.name, ttable.value, orderby=table.name) if not countries: return [] countries_by_id = OrderedDict() countries_by_code = OrderedDict() for row in countries: location = row["gis_location"] countries_by_id[location.id] = location.name countries_by_code[row["gis_location_tag"].value] = location.name # Cache in the session gis.countries_by_id = countries_by_id gis.countries_by_code = countries_by_code if key_type == "id": return countries_by_id else: return countries_by_code elif key_type == "id": return gis.countries_by_id else: return gis.countries_by_code # ------------------------------------------------------------------------- @staticmethod def get_country(key, key_type="id"): """ Returns country name for given code or id from L0 locations. The key can be either location id or country code, as specified by key_type. """ if key: if current.gis.get_countries(key_type): if key_type == "id": return current.session.gis.countries_by_id[key] else: return current.session.gis.countries_by_code[key] return None # ------------------------------------------------------------------------- def get_parent_country(self, location, key_type="id"): """ Returns the parent country for a given record @param: location: the location or id to search for @param: key_type: whether to return an id or code @ToDo: Optimise to not use try/except """ if not location: return None db = current.db s3db = current.s3db # @ToDo: Avoid try/except here! # - separate parameters best as even isinstance is expensive try: # location is passed as integer (location_id) table = s3db.gis_location location = db(table.id == location).select(table.id, table.path, table.level, limitby=(0, 1), cache=s3db.cache).first() except: # location is passed as record pass if location.level == "L0": if key_type == "id": return location.id elif key_type == "code": ttable = s3db.gis_location_tag query = (ttable.tag == "ISO2") & \ (ttable.location_id == location.id) tag = db(query).select(ttable.value, limitby=(0, 1)).first() try: return tag.value except: return None else: parents = self.get_parents(location.id, feature=location) if parents: for row in parents: if row.level == "L0": if key_type == "id": return row.id elif key_type == "code": ttable = s3db.gis_location_tag query = (ttable.tag == "ISO2") & \ (ttable.location_id == row.id) tag = db(query).select(ttable.value, limitby=(0, 1)).first() try: return tag.value except: return None return None # ------------------------------------------------------------------------- def get_default_country(self, key_type="id"): """ Returns the default country for the active gis_config @param: key_type: whether to return an id or code """ config = GIS.get_config() if config.default_location_id: return self.get_parent_country(config.default_location_id, key_type=key_type) return None # ------------------------------------------------------------------------- def get_features_in_polygon(self, location, tablename=None, category=None): """ Returns a gluon.sql.Rows of Features within a Polygon. The Polygon can be either a WKT string or the ID of a record in the gis_location table Currently unused. @ToDo: Optimise to not use try/except """ from shapely.geos import ReadingError from shapely.wkt import loads as wkt_loads try: # Enable C-based speedups available from 1.2.10+ from shapely import speedups speedups.enable() except: current.log.info("S3GIS", "Upgrade Shapely for Performance enhancements") db = current.db s3db = current.s3db locations = s3db.gis_location try: location_id = int(location) # Check that the location is a polygon location = db(locations.id == location_id).select(locations.wkt, locations.lon_min, locations.lon_max, locations.lat_min, locations.lat_max, limitby=(0, 1) ).first() if location: wkt = location.wkt if wkt and (wkt.startswith("POLYGON") or \ wkt.startswith("MULTIPOLYGON")): # ok lon_min = location.lon_min lon_max = location.lon_max lat_min = location.lat_min lat_max = location.lat_max else: current.log.error("Location searched within isn't a Polygon!") return None except: # @ToDo: need specific exception wkt = location if (wkt.startswith("POLYGON") or wkt.startswith("MULTIPOLYGON")): # ok lon_min = None else: current.log.error("This isn't a Polygon!") return None try: polygon = wkt_loads(wkt) except: # @ToDo: need specific exception current.log.error("Invalid Polygon!") return None table = s3db[tablename] if "location_id" not in table.fields(): # @ToDo: Add any special cases to be able to find the linked location current.log.error("This table doesn't have a location_id!") return None query = (table.location_id == locations.id) if "deleted" in table.fields: query &= (table.deleted == False) # @ToDo: Check AAA (do this as a resource filter?) features = db(query).select(locations.wkt, locations.lat, locations.lon, table.ALL) output = Rows() # @ToDo: provide option to use PostGIS/Spatialite # settings = current.deployment_settings # if settings.gis.spatialdb and settings.database.db_type == "postgres": if lon_min is None: # We have no BBOX so go straight to the full geometry check for row in features: _location = row.gis_location wkt = _location.wkt if wkt is None: lat = _location.lat lon = _location.lon if lat is not None and lon is not None: wkt = self.latlon_to_wkt(lat, lon) else: continue try: shape = wkt_loads(wkt) if shape.intersects(polygon): # Save Record output.records.append(row) except ReadingError: current.log.error("Error reading wkt of location with id", value=row.id) else: # 1st check for Features included within the bbox (faster) def in_bbox(row): _location = row.gis_location return (_location.lon > lon_min) & \ (_location.lon < lon_max) & \ (_location.lat > lat_min) & \ (_location.lat < lat_max) for row in features.find(lambda row: in_bbox(row)): # Search within this subset with a full geometry check # Uses Shapely. _location = row.gis_location wkt = _location.wkt if wkt is None: lat = _location.lat lon = _location.lon if lat is not None and lon is not None: wkt = self.latlon_to_wkt(lat, lon) else: continue try: shape = wkt_loads(wkt) if shape.intersects(polygon): # Save Record output.records.append(row) except ReadingError: current.log.error("Error reading wkt of location with id", value = row.id) return output # ------------------------------------------------------------------------- @staticmethod def get_polygon_from_bounds(bbox): """ Given a gis_location record or a bounding box dict with keys lon_min, lon_max, lat_min, lat_max, construct a WKT polygon with points at the corners. """ lon_min = bbox["lon_min"] lon_max = bbox["lon_max"] lat_min = bbox["lat_min"] lat_max = bbox["lat_max"] # Take the points in a counterclockwise direction. points = [(lon_min, lat_min), (lon_min, lat_max), (lon_max, lat_max), (lon_min, lat_max), (lon_min, lat_min)] pairs = ["%s %s" % (p[0], p[1]) for p in points] wkt = "POLYGON ((%s))" % ", ".join(pairs) return wkt # ------------------------------------------------------------------------- @staticmethod def get_bounds_from_radius(lat, lon, radius): """ Compute a bounding box given a Radius (in km) of a LatLon Location Note the order of the parameters. @return a dict containing the bounds with keys min_lon, max_lon, min_lat, max_lat See: http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates """ import math radians = math.radians degrees = math.degrees MIN_LAT = radians(-90) # -PI/2 MAX_LAT = radians(90) # PI/2 MIN_LON = radians(-180) # -PI MAX_LON = radians(180) # PI # Convert to radians for the calculation r = float(radius) / RADIUS_EARTH radLat = radians(lat) radLon = radians(lon) # Calculate the bounding box minLat = radLat - r maxLat = radLat + r if (minLat > MIN_LAT) and (maxLat < MAX_LAT): deltaLon = math.asin(math.sin(r) / math.cos(radLat)) minLon = radLon - deltaLon if (minLon < MIN_LON): minLon += 2 * math.pi maxLon = radLon + deltaLon if (maxLon > MAX_LON): maxLon -= 2 * math.pi else: # Special care for Poles & 180 Meridian: # http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates#PolesAnd180thMeridian minLat = max(minLat, MIN_LAT) maxLat = min(maxLat, MAX_LAT) minLon = MIN_LON maxLon = MAX_LON # Convert back to degrees minLat = degrees(minLat) minLon = degrees(minLon) maxLat = degrees(maxLat) maxLon = degrees(maxLon) return {"lat_min": minLat, "lat_max": maxLat, "lon_min": minLon, "lon_max": maxLon, } # ------------------------------------------------------------------------- def get_features_in_radius(self, lat, lon, radius, tablename=None, category=None): """ Returns Features within a Radius (in km) of a LatLon Location Unused """ import math db = current.db settings = current.deployment_settings if settings.get_gis_spatialdb() and \ settings.get_database_type() == "postgres": # Use PostGIS routine # The ST_DWithin function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries. # @ToDo: Support optional Category (make this a generic filter?) import psycopg2 import psycopg2.extras # Convert km to degrees (since we're using the_geom not the_geog) radius = math.degrees(float(radius) / RADIUS_EARTH) dbstr = "dbname=%(database)s user=%(username)s " \ "password=%(password)s host=%(host)s port=%(port)s" % \ settings.db_params connection = psycopg2.connect(dbstr) cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor) info_string = "SELECT column_name, udt_name FROM information_schema.columns WHERE table_name = 'gis_location' or table_name = '%s';" % tablename cursor.execute(info_string) # @ToDo: Look at more optimal queries for just those fields we need if tablename: # Lookup the resource query_string = cursor.mogrify("SELECT * FROM gis_location, %s WHERE %s.location_id = gis_location.id and ST_DWithin (ST_GeomFromText ('POINT (%s %s)', 4326), the_geom, %s);" % (tablename, tablename, lon, lat, radius)) else: # Lookup the raw Locations query_string = cursor.mogrify("SELECT * FROM gis_location WHERE ST_DWithin (ST_GeomFromText ('POINT (%s %s)', 4326), the_geom, %s);" % (lon, lat, radius)) cursor.execute(query_string) # @ToDo: Export Rows? features = [] for record in cursor: d = dict(record.items()) row = Storage() # @ToDo: Optional support for Polygons if tablename: row.gis_location = Storage() row.gis_location.id = d["id"] row.gis_location.lat = d["lat"] row.gis_location.lon = d["lon"] row.gis_location.lat_min = d["lat_min"] row.gis_location.lon_min = d["lon_min"] row.gis_location.lat_max = d["lat_max"] row.gis_location.lon_max = d["lon_max"] row[tablename] = Storage() row[tablename].id = d["id"] row[tablename].name = d["name"] else: row.name = d["name"] row.id = d["id"] row.lat = d["lat"] row.lon = d["lon"] row.lat_min = d["lat_min"] row.lon_min = d["lon_min"] row.lat_max = d["lat_max"] row.lon_max = d["lon_max"] features.append(row) return features #elif settings.database.db_type == "mysql": # Do the calculation in MySQL to pull back only the relevant rows # Raw MySQL Formula from: http://blog.peoplesdns.com/archives/24 # PI = 3.141592653589793, mysql's pi() function returns 3.141593 #pi = math.pi #query = """SELECT name, lat, lon, acos(SIN( PI()* 40.7383040 /180 )*SIN( PI()*lat/180 ))+(cos(PI()* 40.7383040 /180)*COS( PI()*lat/180) *COS(PI()*lon/180-PI()* -73.99319 /180))* 3963.191 #AS distance #FROM gis_location #WHERE 1=1 #AND 3963.191 * ACOS( (SIN(PI()* 40.7383040 /180)*SIN(PI() * lat/180)) + (COS(PI()* 40.7383040 /180)*cos(PI()*lat/180)*COS(PI() * lon/180-PI()* -73.99319 /180))) < = 1.5 #ORDER BY 3963.191 * ACOS((SIN(PI()* 40.7383040 /180)*SIN(PI()*lat/180)) + (COS(PI()* 40.7383040 /180)*cos(PI()*lat/180)*COS(PI() * lon/180-PI()* -73.99319 /180)))""" # db.executesql(query) else: # Calculate in Python # Pull back all the rows within a square bounding box (faster than checking all features manually) # Then check each feature within this subset # http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates # @ToDo: Support optional Category (make this a generic filter?) bbox = self.get_bounds_from_radius(lat, lon, radius) # shortcut locations = db.gis_location query = (locations.lat > bbox["lat_min"]) & \ (locations.lat < bbox["lat_max"]) & \ (locations.lon > bbox["lon_min"]) & \ (locations.lon < bbox["lon_max"]) deleted = (locations.deleted == False) empty = (locations.lat != None) & (locations.lon != None) query = deleted & empty & query if tablename: # Lookup the resource table = current.s3db[tablename] query &= (table.location_id == locations.id) records = db(query).select(table.ALL, locations.id, locations.name, locations.level, locations.lat, locations.lon, locations.lat_min, locations.lon_min, locations.lat_max, locations.lon_max) else: # Lookup the raw Locations records = db(query).select(locations.id, locations.name, locations.level, locations.lat, locations.lon, locations.lat_min, locations.lon_min, locations.lat_max, locations.lon_max) features = Rows() for row in records: # Calculate the Great Circle distance if tablename: distance = self.greatCircleDistance(lat, lon, row["gis_location.lat"], row["gis_location.lon"]) else: distance = self.greatCircleDistance(lat, lon, row.lat, row.lon) if distance < radius: features.records.append(row) else: # skip continue return features # ------------------------------------------------------------------------- def get_latlon(self, feature_id, filter=False): """ Returns the Lat/Lon for a Feature used by display_feature() in gis controller @param feature_id: the feature ID @param filter: Filter out results based on deployment_settings """ db = current.db table = db.gis_location feature = db(table.id == feature_id).select(table.id, table.lat, table.lon, table.parent, table.path, limitby=(0, 1)).first() # Zero is an allowed value, hence explicit test for None. if "lon" in feature and "lat" in feature and \ (feature.lat is not None) and (feature.lon is not None): return {"lon": feature.lon, "lat": feature.lat, } else: # Step through ancestors to first with lon, lat. parents = self.get_parents(feature.id, feature=feature) if parents: for row in parents: lon = row.get("lon", None) lat = row.get("lat", None) if (lon is not None) and (lat is not None): return {"lon": lon, "lat": lat, } # Invalid feature_id return None # ------------------------------------------------------------------------- @staticmethod def get_locations(table, query, join = True, geojson = True, ): """ Returns the locations for an XML export - used by GIS.get_location_data() and S3PivotTable.geojson() @ToDo: Support multiple locations for a single resource (e.g. a Project working in multiple Communities) """ db = current.db tablename = table._tablename gtable = current.s3db.gis_location settings = current.deployment_settings tolerance = settings.get_gis_simplify_tolerance() output = {} if settings.get_gis_spatialdb(): if geojson: precision = settings.get_gis_precision() if tolerance: # Do the Simplify & GeoJSON direct from the DB web2py_installed_version = parse_version(global_settings.web2py_version) web2py_installed_datetime = web2py_installed_version[4] # datetime_index = 4 if web2py_installed_datetime >= datetime.datetime(2015, 1, 17, 0, 7, 4): # Use http://www.postgis.org/docs/ST_SimplifyPreserveTopology.html rows = db(query).select(table.id, gtable.the_geom.st_simplifypreservetopology(tolerance).st_asgeojson(precision=precision).with_alias("geojson")) else: # Use http://www.postgis.org/docs/ST_Simplify.html rows = db(query).select(table.id, gtable.the_geom.st_simplify(tolerance).st_asgeojson(precision=precision).with_alias("geojson")) else: # Do the GeoJSON direct from the DB rows = db(query).select(table.id, gtable.the_geom.st_asgeojson(precision=precision).with_alias("geojson")) for row in rows: key = row[tablename].id if key in output: output[key].append(row.geojson) else: output[key] = [row.geojson] else: if tolerance: # Do the Simplify direct from the DB rows = db(query).select(table.id, gtable.the_geom.st_simplify(tolerance).st_astext().with_alias("wkt")) else: rows = db(query).select(table.id, gtable.the_geom.st_astext().with_alias("wkt")) for row in rows: key = row[tablename].id if key in output: output[key].append(row.wkt) else: output[key] = [row.wkt] else: rows = db(query).select(table.id, gtable.wkt) simplify = GIS.simplify if geojson: # Simplify the polygon to reduce download size if join: for row in rows: g = simplify(row["gis_location"].wkt, tolerance=tolerance, output="geojson") if g: key = row[tablename].id if key in output: output[key].append(g) else: output[key] = [g] else: # gis_location: always single for row in rows: g = simplify(row.wkt, tolerance=tolerance, output="geojson") if g: output[row.id] = g else: if join: if tolerance: # Simplify the polygon to reduce download size # & also to work around the recursion limit in libxslt # http://blog.gmane.org/gmane.comp.python.lxml.devel/day=20120309 for row in rows: wkt = simplify(row["gis_location"].wkt) if wkt: key = row[tablename].id if key in output: output[key].append(wkt) else: output[key] = [wkt] else: for row in rows: wkt = row["gis_location"].wkt if wkt: key = row[tablename].id if key in output: output[key].append(wkt) else: output[key] = [wkt] else: # gis_location: always single if tolerance: for row in rows: wkt = simplify(row.wkt) if wkt: output[row.id] = wkt else: for row in rows: wkt = row.wkt if wkt: output[row.id] = wkt return output # ------------------------------------------------------------------------- @staticmethod def get_location_data(resource, attr_fields=None, count=None): """ Returns the locations, markers and popup tooltips for an XML export e.g. Feature Layers or Search results (Feature Resources) e.g. Exports in KML, GeoRSS or GPX format Called by S3REST: S3Resource.export_tree() @param: resource - S3Resource instance (required) @param: attr_fields - list of attr_fields to use instead of reading from get_vars or looking up in gis_layer_feature @param: count - total number of features (can actually be more if features have multiple locations) """ tablename = resource.tablename if tablename == "gis_feature_query": # Requires no special handling: XSLT uses normal fields return {} format = current.auth.permission.format geojson = format == "geojson" if geojson: if count and \ count > current.deployment_settings.get_gis_max_features(): headers = {"Content-Type": "application/json"} message = "Too Many Records" status = 509 raise HTTP(status, body=current.xml.json_message(success=False, statuscode=status, message=message), web2py_error=message, **headers) # Lookups per layer not per record if len(tablename) > 19 and \ tablename.startswith("gis_layer_shapefile"): # GIS Shapefile Layer location_data = GIS.get_shapefile_geojson(resource) or {} return location_data elif tablename == "gis_theme_data": # GIS Theme Layer location_data = GIS.get_theme_geojson(resource) or {} return location_data else: # e.g. GIS Feature Layer # e.g. Search results # Lookup Data using this function pass elif format in ("georss", "kml", "gpx"): # Lookup Data using this function pass else: # @ToDo: Bulk lookup of LatLons for S3XML.latlon() return {} NONE = current.messages["NONE"] #if DEBUG: # start = datetime.datetime.now() db = current.db s3db = current.s3db request = current.request get_vars = request.get_vars ftable = s3db.gis_layer_feature layer = None layer_id = get_vars.get("layer", None) if layer_id: # Feature Layer # e.g. Search results loaded as a Feature Resource layer layer = db(ftable.layer_id == layer_id).select(ftable.attr_fields, # @ToDo: Deprecate ftable.popup_fields, ftable.individual, ftable.points, ftable.trackable, limitby=(0, 1) ).first() else: # e.g. KML, GeoRSS or GPX export # e.g. Volunteer Layer in Vulnerability module controller = request.controller function = request.function query = (ftable.controller == controller) & \ (ftable.function == function) layers = db(query).select(ftable.layer_id, ftable.attr_fields, ftable.popup_fields, # @ToDo: Deprecate ftable.style_default, # @ToDo: Rename as no longer really 'style' ftable.individual, ftable.points, ftable.trackable, ) if len(layers) > 1: layers.exclude(lambda row: row.style_default == False) if len(layers) > 1: # We can't provide details for the whole layer, but need to do a per-record check return None if layers: layer = layers.first() layer_id = layer.layer_id if not attr_fields: # Try get_vars attr_fields = get_vars.get("attr", []) if attr_fields: attr_fields = attr_fields.split(",") popup_fields = get_vars.get("popup", []) if popup_fields: popup_fields = popup_fields.split(",") if layer: if not popup_fields: # Lookup from gis_layer_feature popup_fields = layer.popup_fields or [] if not attr_fields: # Lookup from gis_layer_feature # @ToDo: Consider parsing these from style.popup_format instead # - see S3Report.geojson() attr_fields = layer.attr_fields or [] individual = layer.individual points = layer.points trackable = layer.trackable else: if not popup_fields: popup_fields = ["name"] individual = False points = False trackable = False table = resource.table pkey = table._id.name attributes = {} markers = {} styles = {} _pkey = table[pkey] # Ensure there are no ID represents to confuse things _pkey.represent = None if geojson: # Build the Attributes now so that representations can be # looked-up in bulk rather than as a separate lookup per record if popup_fields: # Old-style attr_fields = list(set(popup_fields + attr_fields)) if attr_fields: attr = {} # Make a copy for the pkey insertion fields = list(attr_fields) if pkey not in fields: fields.insert(0, pkey) data = resource.select(fields, limit = None, raw_data = True, represent = True, show_links = False) attr_cols = {} for f in data["rfields"]: fname = f.fname selector = f.selector if fname in attr_fields or selector in attr_fields: fieldname = f.colname tname, fname = fieldname.split(".") try: ftype = db[tname][fname].type except AttributeError: # FieldMethod ftype = None except KeyError: current.log.debug("SGIS: Field %s doesn't exist in table %s" % (fname, tname)) continue attr_cols[fieldname] = (ftype, fname) _pkey = str(_pkey) for row in data["rows"]: record_id = int(row[_pkey]) if attr_cols: attribute = {} for fieldname in attr_cols: represent = row[fieldname] if represent is not None and \ represent not in (NONE, ""): # Skip empty fields _attr = attr_cols[fieldname] ftype = _attr[0] if ftype == "integer": if isinstance(represent, lazyT): # Integer is just a lookup key represent = s3_str(represent) else: # Attributes should be numbers not strings # (@ToDo: Add a JS i18n formatter for the tooltips) # NB This also relies on decoding within geojson/export.xsl and S3XML.__element2json() represent = row["_row"][fieldname] elif ftype in ("double", "float"): # Attributes should be numbers not strings # (@ToDo: Add a JS i18n formatter for the tooltips) represent = row["_row"][fieldname] else: represent = s3_str(represent) attribute[_attr[1]] = represent attr[record_id] = attribute attributes[tablename] = attr #if DEBUG: # end = datetime.datetime.now() # duration = end - start # duration = "{:.2f}".format(duration.total_seconds()) # if layer_id: # layer_name = db(ftable.id == layer_id).select(ftable.name, # limitby=(0, 1) # ).first().name # else: # layer_name = "Unknown" # _debug("Attributes lookup of layer %s completed in %s seconds", # layer_name, # duration, # ) _markers = get_vars.get("markers", None) if _markers: # Add a per-feature Marker marker_fn = s3db.get_config(tablename, "marker_fn") if marker_fn: m = {} for record in resource: m[record[pkey]] = marker_fn(record) else: # No configuration found so use default marker for all c, f = tablename.split("_", 1) m = GIS.get_marker(c, f) markers[tablename] = m if individual: # Add a per-feature Style # Optionally restrict to a specific Config? #config = GIS.get_config() stable = s3db.gis_style query = (stable.deleted == False) & \ (stable.layer_id == layer_id) & \ (stable.record_id.belongs(resource._ids)) #((stable.config_id == config.id) | # (stable.config_id == None)) rows = db(query).select(stable.record_id, stable.style) for row in rows: styles[row.record_id] = json.dumps(row.style, separators=SEPARATORS) styles[tablename] = styles else: # KML, GeoRSS or GPX marker_fn = s3db.get_config(tablename, "marker_fn") if marker_fn: # Add a per-feature Marker for record in resource: markers[record[pkey]] = marker_fn(record) else: # No configuration found so use default marker for all c, f = tablename.split("_", 1) markers = GIS.get_marker(c, f) markers[tablename] = markers # Lookup the LatLons now so that it can be done as a single # query rather than per record #if DEBUG: # start = datetime.datetime.now() latlons = {} #wkts = {} geojsons = {} gtable = s3db.gis_location if trackable: # Use S3Track ids = resource._ids # Ensure IDs in ascending order ids.sort() try: tracker = S3Trackable(table, record_ids=ids) except SyntaxError: # This table isn't trackable pass else: _latlons = tracker.get_location(_fields=[gtable.lat, gtable.lon], empty = False, ) index = 0 for _id in ids: _location = _latlons[index] latlons[_id] = (_location.lat, _location.lon) index += 1 if not latlons: join = True #custom = False if "location_id" in table.fields: query = (table.id.belongs(resource._ids)) & \ (table.location_id == gtable.id) elif "site_id" in table.fields: stable = s3db.org_site query = (table.id.belongs(resource._ids)) & \ (table.site_id == stable.site_id) & \ (stable.location_id == gtable.id) elif tablename == "gis_location": join = False query = (table.id.belongs(resource._ids)) else: # Look at the Context context = resource.get_config("context") if context: location_context = context.get("location") else: location_context = None if not location_context: # Can't display this resource on the Map return None # @ToDo: Proper system rather than this hack_which_works_for_current_usecase # Resolve selector (which automatically attaches any required component) rfield = resource.resolve_selector(location_context) if "." in location_context: # Component alias, cfield = location_context.split(".", 1) try: component = resource.components[alias] except KeyError: # Invalid alias # Can't display this resource on the Map return None ctablename = component.tablename ctable = s3db[ctablename] query = (table.id.belongs(resource._ids)) & \ rfield.join[ctablename] & \ (ctable[cfield] == gtable.id) #custom = True # @ToDo: #elif "$" in location_context: else: # Can't display this resource on the Map return None if geojson and not points: geojsons[tablename] = GIS.get_locations(table, query, join, geojson) # @ToDo: Support Polygons in KML, GPX & GeoRSS #else: # wkts[tablename] = GIS.get_locations(table, query, join, geojson) else: # Points rows = db(query).select(table.id, gtable.lat, gtable.lon) #if custom: # # Add geoJSONs #elif join: if join: for row in rows: # @ToDo: Support records with multiple locations # (e.g. an Org with multiple Facs) _location = row["gis_location"] latlons[row[tablename].id] = (_location.lat, _location.lon) else: # gis_location: Always single for row in rows: latlons[row.id] = (row.lat, row.lon) _latlons = {} if latlons: _latlons[tablename] = latlons #if DEBUG: # end = datetime.datetime.now() # duration = end - start # duration = "{:.2f}".format(duration.total_seconds()) # _debug("latlons lookup of layer %s completed in %s seconds", # layer_name, # duration, # ) # Used by S3XML's gis_encode() return {"geojsons": geojsons, "latlons": _latlons, #"wkts": wkts, "attributes": attributes, "markers": markers, "styles": styles, } # ------------------------------------------------------------------------- @staticmethod def get_marker(controller=None, function=None, filter=None, ): """ Returns a Marker dict - called by xml.gis_encode() for non-geojson resources - called by S3Map.widget() if no marker_fn supplied """ marker = None if controller and function: # Lookup marker in the gis_style table db = current.db s3db = current.s3db ftable = s3db.gis_layer_feature stable = s3db.gis_style mtable = s3db.gis_marker config = GIS.get_config() query = (ftable.controller == controller) & \ (ftable.function == function) & \ (ftable.aggregate == False) left = (stable.on((stable.layer_id == ftable.layer_id) & \ (stable.record_id == None) & \ ((stable.config_id == config.id) | \ (stable.config_id == None))), mtable.on(mtable.id == stable.marker_id), ) if filter: query &= (ftable.filter == filter) if current.deployment_settings.get_database_type() == "postgres": # None is last orderby = stable.config_id else: # None is 1st orderby = ~stable.config_id layers = db(query).select(mtable.image, mtable.height, mtable.width, ftable.style_default, stable.gps_marker, left=left, orderby=orderby) if len(layers) > 1: layers.exclude(lambda row: row["gis_layer_feature.style_default"] == False) if len(layers) == 1: layer = layers.first() else: # Can't differentiate layer = None if layer: _marker = layer["gis_marker"] if _marker.image: marker = {"image": _marker.image, "height": _marker.height, "width": _marker.width, "gps_marker": layer["gis_style"].gps_marker, } if not marker: # Default marker = Marker().as_dict() return marker # ------------------------------------------------------------------------- @staticmethod def get_style(layer_id=None, aggregate=None, ): """ Returns a Style dict - called by S3Report.geojson() """ style = None if layer_id: style = Style(layer_id=layer_id, aggregate=aggregate).as_dict() if not style: # Default style = Style().as_dict() return style # ------------------------------------------------------------------------- @staticmethod def get_screenshot(config_id, temp=True, height=None, width=None): """ Save a Screenshot of a saved map @requires: PhantomJS http://phantomjs.org Selenium https://pypi.python.org/pypi/selenium """ # @ToDo: allow selection of map_id map_id = "default_map" #from selenium import webdriver # We include a Custom version which is patched to access native PhantomJS functions from: # https://github.com/watsonmw/ghostdriver/commit/d9b65ed014ed9ff8a5e852cc40e59a0fd66d0cf1 from webdriver import WebDriver from selenium.common.exceptions import TimeoutException, WebDriverException from selenium.webdriver.support.ui import WebDriverWait request = current.request cachepath = os.path.join(request.folder, "static", "cache", "jpg") if not os.path.exists(cachepath): try: os.mkdir(cachepath) except OSError as os_error: error = "GIS: JPEG files cannot be saved: %s %s" % \ (cachepath, os_error) current.log.error(error) current.session.error = error redirect(URL(c="gis", f="index", vars={"config": config_id})) # Copy the current working directory to revert back to later cwd = os.getcwd() # Change to the Cache folder (can't render directly there from execute_phantomjs) os.chdir(cachepath) #driver = webdriver.PhantomJS() # Disable Proxy for Win32 Network Latency issue driver = WebDriver(service_args=["--proxy-type=none"]) # Change back for other parts os.chdir(cwd) settings = current.deployment_settings if height is None: # Set the size of the browser to match the map height = settings.get_gis_map_height() if width is None: width = settings.get_gis_map_width() # For Screenshots #height = 410 #width = 820 driver.set_window_size(width + 5, height + 20) # Load the homepage # (Cookie needs to be set on same domain as it takes effect) base_url = "%s/%s" % (settings.get_base_public_url(), request.application) driver.get(base_url) response = current.response session_id = response.session_id if not current.auth.override: # Reuse current session to allow access to ACL-controlled resources driver.add_cookie({"name": response.session_id_name, "value": session_id, "path": "/", }) # For sync connections current.session._unlock(response) # Load the map url = "%s/gis/map_viewing_client?print=1&config=%s" % (base_url, config_id) driver.get(url) # Wait for map to load (including it's layers) # Alternative approach: https://raw.githubusercontent.com/ariya/phantomjs/master/examples/waitfor.js def map_loaded(driver): test = '''return S3.gis.maps['%s'].s3.loaded''' % map_id try: result = driver.execute_script(test) except WebDriverException: result = False return result try: # Wait for up to 100s (large screenshots take a long time for layers to load) WebDriverWait(driver, 100).until(map_loaded) except TimeoutException as e: driver.quit() current.log.error("Timeout: %s" % e) return None # Save the Output # @ToDo: Can we use StringIO instead of cluttering filesystem? # @ToDo: Allow option of PDF (as well as JPG) # https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js if temp: filename = "%s.jpg" % session_id else: filename = "config_%s.jpg" % config_id # Cannot control file size (no access to clipRect) or file format #driver.save_screenshot(os.path.join(cachepath, filename)) #driver.page.clipRect = {"top": 10, # "left": 5, # "width": width, # "height": height # } #driver.page.render(filename, {"format": "jpeg", "quality": "100"}) script = ''' var page = this; page.clipRect = {top: 10, left: 5, width: %(width)s, height: %(height)s }; page.render('%(filename)s', {format: 'jpeg', quality: '100'});''' % \ {"width": width, "height": height, "filename": filename, } try: result = driver.execute_phantomjs(script) except WebDriverException as e: driver.quit() current.log.error("WebDriver crashed: %s" % e) return None driver.quit() if temp: # This was a temporary config for creating the screenshot, then delete it now ctable = current.s3db.gis_config the_set = current.db(ctable.id == config_id) config = the_set.select(ctable.temp, limitby=(0, 1) ).first() try: if config.temp: the_set.delete() except: # Record not found? pass # Pass the result back to the User return filename # ------------------------------------------------------------------------- @staticmethod def get_shapefile_geojson(resource): """ Lookup Shapefile Layer polygons once per layer and not per-record Called by S3REST: S3Resource.export_tree() @ToDo: Vary simplification level & precision by Zoom level - store this in the style? """ db = current.db #tablename = "gis_layer_shapefile_%s" % resource._ids[0] tablename = resource.tablename table = db[tablename] query = resource.get_query() fields = [] fappend = fields.append for f in table.fields: if f not in ("layer_id", "lat", "lon"): fappend(f) attributes = {} geojsons = {} settings = current.deployment_settings tolerance = settings.get_gis_simplify_tolerance() if settings.get_gis_spatialdb(): # Do the Simplify & GeoJSON direct from the DB fields.remove("the_geom") fields.remove("wkt") _fields = [table[f] for f in fields] rows = db(query).select(table.the_geom.st_simplify(tolerance).st_asgeojson(precision=4).with_alias("geojson"), *_fields) for row in rows: _row = row[tablename] _id = _row.id geojsons[_id] = row.geojson _attributes = {} for f in fields: if f not in ("id"): _attributes[f] = _row[f] attributes[_id] = _attributes else: _fields = [table[f] for f in fields] rows = db(query).select(*_fields) simplify = GIS.simplify for row in rows: # Simplify the polygon to reduce download size geojson = simplify(row.wkt, tolerance=tolerance, output="geojson") _id = row.id if geojson: geojsons[_id] = geojson _attributes = {} for f in fields: if f not in ("id", "wkt"): _attributes[f] = row[f] attributes[_id] = _attributes _attributes = {} _attributes[tablename] = attributes _geojsons = {} _geojsons[tablename] = geojsons # return 'locations' return {"attributes": _attributes, "geojsons": _geojsons, } # ------------------------------------------------------------------------- @staticmethod def get_theme_geojson(resource): """ Lookup Theme Layer polygons once per layer and not per-record Called by S3REST: S3Resource.export_tree() @ToDo: Vary precision by Lx - store this (& tolerance map) in the style? """ s3db = current.s3db tablename = "gis_theme_data" table = s3db.gis_theme_data gtable = s3db.gis_location query = (table.id.belongs(resource._ids)) & \ (table.location_id == gtable.id) geojsons = {} # @ToDo: How to get the tolerance to vary by level? # - add Stored Procedure? #if current.deployment_settings.get_gis_spatialdb(): # # Do the Simplify & GeoJSON direct from the DB # rows = current.db(query).select(table.id, # gtable.the_geom.st_simplify(0.01).st_asgeojson(precision=4).with_alias("geojson")) # for row in rows: # geojsons[row["gis_theme_data.id"]] = row.geojson #else: rows = current.db(query).select(table.id, gtable.level, gtable.wkt) simplify = GIS.simplify tolerance = {"L0": 0.01, "L1": 0.005, "L2": 0.00125, "L3": 0.000625, "L4": 0.0003125, "L5": 0.00015625, } for row in rows: grow = row.gis_location # Simplify the polygon to reduce download size geojson = simplify(grow.wkt, tolerance=tolerance[grow.level], output="geojson") if geojson: geojsons[row["gis_theme_data.id"]] = geojson _geojsons = {} _geojsons[tablename] = geojsons # Return 'locations' return {"geojsons": _geojsons, } # ------------------------------------------------------------------------- @staticmethod def greatCircleDistance(lat1, lon1, lat2, lon2, quick=True): """ Calculate the shortest distance (in km) over the earth's sphere between 2 points Formulae from: http://www.movable-type.co.uk/scripts/latlong.html (NB We could also use PostGIS functions, where possible, instead of this query) """ import math # shortcuts cos = math.cos sin = math.sin radians = math.radians if quick: # Spherical Law of Cosines (accurate down to around 1m & computationally quick) lat1 = radians(lat1) lat2 = radians(lat2) lon1 = radians(lon1) lon2 = radians(lon2) distance = math.acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon2 - lon1)) * RADIUS_EARTH return distance else: # Haversine #asin = math.asin sqrt = math.sqrt pow = math.pow dLat = radians(lat2 - lat1) dLon = radians(lon2 - lon1) a = pow(sin(dLat / 2), 2) + cos(radians(lat1)) * cos(radians(lat2)) * pow(sin(dLon / 2), 2) c = 2 * math.atan2(sqrt(a), sqrt(1 - a)) #c = 2 * asin(sqrt(a)) # Alternate version # Convert radians to kilometers distance = RADIUS_EARTH * c return distance # ------------------------------------------------------------------------- @staticmethod def create_poly(feature): """ Create a .poly file for OpenStreetMap exports http://wiki.openstreetmap.org/wiki/Osmosis/Polygon_Filter_File_Format """ from shapely.wkt import loads as wkt_loads try: # Enable C-based speedups available from 1.2.10+ from shapely import speedups speedups.enable() except: current.log.info("S3GIS", "Upgrade Shapely for Performance enhancements") name = feature.name if "wkt" in feature: wkt = feature.wkt else: # WKT not included by default in feature, so retrieve this now table = current.s3db.gis_location wkt = current.db(table.id == feature.id).select(table.wkt, limitby=(0, 1) ).first().wkt try: shape = wkt_loads(wkt) except: error = "Invalid WKT: %s" % name current.log.error(error) return error geom_type = shape.geom_type if geom_type == "MultiPolygon": polygons = shape.geoms elif geom_type == "Polygon": polygons = [shape] else: error = "Unsupported Geometry: %s, %s" % (name, geom_type) current.log.error(error) return error if os.path.exists(os.path.join(os.getcwd(), "temp")): # use web2py/temp TEMP = os.path.join(os.getcwd(), "temp") else: import tempfile TEMP = tempfile.gettempdir() filename = "%s.poly" % name filepath = os.path.join(TEMP, filename) File = open(filepath, "w") File.write("%s\n" % filename) count = 1 for polygon in polygons: File.write("%s\n" % count) points = polygon.exterior.coords for point in points: File.write("\t%s\t%s\n" % (point[0], point[1])) File.write("END\n") count += 1 File.write("END\n") File.close() return None # ------------------------------------------------------------------------- @staticmethod def export_admin_areas(countries=[], levels=("L0", "L1", "L2", "L3"), format="geojson", simplify=0.01, precision=4, ): """ Export admin areas to /static/cache for use by interactive web-mapping services - designed for use by the Vulnerability Mapping @param countries: list of ISO2 country codes @param levels: list of which Lx levels to export @param format: Only GeoJSON supported for now (may add KML &/or OSM later) @param simplify: tolerance for the simplification algorithm. False to disable simplification @param precision: number of decimal points to include in the coordinates """ db = current.db s3db = current.s3db table = s3db.gis_location ifield = table.id if countries: ttable = s3db.gis_location_tag cquery = (table.level == "L0") & \ (table.end_date == None) & \ (ttable.location_id == ifield) & \ (ttable.tag == "ISO2") & \ (ttable.value.belongs(countries)) else: # All countries cquery = (table.level == "L0") & \ (table.end_date == None) & \ (table.deleted != True) if current.deployment_settings.get_gis_spatialdb(): spatial = True _field = table.the_geom if simplify: # Do the Simplify & GeoJSON direct from the DB field = _field.st_simplify(simplify).st_asgeojson(precision=precision).with_alias("geojson") else: # Do the GeoJSON direct from the DB field = _field.st_asgeojson(precision=precision).with_alias("geojson") else: spatial = False field = table.wkt if simplify: _simplify = GIS.simplify else: from shapely.wkt import loads as wkt_loads from ..geojson import dumps try: # Enable C-based speedups available from 1.2.10+ from shapely import speedups speedups.enable() except: current.log.info("S3GIS", "Upgrade Shapely for Performance enhancements") folder = os.path.join(current.request.folder, "static", "cache") features = [] append = features.append if "L0" in levels: # Reduce the decimals in output by 1 _decimals = precision -1 if spatial: if simplify: field = _field.st_simplify(simplify).st_asgeojson(precision=_decimals).with_alias("geojson") else: field = _field.st_asgeojson(precision=_decimals).with_alias("geojson") countries = db(cquery).select(ifield, field) for row in countries: if spatial: id = row["gis_location"].id geojson = row.geojson elif simplify: id = row.id wkt = row.wkt if wkt: geojson = _simplify(wkt, tolerance=simplify, precision=_decimals, output="geojson") else: name = db(table.id == id).select(table.name, limitby=(0, 1)).first().name sys.stderr.write("No WKT: L0 %s %s\n" % (name, id)) continue else: id = row.id shape = wkt_loads(row.wkt) # Compact Encoding geojson = dumps(shape, separators=SEPARATORS) if geojson: f = {"type": "Feature", "properties": {"id": id}, "geometry": json.loads(geojson), } append(f) if features: data = {"type": "FeatureCollection", "features": features, } # Output to file filename = os.path.join(folder, "countries.geojson") File = open(filename, "w") File.write(json.dumps(data, separators=SEPARATORS)) File.close() q1 = (table.level == "L1") & \ (table.deleted != True) & \ (table.end_date == None) q2 = (table.level == "L2") & \ (table.deleted != True) & \ (table.end_date == None) q3 = (table.level == "L3") & \ (table.deleted != True) & \ (table.end_date == None) q4 = (table.level == "L4") & \ (table.deleted != True) & \ (table.end_date == None) if "L1" in levels: if "L0" not in levels: countries = db(cquery).select(ifield) if simplify: # We want greater precision when zoomed-in more simplify = simplify / 2 # 0.005 with default setting if spatial: field = _field.st_simplify(simplify).st_asgeojson(precision=precision).with_alias("geojson") for country in countries: if not spatial or "L0" not in levels: _id = country.id else: _id = country["gis_location"].id query = q1 & (table.parent == _id) features = [] append = features.append rows = db(query).select(ifield, field) for row in rows: if spatial: id = row["gis_location"].id geojson = row.geojson elif simplify: id = row.id wkt = row.wkt if wkt: geojson = _simplify(wkt, tolerance=simplify, precision=precision, output="geojson") else: name = db(table.id == id).select(table.name, limitby=(0, 1)).first().name sys.stderr.write("No WKT: L1 %s %s\n" % (name, id)) continue else: id = row.id shape = wkt_loads(row.wkt) # Compact Encoding geojson = dumps(shape, separators=SEPARATORS) if geojson: f = {"type": "Feature", "properties": {"id": id}, "geometry": json.loads(geojson) } append(f) if features: data = {"type": "FeatureCollection", "features": features } # Output to file filename = os.path.join(folder, "1_%s.geojson" % _id) File = open(filename, "w") File.write(json.dumps(data, separators=SEPARATORS)) File.close() else: current.log.debug("No L1 features in %s" % _id) if "L2" in levels: if "L0" not in levels and "L1" not in levels: countries = db(cquery).select(ifield) if simplify: # We want greater precision when zoomed-in more simplify = simplify / 4 # 0.00125 with default setting if spatial: field = _field.st_simplify(simplify).st_asgeojson(precision=precision).with_alias("geojson") for country in countries: if not spatial or "L0" not in levels: id = country.id else: id = country["gis_location"].id query = q1 & (table.parent == id) l1s = db(query).select(ifield) for l1 in l1s: query = q2 & (table.parent == l1.id) features = [] append = features.append rows = db(query).select(ifield, field) for row in rows: if spatial: id = row["gis_location"].id geojson = row.geojson elif simplify: id = row.id wkt = row.wkt if wkt: geojson = _simplify(wkt, tolerance=simplify, precision=precision, output="geojson") else: name = db(table.id == id).select(table.name, limitby=(0, 1)).first().name sys.stderr.write("No WKT: L2 %s %s\n" % (name, id)) continue else: id = row.id shape = wkt_loads(row.wkt) # Compact Encoding geojson = dumps(shape, separators=SEPARATORS) if geojson: f = {"type": "Feature", "properties": {"id": id}, "geometry": json.loads(geojson), } append(f) if features: data = {"type": "FeatureCollection", "features": features, } # Output to file filename = os.path.join(folder, "2_%s.geojson" % l1.id) File = open(filename, "w") File.write(json.dumps(data, separators=SEPARATORS)) File.close() else: current.log.debug("No L2 features in %s" % l1.id) if "L3" in levels: if "L0" not in levels and "L1" not in levels and "L2" not in levels: countries = db(cquery).select(ifield) if simplify: # We want greater precision when zoomed-in more simplify = simplify / 2 # 0.000625 with default setting if spatial: field = _field.st_simplify(simplify).st_asgeojson(precision=precision).with_alias("geojson") for country in countries: if not spatial or "L0" not in levels: id = country.id else: id = country["gis_location"].id query = q1 & (table.parent == id) l1s = db(query).select(ifield) for l1 in l1s: query = q2 & (table.parent == l1.id) l2s = db(query).select(ifield) for l2 in l2s: query = q3 & (table.parent == l2.id) features = [] append = features.append rows = db(query).select(ifield, field) for row in rows: if spatial: id = row["gis_location"].id geojson = row.geojson elif simplify: id = row.id wkt = row.wkt if wkt: geojson = _simplify(wkt, tolerance=simplify, precision=precision, output="geojson") else: name = db(table.id == id).select(table.name, limitby=(0, 1)).first().name sys.stderr.write("No WKT: L3 %s %s\n" % (name, id)) continue else: id = row.id shape = wkt_loads(row.wkt) # Compact Encoding geojson = dumps(shape, separators=SEPARATORS) if geojson: f = {"type": "Feature", "properties": {"id": id}, "geometry": json.loads(geojson), } append(f) if features: data = {"type": "FeatureCollection", "features": features, } # Output to file filename = os.path.join(folder, "3_%s.geojson" % l2.id) File = open(filename, "w") File.write(json.dumps(data, separators=SEPARATORS)) File.close() else: current.log.debug("No L3 features in %s" % l2.id) if "L4" in levels: if "L0" not in levels and "L1" not in levels and "L2" not in levels and "L3" not in levels: countries = db(cquery).select(ifield) if simplify: # We want greater precision when zoomed-in more simplify = simplify / 2 # 0.0003125 with default setting if spatial: field = _field.st_simplify(simplify).st_asgeojson(precision=precision).with_alias("geojson") for country in countries: if not spatial or "L0" not in levels: id = country.id else: id = country["gis_location"].id query = q1 & (table.parent == id) l1s = db(query).select(ifield) for l1 in l1s: query = q2 & (table.parent == l1.id) l2s = db(query).select(ifield) for l2 in l2s: query = q3 & (table.parent == l2.id) l3s = db(query).select(ifield) for l3 in l3s: query = q4 & (table.parent == l3.id) features = [] append = features.append rows = db(query).select(ifield, field) for row in rows: if spatial: id = row["gis_location"].id geojson = row.geojson elif simplify: id = row.id wkt = row.wkt if wkt: geojson = _simplify(wkt, tolerance=simplify, precision=precision, output="geojson") else: name = db(table.id == id).select(table.name, limitby=(0, 1)).first().name sys.stderr.write("No WKT: L4 %s %s\n" % (name, id)) continue else: id = row.id shape = wkt_loads(row.wkt) # Compact Encoding geojson = dumps(shape, separators=SEPARATORS) if geojson: f = {"type": "Feature", "properties": {"id": id}, "geometry": json.loads(geojson), } append(f) if features: data = {"type": "FeatureCollection", "features": features, } # Output to file filename = os.path.join(folder, "4_%s.geojson" % l3.id) File = open(filename, "w") File.write(json.dumps(data, separators=SEPARATORS)) File.close() else: current.log.debug("No L4 features in %s" % l3.id) # ------------------------------------------------------------------------- def import_admin_areas(self, source="gadmv1", countries=[], levels=["L0", "L1", "L2"] ): """ Import Admin Boundaries into the Locations table @param source - Source to get the data from. Currently only GADM is supported: http://gadm.org @param countries - List of ISO2 countrycodes to download data for defaults to all countries @param levels - Which levels of the hierarchy to import. defaults to all 3 supported levels """ if source == "gadmv1": try: from osgeo import ogr except: current.log.error("Unable to import ogr. Please install python-gdal bindings: GDAL-1.8.1+") return if "L0" in levels: self.import_gadm1_L0(ogr, countries=countries) if "L1" in levels: self.import_gadm1(ogr, "L1", countries=countries) if "L2" in levels: self.import_gadm1(ogr, "L2", countries=countries) current.log.debug("All done!") elif source == "gadmv1": try: from osgeo import ogr except: current.log.error("Unable to import ogr. Please install python-gdal bindings: GDAL-1.8.1+") return if "L0" in levels: self.import_gadm2(ogr, "L0", countries=countries) if "L1" in levels: self.import_gadm2(ogr, "L1", countries=countries) if "L2" in levels: self.import_gadm2(ogr, "L2", countries=countries) current.log.debug("All done!") else: current.log.warning("Only GADM is currently supported") return return # ------------------------------------------------------------------------- @staticmethod def import_gadm1_L0(ogr, countries=[]): """ Import L0 Admin Boundaries into the Locations table from GADMv1 - designed to be called from import_admin_areas() - assumes that basic prepop has been done, so that no new records need to be created @param ogr - The OGR Python module @param countries - List of ISO2 countrycodes to download data for defaults to all countries """ db = current.db s3db = current.s3db ttable = s3db.gis_location_tag table = db.gis_location layer = { "url" : "http://gadm.org/data/gadm_v1_lev0_shp.zip", "zipfile" : "gadm_v1_lev0_shp.zip", "shapefile" : "gadm1_lev0", "codefield" : "ISO2", # This field is used to uniquely identify the L0 for updates "code2field" : "ISO" # This field is used to uniquely identify the L0 for parenting the L1s } # Copy the current working directory to revert back to later cwd = os.getcwd() # Create the working directory TEMP = os.path.join(cwd, "temp") if not os.path.exists(TEMP): # use web2py/temp/GADMv1 as a cache import tempfile TEMP = tempfile.gettempdir() tempPath = os.path.join(TEMP, "GADMv1") if not os.path.exists(tempPath): try: os.mkdir(tempPath) except OSError: current.log.error("Unable to create temp folder %s!" % tempPath) return # Set the current working directory os.chdir(tempPath) layerName = layer["shapefile"] # Check if file has already been downloaded fileName = layer["zipfile"] if not os.path.isfile(fileName): # Download the file from gluon.tools import fetch url = layer["url"] current.log.debug("Downloading %s" % url) try: file = fetch(url) except URLError as exception: current.log.error(exception) return fp = StringIO(file) else: current.log.debug("Using existing file %s" % fileName) fp = open(fileName) # Unzip it current.log.debug("Unzipping %s" % layerName) import zipfile myfile = zipfile.ZipFile(fp) for ext in ("dbf", "prj", "sbn", "sbx", "shp", "shx"): fileName = "%s.%s" % (layerName, ext) file = myfile.read(fileName) f = open(fileName, "w") f.write(file) f.close() myfile.close() # Use OGR to read Shapefile current.log.debug("Opening %s.shp" % layerName) ds = ogr.Open("%s.shp" % layerName) if ds is None: current.log.error("Open failed.\n") return lyr = ds.GetLayerByName(layerName) lyr.ResetReading() codeField = layer["codefield"] code2Field = layer["code2field"] for feat in lyr: code = feat.GetField(codeField) if not code: # Skip the entries which aren't countries continue if countries and code not in countries: # Skip the countries which we're not interested in continue geom = feat.GetGeometryRef() if geom is not None: if geom.GetGeometryType() == ogr.wkbPoint: pass else: query = (table.id == ttable.location_id) & \ (ttable.tag == "ISO2") & \ (ttable.value == code) wkt = geom.ExportToWkt() if wkt.startswith("LINESTRING"): gis_feature_type = 2 elif wkt.startswith("POLYGON"): gis_feature_type = 3 elif wkt.startswith("MULTIPOINT"): gis_feature_type = 4 elif wkt.startswith("MULTILINESTRING"): gis_feature_type = 5 elif wkt.startswith("MULTIPOLYGON"): gis_feature_type = 6 elif wkt.startswith("GEOMETRYCOLLECTION"): gis_feature_type = 7 code2 = feat.GetField(code2Field) #area = feat.GetField("Shape_Area") try: id = db(query).select(table.id, limitby=(0, 1)).first().id query = (table.id == id) db(query).update(gis_feature_type=gis_feature_type, wkt=wkt) ttable.insert(location_id = id, tag = "ISO3", value = code2) #ttable.insert(location_id = location_id, # tag = "area", # value = area) except db._adapter.driver.OperationalError: current.log.error(sys.exc_info()[1]) else: current.log.debug("No geometry\n") # Close the shapefile ds.Destroy() db.commit() # Revert back to the working directory as before. os.chdir(cwd) return # ------------------------------------------------------------------------- def import_gadm1(self, ogr, level="L1", countries=[]): """ Import L1 Admin Boundaries into the Locations table from GADMv1 - designed to be called from import_admin_areas() - assumes a fresh database with just Countries imported @param ogr - The OGR Python module @param level - "L1" or "L2" @param countries - List of ISO2 countrycodes to download data for defaults to all countries """ if level == "L1": layer = { "url" : "http://gadm.org/data/gadm_v1_lev1_shp.zip", "zipfile" : "gadm_v1_lev1_shp.zip", "shapefile" : "gadm1_lev1", "namefield" : "NAME_1", # Uniquely identify the L1 for updates "sourceCodeField" : "ID_1", "edenCodeField" : "GADM1", # Uniquely identify the L0 for parenting the L1s "parent" : "L0", "parentSourceCodeField" : "ISO", "parentEdenCodeField" : "ISO3", } elif level == "L2": layer = { "url" : "http://biogeo.ucdavis.edu/data/gadm/gadm_v1_lev2_shp.zip", "zipfile" : "gadm_v1_lev2_shp.zip", "shapefile" : "gadm_v1_lev2", "namefield" : "NAME_2", # Uniquely identify the L2 for updates "sourceCodeField" : "ID_2", "edenCodeField" : "GADM2", # Uniquely identify the L0 for parenting the L1s "parent" : "L1", "parentSourceCodeField" : "ID_1", "parentEdenCodeField" : "GADM1", } else: current.log.warning("Level %s not supported!" % level) return import csv import shutil import zipfile db = current.db s3db = current.s3db cache = s3db.cache table = s3db.gis_location ttable = s3db.gis_location_tag csv.field_size_limit(2**20 * 100) # 100 megs # Not all the data is encoded like this # (unable to determine encoding - appears to be damaged in source): # Azerbaijan L1 # Vietnam L1 & L2 ENCODING = "cp1251" # from http://docs.python.org/library/csv.html#csv-examples # TODO rewrite for Py3 def latin_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs): for row in csv.reader(unicode_csv_data): yield [unicode(cell, ENCODING) for cell in row] # TODO rewrite for Py3 def latin_dict_reader(data, dialect=csv.excel, **kwargs): reader = latin_csv_reader(data, dialect=dialect, **kwargs) headers = reader.next() for r in reader: yield dict(zip(headers, r)) # Copy the current working directory to revert back to later cwd = os.getcwd() # Create the working directory TEMP = os.path.join(cwd, "temp") if not os.path.exists(TEMP): # use web2py/temp/GADMv1 as a cache import tempfile TEMP = tempfile.gettempdir() tempPath = os.path.join(TEMP, "GADMv1") if not os.path.exists(tempPath): try: os.mkdir(tempPath) except OSError: current.log.error("Unable to create temp folder %s!" % tempPath) return # Set the current working directory os.chdir(tempPath) # Remove any existing CSV folder to allow the new one to be created try: shutil.rmtree("CSV") except OSError: # Folder doesn't exist, so should be creatable pass layerName = layer["shapefile"] # Check if file has already been downloaded fileName = layer["zipfile"] if not os.path.isfile(fileName): # Download the file from gluon.tools import fetch url = layer["url"] current.log.debug("Downloading %s" % url) try: file = fetch(url) except URLError as exception: current.log.error(exception) # Revert back to the working directory as before. os.chdir(cwd) return fp = StringIO(file) else: current.log.debug("Using existing file %s" % fileName) fp = open(fileName) # Unzip it current.log.debug("Unzipping %s" % layerName) myfile = zipfile.ZipFile(fp) for ext in ("dbf", "prj", "sbn", "sbx", "shp", "shx"): fileName = "%s.%s" % (layerName, ext) file = myfile.read(fileName) f = open(fileName, "w") f.write(file) f.close() myfile.close() # Convert to CSV current.log.debug("Converting %s.shp to CSV" % layerName) # Simplified version of generic Shapefile Importer: # http://svn.osgeo.org/gdal/trunk/gdal/swig/python/samples/ogr2ogr.py bSkipFailures = False nGroupTransactions = 200 nFIDToFetch = ogr.NullFID inputFileName = "%s.shp" % layerName inputDS = ogr.Open(inputFileName, False) outputFileName = "CSV" outputDriver = ogr.GetDriverByName("CSV") outputDS = outputDriver.CreateDataSource(outputFileName, options=[]) # GADM only has 1 layer/source inputLayer = inputDS.GetLayer(0) inputFDefn = inputLayer.GetLayerDefn() # Create the output Layer outputLayer = outputDS.CreateLayer(layerName) # Copy all Fields #papszFieldTypesToString = [] inputFieldCount = inputFDefn.GetFieldCount() panMap = [-1] * inputFieldCount outputFDefn = outputLayer.GetLayerDefn() nDstFieldCount = 0 if outputFDefn is not None: nDstFieldCount = outputFDefn.GetFieldCount() for iField in range(inputFieldCount): inputFieldDefn = inputFDefn.GetFieldDefn(iField) oFieldDefn = ogr.FieldDefn(inputFieldDefn.GetNameRef(), inputFieldDefn.GetType()) oFieldDefn.SetWidth(inputFieldDefn.GetWidth()) oFieldDefn.SetPrecision(inputFieldDefn.GetPrecision()) # The field may have been already created at layer creation iDstField = -1 if outputFDefn is not None: iDstField = outputFDefn.GetFieldIndex(oFieldDefn.GetNameRef()) if iDstField >= 0: panMap[iField] = iDstField elif outputLayer.CreateField(oFieldDefn) == 0: # now that we've created a field, GetLayerDefn() won't return NULL if outputFDefn is None: outputFDefn = outputLayer.GetLayerDefn() panMap[iField] = nDstFieldCount nDstFieldCount = nDstFieldCount + 1 # Transfer features nFeaturesInTransaction = 0 #iSrcZField = -1 inputLayer.ResetReading() if nGroupTransactions > 0: outputLayer.StartTransaction() while True: poDstFeature = None if nFIDToFetch != ogr.NullFID: # Only fetch feature on first pass. if nFeaturesInTransaction == 0: poFeature = inputLayer.GetFeature(nFIDToFetch) else: poFeature = None else: poFeature = inputLayer.GetNextFeature() if poFeature is None: break nParts = 0 nIters = 1 for iPart in range(nIters): nFeaturesInTransaction = nFeaturesInTransaction + 1 if nFeaturesInTransaction == nGroupTransactions: outputLayer.CommitTransaction() outputLayer.StartTransaction() nFeaturesInTransaction = 0 poDstFeature = ogr.Feature(outputLayer.GetLayerDefn()) if poDstFeature.SetFromWithMap(poFeature, 1, panMap) != 0: if nGroupTransactions > 0: outputLayer.CommitTransaction() current.log.error("Unable to translate feature %d from layer %s" % \ (poFeature.GetFID(), inputFDefn.GetName())) # Revert back to the working directory as before. os.chdir(cwd) return poDstGeometry = poDstFeature.GetGeometryRef() if poDstGeometry is not None: if nParts > 0: # For -explodecollections, extract the iPart(th) of the geometry poPart = poDstGeometry.GetGeometryRef(iPart).Clone() poDstFeature.SetGeometryDirectly(poPart) poDstGeometry = poPart if outputLayer.CreateFeature(poDstFeature) != 0 and \ not bSkipFailures: if nGroupTransactions > 0: outputLayer.RollbackTransaction() # Revert back to the working directory as before. os.chdir(cwd) return if nGroupTransactions > 0: outputLayer.CommitTransaction() # Cleanup outputDS.Destroy() inputDS.Destroy() fileName = "%s.csv" % layerName filePath = os.path.join("CSV", fileName) os.rename(filePath, fileName) os.removedirs("CSV") # Use OGR to read SHP for geometry current.log.debug("Opening %s.shp" % layerName) ds = ogr.Open("%s.shp" % layerName) if ds is None: current.log.debug("Open failed.\n") # Revert back to the working directory as before. os.chdir(cwd) return lyr = ds.GetLayerByName(layerName) lyr.ResetReading() # Use CSV for Name current.log.debug("Opening %s.csv" % layerName) rows = latin_dict_reader(open("%s.csv" % layerName)) nameField = layer["namefield"] sourceCodeField = layer["sourceCodeField"] edenCodeField = layer["edenCodeField"] parentSourceCodeField = layer["parentSourceCodeField"] parentLevel = layer["parent"] parentEdenCodeField = layer["parentEdenCodeField"] parentCodeQuery = (ttable.tag == parentEdenCodeField) count = 0 for row in rows: # Read Attributes feat = lyr[count] parentCode = feat.GetField(parentSourceCodeField) query = (table.level == parentLevel) & \ parentCodeQuery & \ (ttable.value == parentCode) parent = db(query).select(table.id, ttable.value, limitby=(0, 1), cache=cache).first() if not parent: # Skip locations for which we don't have a valid parent current.log.warning("Skipping - cannot find parent with key: %s, value: %s" % \ (parentEdenCodeField, parentCode)) count += 1 continue if countries: # Skip the countries which we're not interested in if level == "L1": if parent["gis_location_tag"].value not in countries: #current.log.warning("Skipping %s as not in countries list" % parent["gis_location_tag"].value) count += 1 continue else: # Check grandparent country = self.get_parent_country(parent.id, key_type="code") if country not in countries: count += 1 continue # This is got from CSV in order to be able to handle the encoding name = row.pop(nameField) name.encode("utf8") code = feat.GetField(sourceCodeField) #area = feat.GetField("Shape_Area") geom = feat.GetGeometryRef() if geom is not None: if geom.GetGeometryType() == ogr.wkbPoint: lat = geom.GetX() lon = geom.GetY() id = table.insert(name=name, level=level, gis_feature_type=1, lat=lat, lon=lon, parent=parent.id) ttable.insert(location_id = id, tag = edenCodeField, value = code) # ttable.insert(location_id = id, # tag = "area", # value = area) else: wkt = geom.ExportToWkt() if wkt.startswith("LINESTRING"): gis_feature_type = 2 elif wkt.startswith("POLYGON"): gis_feature_type = 3 elif wkt.startswith("MULTIPOINT"): gis_feature_type = 4 elif wkt.startswith("MULTILINESTRING"): gis_feature_type = 5 elif wkt.startswith("MULTIPOLYGON"): gis_feature_type = 6 elif wkt.startswith("GEOMETRYCOLLECTION"): gis_feature_type = 7 id = table.insert(name=name, level=level, gis_feature_type=gis_feature_type, wkt=wkt, parent=parent.id) ttable.insert(location_id = id, tag = edenCodeField, value = code) # ttable.insert(location_id = id, # tag = "area", # value = area) else: current.log.debug("No geometry\n") count += 1 # Close the shapefile ds.Destroy() db.commit() current.log.debug("Updating Location Tree...") try: self.update_location_tree() except MemoryError: # If doing all L2s, it can break memory limits # @ToDo: Check now that we're doing by level current.log.critical("Memory error when trying to update_location_tree()!") db.commit() # Revert back to the working directory as before. os.chdir(cwd) return # ------------------------------------------------------------------------- @staticmethod def import_gadm2(ogr, level="L0", countries=[]): """ Import Admin Boundaries into the Locations table from GADMv2 - designed to be called from import_admin_areas() - assumes that basic prepop has been done, so that no new L0 records need to be created @param ogr - The OGR Python module @param level - The OGR Python module @param countries - List of ISO2 countrycodes to download data for defaults to all countries @ToDo: Complete this - not currently possible to get all data from the 1 file easily - no ISO2 - needs updating for gis_location_tag model - only the lowest available levels accessible - use GADMv1 for L0, L1, L2 & GADMv2 for specific lower? """ if level == "L0": codeField = "ISO2" # This field is used to uniquely identify the L0 for updates code2Field = "ISO" # This field is used to uniquely identify the L0 for parenting the L1s elif level == "L1": #nameField = "NAME_1" codeField = "ID_1" # This field is used to uniquely identify the L1 for updates code2Field = "ISO" # This field is used to uniquely identify the L0 for parenting the L1s #parent = "L0" #parentCode = "code2" elif level == "L2": #nameField = "NAME_2" codeField = "ID_2" # This field is used to uniquely identify the L2 for updates code2Field = "ID_1" # This field is used to uniquely identify the L1 for parenting the L2s #parent = "L1" #parentCode = "code" else: current.log.error("Level %s not supported!" % level) return db = current.db s3db = current.s3db table = s3db.gis_location url = "http://gadm.org/data2/gadm_v2_shp.zip" zipfile = "gadm_v2_shp.zip" shapefile = "gadm2" # Copy the current working directory to revert back to later old_working_directory = os.getcwd() # Create the working directory if os.path.exists(os.path.join(os.getcwd(), "temp")): # use web2py/temp/GADMv2 as a cache TEMP = os.path.join(os.getcwd(), "temp") else: import tempfile TEMP = tempfile.gettempdir() tempPath = os.path.join(TEMP, "GADMv2") try: os.mkdir(tempPath) except OSError: # Folder already exists - reuse pass # Set the current working directory os.chdir(tempPath) layerName = shapefile # Check if file has already been downloaded fileName = zipfile if not os.path.isfile(fileName): # Download the file from gluon.tools import fetch current.log.debug("Downloading %s" % url) try: file = fetch(url) except URLError as exception: current.log.error(exception) return fp = StringIO(file) else: current.log.debug("Using existing file %s" % fileName) fp = open(fileName) # Unzip it current.log.debug("Unzipping %s" % layerName) import zipfile myfile = zipfile.ZipFile(fp) for ext in ("dbf", "prj", "sbn", "sbx", "shp", "shx"): fileName = "%s.%s" % (layerName, ext) file = myfile.read(fileName) f = open(fileName, "w") f.write(file) f.close() myfile.close() # Use OGR to read Shapefile current.log.debug("Opening %s.shp" % layerName) ds = ogr.Open("%s.shp" % layerName) if ds is None: current.log.debug("Open failed.\n") return lyr = ds.GetLayerByName(layerName) lyr.ResetReading() for feat in lyr: code = feat.GetField(codeField) if not code: # Skip the entries which aren't countries continue if countries and code not in countries: # Skip the countries which we're not interested in continue geom = feat.GetGeometryRef() if geom is not None: if geom.GetGeometryType() == ogr.wkbPoint: pass else: ## FIXME ##query = (table.code == code) wkt = geom.ExportToWkt() if wkt.startswith("LINESTRING"): gis_feature_type = 2 elif wkt.startswith("POLYGON"): gis_feature_type = 3 elif wkt.startswith("MULTIPOINT"): gis_feature_type = 4 elif wkt.startswith("MULTILINESTRING"): gis_feature_type = 5 elif wkt.startswith("MULTIPOLYGON"): gis_feature_type = 6 elif wkt.startswith("GEOMETRYCOLLECTION"): gis_feature_type = 7 #code2 = feat.GetField(code2Field) #area = feat.GetField("Shape_Area") try: ## FIXME db(query).update(gis_feature_type=gis_feature_type, wkt=wkt) #code2=code2, #area=area except db._adapter.driver.OperationalError as exception: current.log.error(exception) else: current.log.debug("No geometry\n") # Close the shapefile ds.Destroy() db.commit() # Revert back to the working directory as before. os.chdir(old_working_directory) return # ------------------------------------------------------------------------- def import_geonames(self, country, level=None): """ Import Locations from the Geonames database @param country: the 2-letter country code @param level: the ADM level to import Designed to be run from the CLI Levels should be imported sequentially. It is assumed that L0 exists in the DB already L1-L3 may have been imported from Shapefiles with Polygon info Geonames can then be used to populate the lower levels of hierarchy """ import codecs from shapely.geometry import point from shapely.geos import ReadingError from shapely.wkt import loads as wkt_loads try: # Enable C-based speedups available from 1.2.10+ from shapely import speedups speedups.enable() except: current.log.info("S3GIS", "Upgrade Shapely for Performance enhancements") db = current.db s3db = current.s3db #cache = s3db.cache request = current.request #settings = current.deployment_settings table = s3db.gis_location ttable = s3db.gis_location_tag url = "http://download.geonames.org/export/dump/" + country + ".zip" cachepath = os.path.join(request.folder, "cache") filename = country + ".txt" filepath = os.path.join(cachepath, filename) if os.access(filepath, os.R_OK): cached = True else: cached = False if not os.access(cachepath, os.W_OK): current.log.error("Folder not writable", cachepath) return if not cached: # Download File from gluon.tools import fetch try: f = fetch(url) except HTTPError: e = sys.exc_info()[1] current.log.error("HTTP Error", e) return except URLError: e = sys.exc_info()[1] current.log.error("URL Error", e) return # Unzip File if f[:2] == "PK": # Unzip fp = StringIO(f) import zipfile myfile = zipfile.ZipFile(fp) try: # Python 2.6+ only :/ # For now, 2.5 users need to download/unzip manually to cache folder myfile.extract(filename, cachepath) myfile.close() except IOError: current.log.error("Zipfile contents don't seem correct!") myfile.close() return f = codecs.open(filepath, encoding="utf-8") # Downloaded file is worth keeping #os.remove(filepath) if level == "L1": fc = "ADM1" parent_level = "L0" elif level == "L2": fc = "ADM2" parent_level = "L1" elif level == "L3": fc = "ADM3" parent_level = "L2" elif level == "L4": fc = "ADM4" parent_level = "L3" else: # 5 levels of hierarchy or 4? # @ToDo make more extensible still #gis_location_hierarchy = self.get_location_hierarchy() try: #label = gis_location_hierarchy["L5"] level = "L5" parent_level = "L4" except: # ADM4 data in Geonames isn't always good (e.g. PK bad) level = "L4" parent_level = "L3" finally: fc = "PPL" deleted = (table.deleted == False) query = deleted & (table.level == parent_level) # Do the DB query once (outside loop) all_parents = db(query).select(table.wkt, table.lon_min, table.lon_max, table.lat_min, table.lat_max, table.id) if not all_parents: # No locations in the parent level found # - use the one higher instead parent_level = "L" + str(int(parent_level[1:]) + 1) query = deleted & (table.level == parent_level) all_parents = db(query).select(table.wkt, table.lon_min, table.lon_max, table.lat_min, table.lat_max, table.id) # Parse File current_row = 0 for line in f: current_row += 1 # Format of file: http://download.geonames.org/export/dump/readme.txt geonameid, \ name, \ asciiname, \ alternatenames, \ lat, \ lon, \ feature_class, \ feature_code, \ country_code, \ cc2, \ admin1_code, \ admin2_code, \ admin3_code, \ admin4_code, \ population, \ elevation, \ gtopo30, \ timezone, \ modification_date = line.split("\t") if feature_code == fc: # Add WKT lat = float(lat) lon = float(lon) wkt = self.latlon_to_wkt(lat, lon) shape = point.Point(lon, lat) # Add Bounds lon_min = lon_max = lon lat_min = lat_max = lat # Locate Parent parent = "" # 1st check for Parents whose bounds include this location (faster) def in_bbox(row): return (row.lon_min < lon_min) & \ (row.lon_max > lon_max) & \ (row.lat_min < lat_min) & \ (row.lat_max > lat_max) for row in all_parents.find(lambda row: in_bbox(row)): # Search within this subset with a full geometry check # Uses Shapely. # @ToDo provide option to use PostGIS/Spatialite try: parent_shape = wkt_loads(row.wkt) if parent_shape.intersects(shape): parent = row.id # Should be just a single parent break except ReadingError: current.log.error("Error reading wkt of location with id", row.id) # Add entry to database new_id = table.insert(name=name, level=level, parent=parent, lat=lat, lon=lon, wkt=wkt, lon_min=lon_min, lon_max=lon_max, lat_min=lat_min, lat_max=lat_max) ttable.insert(location_id=new_id, tag="geonames", value=geonameid) else: continue current.log.debug("All done!") return # ------------------------------------------------------------------------- @staticmethod def latlon_to_wkt(lat, lon): """ Convert a LatLon to a WKT string >>> s3gis.latlon_to_wkt(6, 80) 'POINT(80 6)' """ WKT = "POINT(%f %f)" % (lon, lat) return WKT # ------------------------------------------------------------------------- @staticmethod def parse_location(wkt, lon=None, lat=None): """ Parses a location from wkt, returning wkt, lat, lon, bounding box and type. For points, wkt may be None if lat and lon are provided; wkt will be generated. For lines and polygons, the lat, lon returned represent the shape's centroid. Centroid and bounding box will be None if Shapely is not available. """ if not wkt: if not lon is not None and lat is not None: raise RuntimeError("Need wkt or lon+lat to parse a location") wkt = "POINT(%f %f)" % (lon, lat) geom_type = GEOM_TYPES["point"] bbox = (lon, lat, lon, lat) else: try: from shapely.wkt import loads as wkt_loads SHAPELY = True except: SHAPELY = False if SHAPELY: shape = wkt_loads(wkt) centroid = shape.centroid lat = centroid.y lon = centroid.x geom_type = GEOM_TYPES[shape.type.lower()] bbox = shape.bounds else: lat = None lon = None geom_type = GEOM_TYPES[wkt.split("(")[0].lower()] bbox = None res = {"wkt": wkt, "lat": lat, "lon": lon, "gis_feature_type": geom_type} if bbox: res["lon_min"], res["lat_min"], res["lon_max"], res["lat_max"] = bbox return res # ------------------------------------------------------------------------- @staticmethod def update_location_tree(feature=None, all_locations=False, propagating=False): """ Update GIS Locations' Materialized path, Lx locations, Lat/Lon & the_geom @param feature: a feature dict to update the tree for - if not provided then update the whole tree @param all_locations: passed to recursive calls to indicate that this is an update of the whole tree. Used to avoid repeated attempts to update hierarchy locations with missing data (e.g. lacking some ancestor level). @param propagating: passed to recursive calls to indicate that this is a propagation update. Used to avoid repeated attempts to update hierarchy locations with missing data (e.g. lacking some ancestor level). returns the path of the feature Called onaccept for locations (async, where-possible) """ # During prepopulate, for efficiency, we don't update the location # tree, but rather leave that til after prepopulate is complete. if GIS.disable_update_location_tree: return None db = current.db try: table = db.gis_location except: table = current.s3db.gis_location update_location_tree = GIS.update_location_tree wkt_centroid = GIS.wkt_centroid fields = (table.id, table.name, table.level, table.path, table.parent, table.L0, table.L1, table.L2, table.L3, table.L4, table.L5, table.lat, table.lon, table.wkt, table.inherited ) # --------------------------------------------------------------------- def fixup(feature): """ Fix all the issues with a Feature, assuming that - the corrections are in the feature - or they are Bounds / Centroid / WKT / the_geom issues """ form = Storage() form.vars = form_vars = feature form.errors = Storage() if not form_vars.get("wkt"): # Point form_vars.update(gis_feature_type="1") # Calculate Bounds / Centroid / WKT / the_geom wkt_centroid(form) if form.errors: current.log.error("S3GIS: %s" % form.errors) else: wkt = form_vars.wkt if wkt and not wkt.startswith("POI"): # Polygons aren't inherited form_vars.update(inherited = False) if "update_record" in form_vars: # Must be a Row new_vars = {} table_fields = table.fields for v in form_vars: if v in table_fields: new_vars[v] = form_vars[v] form_vars = new_vars try: db(table.id == feature.id).update(**form_vars) except MemoryError: current.log.error("S3GIS: Unable to set bounds & centroid for feature %s: MemoryError" % feature.id) # --------------------------------------------------------------------- def propagate(parent): """ Propagate Lat/Lon down to any Features which inherit from this one @param parent: gis_location id of parent """ # No need to filter out deleted since the parent FK is None for these records query = (table.parent == parent) & \ (table.inherited == True) rows = db(query).select(*fields) for row in rows: try: update_location_tree(row, propagating=True) except RuntimeError: current.log.error("Cannot propagate inherited latlon to child %s of location ID %s: too much recursion" % \ (row.id, parent)) if not feature: # We are updating all locations. all_locations = True # Do in chunks to save memory and also do in correct order all_fields = (table.id, table.name, table.gis_feature_type, table.L0, table.L1, table.L2, table.L3, table.L4, table.lat, table.lon, table.wkt, table.inherited, # Handle Countries which start with Bounds set, yet are Points table.lat_min, table.lon_min, table.lat_max, table.lon_max, table.path, table.parent) for level in ("L0", "L1", "L2", "L3", "L4", "L5", None): query = (table.level == level) & (table.deleted == False) try: features = db(query).select(*all_fields) except MemoryError: current.log.error("S3GIS: Unable to update Location Tree for level %s: MemoryError" % level) else: for feature in features: feature["level"] = level wkt = feature["wkt"] if wkt and not wkt.startswith("POI"): # Polygons aren't inherited feature["inherited"] = False update_location_tree(feature) # all_locations is False here # All Done! return # Single Feature id = str(feature["id"]) if "id" in feature else None if not id: # Nothing we can do raise ValueError feature_get = feature.get # L0 level = feature_get("level", False) name = feature_get("name", False) path = feature_get("path", False) # If we're processing all locations, and this is a hierarchy location, # and has already been processed (as evidenced by having a path) do not # process it again. Locations with a gap in their ancestor levels will # be regarded as missing data and sent through update_location_tree # recursively, but that missing data will not be filled in after the # location is processed once during the all-locations call. if all_locations and path and level: # This hierarchy location is already finalized. return path lat = feature_get("lat", False) lon = feature_get("lon", False) wkt = feature_get("wkt", False) L0 = feature_get("L0", False) if level == "L0": if name is False or path is False or lat is False or lon is False or \ wkt is False or L0 is False: # Get the whole feature feature = db(table.id == id).select(table.id, table.name, table.path, table.lat, table.lon, table.wkt, table.L0, limitby=(0, 1)).first() name = feature.name path = feature.path lat = feature.lat lon = feature.lon wkt = feature.wkt L0 = feature.L0 if path != id or L0 != name or not wkt or lat is None: # Fix everything up path = id if lat is False: lat = None if lon is False: lon = None fix_vars = {"inherited": False, "path": path, "lat": lat, "lon": lon, "wkt": wkt or None, "L0": name, "L1": None, "L2": None, "L3": None, "L4": None, "L5": None, } feature.update(**fix_vars) fixup(feature) if not all_locations: # Ensure that any locations which inherit their latlon from this one get updated propagate(id) return path fixup_required = False # L1 inherited = feature_get("inherited", None) parent = feature_get("parent", False) L1 = feature_get("L1", False) if level == "L1": if inherited is None or name is False or parent is False or path is False or \ lat is False or lon is False or wkt is False or \ L0 is False or L1 is False: # Get the whole feature feature = db(table.id == id).select(table.id, table.inherited, table.name, table.parent, table.path, table.lat, table.lon, table.wkt, table.L0, table.L1, limitby=(0, 1)).first() inherited = feature.inherited name = feature.name parent = feature.parent path = feature.path lat = feature.lat lon = feature.lon wkt = feature.wkt L0 = feature.L0 L1 = feature.L1 if parent: _path = "%s/%s" % (parent, id) _L0 = db(table.id == parent).select(table.name, table.lat, table.lon, limitby=(0, 1)).first() L0_name = _L0.name L0_lat = _L0.lat L0_lon = _L0.lon else: _path = id L0_name = None L0_lat = None L0_lon = None if inherited or lat is None or lon is None: fixup_required = True inherited = True lat = L0_lat lon = L0_lon elif path != _path or L0 != L0_name or L1 != name or not wkt: fixup_required = True if fixup_required: # Fix everything up if lat is False: lat = None if lon is False: lon = None fix_vars = {"inherited": inherited, "path": _path, "lat": lat, "lon": lon, "wkt": wkt or None, "L0": L0_name, "L1": name, "L2": None, "L3": None, "L4": None, "L5": None, } feature.update(**fix_vars) fixup(feature) if not all_locations: # Ensure that any locations which inherit their latlon from this one get updated propagate(id) return _path # L2 L2 = feature_get("L2", False) if level == "L2": if inherited is None or name is False or parent is False or path is False or \ lat is False or lon is False or wkt is False or \ L0 is False or L1 is False or L2 is False: # Get the whole feature feature = db(table.id == id).select(table.id, table.inherited, table.name, table.parent, table.path, table.lat, table.lon, table.wkt, table.L0, table.L1, table.L2, limitby=(0, 1)).first() inherited = feature.inherited name = feature.name parent = feature.parent path = feature.path lat = feature.lat lon = feature.lon wkt = feature.wkt L0 = feature.L0 L1 = feature.L1 L2 = feature.L2 if parent: Lx = db(table.id == parent).select(table.name, table.level, table.parent, table.lat, table.lon, limitby=(0, 1)).first() if Lx.level == "L1": L1_name = Lx.name _parent = Lx.parent if _parent: _path = "%s/%s/%s" % (_parent, parent, id) L0_name = db(table.id == _parent).select(table.name, limitby=(0, 1), cache=current.s3db.cache ).first().name else: _path = "%s/%s" % (parent, id) L0_name = None elif Lx.level == "L0": _path = "%s/%s" % (parent, id) L0_name = Lx.name L1_name = None else: current.log.error("Parent of L2 Location ID %s has invalid level: %s is %s" % \ (id, parent, Lx.level)) #raise ValueError return "%s/%s" % (parent, id) Lx_lat = Lx.lat Lx_lon = Lx.lon else: _path = id L0_name = None L1_name = None Lx_lat = None Lx_lon = None if inherited or lat is None or lon is None: fixup_required = True inherited = True lat = Lx_lat lon = Lx_lon wkt = None elif path != _path or L0 != L0_name or L1 != L1_name or L2 != name or not wkt: fixup_required = True if fixup_required: # Fix everything up if lat is False: lat = None if lon is False: lon = None fix_vars = {"inherited": inherited, "path": _path, "lat": lat, "lon": lon, "wkt": wkt or None, "L0": L0_name, "L1": L1_name, "L2": name, "L3": None, "L4": None, "L5": None, } feature.update(**fix_vars) fixup(feature) if not all_locations: # Ensure that any locations which inherit their latlon from this one get updated propagate(id) return _path # L3 L3 = feature_get("L3", False) if level == "L3": if inherited is None or name is False or parent is False or path is False or \ lat is False or lon is False or wkt is False or \ L0 is False or L1 is False or L2 is False or L3 is False: # Get the whole feature feature = db(table.id == id).select(table.id, table.inherited, table.name, table.parent, table.path, table.lat, table.lon, table.wkt, table.L0, table.L1, table.L2, table.L3, limitby=(0, 1)).first() inherited = feature.inherited name = feature.name parent = feature.parent path = feature.path lat = feature.lat lon = feature.lon wkt = feature.wkt L0 = feature.L0 L1 = feature.L1 L2 = feature.L2 L3 = feature.L3 if parent: Lx = db(table.id == parent).select(table.id, table.name, table.level, table.parent, table.path, table.lat, table.lon, table.L0, table.L1, limitby=(0, 1)).first() if Lx.level == "L2": L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.name _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name and L1_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.L1, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 L1_name = Lx.L1 elif Lx.level == "L1": L0_name = Lx.L0 L1_name = Lx.name L2_name = None _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 elif Lx.level == "L0": _path = "%s/%s" % (parent, id) L0_name = Lx.name L1_name = None L2_name = None else: current.log.error("Parent of L3 Location ID %s has invalid level: %s is %s" % \ (id, parent, Lx.level)) #raise ValueError return "%s/%s" % (parent, id) Lx_lat = Lx.lat Lx_lon = Lx.lon else: _path = id L0_name = None L1_name = None L2_name = None Lx_lat = None Lx_lon = None if inherited or lat is None or lon is None: fixup_required = True inherited = True lat = Lx_lat lon = Lx_lon wkt = None elif path != _path or L0 != L0_name or L1 != L1_name or L2 != L2_name or L3 != name or not wkt: fixup_required = True if fixup_required: # Fix everything up if lat is False: lat = None if lon is False: lon = None fix_vars = {"inherited": inherited, "path": _path, "lat": lat, "lon": lon, "wkt": wkt or None, "L0": L0_name, "L1": L1_name, "L2": L2_name, "L3": name, "L4": None, "L5": None, } feature.update(**fix_vars) fixup(feature) if not all_locations: # Ensure that any locations which inherit their latlon from this one get updated propagate(id) return _path # L4 L4 = feature_get("L4", False) if level == "L4": if inherited is None or name is False or parent is False or path is False or \ lat is False or lon is False or wkt is False or \ L0 is False or L1 is False or L2 is False or L3 is False or L4 is False: # Get the whole feature feature = db(table.id == id).select(table.id, table.inherited, table.name, table.parent, table.path, table.lat, table.lon, table.wkt, table.L0, table.L1, table.L2, table.L3, table.L4, limitby=(0, 1)).first() inherited = feature.inherited name = feature.name parent = feature.parent path = feature.path lat = feature.lat lon = feature.lon wkt = feature.wkt L0 = feature.L0 L1 = feature.L1 L2 = feature.L2 L3 = feature.L3 L4 = feature.L4 if parent: Lx = db(table.id == parent).select(table.id, table.name, table.level, table.parent, table.path, table.lat, table.lon, table.L0, table.L1, table.L2, limitby=(0, 1)).first() if Lx.level == "L3": L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.L2 L3_name = Lx.name _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name and L1_name and L2_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.L1, table.L2, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.L2 elif Lx.level == "L2": L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.name L3_name = None _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name and L1_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.L1, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 L1_name = Lx.L1 elif Lx.level == "L1": L0_name = Lx.L0 L1_name = Lx.name L2_name = None L3_name = None _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 elif Lx.level == "L0": _path = "%s/%s" % (parent, id) L0_name = Lx.name L1_name = None L2_name = None L3_name = None else: current.log.error("Parent of L3 Location ID %s has invalid level: %s is %s" % \ (id, parent, Lx.level)) #raise ValueError return "%s/%s" % (parent, id) Lx_lat = Lx.lat Lx_lon = Lx.lon else: _path = id L0_name = None L1_name = None L2_name = None L3_name = None Lx_lat = None Lx_lon = None if inherited or lat is None or lon is None: fixup_required = True inherited = True lat = Lx_lat lon = Lx_lon wkt = None elif path != _path or L0 != L0_name or L1 != L1_name or L2 != L2_name or L3 != L3_name or L4 != name or not wkt: fixup_required = True if fixup_required: # Fix everything up if lat is False: lat = None if lon is False: lon = None fix_vars = {"inherited": inherited, "path": _path, "lat": lat, "lon": lon, "wkt": wkt or None, "L0": L0_name, "L1": L1_name, "L2": L2_name, "L3": L3_name, "L4": name, "L5": None, } feature.update(**fix_vars) fixup(feature) if not all_locations: # Ensure that any locations which inherit their latlon from this one get updated propagate(id) return _path # L5 L5 = feature_get("L5", False) if level == "L5": if inherited is None or name is False or parent is False or path is False or \ lat is False or lon is False or wkt is False or \ L0 is False or L1 is False or L2 is False or L3 is False or L4 is False or L5 is False: # Get the whole feature feature = db(table.id == id).select(table.id, table.inherited, table.name, table.parent, table.path, table.lat, table.lon, table.wkt, table.L0, table.L1, table.L2, table.L3, table.L4, table.L5, limitby=(0, 1)).first() inherited = feature.inherited name = feature.name parent = feature.parent path = feature.path lat = feature.lat lon = feature.lon wkt = feature.wkt L0 = feature.L0 L1 = feature.L1 L2 = feature.L2 L3 = feature.L3 L4 = feature.L4 L5 = feature.L5 if parent: Lx = db(table.id == parent).select(table.id, table.name, table.level, table.parent, table.path, table.lat, table.lon, table.L0, table.L1, table.L2, table.L3, limitby=(0, 1)).first() if Lx.level == "L4": L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.L2 L3_name = Lx.L3 L4_name = Lx.name _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name and L1_name and L2_name and L3_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.L1, table.L2, table.L3, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.L2 L3_name = Lx.L3 elif Lx.level == "L3": L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.L2 L3_name = Lx.name L4_name = None _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name and L1_name and L2_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.L1, table.L2, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.L2 elif Lx.level == "L2": L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.name L3_name = None L4_name = None _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name and L1_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.L1, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 L1_name = Lx.L1 elif Lx.level == "L1": L0_name = Lx.L0 L1_name = Lx.name L2_name = None L3_name = None L4_name = None _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 elif Lx.level == "L0": _path = "%s/%s" % (parent, id) L0_name = Lx.name L1_name = None L2_name = None L3_name = None L4_name = None else: current.log.error("Parent of L3 Location ID %s has invalid level: %s is %s" % \ (id, parent, Lx.level)) #raise ValueError return "%s/%s" % (parent, id) Lx_lat = Lx.lat Lx_lon = Lx.lon else: _path = id L0_name = None L1_name = None L2_name = None L3_name = None L4_name = None Lx_lat = None Lx_lon = None if inherited or lat is None or lon is None: fixup_required = True inherited = True lat = Lx_lat lon = Lx_lon wkt = None elif path != _path or L0 != L0_name or L1 != L1_name or L2 != L2_name or L3 != L3_name or L4 != L4_name or L5 != name or not wkt: fixup_required = True if fixup_required: # Fix everything up if lat is False: lat = None if lon is False: lon = None fix_vars = {"inherited": inherited, "path": _path, "lat": lat, "lon": lon, "wkt": wkt or None, "L0": L0_name, "L1": L1_name, "L2": L2_name, "L3": L3_name, "L4": L4_name, "L5": name, } feature.update(**fix_vars) fixup(feature) if not all_locations: # Ensure that any locations which inherit their latlon from this one get updated propagate(id) return _path # Specific Location # - or unspecified (which we should avoid happening as inefficient) if inherited is None or level is False or name is False or parent is False or path is False or \ lat is False or lon is False or wkt is False or \ L0 is False or L1 is False or L2 is False or L3 is False or L4 is False or L5 is False: # Get the whole feature feature = db(table.id == id).select(table.id, table.inherited, table.level, table.name, table.parent, table.path, table.lat, table.lon, table.wkt, table.L0, table.L1, table.L2, table.L3, table.L4, table.L5, limitby=(0, 1)).first() inherited = feature.inherited level = feature.level name = feature.name parent = feature.parent path = feature.path lat = feature.lat lon = feature.lon wkt = feature.wkt L0 = feature.L0 L1 = feature.L1 L2 = feature.L2 L3 = feature.L3 L4 = feature.L4 L5 = feature.L5 L0_name = name if level == "L0" else None L1_name = name if level == "L1" else None L2_name = name if level == "L2" else None L3_name = name if level == "L3" else None L4_name = name if level == "L4" else None L5_name = name if level == "L5" else None if parent: Lx = db(table.id == parent).select(table.id, table.name, table.level, table.parent, table.path, table.lat, table.lon, table.L0, table.L1, table.L2, table.L3, table.L4, limitby=(0, 1)).first() if Lx.level == "L5": L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.L2 L3_name = Lx.L3 L4_name = Lx.L4 L5_name = Lx.name _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name and L1_name and L2_name and L3_name and L4_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.L1, table.L2, table.L3, table.L4, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.L2 L3_name = Lx.L3 L4_name = Lx.L4 elif Lx.level == "L4": L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.L2 L3_name = Lx.L3 L4_name = Lx.name _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name and L1_name and L2_name and L3_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.L1, table.L2, table.L3, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.L2 L3_name = Lx.L3 elif Lx.level == "L3": L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.L2 L3_name = Lx.name _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name and L1_name and L2_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.L1, table.L2, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.L2 elif Lx.level == "L2": L0_name = Lx.L0 L1_name = Lx.L1 L2_name = Lx.name _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name and L1_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.L1, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 L1_name = Lx.L1 elif Lx.level == "L1": L0_name = Lx.L0 L1_name = Lx.name _path = Lx.path # Don't try to fixup ancestors when we're coming from a propagate if propagating or (_path and L0_name): _path = "%s/%s" % (_path, id) else: # This feature needs to be updated _path = update_location_tree(Lx, all_locations) _path = "%s/%s" % (_path, id) # Query again Lx = db(table.id == parent).select(table.L0, table.lat, table.lon, limitby=(0, 1) ).first() L0_name = Lx.L0 elif Lx.level == "L0": _path = "%s/%s" % (parent, id) L0_name = Lx.name else: current.log.error("Parent of L3 Location ID %s has invalid level: %s is %s" % \ (id, parent, Lx.level)) #raise ValueError return "%s/%s" % (parent, id) Lx_lat = Lx.lat Lx_lon = Lx.lon else: _path = id Lx_lat = None Lx_lon = None if inherited or lat is None or lon is None: fixup_required = True inherited = True lat = Lx_lat lon = Lx_lon wkt = None elif path != _path or L0 != L0_name or L1 != L1_name or L2 != L2_name or L3 != L3_name or L4 != L4_name or L5 != L5_name or not wkt: fixup_required = True if fixup_required: # Fix everything up if lat is False: lat = None if lon is False: lon = None fix_vars = {"inherited": inherited, "path": _path, "lat": lat, "lon": lon, "wkt": wkt or None, "L0": L0_name, "L1": L1_name, "L2": L2_name, "L3": L3_name, "L4": L4_name, "L5": L5_name, } feature.update(**fix_vars) fixup(feature) if not all_locations: # Ensure that any locations which inherit their latlon from this one get updated propagate(id) return _path # ------------------------------------------------------------------------- @staticmethod def wkt_centroid(form): """ OnValidation callback: If a WKT is defined: validate the format, calculate the LonLat of the Centroid, and set bounds Else if a LonLat is defined: calculate the WKT for the Point. """ form_vars = form.vars if form_vars.get("gis_feature_type", None) == "1": # Point lat = form_vars.get("lat", None) lon = form_vars.get("lon", None) if (lon is None and lat is None) or \ (lon == "" and lat == ""): # No Geometry available # Don't clobber existing records (e.g. in Prepop) #form_vars.gis_feature_type = "0" # Cannot create WKT, so Skip return elif lat is None or lat == "": # Can't just have lon without lat form.errors["lat"] = current.messages.lat_empty elif lon is None or lon == "": form.errors["lon"] = current.messages.lon_empty else: form_vars.wkt = "POINT(%(lon)s %(lat)s)" % form_vars radius = form_vars.get("radius", None) if radius: bbox = GIS.get_bounds_from_radius(lat, lon, radius) form_vars.lat_min = bbox["lat_min"] form_vars.lon_min = bbox["lon_min"] form_vars.lat_max = bbox["lat_max"] form_vars.lon_max = bbox["lon_max"] else: if "lon_min" not in form_vars or form_vars.lon_min is None: form_vars.lon_min = lon if "lon_max" not in form_vars or form_vars.lon_max is None: form_vars.lon_max = lon if "lat_min" not in form_vars or form_vars.lat_min is None: form_vars.lat_min = lat if "lat_max" not in form_vars or form_vars.lat_max is None: form_vars.lat_max = lat else: wkt = form_vars.get("wkt", None) if wkt: if wkt[0] == "{": # This is a GeoJSON geometry from shapely.geometry import shape as shape_loads try: js = json.load(wkt) shape = shape_loads(js) except: form.errors["wkt"] = current.messages.invalid_wkt return else: form_vars.wkt = shape.wkt else: # Assume WKT warning = None from shapely.wkt import loads as wkt_loads try: shape = wkt_loads(wkt) except: try: # Perhaps this is really a LINESTRING (e.g. OSM import of an unclosed Way) linestring = "LINESTRING%s" % wkt[8:-1] shape = wkt_loads(linestring) form_vars.wkt = linestring except: form.errors["wkt"] = current.messages.invalid_wkt return else: if shape.wkt != form_vars.wkt: # If this is too heavy a check for some deployments, add a deployment_setting to disable the check & just do it silently # Use Shapely to clean up the defective WKT (e.g. trailing chars) warning = s3_str(current.T("Source WKT has been cleaned by Shapely")) form_vars.wkt = shape.wkt if shape.has_z: # Shapely export of WKT is 2D only if warning: warning = "%s, %s" % s3_str(current.T("Only 2D geometry stored as PostGIS cannot handle 3D geometries")) else: warning = s3_str(current.T("Only 2D geometry stored as PostGIS cannot handle 3D geometries")) if warning: current.session.warning = warning gis_feature_type = shape.type if gis_feature_type == "Point": form_vars.gis_feature_type = 1 elif gis_feature_type == "LineString": form_vars.gis_feature_type = 2 elif gis_feature_type == "Polygon": form_vars.gis_feature_type = 3 elif gis_feature_type == "MultiPoint": form_vars.gis_feature_type = 4 elif gis_feature_type == "MultiLineString": form_vars.gis_feature_type = 5 elif gis_feature_type == "MultiPolygon": form_vars.gis_feature_type = 6 elif gis_feature_type == "GeometryCollection": form_vars.gis_feature_type = 7 try: centroid_point = shape.centroid form_vars.lon = centroid_point.x form_vars.lat = centroid_point.y bounds = shape.bounds if gis_feature_type != "Point" or \ "lon_min" not in form_vars or form_vars.lon_min is None or \ form_vars.lon_min == form_vars.lon_max: # Update bounds unless we have a 'Point' which has already got wider Bounds specified (such as a country) form_vars.lon_min = bounds[0] form_vars.lat_min = bounds[1] form_vars.lon_max = bounds[2] form_vars.lat_max = bounds[3] except: form.errors.gis_feature_type = current.messages.centroid_error else: lat = form_vars.get("lat", None) lon = form_vars.get("lon", None) if (lon is None and lat is None) or \ (lon == "" and lat == ""): # No Geometry available # Don't clobber existing records (e.g. in Prepop) #form_vars.gis_feature_type = "0" # Cannot create WKT, so Skip return else: # Point form_vars.gis_feature_type = "1" if lat is None or lat == "": form.errors["lat"] = current.messages.lat_empty elif lon is None or lon == "": form.errors["lon"] = current.messages.lon_empty else: form_vars.wkt = "POINT(%(lon)s %(lat)s)" % form_vars if "lon_min" not in form_vars or form_vars.lon_min is None: form_vars.lon_min = lon if "lon_max" not in form_vars or form_vars.lon_max is None: form_vars.lon_max = lon if "lat_min" not in form_vars or form_vars.lat_min is None: form_vars.lat_min = lat if "lat_max" not in form_vars or form_vars.lat_max is None: form_vars.lat_max = lat if current.deployment_settings.get_gis_spatialdb(): # Also populate the spatial field form_vars.the_geom = form_vars.wkt # ------------------------------------------------------------------------- @staticmethod def query_features_by_bbox(lon_min, lat_min, lon_max, lat_max): """ Returns a query of all Locations inside the given bounding box """ table = current.s3db.gis_location query = (table.lat_min <= lat_max) & \ (table.lat_max >= lat_min) & \ (table.lon_min <= lon_max) & \ (table.lon_max >= lon_min) return query # ------------------------------------------------------------------------- @staticmethod def get_features_by_bbox(lon_min, lat_min, lon_max, lat_max): """ Returns Rows of Locations whose shape intersects the given bbox. """ query = current.gis.query_features_by_bbox(lon_min, lat_min, lon_max, lat_max) return current.db(query).select() # ------------------------------------------------------------------------- @staticmethod def get_features_by_shape(shape): """ Returns Rows of locations which intersect the given shape. Relies on Shapely for wkt parsing and intersection. @ToDo: provide an option to use PostGIS/Spatialite """ from shapely.geos import ReadingError from shapely.wkt import loads as wkt_loads try: # Enable C-based speedups available from 1.2.10+ from shapely import speedups speedups.enable() except: current.log.info("S3GIS", "Upgrade Shapely for Performance enhancements") table = current.s3db.gis_location in_bbox = current.gis.query_features_by_bbox(*shape.bounds) has_wkt = (table.wkt != None) & (table.wkt != "") for loc in current.db(in_bbox & has_wkt).select(): try: location_shape = wkt_loads(loc.wkt) if location_shape.intersects(shape): yield loc except ReadingError: current.log.error("Error reading wkt of location with id", loc.id) # ------------------------------------------------------------------------- @staticmethod def get_features_by_latlon(lat, lon): """ Returns a generator of locations whose shape intersects the given LatLon. Relies on Shapely. @todo: provide an option to use PostGIS/Spatialite """ from shapely.geometry import point return current.gis.get_features_by_shape(point.Point(lon, lat)) # ------------------------------------------------------------------------- @staticmethod def get_features_by_feature(feature): """ Returns all Locations whose geometry intersects the given feature. Relies on Shapely. @ToDo: provide an option to use PostGIS/Spatialite """ from shapely.wkt import loads as wkt_loads shape = wkt_loads(feature.wkt) return current.gis.get_features_by_shape(shape) # ------------------------------------------------------------------------- @staticmethod def set_all_bounds(): """ Sets bounds for all locations without them. If shapely is present, and a location has wkt, bounds of the geometry are used. Otherwise, the (lat, lon) are used as bounds. """ try: from shapely.wkt import loads as wkt_loads SHAPELY = True except: SHAPELY = False db = current.db table = current.s3db.gis_location # Query to find all locations without bounds set no_bounds = (table.lon_min == None) & \ (table.lat_min == None) & \ (table.lon_max == None) & \ (table.lat_max == None) & \ (table.lat != None) & \ (table.lon != None) if SHAPELY: # Refine to those locations with a WKT field wkt_no_bounds = no_bounds & (table.wkt != None) & (table.wkt != "") for location in db(wkt_no_bounds).select(table.wkt): try : shape = wkt_loads(location.wkt) except: current.log.error("Error reading WKT", location.wkt) continue bounds = shape.bounds table[location.id] = {"lon_min": bounds[0], "lat_min": bounds[1], "lon_max": bounds[2], "lat_max": bounds[3], } # Anything left, we assume is a Point, so set the bounds to be the same db(no_bounds).update(lon_min=table.lon, lat_min=table.lat, lon_max=table.lon, lat_max=table.lat) # ------------------------------------------------------------------------- @staticmethod def simplify(wkt, tolerance=None, preserve_topology=True, output="wkt", precision=None ): """ Simplify a complex Polygon using the Douglas-Peucker algorithm - NB This uses Python, better performance will be gained by doing this direct from the database if you are using PostGIS: ST_Simplify() is available as db(query).select(table.the_geom.st_simplify(tolerance).st_astext().with_alias('wkt')).first().wkt db(query).select(table.the_geom.st_simplify(tolerance).st_asgeojson().with_alias('geojson')).first().geojson @param wkt: the WKT string to be simplified (usually coming from a gis_location record) @param tolerance: how aggressive a simplification to perform @param preserve_topology: whether the simplified geometry should be maintained @param output: whether to output as WKT or GeoJSON format @param precision: the number of decimal places to include in the output """ from shapely.geometry import Point, LineString, Polygon, MultiPolygon from shapely.wkt import loads as wkt_loads try: # Enable C-based speedups available from 1.2.10+ from shapely import speedups speedups.enable() except: current.log.info("S3GIS", "Upgrade Shapely for Performance enhancements") try: shape = wkt_loads(wkt) except: wkt = wkt[10] if wkt else wkt current.log.error("Invalid Shape: %s" % wkt) return None settings = current.deployment_settings if not precision: precision = settings.get_gis_precision() if tolerance is None: tolerance = settings.get_gis_simplify_tolerance() if tolerance: shape = shape.simplify(tolerance, preserve_topology) # Limit the number of decimal places formatter = ".%sf" % precision def shrink_polygon(shape): """ Helper Function """ points = shape.exterior.coords coords = [] cappend = coords.append for point in points: x = float(format(point[0], formatter)) y = float(format(point[1], formatter)) cappend((x, y)) return Polygon(LineString(coords)) geom_type = shape.geom_type if geom_type == "MultiPolygon": polygons = shape.geoms p = [] pappend = p.append for polygon in polygons: pappend(shrink_polygon(polygon)) shape = MultiPolygon([s for s in p]) elif geom_type == "Polygon": shape = shrink_polygon(shape) elif geom_type == "LineString": points = shape.coords coords = [] cappend = coords.append for point in points: x = float(format(point[0], formatter)) y = float(format(point[1], formatter)) cappend((x, y)) shape = LineString(coords) elif geom_type == "Point": x = float(format(shape.x, formatter)) y = float(format(shape.y, formatter)) shape = Point(x, y) else: current.log.info("Cannot yet shrink Geometry: %s" % geom_type) # Output if output == "wkt": output = shape.to_wkt() elif output == "geojson": from ..geojson import dumps # Compact Encoding output = dumps(shape, separators=SEPARATORS) return output # ------------------------------------------------------------------------- def show_map(self, id = "default_map", height = None, width = None, bbox = {}, lat = None, lon = None, zoom = None, projection = None, add_feature = False, add_feature_active = False, add_line = False, add_line_active = False, add_polygon = False, add_polygon_active = False, add_circle = False, add_circle_active = False, features = None, feature_queries = None, feature_resources = None, wms_browser = {}, catalogue_layers = False, legend = False, toolbar = False, area = False, color_picker = False, clear_layers = None, nav = None, print_control = None, print_mode = False, save = False, search = False, mouse_position = None, overview = None, permalink = None, scaleline = None, zoomcontrol = None, zoomWheelEnabled = True, mgrs = {}, window = False, window_hide = False, closable = True, maximizable = True, collapsed = False, callback = "DEFAULT", plugins = None, ): """ Returns the HTML to display a map Normally called in the controller as: map = gis.show_map() In the view, put: {{=XML(map)}} @param id: ID to uniquely identify this map if there are several on a page @param height: Height of viewport (if not provided then the default deployment setting is used) @param width: Width of viewport (if not provided then the default deployment setting is used) @param bbox: default Bounding Box of viewport (if not provided then the Lat/Lon/Zoom are used) (Dict): {"lon_min" : float, "lat_min" : float, "lon_max" : float, "lat_max" : float, } @param lat: default Latitude of viewport (if not provided then the default setting from the Map Service Catalogue is used) @param lon: default Longitude of viewport (if not provided then the default setting from the Map Service Catalogue is used) @param zoom: default Zoom level of viewport (if not provided then the default setting from the Map Service Catalogue is used) @param projection: EPSG code for the Projection to use (if not provided then the default setting from the Map Service Catalogue is used) @param add_feature: Whether to include a DrawFeature control to allow adding a marker to the map @param add_feature_active: Whether the DrawFeature control should be active by default @param add_polygon: Whether to include a DrawFeature control to allow drawing a polygon over the map @param add_polygon_active: Whether the DrawFeature control should be active by default @param add_circle: Whether to include a DrawFeature control to allow drawing a circle over the map @param add_circle_active: Whether the DrawFeature control should be active by default @param features: Simple Features to overlay on Map (no control over appearance & not interactive) [wkt] @param feature_queries: Feature Queries to overlay onto the map & their options (List of Dicts): [{"name" : T("MyLabel"), # A string: the label for the layer "query" : query, # A gluon.sql.Rows of gis_locations, which can be from a simple query or a Join. # Extra fields can be added for 'popup_url', 'popup_label' & either # 'marker' (url/height/width) or 'shape' (with optional 'colour' & 'size') "active" : True, # Is the feed displayed upon load or needs ticking to load afterwards? "marker" : None, # Optional: A per-Layer marker query or marker_id for the icon used to display the feature "opacity" : 1, # Optional "cluster_attribute", # Optional "cluster_distance", # Optional "cluster_threshold" # Optional }] @param feature_resources: REST URLs for (filtered) resources to overlay onto the map & their options (List of Dicts): [{"name" : T("MyLabel"), # A string: the label for the layer "id" : "search", # A string: the id for the layer (for manipulation by JavaScript) "active" : True, # Is the feed displayed upon load or needs ticking to load afterwards? EITHER: "layer_id" : 1, # An integer: the layer_id to load (optional alternative to specifying URL/tablename/marker) "filter" : "filter", # A string: an optional URL filter which *replaces* any in the layer OR: "tablename" : "module_resource", # A string: the tablename (used to determine whether to locate via location_id or site_id) "url" : "/eden/module/resource.geojson?filter", # A URL to load the resource "marker" : None, # Optional: A per-Layer marker dict for the icon used to display the feature (overrides layer_id if-set) "opacity" : 1, # Optional (overrides layer_id if-set) "cluster_attribute", # Optional (overrides layer_id if-set) "cluster_distance", # Optional (overrides layer_id if-set) "cluster_threshold", # Optional (overrides layer_id if-set) "dir", # Optional (overrides layer_id if-set) "style", # Optional (overrides layer_id if-set) }] @param wms_browser: WMS Server's GetCapabilities & options (dict) {"name": T("MyLabel"), # Name for the Folder in LayerTree "url": string # URL of GetCapabilities } @param catalogue_layers: Show all the enabled Layers from the GIS Catalogue Defaults to False: Just show the default Base layer @param legend: True: Show the GeoExt Legend panel, False: No Panel, "float": New floating Legend Panel @param toolbar: Show the Icon Toolbar of Controls @param area: Show the Area tool on the Toolbar @param color_picker: Show the Color Picker tool on the Toolbar (used for S3LocationSelector...pick up in postprocess) If a style is provided then this is used as the default style @param nav: Show the Navigation controls on the Toolbar @param save: Show the Save tool on the Toolbar @param search: Show the Geonames search box (requires a username to be configured) @param mouse_position: Show the current coordinates in the bottom-right of the map. 3 Options: 'normal', 'mgrs', False (defaults to checking deployment_settings, which defaults to 'normal') @param overview: Show the Overview Map (defaults to checking deployment_settings, which defaults to True) @param permalink: Show the Permalink control (defaults to checking deployment_settings, which defaults to True) @param scaleline: Show the ScaleLine control (defaults to checking deployment_settings, which defaults to True) @param zoomcontrol: Show the Zoom control (defaults to checking deployment_settings, which defaults to True) @param mgrs: Use the MGRS Control to select PDFs {"name": string, # Name for the Control "url": string # URL of PDF server } @ToDo: Also add MGRS Search support: http://gxp.opengeo.org/master/examples/mgrs.html @param window: Have viewport pop out of page into a resizable window @param window_hide: Have the window hidden by default, ready to appear (e.g. on clicking a button) @param closable: In Window mode, whether the window is closable or not @param collapsed: Start the Tools panel (West region) collapsed @param callback: Code to run once the Map JavaScript has loaded @param plugins: an iterable of objects which support the following methods: .extend_gis_map(map) Client-side portion suppoprts the following methods: .addToMapWindow(items) .setup(map) """ return MAP(id = id, height = height, width = width, bbox = bbox, lat = lat, lon = lon, zoom = zoom, projection = projection, add_feature = add_feature, add_feature_active = add_feature_active, add_line = add_line, add_line_active = add_line_active, add_polygon = add_polygon, add_polygon_active = add_polygon_active, add_circle = add_circle, add_circle_active = add_circle_active, features = features, feature_queries = feature_queries, feature_resources = feature_resources, wms_browser = wms_browser, catalogue_layers = catalogue_layers, legend = legend, toolbar = toolbar, area = area, color_picker = color_picker, clear_layers = clear_layers, nav = nav, print_control = print_control, print_mode = print_mode, save = save, search = search, mouse_position = mouse_position, overview = overview, permalink = permalink, scaleline = scaleline, zoomcontrol = zoomcontrol, zoomWheelEnabled = zoomWheelEnabled, mgrs = mgrs, window = window, window_hide = window_hide, closable = closable, maximizable = maximizable, collapsed = collapsed, callback = callback, plugins = plugins, ) # ============================================================================= class MAP(DIV): """ HTML Helper to render a Map - allows the Map to be generated only when being rendered - used by gis.show_map() """ def __init__(self, **opts): """ :param **opts: options to pass to the Map for server-side processing """ # We haven't yet run _setup() self.setup = False self.callback = None self.error_message = None self.components = [] # Options for server-side processing self.opts = opts opts_get = opts.get self.id = map_id = opts_get("id", "default_map") # Options for client-side processing self.options = {} # Adapt CSS to size of Map _class = "map_wrapper" if opts_get("window"): _class = "%s fullscreen" % _class if opts_get("print_mode"): _class = "%s print" % _class self.attributes = {"_class": _class, "_id": map_id, } self.parent = None # Show Color Picker? if opts_get("color_picker"): # Can't be done in _setup() as usually run from xml() and hence we've already passed this part of the layout.html s3 = current.response.s3 if s3.debug: style = "plugins/spectrum.css" else: style = "plugins/spectrum.min.css" if style not in s3.stylesheets: s3.stylesheets.append(style) # ------------------------------------------------------------------------- def _setup(self): """ Setup the Map - not done during init() to be as Lazy as possible - separated from xml() in order to be able to read options to put into scripts (callback or otherwise) """ # Fresh _setup() call, reset error message self.error_message = None auth = current.auth # Read configuration config = GIS.get_config() if not config: # No prepop - Bail if auth.s3_has_permission("create", "gis_hierarchy"): error_message = DIV(_class="mapError") # Deliberately not T() to save unneccessary load on translators error_message.append("Map cannot display without GIS config!") error_message.append(XML(" (You can can create one ")) error_message.append(A("here", _href=URL(c="gis", f="config"))) error_message.append(")") self.error_message = error_message else: self.error_message = DIV( "Map cannot display without GIS config!", # Deliberately not T() to save unneccessary load on translators _class="mapError" ) return None T = current.T db = current.db s3db = current.s3db request = current.request response = current.response if not response.warning: response.warning = "" s3 = response.s3 ctable = db.gis_config settings = current.deployment_settings MAP_ADMIN = auth.s3_has_role(current.session.s3.system_roles.MAP_ADMIN) opts_get = self.opts.get # Support bookmarks (such as from the control) # - these over-ride the arguments get_vars_get = request.get_vars.get # JS Globals js_globals = {} # Map Options for client-side processing options = {} # Strings used by all Maps i18n = {"gis_base_layers": T("Base Layers"), "gis_overlays": T(settings.get_gis_label_overlays()), "gis_layers": T(settings.get_gis_layers_label()), "gis_draft_layer": T("Draft Features"), "gis_cluster_multiple": T("There are multiple records at this location"), "gis_loading": T("Loading"), "gis_requires_login": T("Requires Login"), "gis_too_many_features": T("There are too many features, please Zoom In or Filter"), "gis_zoomin": T("Zoom In"), } ########## # Loader ########## self.append(DIV(DIV(_class="map_loader"), _id="%s_panel" % self.id)) ########## # Viewport ########## height = opts_get("height", None) if height: map_height = height else: map_height = settings.get_gis_map_height() options["map_height"] = map_height width = opts_get("width", None) if width: map_width = width else: map_width = settings.get_gis_map_width() options["map_width"] = map_width zoom = get_vars_get("zoom", None) if zoom is not None: zoom = int(zoom) else: zoom = opts_get("zoom", None) if not zoom: zoom = config.zoom options["zoom"] = zoom or 1 # Bounding Box or Center/Zoom bbox = opts_get("bbox", None) if (bbox and (-90 <= bbox["lat_max"] <= 90) and (-90 <= bbox["lat_min"] <= 90) and (-180 <= bbox["lon_max"] <= 180) and (-180 <= bbox["lon_min"] <= 180) ): # We have sane Bounds provided, so we should use them pass elif zoom is None: # Build Bounds from Config bbox = config else: # No bounds or we've been passed bounds which aren't sane bbox = None # Use Lat/Lon/Zoom to center instead lat = get_vars_get("lat", None) if lat is not None: lat = float(lat) else: lat = opts_get("lat", None) if lat is None or lat == "": lat = config.lat lon = get_vars_get("lon", None) if lon is not None: lon = float(lon) else: lon = opts_get("lon", None) if lon is None or lon == "": lon = config.lon if bbox: # Calculate from Bounds options["bbox"] = [bbox["lon_min"], # left bbox["lat_min"], # bottom bbox["lon_max"], # right bbox["lat_max"], # top ] else: options["lat"] = lat options["lon"] = lon options["numZoomLevels"] = config.zoom_levels options["restrictedExtent"] = (config.lon_min, config.lat_min, config.lon_max, config.lat_max, ) ############ # Projection ############ projection = opts_get("projection", None) if not projection: projection = config.epsg options["projection"] = projection if projection not in (900913, 4326): # Test for Valid Projection file in Proj4JS library projpath = os.path.join( request.folder, "static", "scripts", "gis", "proj4js", \ "lib", "defs", "EPSG%s.js" % projection ) try: f = open(projpath, "r") f.close() except: if projection: proj4js = config.proj4js if proj4js: # Create it try: f = open(projpath, "w") except IOError as e: response.error = \ T("Map not available: Cannot write projection file - %s") % e else: f.write('''Proj4js.defs["EPSG:4326"]="%s"''' % proj4js) f.close() else: response.warning = \ T("Map not available: Projection %(projection)s not supported - please add definition to %(path)s") % \ {"projection": "'%s'" % projection, "path": "/static/scripts/gis/proj4js/lib/defs", } else: response.error = \ T("Map not available: No Projection configured") return None options["maxExtent"] = config.maxExtent options["units"] = config.units ######## # Marker ######## if config.marker_image: options["marker_default"] = {"i": config.marker_image, "h": config.marker_height, "w": config.marker_width, } # @ToDo: show_map() opts with fallback to settings # Keep these in sync with scaleImage() in s3.gis.js marker_max_height = settings.get_gis_marker_max_height() if marker_max_height != 35: options["max_h"] = marker_max_height marker_max_width = settings.get_gis_marker_max_width() if marker_max_width != 30: options["max_w"] = marker_max_width ######### # Colours ######### # Keep these in sync with s3.gis.js cluster_fill = settings.get_gis_cluster_fill() if cluster_fill and cluster_fill != '8087ff': options["cluster_fill"] = cluster_fill cluster_stroke = settings.get_gis_cluster_stroke() if cluster_stroke and cluster_stroke != '2b2f76': options["cluster_stroke"] = cluster_stroke select_fill = settings.get_gis_select_fill() if select_fill and select_fill != 'ffdc33': options["select_fill"] = select_fill select_stroke = settings.get_gis_select_stroke() if select_stroke and select_stroke != 'ff9933': options["select_stroke"] = select_stroke if not settings.get_gis_cluster_label(): options["cluster_label"] = False ######## # Layout ######## if not opts_get("closable", False): options["windowNotClosable"] = True if opts_get("window", False): options["window"] = True if opts_get("window_hide", False): options["windowHide"] = True if opts_get("maximizable", False): options["maximizable"] = True else: options["maximizable"] = False # Collapsed if opts_get("collapsed", False): options["west_collapsed"] = True # LayerTree if not settings.get_gis_layer_tree_base(): options["hide_base"] = True if not settings.get_gis_layer_tree_overlays(): options["hide_overlays"] = True if not settings.get_gis_layer_tree_expanded(): options["folders_closed"] = True if settings.get_gis_layer_tree_radio(): options["folders_radio"] = True ####### # Tools ####### # Toolbar if opts_get("toolbar", False): options["toolbar"] = True i18n["gis_length_message"] = T("The length is") i18n["gis_length_tooltip"] = T("Measure Length: Click the points along the path & end with a double-click") i18n["gis_zoomfull"] = T("Zoom to maximum map extent") if settings.get_gis_geolocate_control(): # Presence of label turns feature on in s3.gis.js # @ToDo: Provide explicit option to support multiple maps in a page with different options i18n["gis_geoLocate"] = T("Zoom to Current Location") # Search if opts_get("search", False): geonames_username = settings.get_gis_geonames_username() if geonames_username: # Presence of username turns feature on in s3.gis.js options["geonames"] = geonames_username # Presence of label adds support JS in Loader i18n["gis_search"] = T("Search location in Geonames") #i18n["gis_search_no_internet"] = T("Geonames.org search requires Internet connectivity!") # Show NAV controls? # e.g. removed within S3LocationSelector[Widget] nav = opts_get("nav", None) if nav is None: nav = settings.get_gis_nav_controls() if nav: i18n["gis_zoominbutton"] = T("Zoom In: click in the map or use the left mouse button and drag to create a rectangle") i18n["gis_zoomout"] = T("Zoom Out: click in the map or use the left mouse button and drag to create a rectangle") i18n["gis_pan"] = T("Pan Map: keep the left mouse button pressed and drag the map") i18n["gis_navPrevious"] = T("Previous View") i18n["gis_navNext"] = T("Next View") else: options["nav"] = False # Show Area control? if opts_get("area", False): options["area"] = True i18n["gis_area_message"] = T("The area is") i18n["gis_area_tooltip"] = T("Measure Area: Click the points around the polygon & end with a double-click") # Show Color Picker? color_picker = opts_get("color_picker", False) if color_picker: options["color_picker"] = True if color_picker is not True: options["draft_style"] = json.loads(color_picker) #i18n["gis_color_picker_tooltip"] = T("Select Color") i18n["gis_cancelText"] = T("cancel") i18n["gis_chooseText"] = T("choose") i18n["gis_togglePaletteMoreText"] = T("more") i18n["gis_togglePaletteLessText"] = T("less") i18n["gis_clearText"] = T("Clear Color Selection") i18n["gis_noColorSelectedText"] = T("No Color Selected") # Show Print control? print_control = opts_get("print_control") is not False and settings.get_gis_print() if print_control: # @ToDo: Use internal Printing or External Service # http://eden.sahanafoundation.org/wiki/BluePrint/GIS/Printing #print_service = settings.get_gis_print_service() #if print_service: # print_tool = {"url": string, # URL of print service (e.g. http://localhost:8080/geoserver/pdf/) # "mapTitle": string, # Title for the Printed Map (optional) # "subTitle": string # subTitle for the Printed Map (optional) # } options["print"] = True i18n["gis_print"] = T("Print") i18n["gis_paper_size"] = T("Paper Size") i18n["gis_print_tip"] = T("Take a screenshot of the map which can be printed") # Show Save control? # e.g. removed within S3LocationSelector[Widget] if opts_get("save") is True and auth.s3_logged_in(): options["save"] = True i18n["gis_save"] = T("Save: Default Lat, Lon & Zoom for the Viewport") if MAP_ADMIN or (config.pe_id == auth.user.pe_id): # Personal config or MapAdmin, so Save Button does Updates options["config_id"] = config.id # OSM Authoring pe_id = auth.user.pe_id if auth.s3_logged_in() else None if pe_id and s3db.auth_user_options_get_osm(pe_id): # Presence of label turns feature on in s3.gis.js # @ToDo: Provide explicit option to support multiple maps in a page with different options i18n["gis_potlatch"] = T("Edit the OpenStreetMap data for this area") i18n["gis_osm_zoom_closer"] = T("Zoom in closer to Edit OpenStreetMap layer") # MGRS PDF Browser mgrs = opts_get("mgrs", None) if mgrs: options["mgrs_name"] = mgrs["name"] options["mgrs_url"] = mgrs["url"] else: # No toolbar if opts_get("save") is True: self.opts["save"] = "float" # Show Save control? # e.g. removed within S3LocationSelector[Widget] if opts_get("save") == "float" and auth.s3_logged_in(): permit = auth.s3_has_permission if permit("create", ctable): options["save"] = "float" i18n["gis_save_map"] = T("Save Map") i18n["gis_new_map"] = T("Save as New Map?") i18n["gis_name_map"] = T("Name of Map") i18n["save"] = T("Save") i18n["saved"] = T("Saved") config_id = config.id _config = db(ctable.id == config_id).select(ctable.uuid, ctable.name, limitby=(0, 1), ).first() if MAP_ADMIN: i18n["gis_my_maps"] = T("Saved Maps") else: options["pe_id"] = auth.user.pe_id i18n["gis_my_maps"] = T("My Maps") if permit("update", ctable, record_id=config_id): options["config_id"] = config_id options["config_name"] = _config.name elif _config.uuid != "SITE_DEFAULT": options["config_name"] = _config.name # Legend panel legend = opts_get("legend", False) if legend: i18n["gis_legend"] = T("Legend") if legend == "float": options["legend"] = "float" if settings.get_gis_layer_metadata(): options["metadata"] = True # MAP_ADMIN better for simpler deployments #if auth.s3_has_permission("create", "cms_post_layer"): if MAP_ADMIN: i18n["gis_metadata_create"] = T("Create 'More Info'") i18n["gis_metadata_edit"] = T("Edit 'More Info'") else: i18n["gis_metadata"] = T("More Info") else: options["legend"] = True # Draw Feature Controls if opts_get("add_feature", False): i18n["gis_draw_feature"] = T("Add Point") if opts_get("add_feature_active", False): options["draw_feature"] = "active" else: options["draw_feature"] = "inactive" if opts_get("add_line", False): i18n["gis_draw_line"] = T("Add Line") if opts_get("add_line_active", False): options["draw_line"] = "active" else: options["draw_line"] = "inactive" if opts_get("add_polygon", False): i18n["gis_draw_polygon"] = T("Add Polygon") i18n["gis_draw_polygon_clear"] = T("Clear Polygon") if opts_get("add_polygon_active", False): options["draw_polygon"] = "active" else: options["draw_polygon"] = "inactive" if opts_get("add_circle", False): i18n["gis_draw_circle"] = T("Add Circle") if opts_get("add_circle_active", False): options["draw_circle"] = "active" else: options["draw_circle"] = "inactive" # Clear Layers clear_layers = opts_get("clear_layers") is not False and settings.get_gis_clear_layers() if clear_layers: options["clear_layers"] = clear_layers i18n["gis_clearlayers"] = T("Clear all Layers") # Layer Properties if settings.get_gis_layer_properties(): # Presence of label turns feature on in s3.gis.js i18n["gis_properties"] = T("Layer Properties") # Upload Layer if settings.get_gis_geoserver_password(): # Presence of label adds support JS in Loader and turns feature on in s3.gis.js # @ToDo: Provide explicit option to support multiple maps in a page with different options i18n["gis_uploadlayer"] = T("Upload Shapefile") # WMS Browser wms_browser = opts_get("wms_browser", None) if wms_browser: options["wms_browser_name"] = wms_browser["name"] # urlencode the URL options["wms_browser_url"] = urllib_quote(wms_browser["url"]) # Mouse Position # 'normal', 'mgrs' or 'off' mouse_position = opts_get("mouse_position", None) if mouse_position is None: mouse_position = settings.get_gis_mouse_position() if mouse_position == "mgrs": options["mouse_position"] = "mgrs" # Tell loader to load support scripts js_globals["mgrs"] = True elif mouse_position: options["mouse_position"] = True # Overview Map overview = opts_get("overview", None) if overview is None: overview = settings.get_gis_overview() if not overview: options["overview"] = False # Permalink permalink = opts_get("permalink", None) if permalink is None: permalink = settings.get_gis_permalink() if not permalink: options["permalink"] = False # ScaleLine scaleline = opts_get("scaleline", None) if scaleline is None: scaleline = settings.get_gis_scaleline() if not scaleline: options["scaleline"] = False # Zoom control zoomcontrol = opts_get("zoomcontrol", None) if zoomcontrol is None: zoomcontrol = settings.get_gis_zoomcontrol() if not zoomcontrol: options["zoomcontrol"] = False zoomWheelEnabled = opts_get("zoomWheelEnabled", True) if not zoomWheelEnabled: options["no_zoom_wheel"] = True ######## # Layers ######## # Duplicate Features to go across the dateline? # @ToDo: Action this again (e.g. for DRRPP) if settings.get_gis_duplicate_features(): options["duplicate_features"] = True # Features features = opts_get("features", None) if features: options["features"] = addFeatures(features) # Feature Queries feature_queries = opts_get("feature_queries", None) if feature_queries: options["feature_queries"] = addFeatureQueries(feature_queries) # Feature Resources feature_resources = opts_get("feature_resources", None) if feature_resources: options["feature_resources"] = addFeatureResources(feature_resources) # Layers db = current.db ltable = db.gis_layer_config etable = db.gis_layer_entity query = (ltable.deleted == False) join = [etable.on(etable.layer_id == ltable.layer_id)] fields = [etable.instance_type, ltable.layer_id, ltable.enabled, ltable.visible, ltable.base, ltable.dir, ] if opts_get("catalogue_layers", False): # Add all enabled Layers from the Catalogue stable = db.gis_style mtable = db.gis_marker query &= (ltable.config_id.belongs(config.ids)) join.append(ctable.on(ctable.id == ltable.config_id)) fields.extend((stable.style, stable.cluster_distance, stable.cluster_threshold, stable.opacity, stable.popup_format, mtable.image, mtable.height, mtable.width, ctable.pe_type)) left = [stable.on((stable.layer_id == etable.layer_id) & \ (stable.record_id == None) & \ ((stable.config_id == ctable.id) | \ (stable.config_id == None))), mtable.on(mtable.id == stable.marker_id), ] limitby = None # @ToDo: Need to fix this?: make the style lookup a different call if settings.get_database_type() == "postgres": # None is last orderby = [ctable.pe_type, stable.config_id] else: # None is 1st orderby = [ctable.pe_type, ~stable.config_id] if settings.get_gis_layer_metadata(): cptable = s3db.cms_post_layer left.append(cptable.on(cptable.layer_id == etable.layer_id)) fields.append(cptable.post_id) else: # Add just the default Base Layer query &= (ltable.base == True) & \ (ltable.config_id == config.id) # Base layer doesn't need a style left = None limitby = (0, 1) orderby = None layer_types = [] lappend = layer_types.append layers = db(query).select(join=join, left=left, limitby=limitby, orderby=orderby, *fields) if not layers: # Use Site Default base layer # (Base layer doesn't need a style) query = (etable.id == ltable.layer_id) & \ (ltable.config_id == ctable.id) & \ (ctable.uuid == "SITE_DEFAULT") & \ (ltable.base == True) & \ (ltable.enabled == True) layers = db(query).select(*fields, limitby=(0, 1)) if not layers: # Just show EmptyLayer layer_types = [LayerEmpty] for layer in layers: layer_type = layer["gis_layer_entity.instance_type"] if layer_type == "gis_layer_openstreetmap": lappend(LayerOSM) elif layer_type == "gis_layer_google": # NB v3 doesn't work when initially hidden lappend(LayerGoogle) elif layer_type == "gis_layer_arcrest": lappend(LayerArcREST) elif layer_type == "gis_layer_bing": lappend(LayerBing) elif layer_type == "gis_layer_tms": lappend(LayerTMS) elif layer_type == "gis_layer_wms": lappend(LayerWMS) elif layer_type == "gis_layer_xyz": lappend(LayerXYZ) elif layer_type == "gis_layer_empty": lappend(LayerEmpty) elif layer_type == "gis_layer_js": lappend(LayerJS) elif layer_type == "gis_layer_theme": lappend(LayerTheme) elif layer_type == "gis_layer_geojson": lappend(LayerGeoJSON) elif layer_type == "gis_layer_gpx": lappend(LayerGPX) elif layer_type == "gis_layer_coordinate": lappend(LayerCoordinate) elif layer_type == "gis_layer_georss": lappend(LayerGeoRSS) elif layer_type == "gis_layer_kml": lappend(LayerKML) elif layer_type == "gis_layer_openweathermap": lappend(LayerOpenWeatherMap) elif layer_type == "gis_layer_shapefile": lappend(LayerShapefile) elif layer_type == "gis_layer_wfs": lappend(LayerWFS) elif layer_type == "gis_layer_feature": lappend(LayerFeature) # Make unique layer_types = set(layer_types) scripts = [] scripts_append = scripts.append for LayerType in layer_types: try: # Instantiate the Class layer = LayerType(layers, openlayers=2) layer.as_dict(options) for script in layer.scripts: scripts_append(script) except Exception as exception: error = "%s not shown: %s" % (LayerType.__name__, exception) current.log.error(error) if s3.debug: raise HTTP(500, error) else: response.warning += error # WMS getFeatureInfo # (loads conditionally based on whether queryable WMS Layers have been added) if s3.gis.get_feature_info and settings.get_gis_getfeature_control(): # Presence of label turns feature on # @ToDo: Provide explicit option to support multiple maps in a page # with different options i18n["gis_get_feature_info"] = T("Get Feature Info") i18n["gis_feature_info"] = T("Feature Info") # Callback can be set before _setup() if not self.callback: self.callback = opts_get("callback", "DEFAULT") # These can be read/modified after _setup() & before xml() self.options = options self.globals = js_globals self.i18n = i18n self.scripts = scripts # Set up map plugins # - currently just used by Climate # @ToDo: Get these working with new loader # This, and any code it generates, is done last # However, map plugin should not assume this. self.plugin_callbacks = [] plugins = opts_get("plugins", None) if plugins: for plugin in plugins: plugin.extend_gis_map(self) # Flag to xml() that we've already been run self.setup = True return options # ------------------------------------------------------------------------- def xml(self): """ Render the Map - this is primarily done by inserting a lot of JavaScript - CSS loaded as-standard to avoid delays in page loading - HTML added in init() as a component """ if not self.setup: result = self._setup() if result is None: if self.error_message: self.append(self.error_message) return super(MAP, self).xml() return "" # Add ExtJS # @ToDo: Do this conditionally on whether Ext UI is used s3_include_ext() dumps = json.dumps s3 = current.response.s3 js_global = s3.js_global js_global_append = js_global.append i18n_dict = self.i18n i18n = [] i18n_append = i18n.append for key, val in i18n_dict.items(): line = '''i18n.%s="%s"''' % (key, val) if line not in i18n: i18n_append(line) i18n = '''\n'''.join(i18n) if i18n not in js_global: js_global_append(i18n) globals_dict = self.globals js_globals = [] for key, val in globals_dict.items(): line = '''S3.gis.%s=%s''' % (key, dumps(val, separators=SEPARATORS)) if line not in js_globals: js_globals.append(line) js_globals = '''\n'''.join(js_globals) if js_globals not in js_global: js_global_append(js_globals) # Underscore for Popup Templates s3_include_underscore() debug = s3.debug scripts = s3.scripts if self.opts.get("color_picker", False): if debug: script = URL(c="static", f="scripts/spectrum.js") else: script = URL(c="static", f="scripts/spectrum.min.js") if script not in scripts: scripts.append(script) if debug: script = URL(c="static", f="scripts/S3/s3.gis.loader.js") else: script = URL(c="static", f="scripts/S3/s3.gis.loader.min.js") if script not in scripts: scripts.append(script) callback = self.callback map_id = self.id options = self.options projection = options["projection"] try: options = dumps(options, separators=SEPARATORS) except Exception as exception: current.log.error("Map %s failed to initialise" % map_id, exception) plugin_callbacks = '''\n'''.join(self.plugin_callbacks) if callback: if callback == "DEFAULT": if map_id == "default_map": callback = '''S3.gis.show_map(null,%s)''' % options else: callback = '''S3.gis.show_map(%s,%s)''' % (map_id, options) else: # Store options where they can be read by a later show_map() js_global_append('''S3.gis.options["%s"]=%s''' % (map_id, options)) script = URL(c="static", f="scripts/yepnope.1.5.4-min.js") if script not in scripts: scripts.append(script) if plugin_callbacks: callback = '''%s\n%s''' % (callback, plugin_callbacks) callback = '''function(){%s}''' % callback else: # Store options where they can be read by a later show_map() js_global_append('''S3.gis.options["%s"]=%s''' % (map_id, options)) if plugin_callbacks: callback = '''function(){%s}''' % plugin_callbacks else: callback = '''null''' loader = \ '''s3_gis_loadjs(%(debug)s,%(projection)s,%(callback)s,%(scripts)s)''' \ % {"debug": "true" if debug else "false", "projection": projection, "callback": callback, "scripts": self.scripts, } jquery_ready = s3.jquery_ready if loader not in jquery_ready: jquery_ready.append(loader) # Return the HTML return super(MAP, self).xml() # ============================================================================= class MAP2(DIV): """ HTML Helper to render a Map - allows the Map to be generated only when being rendered This is the Work-in-Progress update of MAP() to OpenLayers 6 """ def __init__(self, **opts): """ :param **opts: options to pass to the Map for server-side processing """ self.opts = opts # Pass options to DIV() opts_get = opts.get map_id = opts_get("id", "default_map") height = opts_get("height", current.deployment_settings.get_gis_map_height()) self.attributes = {"_id": map_id, "_style": "height:%ipx;width:100%%" % height, } # @ToDo: Add HTML Controls (Toolbar, LayerTree, etc) self.components = [DIV(_class="s3-gis-tooltip"), ] # Load CSS now as too late in xml() stylesheets = current.response.s3.stylesheets stylesheet = "gis/ol6.css" if stylesheet not in stylesheets: stylesheets.append(stylesheet) # @ToDo: Move this to Theme stylesheet = "gis/ol6_popup.css" if stylesheet not in stylesheets: stylesheets.append(stylesheet) # ------------------------------------------------------------------------- def _options(self): """ Configuration for the Map """ # Read Map Config config = GIS.get_config() if not config: # No prepop => Bail return None options = {} # i18n if current.session.s3.language != "en": T = current.T options["i18n"] = {"loading": s3_str(T("Loading")), "requires_login": s3_str(T("Requires Login")), } # Read options for this Map get_vars_get = current.request.get_vars.get opts_get = self.opts.get settings = current.deployment_settings ########## # Viewport ########## #options["height"] = opts_get("height", settings.get_gis_map_height()) #options["width"] = opts_get("width", settings.get_gis_map_width()) zoom = get_vars_get("zoom", None) if zoom is not None: zoom = int(zoom) else: zoom = opts_get("zoom", None) if not zoom: zoom = config.zoom options["zoom"] = zoom or 0 # Bounding Box or Center/Zoom bbox = opts_get("bbox", None) if (bbox and (-90 <= bbox["lat_max"] <= 90) and (-90 <= bbox["lat_min"] <= 90) and (-180 <= bbox["lon_max"] <= 180) and (-180 <= bbox["lon_min"] <= 180) ): # We have sane Bounds provided, so we should use them pass elif zoom is None: # Build Bounds from Config bbox = config else: # No bounds or we've been passed bounds which aren't sane bbox = None # Use Lat/Lon/Zoom to center instead lat = get_vars_get("lat", None) if lat is not None: lat = float(lat) else: lat = opts_get("lat", None) if lat is None or lat == "": lat = config.lat lon = get_vars_get("lon", None) if lon is not None: lon = float(lon) else: lon = opts_get("lon", None) if lon is None or lon == "": lon = config.lon if bbox: # Calculate from Bounds options["bbox"] = [bbox["lon_min"], # left bbox["lat_min"], # bottom bbox["lon_max"], # right bbox["lat_max"], # top ] else: options["lat"] = lat options["lon"] = lon #options["numZoomLevels"] = config.zoom_levels #options["restrictedExtent"] = (config.lon_min, # config.lat_min, # config.lon_max, # config.lat_max, # ) ############ # Projection ############ #projection = opts_get("projection", config.epsg) #if projection == 90013: # # New EPSG for Spherical Mercator # projection = 3857 #options["projection"] = projection #if projection not in (3857, 4326): # # Test for Valid Projection file in Proj4JS library # projpath = os.path.join( # request.folder, "static", "scripts", "gis", "proj4js", \ # "lib", "defs", "EPSG%s.js" % projection # ) # try: # f = open(projpath, "r") # f.close() # except: # if projection: # proj4js = config.proj4js # if proj4js: # # Create it # try: # f = open(projpath, "w") # except IOError as e: # response.error = \ # T("Map not available: Cannot write projection file - %s") % e # else: # f.write('''Proj4js.defs["EPSG:4326"]="%s"''' % proj4js) # f.close() # else: # response.warning = \ #T("Map not available: Projection %(projection)s not supported - please add definition to %(path)s") % \ #{"projection": "'%s'" % projection, # "path": "/static/scripts/gis/proj4js/lib/defs", # } # else: # response.error = \ # T("Map not available: No Projection configured") # return None # options["maxExtent"] = config.maxExtent # options["units"] = config.units ################## # Marker (Default) ################## if config.marker_image: options["marker"] = config.marker_image ######## # Layers ######## # Duplicate Features to go across the dateline? # @ToDo: Action this again (e.g. for DRRPP) #if settings.get_gis_duplicate_features(): # options["duplicate_features"] = True # Features features = opts_get("features", None) if features: options["features"] = addFeatures(features) # Feature Queries feature_queries = opts_get("feature_queries", None) if feature_queries: options["feature_queries"] = addFeatureQueries(feature_queries) # Feature Resources feature_resources = opts_get("feature_resources", None) if feature_resources: options["feature_resources"] = addFeatureResources(feature_resources) # Layers db = current.db ctable = db.gis_config ltable = db.gis_layer_config etable = db.gis_layer_entity query = (ltable.deleted == False) join = [etable.on(etable.layer_id == ltable.layer_id)] fields = [etable.instance_type, ltable.layer_id, ltable.enabled, ltable.visible, ltable.base, ltable.dir, ] if opts_get("catalogue_layers", False): # Add all enabled Layers from the Catalogue stable = db.gis_style mtable = db.gis_marker query &= (ltable.config_id.belongs(config.ids)) join.append(ctable.on(ctable.id == ltable.config_id)) fields.extend((stable.style, stable.cluster_distance, stable.cluster_threshold, stable.opacity, stable.popup_format, mtable.image, mtable.height, mtable.width, ctable.pe_type)) left = [stable.on((stable.layer_id == etable.layer_id) & \ (stable.record_id == None) & \ ((stable.config_id == ctable.id) | \ (stable.config_id == None))), mtable.on(mtable.id == stable.marker_id), ] limitby = None # @ToDo: Need to fix this?: make the style lookup a different call if settings.get_database_type() == "postgres": # None is last orderby = [ctable.pe_type, stable.config_id] else: # None is 1st orderby = [ctable.pe_type, ~stable.config_id] if settings.get_gis_layer_metadata(): cptable = current.s3db.cms_post_layer left.append(cptable.on(cptable.layer_id == etable.layer_id)) fields.append(cptable.post_id) else: # Add just the default Base Layer query &= (ltable.base == True) & \ (ltable.config_id == config.id) # Base layer doesn't need a style left = None limitby = (0, 1) orderby = None layer_types = [] lappend = layer_types.append layers = db(query).select(join=join, left=left, limitby=limitby, orderby=orderby, *fields) if not layers: # Use Site Default base layer # (Base layer doesn't need a style) query = (etable.id == ltable.layer_id) & \ (ltable.config_id == ctable.id) & \ (ctable.uuid == "SITE_DEFAULT") & \ (ltable.base == True) & \ (ltable.enabled == True) layers = db(query).select(*fields, limitby=(0, 1)) if not layers: # Just show EmptyLayer layer_types = [LayerEmpty] for layer in layers: layer_type = layer["gis_layer_entity.instance_type"] if layer_type == "gis_layer_openstreetmap": lappend(LayerOSM) elif layer_type == "gis_layer_google": # NB v3 doesn't work when initially hidden lappend(LayerGoogle) elif layer_type == "gis_layer_arcrest": lappend(LayerArcREST) elif layer_type == "gis_layer_bing": lappend(LayerBing) elif layer_type == "gis_layer_tms": lappend(LayerTMS) elif layer_type == "gis_layer_wms": lappend(LayerWMS) elif layer_type == "gis_layer_xyz": lappend(LayerXYZ) elif layer_type == "gis_layer_empty": lappend(LayerEmpty) elif layer_type == "gis_layer_js": lappend(LayerJS) elif layer_type == "gis_layer_theme": lappend(LayerTheme) elif layer_type == "gis_layer_geojson": lappend(LayerGeoJSON) elif layer_type == "gis_layer_gpx": lappend(LayerGPX) elif layer_type == "gis_layer_coordinate": lappend(LayerCoordinate) elif layer_type == "gis_layer_georss": lappend(LayerGeoRSS) elif layer_type == "gis_layer_kml": lappend(LayerKML) elif layer_type == "gis_layer_openweathermap": lappend(LayerOpenWeatherMap) elif layer_type == "gis_layer_shapefile": lappend(LayerShapefile) elif layer_type == "gis_layer_wfs": lappend(LayerWFS) elif layer_type == "gis_layer_feature": lappend(LayerFeature) # Make unique layer_types = set(layer_types) scripts = [] scripts_append = scripts.append for LayerType in layer_types: try: # Instantiate the Class layer = LayerType(layers) layer.as_dict(options) for script in layer.scripts: scripts_append(script) except Exception as exception: error = "%s not shown: %s" % (LayerType.__name__, exception) current.log.error(error) response = current.response if response.s3.debug: raise HTTP(500, error) else: response.warning += error return options # ------------------------------------------------------------------------- def xml(self): """ Render the Map - this is primarily done by inserting JavaScript """ # Read Map Config options = self._options() if options is None: # No Map Config: Just show error in the DIV auth = current.auth if auth.s3_has_permission("create", "gis_hierarchy"): error_message = DIV(_class="mapError") # Deliberately not T() to save unneccessary load on translators error_message.append("Map cannot display without GIS config!") error_message.append(XML(" (You can can create one ")) error_message.append(A("here", _href=URL(c="gis", f="config"))) error_message.append(")") else: error_message = DIV( "Map cannot display without GIS config!", # Deliberately not T() to save unneccessary load on translators _class="mapError" ) self.components = [error_message] return super(MAP2, self).xml() map_id = self.opts.get("id", "default_map") options = json.dumps(options, separators=SEPARATORS) # Insert the JavaScript appname = current.request.application s3 = current.response.s3 # Underscore for Popup Templates s3_include_underscore() # OpenLayers script = "/%s/static/scripts/gis/ol.js" % appname if script not in s3.scripts: s3.scripts.append(script) # S3 GIS if s3.debug: script = "/%s/static/scripts/S3/s3.ui.gis.js" % appname else: script = "/%s/static/scripts/S3/s3.ui.gis.min.js" % appname if script not in s3.scripts_modules: s3.scripts_modules.append(script) script = '''$('#%(map_id)s').showMap(%(options)s)''' % {"map_id": map_id, "options": options, } s3.jquery_ready.append(script) # Return the HTML return super(MAP2, self).xml() # ============================================================================= def addFeatures(features): """ Add Simple Features to the Draft layer - used by S3LocationSelectorWidget @todo: obsolete? """ simplify = GIS.simplify _f = [] append = _f.append for feature in features: geojson = simplify(feature, output="geojson") if geojson: f = {"type": "Feature", "geometry": json.loads(geojson), } append(f) return _f # ============================================================================= def addFeatureQueries(feature_queries): """ Add Feature Queries to the map - These can be Rows or Storage() NB These considerations need to be taken care of before arriving here: Security of data Localisation of name/popup_label """ db = current.db s3db = current.s3db cache = s3db.cache request = current.request controller = request.controller function = request.function fqtable = s3db.gis_feature_query mtable = s3db.gis_marker auth = current.auth auth_user = auth.user if auth_user: created_by = auth_user.id s3_make_session_owner = auth.s3_make_session_owner else: # Anonymous # @ToDo: A deployment with many Anonymous Feature Queries being # accessed will need to change this design - e.g. use session ID instead created_by = None layers_feature_query = [] append = layers_feature_query.append for layer in feature_queries: name = str(layer["name"]) _layer = {"name": name} name_safe = re.sub(r"\W", "_", name) # Lat/Lon via Join or direct? try: layer["query"][0].gis_location.lat join = True except: join = False # Push the Features into a temporary table in order to have them accessible via GeoJSON # @ToDo: Maintenance Script to clean out old entries (> 24 hours?) cname = "%s_%s_%s" % (name_safe, controller, function) # Clear old records query = (fqtable.name == cname) & \ (fqtable.created_by == created_by) db(query).delete() for row in layer["query"]: rowdict = {"name" : cname} if join: rowdict["lat"] = row.gis_location.lat rowdict["lon"] = row.gis_location.lon else: rowdict["lat"] = row["lat"] rowdict["lon"] = row["lon"] if "popup_url" in row: rowdict["popup_url"] = row["popup_url"] if "popup_label" in row: rowdict["popup_label"] = row["popup_label"] if "marker" in row: rowdict["marker_url"] = URL(c="static", f="img", args=["markers", row["marker"].image]) rowdict["marker_height"] = row["marker"].height rowdict["marker_width"] = row["marker"].width else: if "marker_url" in row: rowdict["marker_url"] = row["marker_url"] if "marker_height" in row: rowdict["marker_height"] = row["marker_height"] if "marker_width" in row: rowdict["marker_width"] = row["marker_width"] if "shape" in row: rowdict["shape"] = row["shape"] if "size" in row: rowdict["size"] = row["size"] if "colour" in row: rowdict["colour"] = row["colour"] if "opacity" in row: rowdict["opacity"] = row["opacity"] record_id = fqtable.insert(**rowdict) if not created_by: s3_make_session_owner(fqtable, record_id) # URL to retrieve the data url = "%s.geojson?feature_query.name=%s&feature_query.created_by=%s" % \ (URL(c="gis", f="feature_query"), cname, created_by) _layer["url"] = url if "active" in layer and not layer["active"]: _layer["visibility"] = False if "marker" in layer: # per-Layer Marker marker = layer["marker"] if isinstance(marker, int): # integer (marker_id) not row marker = db(mtable.id == marker).select(mtable.image, mtable.height, mtable.width, limitby=(0, 1), cache=cache ).first() if marker: # @ToDo: Single option as Marker.as_json_dict() _layer["marker_url"] = marker["image"] _layer["marker_height"] = marker["height"] _layer["marker_width"] = marker["width"] if "opacity" in layer and layer["opacity"] != 1: _layer["opacity"] = "%.1f" % layer["opacity"] if "cluster_attribute" in layer and \ layer["cluster_attribute"] != CLUSTER_ATTRIBUTE: _layer["cluster_attribute"] = layer["cluster_attribute"] if "cluster_distance" in layer and \ layer["cluster_distance"] != CLUSTER_DISTANCE: _layer["cluster_distance"] = layer["cluster_distance"] if "cluster_threshold" in layer and \ layer["cluster_threshold"] != CLUSTER_THRESHOLD: _layer["cluster_threshold"] = layer["cluster_threshold"] append(_layer) return layers_feature_query # ============================================================================= def addFeatureResources(feature_resources): """ Add Feature Resources to the map - REST URLs to back-end resources """ T = current.T db = current.db s3db = current.s3db ftable = s3db.gis_layer_feature ltable = s3db.gis_layer_config # Better to do a separate query #mtable = s3db.gis_marker stable = db.gis_style config = GIS.get_config() config_id = config.id postgres = current.deployment_settings.get_database_type() == "postgres" layers_feature_resource = [] append = layers_feature_resource.append for layer in feature_resources: name = s3_str(layer["name"]) _layer = {"name": name} _id = layer.get("id") if _id: _id = str(_id) else: _id = name _id = re.sub(r"\W", "_", _id) _layer["id"] = _id # Are we loading a Catalogue Layer or a simple URL? layer_id = layer.get("layer_id", None) if layer_id: query = (ftable.layer_id == layer_id) left = [ltable.on((ltable.layer_id == layer_id) & \ (ltable.config_id == config_id)), stable.on((stable.layer_id == layer_id) & \ ((stable.config_id == config_id) | \ (stable.config_id == None)) & \ (stable.record_id == None) & \ (stable.aggregate == False)), # Better to do a separate query #mtable.on(mtable.id == stable.marker_id), ] # @ToDo: Need to fix this?: make the style lookup a different call if postgres: # None is last orderby = stable.config_id else: # None is 1st orderby = ~stable.config_id row = db(query).select(ftable.layer_id, ftable.controller, ftable.function, ftable.filter, ftable.aggregate, ftable.trackable, ftable.use_site, # @ToDo: Deprecate Legacy ftable.popup_fields, # @ToDo: Deprecate Legacy ftable.popup_label, ftable.cluster_attribute, ltable.dir, # Better to do a separate query #mtable.image, #mtable.height, #mtable.width, stable.marker_id, stable.opacity, stable.popup_format, # @ToDo: If-required #stable.url_format, stable.cluster_distance, stable.cluster_threshold, stable.style, left=left, limitby=(0, 1), orderby=orderby, ).first() _dir = layer.get("dir", row["gis_layer_config.dir"]) # Better to do a separate query #_marker = row["gis_marker"] _style = row["gis_style"] row = row["gis_layer_feature"] if row.use_site: maxdepth = 1 else: maxdepth = 0 opacity = layer.get("opacity", _style.opacity) or 1 cluster_attribute = layer.get("cluster_attribute", row.cluster_attribute) or \ CLUSTER_ATTRIBUTE cluster_distance = layer.get("cluster_distance", _style.cluster_distance) or \ CLUSTER_DISTANCE cluster_threshold = layer.get("cluster_threshold", _style.cluster_threshold) if cluster_threshold is None: cluster_threshold = CLUSTER_THRESHOLD style = layer.get("style", None) if style: try: # JSON Object? style = json.loads(style) except: current.log.error("Invalid Style: %s" % style) style = None else: style = _style.style #url_format = _style.url_format aggregate = layer.get("aggregate", row.aggregate) if aggregate: url = "%s.geojson?layer=%i&show_ids=true" % \ (URL(c=row.controller, f=row.function, args="report"), row.layer_id) #if not url_format: # Use gis/location controller in all reports url_format = "%s/{id}.plain" % URL(c="gis", f="location") else: _url = URL(c=row.controller, f=row.function) url = "%s.geojson?layer=%i&components=None&show_ids=true&maxdepth=%s" % \ (_url, row.layer_id, maxdepth) #if not url_format: url_format = "%s/{id}.plain" % _url # Use specified filter or fallback to the one in the layer _filter = layer.get("filter", row.filter) if _filter: url = "%s&%s" % (url, _filter) if row.trackable: url = "%s&track=1" % url if not style: marker = layer.get("marker") if marker: marker = Marker(marker).as_json_dict() elif _style.marker_id: marker = Marker(marker_id=_style.marker_id).as_json_dict() popup_format = _style.popup_format if not popup_format: # Old-style popup_fields = row["popup_fields"] if popup_fields: popup_label = row["popup_label"] if popup_label: popup_format = "{%s} (%s)" % (popup_fields[0], current.T(popup_label)) else: popup_format = "%s" % popup_fields[0] for f in popup_fields[1:]: popup_format = "%s<br />{%s}" % (popup_format, f) else: # URL to retrieve the data url = layer["url"] tablename = layer["tablename"] table = s3db[tablename] # Optimise the query if "location_id" in table.fields: maxdepth = 0 elif "site_id" in table.fields: maxdepth = 1 elif tablename == "gis_location": maxdepth = 0 else: # Not much we can do! # @ToDo: Use Context continue options = "components=None&maxdepth=%s&show_ids=true" % maxdepth if "?" in url: url = "%s&%s" % (url, options) else: url = "%s?%s" % (url, options) opacity = layer.get("opacity", 1) cluster_attribute = layer.get("cluster_attribute", CLUSTER_ATTRIBUTE) cluster_distance = layer.get("cluster_distance", CLUSTER_DISTANCE) cluster_threshold = layer.get("cluster_threshold", CLUSTER_THRESHOLD) _dir = layer.get("dir", None) style = layer.get("style", None) if style: try: # JSON Object? style = json.loads(style) except: current.log.error("Invalid Style: %s" % style) style = None if not style: marker = layer.get("marker", None) if marker: marker = Marker(marker).as_json_dict() popup_format = layer.get("popup_format") url_format = layer.get("url_format") if "active" in layer and not layer["active"]: _layer["visibility"] = False if opacity != 1: _layer["opacity"] = "%.1f" % opacity if popup_format: if "T(" in popup_format: # i18n items = regex_translate.findall(popup_format) for item in items: titem = str(T(item[1:-1])) popup_format = popup_format.replace("T(%s)" % item, titem) _layer["popup_format"] = popup_format if url_format: _layer["url_format"] = url_format if cluster_attribute != CLUSTER_ATTRIBUTE: _layer["cluster_attribute"] = cluster_attribute if cluster_distance != CLUSTER_DISTANCE: _layer["cluster_distance"] = cluster_distance if cluster_threshold != CLUSTER_THRESHOLD: _layer["cluster_threshold"] = cluster_threshold if _dir: _layer["dir"] = _dir if style: _layer["style"] = style elif marker: # Per-layer Marker _layer["marker"] = marker else: # Request the server to provide per-feature Markers url = "%s&markers=1" % url _layer["url"] = url append(_layer) return layers_feature_resource # ============================================================================= class Layer(object): """ Abstract base class for Layers from Catalogue """ def __init__(self, all_layers, openlayers=6): self.openlayers = openlayers sublayers = [] append = sublayers.append # List of Scripts to load async with the Map JavaScript self.scripts = [] s3_has_role = current.auth.s3_has_role tablename = self.tablename table = current.s3db[tablename] fields = table.fields metafields = s3_all_meta_field_names() fields = [table[f] for f in fields if f not in metafields] layer_ids = [row["gis_layer_config.layer_id"] for row in all_layers if \ row["gis_layer_entity.instance_type"] == tablename] query = (table.layer_id.belongs(set(layer_ids))) rows = current.db(query).select(*fields) SubLayer = self.SubLayer # Flag to show whether we've set the default baselayer # (otherwise a config higher in the hierarchy can overrule one lower down) base = True # Layers requested to be visible via URL (e.g. embedded map) visible = current.request.get_vars.get("layers", None) if visible: visible = visible.split(".") else: visible = [] metadata = current.deployment_settings.get_gis_layer_metadata() styled = self.style for record in rows: layer_id = record.layer_id # Find the 1st row in all_layers which matches this for row in all_layers: if row["gis_layer_config.layer_id"] == layer_id: layer_config = row["gis_layer_config"] break # Check if layer is enabled if layer_config.enabled is False: continue # Check user is allowed to access the layer role_required = record.role_required if role_required and not s3_has_role(role_required): continue # All OK - add SubLayer record["visible"] = layer_config.visible or str(layer_id) in visible if base and layer_config.base: # var name can't conflict with OSM/WMS/ArcREST layers record["_base"] = True base = False else: record["_base"] = False record["dir"] = layer_config.dir if styled: style = row.get("gis_style", None) if style: style_dict = style.style if isinstance(style_dict, basestring): # Matryoshka (=double-serialized JSON)? # - should no longer happen, but a (now-fixed) bug # regularly produced double-serialized JSON, so # catching it here to keep it working with legacy # databases: try: style_dict = json.loads(style_dict) except ValueError: pass if style_dict: record["style"] = style_dict else: record["style"] = None marker = row.get("gis_marker", None) if marker: record["marker"] = Marker(marker) #if style.marker_id: # record["marker"] = Marker(marker_id=style.marker_id) else: # Default Marker? record["marker"] = Marker(tablename=tablename) record["opacity"] = style.opacity or 1 record["popup_format"] = style.popup_format record["cluster_distance"] = style.cluster_distance or CLUSTER_DISTANCE if style.cluster_threshold != None: record["cluster_threshold"] = style.cluster_threshold else: record["cluster_threshold"] = CLUSTER_THRESHOLD else: record["style"] = None record["opacity"] = 1 record["popup_format"] = None record["cluster_distance"] = CLUSTER_DISTANCE record["cluster_threshold"] = CLUSTER_THRESHOLD # Default Marker? record["marker"] = Marker(tablename=tablename) if metadata: post_id = row.get("cms_post_layer.post_id", None) record["post_id"] = post_id if tablename in ("gis_layer_bing", "gis_layer_google"): # SubLayers handled differently append(record) else: append(SubLayer(record, openlayers)) # Alphasort layers # - client will only sort within their type: s3.gis.layers.js self.sublayers = sorted(sublayers, key=lambda row: row.name) # ------------------------------------------------------------------------- def as_dict(self, options=None): """ Output the Layers as a Python dict """ sublayer_dicts = [] append = sublayer_dicts.append sublayers = self.sublayers for sublayer in sublayers: # Read the output dict for this sublayer sublayer_dict = sublayer.as_dict() if sublayer_dict: # Add this layer to the list of layers for this layer type append(sublayer_dict) if sublayer_dicts: if options: # Used by Map._setup() options[self.dictname] = sublayer_dicts else: # Used by as_json() and hence as_javascript() return sublayer_dicts # ------------------------------------------------------------------------- def as_json(self): """ Output the Layers as JSON """ result = self.as_dict() if result: #return json.dumps(result, indent=4, separators=(",", ": "), sort_keys=True) return json.dumps(result, separators=SEPARATORS) # ------------------------------------------------------------------------- def as_javascript(self): """ Output the Layers as global Javascript - suitable for inclusion in the HTML page """ result = self.as_json() if result: return '''S3.gis.%s=%s\n''' % (self.dictname, result) # ------------------------------------------------------------------------- class SubLayer(object): def __init__(self, record, openlayers): # Ensure all attributes available (even if Null) self.__dict__.update(record) del record if current.deployment_settings.get_L10n_translate_gis_layer(): self.safe_name = re.sub('[\\"]', "", s3_str(current.T(self.name))) else: self.safe_name = re.sub('[\\"]', "", self.name) self.openlayers = openlayers if hasattr(self, "projection_id"): self.projection = Projection(self.projection_id) def setup_clustering(self, output): if hasattr(self, "cluster_attribute"): cluster_attribute = self.cluster_attribute else: cluster_attribute = None cluster_distance = self.cluster_distance cluster_threshold = self.cluster_threshold if cluster_attribute and \ cluster_attribute != CLUSTER_ATTRIBUTE: output["cluster_attribute"] = cluster_attribute if cluster_distance != CLUSTER_DISTANCE: output["cluster_distance"] = cluster_distance if cluster_threshold != CLUSTER_THRESHOLD: output["cluster_threshold"] = cluster_threshold def setup_folder(self, output): if self.dir: output["dir"] = s3_str(current.T(self.dir)) def setup_folder_and_visibility(self, output): if not self.visible: output["visibility"] = False if self.dir: output["dir"] = s3_str(current.T(self.dir)) def setup_folder_visibility_and_opacity(self, output): if not self.visible: output["visibility"] = False if self.opacity != 1: output["opacity"] = "%.1f" % self.opacity if self.dir: output["dir"] = s3_str(current.T(self.dir)) # --------------------------------------------------------------------- @staticmethod def add_attributes_if_not_default(output, **values_and_defaults): # could also write values in debug mode, to check if defaults ignored. # could also check values are not being overwritten. for key, (value, defaults) in values_and_defaults.items(): if value not in defaults: output[key] = value # ----------------------------------------------------------------------------- class LayerArcREST(Layer): """ ArcGIS REST Layers from Catalogue """ tablename = "gis_layer_arcrest" dictname = "layers_arcrest" style = False # ------------------------------------------------------------------------- class SubLayer(Layer.SubLayer): def as_dict(self): # Mandatory attributes output = {"id": self.layer_id, "type": "arcrest", "name": self.safe_name, "url": self.url, } # Attributes which are defaulted client-side if not set self.setup_folder_and_visibility(output) self.add_attributes_if_not_default( output, layers = (self.layers, ([0],)), transparent = (self.transparent, (True,)), base = (self.base, (False,)), _base = (self._base, (False,)), format = (self.img_format, ("png",)), ) return output # ----------------------------------------------------------------------------- class LayerBing(Layer): """ Bing Layers from Catalogue """ tablename = "gis_layer_bing" dictname = "Bing" style = False # ------------------------------------------------------------------------- def as_dict(self, options=None): sublayers = self.sublayers if sublayers: if Projection().epsg != 900913: raise Exception("Cannot display Bing layers unless we're using the Spherical Mercator Projection\n") apikey = current.deployment_settings.get_gis_api_bing() if not apikey: raise Exception("Cannot display Bing layers unless we have an API key\n") # Mandatory attributes ldict = {"ApiKey": apikey } for sublayer in sublayers: # Attributes which are defaulted client-side if not set if sublayer._base: # Set default Base layer ldict["Base"] = sublayer.type if sublayer.type == "aerial": ldict["Aerial"] = {"name": sublayer.name or "Bing Satellite", "id": sublayer.layer_id} elif sublayer.type == "road": ldict["Road"] = {"name": sublayer.name or "Bing Roads", "id": sublayer.layer_id} elif sublayer.type == "hybrid": ldict["Hybrid"] = {"name": sublayer.name or "Bing Hybrid", "id": sublayer.layer_id} if options: # Used by Map._setup() options[self.dictname] = ldict else: # Used by as_json() and hence as_javascript() return ldict # ----------------------------------------------------------------------------- class LayerCoordinate(Layer): """ Coordinate Layer from Catalogue - there should only be one of these """ tablename = "gis_layer_coordinate" dictname = "CoordinateGrid" style = False # ------------------------------------------------------------------------- def as_dict(self, options=None): sublayers = self.sublayers if sublayers: sublayer = sublayers[0] name_safe = re.sub("'", "", sublayer.name) ldict = {"name": name_safe, "visibility": sublayer.visible, "id": sublayer.layer_id, } if options: # Used by Map._setup() options[self.dictname] = ldict else: # Used by as_json() and hence as_javascript() return ldict # ----------------------------------------------------------------------------- class LayerEmpty(Layer): """ Empty Layer from Catalogue - there should only be one of these """ tablename = "gis_layer_empty" dictname = "EmptyLayer" style = False # ------------------------------------------------------------------------- def as_dict(self, options=None): sublayers = self.sublayers if sublayers: sublayer = sublayers[0] name = s3_str(current.T(sublayer.name)) name_safe = re.sub("'", "", name) ldict = {"name": name_safe, "id": sublayer.layer_id, } if sublayer._base: ldict["base"] = True if options: # Used by Map._setup() options[self.dictname] = ldict else: # Used by as_json() and hence as_javascript() return ldict # ----------------------------------------------------------------------------- class LayerFeature(Layer): """ Feature Layers from Catalogue """ tablename = "gis_layer_feature" dictname = "layers_feature" style = True # ------------------------------------------------------------------------- class SubLayer(Layer.SubLayer): def __init__(self, record, openlayers): controller = record.controller self.skip = False if controller is not None: if controller not in current.deployment_settings.modules: # Module is disabled self.skip = True if not current.auth.permission.has_permission("read", c=controller, f=record.function): # User has no permission to this resource (in ACL) self.skip = True else: error = "Feature Layer Record '%s' has no controller" % \ record.name raise Exception(error) super(LayerFeature.SubLayer, self).__init__(record, openlayers) def as_dict(self): if self.skip: # Skip layer return # @ToDo: Option to force all filters via POST? if self.aggregate: # id is used for url_format url = "%s.geojson?layer=%i&show_ids=true" % \ (URL(c=self.controller, f=self.function, args="report"), self.layer_id) # Use gis/location controller in all reports url_format = "%s/{id}.plain" % URL(c="gis", f="location") else: if self.use_site: maxdepth = 1 else: maxdepth = 0 _url = URL(self.controller, self.function) # id is used for url_format url = "%s.geojson?layer=%i&components=None&maxdepth=%s&show_ids=true" % \ (_url, self.layer_id, maxdepth) url_format = "%s/{id}.plain" % _url if self.filter: url = "%s&%s" % (url, self.filter) if self.trackable: url = "%s&track=1" % url # Mandatory attributes output = {"id": self.layer_id, # Defaults client-side if not-provided #"type": "feature", "name": self.safe_name, "url_format": url_format, "url": url, } popup_format = self.popup_format if popup_format: # New-style if "T(" in popup_format: # i18n T = current.T items = regex_translate.findall(popup_format) for item in items: titem = str(T(item[1:-1])) popup_format = popup_format.replace("T(%s)" % item, titem) output["popup_format"] = popup_format else: # @ToDo: Deprecate popup_fields = self.popup_fields if popup_fields: # Old-style popup_label = self.popup_label if popup_label: popup_format = "{%s} (%s)" % (popup_fields[0], current.T(popup_label)) else: popup_format = "%s" % popup_fields[0] for f in popup_fields[1:]: popup_format = "%s<br/>{%s}" % (popup_format, f) output["popup_format"] = popup_format or "" # Attributes which are defaulted client-side if not set self.setup_folder_visibility_and_opacity(output) self.setup_clustering(output) if self.aggregate: # Enable the Cluster Strategy, so that it can be enabled/disabled # depending on the zoom level & hence Points or Polygons output["cluster"] = 1 if not popup_format: # Need this to differentiate from e.g. FeatureQueries output["no_popups"] = 1 if self.style: output["style"] = self.style else: self.marker.add_attributes_to_output(output) return output # ----------------------------------------------------------------------------- class LayerGeoJSON(Layer): """ GeoJSON Layers from Catalogue """ tablename = "gis_layer_geojson" dictname = "layers_geojson" style = True # ------------------------------------------------------------------------- class SubLayer(Layer.SubLayer): def as_dict(self): # Mandatory attributes output = {"id": self.layer_id, "type": "geojson", "name": self.safe_name, "url": self.url, } # Attributes which are defaulted client-side if not set projection = self.projection if projection.epsg != 4326: output["projection"] = projection.epsg self.setup_folder_visibility_and_opacity(output) self.setup_clustering(output) if self.style: output["style"] = self.style else: self.marker.add_attributes_to_output(output) popup_format = self.popup_format if popup_format: if "T(" in popup_format: # i18n T = current.T items = regex_translate.findall(popup_format) for item in items: titem = str(T(item[1:-1])) popup_format = popup_format.replace("T(%s)" % item, titem) output["popup_format"] = popup_format return output # ----------------------------------------------------------------------------- class LayerGeoRSS(Layer): """ GeoRSS Layers from Catalogue """ tablename = "gis_layer_georss" dictname = "layers_georss" style = True def __init__(self, all_layers, openlayers=6): super(LayerGeoRSS, self).__init__(all_layers, openlayers) LayerGeoRSS.SubLayer.cachetable = current.s3db.gis_cache # ------------------------------------------------------------------------- class SubLayer(Layer.SubLayer): def as_dict(self): db = current.db request = current.request response = current.response cachetable = self.cachetable url = self.url # Check to see if we should Download layer to the cache download = True query = (cachetable.source == url) existing_cached_copy = db(query).select(cachetable.modified_on, limitby=(0, 1)).first() refresh = self.refresh or 900 # 15 minutes set if we have no data (legacy DB) if existing_cached_copy: modified_on = existing_cached_copy.modified_on cutoff = modified_on + datetime.timedelta(seconds=refresh) if request.utcnow < cutoff: download = False if download: # Download layer to the Cache from gluon.tools import fetch # @ToDo: Call directly without going via HTTP # @ToDo: Make this async by using S3Task (also use this for the refresh time) fields = "" if self.data: fields = "&data_field=%s" % self.data if self.image: fields = "%s&image_field=%s" % (fields, self.image) _url = "%s%s/update.georss?fetchurl=%s%s" % (current.deployment_settings.get_base_public_url(), URL(c="gis", f="cache_feed"), url, fields) # Keep Session for local URLs cookie = Cookie.SimpleCookie() cookie[response.session_id_name] = response.session_id current.session._unlock(response) try: # @ToDo: Need to commit to not have DB locked with SQLite? fetch(_url, cookie=cookie) if existing_cached_copy: # Clear old selfs which are no longer active query = (cachetable.source == url) & \ (cachetable.modified_on < cutoff) db(query).delete() except Exception as exception: current.log.error("GeoRSS %s download error" % url, exception) # Feed down if existing_cached_copy: # Use cached copy # Should we Update timestamp to prevent every # subsequent request attempting the download? #query = (cachetable.source == url) #db(query).update(modified_on=request.utcnow) pass else: response.warning += "%s down & no cached copy available" % url name_safe = self.safe_name # Pass the GeoJSON URL to the client # Filter to the source of this feed url = "%s.geojson?cache.source=%s" % (URL(c="gis", f="cache_feed"), url) # Mandatory attributes output = {"id": self.layer_id, "type": "georss", "name": name_safe, "url": url, } self.marker.add_attributes_to_output(output) # Attributes which are defaulted client-side if not set if self.refresh != 900: output["refresh"] = self.refresh self.setup_folder_visibility_and_opacity(output) self.setup_clustering(output) return output # ----------------------------------------------------------------------------- class LayerGoogle(Layer): """ Google Layers/Tools from Catalogue """ tablename = "gis_layer_google" dictname = "Google" style = False # ------------------------------------------------------------------------- def as_dict(self, options=None): sublayers = self.sublayers if sublayers: T = current.T spherical_mercator = (Projection().epsg == 900913) settings = current.deployment_settings apikey = settings.get_gis_api_google() s3 = current.response.s3 debug = s3.debug # Google scripts use document.write so cannot be loaded async via yepnope.js s3_scripts = s3.scripts ldict = {} if spherical_mercator: # Earth was the only layer which can run in non-Spherical Mercator # @ToDo: Warning? for sublayer in sublayers: # Attributes which are defaulted client-side if not set #if sublayer.type == "earth": # # Deprecated: # # https://maps-apis.googleblog.com/2014/12/announcing-deprecation-of-google-earth.html # ldict["Earth"] = str(T("Switch to 3D")) # #{"modules":[{"name":"earth","version":"1"}]} # script = "//www.google.com/jsapi?key=" + apikey + "&autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22earth%22%2C%22version%22%3A%221%22%7D%5D%7D" # if script not in s3_scripts: # s3_scripts.append(script) # # Dynamic Loading not supported: https://developers.google.com/loader/#Dynamic # #s3.jquery_ready.append('''try{google.load('earth','1')catch(e){}''') # if debug: # self.scripts.append("gis/gxp/widgets/GoogleEarthPanel.js") # else: # self.scripts.append("gis/gxp/widgets/GoogleEarthPanel.min.js") # s3.js_global.append('''S3.public_url="%s"''' % settings.get_base_public_url()) if sublayer._base: # Set default Base layer ldict["Base"] = sublayer.type if sublayer.type == "satellite": ldict["Satellite"] = {"name": sublayer.name or "Google Satellite", "id": sublayer.layer_id} elif sublayer.type == "maps": ldict["Maps"] = {"name": sublayer.name or "Google Maps", "id": sublayer.layer_id} elif sublayer.type == "hybrid": ldict["Hybrid"] = {"name": sublayer.name or "Google Hybrid", "id": sublayer.layer_id} elif sublayer.type == "streetview": ldict["StreetviewButton"] = "Click where you want to open Streetview" elif sublayer.type == "terrain": ldict["Terrain"] = {"name": sublayer.name or "Google Terrain", "id": sublayer.layer_id} elif sublayer.type == "mapmaker": ldict["MapMaker"] = {"name": sublayer.name or "Google MapMaker", "id": sublayer.layer_id} elif sublayer.type == "mapmakerhybrid": ldict["MapMakerHybrid"] = {"name": sublayer.name or "Google MapMaker Hybrid", "id": sublayer.layer_id} if "MapMaker" in ldict or "MapMakerHybrid" in ldict: # Need to use v2 API # This should be able to be fixed in OpenLayers now since Google have fixed in v3 API: # http://code.google.com/p/gmaps-api-issues/issues/detail?id=2349#c47 script = "//maps.google.com/maps?file=api&v=2&key=%s" % apikey if script not in s3_scripts: s3_scripts.append(script) else: # v3 API (3.0 gives us the latest frozen version, currently 3.30) # Note that it does give a warning: "Google Maps API warning: RetiredVersion" # https://developers.google.com/maps/documentation/javascript/versions script = "//maps.google.com/maps/api/js?v=3.0&key=%s" % apikey if script not in s3_scripts: s3_scripts.append(script) if "StreetviewButton" in ldict: # Streetview doesn't work with v2 API ldict["StreetviewButton"] = str(T("Click where you want to open Streetview")) ldict["StreetviewTitle"] = str(T("Street View")) if debug: self.scripts.append("gis/gxp/widgets/GoogleStreetViewPanel.js") else: self.scripts.append("gis/gxp/widgets/GoogleStreetViewPanel.min.js") if options: # Used by Map._setup() options[self.dictname] = ldict else: # Used by as_json() and hence as_javascript() return ldict # ----------------------------------------------------------------------------- class LayerGPX(Layer): """ GPX Layers from Catalogue """ tablename = "gis_layer_gpx" dictname = "layers_gpx" style = True # ------------------------------------------------------------------------- class SubLayer(Layer.SubLayer): def as_dict(self): url = URL(c="default", f="download", args=self.track) # Mandatory attributes output = {"id": self.layer_id, "name": self.safe_name, "url": url, } # Attributes which are defaulted client-side if not set self.marker.add_attributes_to_output(output) self.add_attributes_if_not_default( output, waypoints = (self.waypoints, (True,)), tracks = (self.tracks, (True,)), routes = (self.routes, (True,)), ) self.setup_folder_visibility_and_opacity(output) self.setup_clustering(output) return output # ----------------------------------------------------------------------------- class LayerJS(Layer): """ JS Layers from Catalogue - these are raw Javascript layers for use by expert OpenLayers people to quickly add/configure new data sources without needing support from back-end Sahana programmers """ tablename = "gis_layer_js" dictname = "layers_js" style = False # ------------------------------------------------------------------------- def as_dict(self, options=None): sublayers = self.sublayers if sublayers: sublayer_dicts = [] append = sublayer_dicts.append for sublayer in sublayers: append(sublayer.code) if options: # Used by Map._setup() options[self.dictname] = sublayer_dicts else: # Used by as_json() and hence as_javascript() return sublayer_dicts # ----------------------------------------------------------------------------- class LayerKML(Layer): """ KML Layers from Catalogue """ tablename = "gis_layer_kml" dictname = "layers_kml" style = True # ------------------------------------------------------------------------- def __init__(self, all_layers, openlayers=6, init=True): "Set up the KML cache, should be done once per request" super(LayerKML, self).__init__(all_layers, openlayers) # Can we cache downloaded KML feeds? # Needed for unzipping & filtering as well # @ToDo: Should we move this folder to static to speed up access to cached content? # Do we need to secure it? request = current.request cachepath = os.path.join(request.folder, "uploads", "gis_cache") if os.path.exists(cachepath): cacheable = os.access(cachepath, os.W_OK) else: try: os.mkdir(cachepath) except OSError as os_error: current.log.error("GIS: KML layers cannot be cached: %s %s" % \ (cachepath, os_error)) cacheable = False else: cacheable = True # @ToDo: Migrate to gis_cache LayerKML.cachetable = current.s3db.gis_cache2 LayerKML.cacheable = cacheable LayerKML.cachepath = cachepath # ------------------------------------------------------------------------- class SubLayer(Layer.SubLayer): def as_dict(self): db = current.db request = current.request cachetable = LayerKML.cachetable cacheable = LayerKML.cacheable #cachepath = LayerKML.cachepath name = self.name if cacheable: _name = urllib_quote(name) _name = _name.replace("%", "_") filename = "%s.file.%s.kml" % (cachetable._tablename, _name) # Should we download a fresh copy of the source file? download = True query = (cachetable.name == name) cached = db(query).select(cachetable.modified_on, limitby=(0, 1)).first() refresh = self.refresh or 900 # 15 minutes set if we have no data (legacy DB) if cached: modified_on = cached.modified_on cutoff = modified_on + datetime.timedelta(seconds=refresh) if request.utcnow < cutoff: download = False if download: # Download file (async, if workers alive) response = current.response session_id_name = response.session_id_name session_id = response.session_id current.s3task.run_async("gis_download_kml", args = [self.id, filename, session_id_name, session_id, ]) if cached: db(query).update(modified_on=request.utcnow) else: cachetable.insert(name=name, file=filename) url = URL(c="default", f="download", args=[filename]) else: # No caching possible (e.g. GAE), display file direct from remote (using Proxy) # (Requires OpenLayers.Layer.KML to be available) url = self.url # Mandatory attributes output = {"id": self.layer_id, "name": self.safe_name, "url": url, } # Attributes which are defaulted client-side if not set self.add_attributes_if_not_default( output, title = (self.title, ("name", None, "")), body = (self.body, ("description", None)), refresh = (self.refresh, (900,)), ) self.setup_folder_visibility_and_opacity(output) self.setup_clustering(output) if self.style: output["style"] = self.style else: self.marker.add_attributes_to_output(output) return output # ----------------------------------------------------------------------------- class LayerOSM(Layer): """ OpenStreetMap Layers from Catalogue @ToDo: Provide a catalogue of standard layers which are fully-defined in static & can just have name over-ridden, as well as fully-custom layers. """ tablename = "gis_layer_openstreetmap" dictname = "layers_osm" style = False # ------------------------------------------------------------------------- class SubLayer(Layer.SubLayer): def as_dict(self): if Projection().epsg not in (3857, 900913): # Cannot display OpenStreetMap layers unless we're using the Spherical Mercator Projection return {} if self.openlayers == 6: # Mandatory attributes output = {#"id": self.layer_id, #"name": self.safe_name, #"url": self.url1, } # Attributes which are defaulted client-side if not set url = self.url1 if not url.endswith("png"): # Convert legacy URL format url = "%s{z}/{x}/{y}.png" % url if self.url2: url = url.replace("/a.", "/{a-c}.") self.add_attributes_if_not_default( output, base = (self.base, (True,)), _base = (self._base, (False,)), url = (url, ("https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png",)), maxZoom = (self.zoom_levels, (19,)), attribution = (self.attribution and self.attribution.replace("\"", "'"), (None,)), ) else: # OpenLayers 2.13 output = {"id": self.layer_id, "name": self.safe_name, "url1": self.url1, } # Attributes which are defaulted client-side if not set self.add_attributes_if_not_default( output, base = (self.base, (True,)), _base = (self._base, (False,)), url2 = (self.url2, ("",)), url3 = (self.url3, ("",)), zoomLevels = (self.zoom_levels, (19,)), attribution = (self.attribution, (None,)), ) self.setup_folder_and_visibility(output) return output # ----------------------------------------------------------------------------- class LayerOpenWeatherMap(Layer): """ OpenWeatherMap Layers from Catalogue """ tablename = "gis_layer_openweathermap" dictname = "OWM" style = False # ------------------------------------------------------------------------- def as_dict(self, options=None): sublayers = self.sublayers if sublayers: if current.response.s3.debug: self.scripts.append("gis/OWM.OpenLayers.js") else: self.scripts.append("gis/OWM.OpenLayers.min.js") ldict = {} for sublayer in sublayers: if sublayer.type == "station": ldict["station"] = {"name": sublayer.name or "Weather Stations", "id": sublayer.layer_id, "dir": sublayer.dir, "visibility": sublayer.visible } elif sublayer.type == "city": ldict["city"] = {"name": sublayer.name or "Current Weather", "id": sublayer.layer_id, "dir": sublayer.dir, "visibility": sublayer.visible } if options: # Used by Map._setup() options[self.dictname] = ldict else: # Used by as_json() and hence as_javascript() return ldict # ----------------------------------------------------------------------------- class LayerShapefile(Layer): """ Shapefile Layers from Catalogue """ tablename = "gis_layer_shapefile" dictname = "layers_shapefile" style = True # ------------------------------------------------------------------------- class SubLayer(Layer.SubLayer): def as_dict(self): url = "%s/%s/data.geojson" % \ (URL(c="gis", f="layer_shapefile"), self.id) if self.filter: url = "%s?layer_shapefile_%s.%s" % (url, self.id, self.filter) # Mandatory attributes output = {"id": self.layer_id, "type": "shapefile", "name": self.safe_name, "url": url, # Shapefile layers don't alter their contents, so don't refresh "refresh": 0, } # Attributes which are defaulted client-side if not set self.add_attributes_if_not_default( output, desc = (self.description, (None, "")), src = (self.source_name, (None, "")), src_url = (self.source_url, (None, "")), ) # We convert on-upload to have BBOX handling work properly #projection = self.projection #if projection.epsg != 4326: # output["projection"] = projection.epsg self.setup_folder_visibility_and_opacity(output) self.setup_clustering(output) if self.style: output["style"] = self.style else: self.marker.add_attributes_to_output(output) return output # ----------------------------------------------------------------------------- class LayerTheme(Layer): """ Theme Layers from Catalogue """ tablename = "gis_layer_theme" dictname = "layers_theme" style = True # ------------------------------------------------------------------------- class SubLayer(Layer.SubLayer): def as_dict(self): url = "%s.geojson?theme_data.layer_theme_id=%i&polygons=1&maxdepth=0" % \ (URL(c="gis", f="theme_data"), self.id) # Mandatory attributes output = {"id": self.layer_id, "type": "theme", "name": self.safe_name, "url": url, } # Attributes which are defaulted client-side if not set self.setup_folder_visibility_and_opacity(output) self.setup_clustering(output) style = self.style if style: output["style"] = style return output # ----------------------------------------------------------------------------- class LayerTMS(Layer): """ TMS Layers from Catalogue """ tablename = "gis_layer_tms" dictname = "layers_tms" style = False # ------------------------------------------------------------------------- class SubLayer(Layer.SubLayer): def as_dict(self): # Mandatory attributes output = {"id": self.layer_id, "type": "tms", "name": self.safe_name, "url": self.url, "layername": self.layername } # Attributes which are defaulted client-side if not set self.add_attributes_if_not_default( output, _base = (self._base, (False,)), url2 = (self.url2, (None,)), url3 = (self.url3, (None,)), format = (self.img_format, ("png", None)), zoomLevels = (self.zoom_levels, (19,)), attribution = (self.attribution, (None,)), ) self.setup_folder(output) return output # ----------------------------------------------------------------------------- class LayerWFS(Layer): """ WFS Layers from Catalogue """ tablename = "gis_layer_wfs" dictname = "layers_wfs" style = True # ------------------------------------------------------------------------- class SubLayer(Layer.SubLayer): def as_dict(self): # Mandatory attributes output = {"id": self.layer_id, "name": self.safe_name, "url": self.url, "title": self.title, "featureType": self.featureType, } # Attributes which are defaulted client-side if not set self.add_attributes_if_not_default( output, version = (self.version, ("1.1.0",)), featureNS = (self.featureNS, (None, "")), geometryName = (self.geometryName, ("the_geom",)), schema = (self.wfs_schema, (None, "")), username = (self.username, (None, "")), password = (self.password, (None, "")), projection = (self.projection.epsg, (4326,)), desc = (self.description, (None, "")), src = (self.source_name, (None, "")), src_url = (self.source_url, (None, "")), refresh = (self.refresh, (0,)), #editable ) self.setup_folder_visibility_and_opacity(output) self.setup_clustering(output) if self.style: output["style"] = self.style else: self.marker.add_attributes_to_output(output) return output # ----------------------------------------------------------------------------- class LayerWMS(Layer): """ WMS Layers from Catalogue """ tablename = "gis_layer_wms" dictname = "layers_wms" style = False # ------------------------------------------------------------------------- def __init__(self, all_layers, openlayers=6): super(LayerWMS, self).__init__(all_layers, openlayers) if self.sublayers: if current.response.s3.debug: self.scripts.append("gis/gxp/plugins/WMSGetFeatureInfo.js") else: self.scripts.append("gis/gxp/plugins/WMSGetFeatureInfo.min.js") # ------------------------------------------------------------------------- class SubLayer(Layer.SubLayer): def as_dict(self): if self.queryable: current.response.s3.gis.get_feature_info = True # Mandatory attributes output = {"id": self.layer_id, "name": self.safe_name, "url": self.url, "layers": self.layers, } # Attributes which are defaulted client-side if not set legend_url = self.legend_url if legend_url and not legend_url.startswith("http"): legend_url = "%s/%s%s" % \ (current.deployment_settings.get_base_public_url(), current.request.application, legend_url) attr = {"transparent": (self.transparent, (True,)), "version": (self.version, ("1.1.1",)), "format": (self.img_format, ("image/png",)), "map": (self.map, (None, "")), "username": (self.username, (None, "")), "password": (self.password, (None, "")), "buffer": (self.buffer, (0,)), "base": (self.base, (False,)), "_base": (self._base, (False,)), "style": (self.style, (None, "")), "bgcolor": (self.bgcolor, (None, "")), "tiled": (self.tiled, (False,)), "legendURL": (legend_url, (None, "")), "queryable": (self.queryable, (False,)), "desc": (self.description, (None, "")), } if current.deployment_settings.get_gis_layer_metadata(): # Use CMS to add info about sources attr["post_id"] = (self.post_id, (None, "")) else: # Link direct to sources attr.update(src = (self.source_name, (None, "")), src_url = (self.source_url, (None, "")), ) self.add_attributes_if_not_default(output, **attr) self.setup_folder_visibility_and_opacity(output) return output # ----------------------------------------------------------------------------- class LayerXYZ(Layer): """ XYZ Layers from Catalogue """ tablename = "gis_layer_xyz" dictname = "layers_xyz" style = False # ------------------------------------------------------------------------- class SubLayer(Layer.SubLayer): def as_dict(self): # Mandatory attributes output = {"id": self.layer_id, "name": self.safe_name, "url": self.url } # Attributes which are defaulted client-side if not set self.add_attributes_if_not_default( output, _base = (self._base, (False,)), url2 = (self.url2, (None,)), url3 = (self.url3, (None,)), format = (self.img_format, ("png", None)), zoomLevels = (self.zoom_levels, (19,)), attribution = (self.attribution, (None,)), ) self.setup_folder(output) return output # ============================================================================= class Marker(object): """ Represents a Map Marker @ToDo: Support Markers in Themes """ def __init__(self, marker=None, marker_id=None, layer_id=None, tablename=None): """ @param marker: Storage object with image/height/width (looked-up in bulk) @param marker_id: id of record in gis_marker @param layer_id: layer_id to lookup marker in gis_style (unused) @param tablename: used to identify whether to provide a default marker as fallback """ no_default = False if not marker: db = current.db s3db = current.s3db mtable = s3db.gis_marker config = None if marker_id: # Lookup the Marker details from it's ID marker = db(mtable.id == marker_id).select(mtable.image, mtable.height, mtable.width, limitby=(0, 1), cache=s3db.cache ).first() elif layer_id: # Check if we have a Marker defined for this Layer config = GIS.get_config() stable = s3db.gis_style query = (stable.layer_id == layer_id) & \ ((stable.config_id == config.id) | \ (stable.config_id == None)) & \ (stable.marker_id == mtable.id) & \ (stable.record_id == None) marker = db(query).select(mtable.image, mtable.height, mtable.width, limitby=(0, 1)).first() if not marker: # Check to see if we're a Polygon/LineString # (& hence shouldn't use a default marker) if tablename == "gis_layer_shapefile": table = db.gis_layer_shapefile query = (table.layer_id == layer_id) layer = db(query).select(table.gis_feature_type, limitby=(0, 1)).first() if layer and layer.gis_feature_type != 1: no_default = True #elif tablename == "gis_layer_feature": # table = db.gis_layer_feature # query = (table.layer_id == layer_id) # layer = db(query).select(table.polygons, # limitby=(0, 1)).first() # if layer and layer.polygons: # no_default = True if marker: self.image = marker["image"] self.height = marker["height"] self.width = marker["width"] elif no_default: self.image = None else: # Default Marker if not config: config = GIS.get_config() self.image = config.marker_image self.height = config.marker_height self.width = config.marker_width # ------------------------------------------------------------------------- def add_attributes_to_output(self, output): """ Called by Layer.as_dict() """ if self.image: output["marker"] = self.as_json_dict() # ------------------------------------------------------------------------- def as_dict(self): """ Called by gis.get_marker(), feature_resources & s3profile """ if self.image: marker = Storage(image = self.image, height = self.height, width = self.width, ) else: marker = None return marker # ------------------------------------------------------------------------- #def as_json(self): # """ # Called by nothing # """ # output = dict(i = self.image, # h = self.height, # w = self.width, # ) # return json.dumps(output, separators=SEPARATORS) # ------------------------------------------------------------------------- def as_json_dict(self): """ Called by Style.as_dict() and add_attributes_to_output() """ if self.image: marker = {"i": self.image, "h": self.height, "w": self.width, } else: marker = None return marker # ============================================================================= class Projection(object): """ Represents a Map Projection """ def __init__(self, projection_id=None): if projection_id: s3db = current.s3db table = s3db.gis_projection query = (table.id == projection_id) projection = current.db(query).select(table.epsg, limitby=(0, 1), cache=s3db.cache).first() else: # Default projection config = GIS.get_config() projection = Storage(epsg = config.epsg) self.epsg = projection.epsg # ============================================================================= class Style(object): """ Represents a Map Style """ def __init__(self, style_id=None, layer_id=None, aggregate=None): db = current.db s3db = current.s3db table = s3db.gis_style fields = [table.marker_id, table.opacity, table.popup_format, # @ToDo: if-required #table.url_format, table.cluster_distance, table.cluster_threshold, table.style, ] if style_id: query = (table.id == style_id) limitby = (0, 1) elif layer_id: config = GIS.get_config() # @ToDo: if record_id: query = (table.layer_id == layer_id) & \ (table.record_id == None) & \ ((table.config_id == config.id) | \ (table.config_id == None)) if aggregate is not None: query &= (table.aggregate == aggregate) fields.append(table.config_id) limitby = (0, 2) else: # Default style for this config # - falling back to Default config config = GIS.get_config() ctable = db.gis_config query = (table.config_id == ctable.id) & \ ((ctable.id == config.id) | \ (ctable.uuid == "SITE_DEFAULT")) & \ (table.layer_id == None) fields.append(ctable.uuid) limitby = (0, 2) styles = db(query).select(*fields, limitby=limitby) if len(styles) > 1: if layer_id: # Remove the general one _filter = lambda row: row.config_id == None else: # Remove the Site Default _filter = lambda row: row["gis_config.uuid"] == "SITE_DEFAULT" styles.exclude(_filter) if styles: style = styles.first() if not layer_id and "gis_style" in style: style = style["gis_style"] else: current.log.error("Style not found!") style = None if style: if style.marker_id: style.marker = Marker(marker_id = style.marker_id) if aggregate is True: # Use gis/location controller in all reports style.url_format = "%s/{id}.plain" % URL(c="gis", f="location") elif layer_id: # Build from controller/function ftable = s3db.gis_layer_feature layer = db(ftable.layer_id == layer_id).select(ftable.controller, ftable.function, limitby=(0, 1) ).first() if layer: style.url_format = "%s/{id}.plain" % \ URL(c=layer.controller, f=layer.function) self.style = style # ------------------------------------------------------------------------- def as_dict(self): """ """ # Not JSON-serializable #return self.style style = self.style output = Storage() if not style: return output if hasattr(style, "marker"): output.marker = style.marker.as_json_dict() opacity = style.opacity if opacity and opacity not in (1, 1.0): output.opacity = style.opacity if style.popup_format: output.popup_format = style.popup_format if style.url_format: output.url_format = style.url_format cluster_distance = style.cluster_distance if cluster_distance is not None and \ cluster_distance != CLUSTER_DISTANCE: output.cluster_distance = cluster_distance cluster_threshold = style.cluster_threshold if cluster_threshold is not None and \ cluster_threshold != CLUSTER_THRESHOLD: output.cluster_threshold = cluster_threshold if style.style: if isinstance(style.style, basestring): # Native JSON try: style.style = json.loads(style.style) except: current.log.error("Unable to decode Style: %s" % style.style) style.style = None output.style = style.style return output # ============================================================================= class S3Map(S3Method): """ Class to generate a Map linked to Search filters """ # ------------------------------------------------------------------------- def apply_method(self, r, **attr): """ Entry point to apply map method to S3Requests - produces a full page with S3FilterWidgets above a Map @param r: the S3Request instance @param attr: controller attributes for the request @return: output object to send to the view """ if r.http == "GET": representation = r.representation if representation == "html": return self.page(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD) # ------------------------------------------------------------------------- def page(self, r, **attr): """ Map page @param r: the S3Request instance @param attr: controller attributes for the request """ if r.representation in ("html", "iframe"): response = current.response resource = self.resource get_config = resource.get_config tablename = resource.tablename widget_id = "default_map" output = {} title = self.crud_string(tablename, "title_map") output["title"] = title # Filter widgets filter_widgets = get_config("filter_widgets", None) if filter_widgets and not self.hide_filter: advanced = False for widget in filter_widgets: if "hidden" in widget.opts and widget.opts.hidden: advanced = resource.get_config("map_advanced", True) break request = self.request from .s3filter import S3FilterForm # Apply filter defaults (before rendering the data!) S3FilterForm.apply_filter_defaults(r, resource) filter_formstyle = get_config("filter_formstyle", None) submit = resource.get_config("map_submit", True) filter_form = S3FilterForm(filter_widgets, formstyle=filter_formstyle, advanced=advanced, submit=submit, ajax=True, # URL to update the Filter Widget Status ajaxurl=r.url(method="filter", vars={}, representation="options"), _class="filter-form", _id="%s-filter-form" % widget_id, ) get_vars = request.get_vars filter_form = filter_form.html(resource, get_vars=get_vars, target=widget_id) else: # Render as empty string to avoid the exception in the view filter_form = "" output["form"] = filter_form # Map output["map"] = self.widget(r, widget_id=widget_id, callback='''S3.search.s3map()''', **attr) # View response.view = self._view(r, "map.html") return output else: r.error(415, current.ERROR.BAD_FORMAT) # ------------------------------------------------------------------------- def widget(self, r, method="map", widget_id=None, visible=True, callback=None, **attr): """ Render a Map widget suitable for use in an S3Filter-based page such as S3Summary @param r: the S3Request @param method: the widget method @param widget_id: the widget ID @param callback: None by default in case DIV is hidden @param visible: whether the widget is initially visible @param attr: controller attributes """ if not widget_id: widget_id = "default_map" gis = current.gis tablename = self.tablename ftable = current.s3db.gis_layer_feature def lookup_layer(prefix, name): query = (ftable.controller == prefix) & \ (ftable.function == name) layers = current.db(query).select(ftable.layer_id, ftable.style_default, ) if len(layers) > 1: layers.exclude(lambda row: row.style_default == False) if len(layers) == 1: layer_id = layers.first().layer_id else: # We can't distinguish layer_id = None return layer_id prefix = r.controller name = r.function layer_id = lookup_layer(prefix, name) if not layer_id: # Try the tablename prefix, name = tablename.split("_", 1) layer_id = lookup_layer(prefix, name) url = URL(extension="geojson", args=None, vars=r.get_vars) # @ToDo: Support maps with multiple layers (Dashboards) #_id = "search_results_%s" % widget_id _id = "search_results" feature_resources = [{"name" : current.T("Search Results"), "id" : _id, "layer_id" : layer_id, "tablename" : tablename, "url" : url, # We activate in callback after ensuring URL is updated for current filter status "active" : False, }] settings = current.deployment_settings catalogue_layers = settings.get_gis_widget_catalogue_layers() legend = settings.get_gis_legend() search = settings.get_gis_search_geonames() toolbar = settings.get_gis_toolbar() wms_browser = settings.get_gis_widget_wms_browser() if wms_browser: config = gis.get_config() if config.wmsbrowser_url: wms_browser = wms_browser = {"name" : config.wmsbrowser_name, "url" : config.wmsbrowser_url, } else: wms_browser = None map = gis.show_map(id = widget_id, feature_resources = feature_resources, catalogue_layers = catalogue_layers, collapsed = True, legend = legend, toolbar = toolbar, save = False, search = search, wms_browser = wms_browser, callback = callback, ) return map # ============================================================================= class S3ExportPOI(S3Method): """ Export point-of-interest resources for a location """ # ------------------------------------------------------------------------- def apply_method(self, r, **attr): """ Apply method. @param r: the S3Request @param attr: controller options for this request """ output = {} if r.http == "GET": output = self.export(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD) return output # ------------------------------------------------------------------------- def export(self, r, **attr): """ Export POI resources. URL options: - "resources" list of tablenames to export records from - "msince" datetime in ISO format, "auto" to use the feed's last update - "update_feed" 0 to skip the update of the feed's last update datetime, useful for trial exports Supported formats: .xml S3XML .osm OSM XML Format .kml Google KML (other formats can be requested, but may give unexpected results) @param r: the S3Request @param attr: controller options for this request """ # Determine request Lx current_lx = r.record if not current_lx: # or not current_lx.level: # Must have a location r.error(400, current.ERROR.BAD_REQUEST) else: self.lx = current_lx.id tables = [] # Parse the ?resources= parameter if "resources" in r.get_vars: resources = r.get_vars["resources"] else: # Fallback to deployment_setting resources = current.deployment_settings.get_gis_poi_export_resources() if not isinstance(resources, list): resources = [resources] [tables.extend(t.split(",")) for t in resources] # Parse the ?update_feed= parameter update_feed = True if "update_feed" in r.get_vars: _update_feed = r.get_vars["update_feed"] if _update_feed == "0": update_feed = False # Parse the ?msince= parameter msince = None if "msince" in r.get_vars: msince = r.get_vars["msince"] if msince.lower() == "auto": msince = "auto" else: msince = s3_parse_datetime(msince) # Export a combined tree tree = self.export_combined_tree(tables, msince=msince, update_feed=update_feed) xml = current.xml # Set response headers response = current.response s3 = response.s3 headers = response.headers representation = r.representation if r.representation in s3.json_formats: as_json = True default = "application/json" else: as_json = False default = "text/xml" headers["Content-Type"] = s3.content_type.get(representation, default) # Find XSLT stylesheet and transform stylesheet = r.stylesheet() if tree and stylesheet is not None: args = Storage(domain=xml.domain, base_url=s3.base_url, utcnow=s3_format_datetime()) tree = xml.transform(tree, stylesheet, **args) if tree: if as_json: output = xml.tree2json(tree, pretty_print=True) else: output = xml.tostring(tree, pretty_print=True) return output # ------------------------------------------------------------------------- def export_combined_tree(self, tables, msince=None, update_feed=True): """ Export a combined tree of all records in tables, which are in Lx, and have been updated since msince. @param tables: list of table names @param msince: minimum modified_on datetime, "auto" for automatic from feed data, None to turn it off @param update_feed: update the last_update datetime in the feed """ db = current.db s3db = current.s3db ftable = s3db.gis_poi_feed lx = self.lx elements = [] for tablename in tables: # Define the resource try: resource = s3db.resource(tablename, components=[]) except AttributeError: # Table not defined (module deactivated?) continue # Check if "location_id" not in resource.fields: # Hardly a POI resource without location_id continue # Add Lx filter self._add_lx_filter(resource, lx) # Get the feed data query = (ftable.tablename == tablename) & \ (ftable.location_id == lx) feed = db(query).select(limitby=(0, 1)).first() if msince == "auto": if feed is None: _msince = None else: _msince = feed.last_update else: _msince = msince # Export the tree and append its element to the element list tree = resource.export_tree(msince=_msince, references=["location_id"]) # Update the feed data if update_feed: muntil = resource.muntil if feed is None: ftable.insert(location_id = lx, tablename = tablename, last_update = muntil) else: feed.update_record(last_update = muntil) elements.extend([c for c in tree.getroot()]) # Combine all elements in one tree and return it tree = current.xml.tree(elements, results=len(elements)) return tree # ------------------------------------------------------------------------- @staticmethod def _add_lx_filter(resource, lx): """ Add a Lx filter for the current location to this resource. @param resource: the resource """ from .s3query import FS query = (FS("location_id$path").contains("/%s/" % lx)) | \ (FS("location_id$path").like("%s/%%" % lx)) resource.add_filter(query) # ============================================================================= class S3ImportPOI(S3Method): """ Import point-of-interest resources for a location """ # ------------------------------------------------------------------------- @staticmethod def apply_method(r, **attr): """ Apply method. @param r: the S3Request @param attr: controller options for this request """ if r.representation == "html": T = current.T s3db = current.s3db request = current.request response = current.response settings = current.deployment_settings s3 = current.response.s3 title = T("Import from OpenStreetMap") resources_list = settings.get_gis_poi_export_resources() uploadpath = os.path.join(request.folder,"uploads/") from .s3utils import s3_yes_no_represent fields = [Field("text1", # Dummy Field to add text inside the Form label = "", default = T("Can read PoIs either from an OpenStreetMap file (.osm) or mirror."), writable = False), Field("file", "upload", length = current.MAX_FILENAME_LENGTH, uploadfolder = uploadpath, label = T("File")), Field("text2", # Dummy Field to add text inside the Form label = "", default = "Or", writable = False), Field("host", default = "localhost", label = T("Host")), Field("database", default = "osm", label = T("Database")), Field("user", default = "osm", label = T("User")), Field("password", "string", default = "planet", label = T("Password")), Field("ignore_errors", "boolean", label = T("Ignore Errors?"), represent = s3_yes_no_represent), Field("resources", label = T("Select resources to import"), requires = IS_IN_SET(resources_list, multiple=True), default = resources_list, widget = SQLFORM.widgets.checkboxes.widget) ] if not r.id: from .s3validators import IS_LOCATION from .s3widgets import S3LocationAutocompleteWidget # dummy field field = s3db.org_office.location_id field.requires = IS_EMPTY_OR(IS_LOCATION()) field.widget = S3LocationAutocompleteWidget() fields.insert(3, field) from .s3utils import s3_mark_required labels, required = s3_mark_required(fields, ["file", "location_id"]) s3.has_required = True form = SQLFORM.factory(*fields, formstyle = settings.get_ui_formstyle(), submit_button = T("Import"), labels = labels, separator = "", table_name = "import_poi" # Dummy table name ) response.view = "create.html" output = {"title": title, "form": form, } if form.accepts(request.vars, current.session): form_vars = form.vars if form_vars.file != "": File = open(uploadpath + form_vars.file, "r") else: # Create .poly file if r.record: record = r.record elif not form_vars.location_id: form.errors["location_id"] = T("Location is Required!") return output else: gtable = s3db.gis_location record = current.db(gtable.id == form_vars.location_id).select(gtable.name, gtable.wkt, limitby=(0, 1) ).first() if record.wkt is None: form.errors["location_id"] = T("Location needs to have WKT!") return output error = GIS.create_poly(record) if error: current.session.error = error redirect(URL(args=r.id)) # Use Osmosis to extract an .osm file using this .poly name = record.name if os.path.exists(os.path.join(os.getcwd(), "temp")): # use web2py/temp TEMP = os.path.join(os.getcwd(), "temp") else: import tempfile TEMP = tempfile.gettempdir() filename = os.path.join(TEMP, "%s.osm" % name) cmd = ["/home/osm/osmosis/bin/osmosis", # @ToDo: deployment_setting "--read-pgsql", "host=%s" % form_vars.host, "database=%s" % form_vars.database, "user=%s" % form_vars.user, "password=%s" % form_vars.password, "--dataset-dump", "--bounding-polygon", "file=%s" % os.path.join(TEMP, "%s.poly" % name), "--write-xml", "file=%s" % filename, ] import subprocess try: #result = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True) subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as e: current.session.error = T("OSM file generation failed: %s") % e.output redirect(URL(args=r.id)) except AttributeError: # Python < 2.7 error = subprocess.call(cmd, shell=True) if error: current.log.debug(cmd) current.session.error = T("OSM file generation failed!") redirect(URL(args=r.id)) try: File = open(filename, "r") except: current.session.error = T("Cannot open created OSM file!") redirect(URL(args=r.id)) stylesheet = os.path.join(request.folder, "static", "formats", "osm", "import.xsl") ignore_errors = form_vars.get("ignore_errors", None) xml = current.xml tree = xml.parse(File) define_resource = s3db.resource response.error = "" import_count = 0 import_res = list(set(form_vars["resources"]) & \ set(resources_list)) for tablename in import_res: try: s3db[tablename] except: # Module disabled continue resource = define_resource(tablename) s3xml = xml.transform(tree, stylesheet_path=stylesheet, name=resource.name) try: resource.import_xml(s3xml, ignore_errors=ignore_errors) import_count += resource.import_count except: response.error += str(sys.exc_info()[1]) if import_count: response.confirmation = "%s %s" % \ (import_count, T("PoIs successfully imported.")) else: response.information = T("No PoIs available.") return output else: raise HTTP(405, current.ERROR.BAD_METHOD) # END =========================================================================
from torch import nn from torch.nn import Module class LatentTransformer(Module): def __init__(self, get_latent_attn, get_latent_ff, num_latent_blocks_per_layer, weight_tie_layers): super().__init__() self.latent_blocks = nn.ModuleList([]) self.num_latent_blocks_per_layer = num_latent_blocks_per_layer for latent_block_index in range(num_latent_blocks_per_layer): should_cache = latent_block_index > 0 and weight_tie_layers cache_args = {'_cache': should_cache} self.latent_blocks.append(nn.ModuleList([ get_latent_attn(**cache_args, name=f"latent_attn_{latent_block_index}"), get_latent_ff(**cache_args, name=f"latent_ff_{latent_block_index}")])) def forward(self, x): for latent_attn, latent_ff in self.latent_blocks: x = latent_attn(x) + x x = latent_ff(x) + x return x def build_perceiver_layers( layers, depth, get_cross_attn, get_cross_ff, get_latent_attn, get_latent_ff, weight_tie_layers, num_latent_blocks_per_layer=1, ): for i in range(depth): should_cache = i > 0 and weight_tie_layers cache_args = {'_cache': should_cache} layers.append(nn.ModuleList([ get_cross_attn(**cache_args, name="cross_attn"), get_cross_ff(**cache_args, name="cross_ff"), LatentTransformer(get_latent_attn, get_latent_ff, num_latent_blocks_per_layer=num_latent_blocks_per_layer, weight_tie_layers=weight_tie_layers)]))
let objectValues = require('lodash').values; /** * Generic tap function. * * @param {mixed} val * @param {Function} callback */ global.tap = function(val, callback) { callback(val); return val; }; /** * Add tap to arrays. * * @param {mixed} val * @param {Function} callback */ Array.prototype.tap = function(callback) { callback(this); return this; }; /** * Flatten the given array. * * @param {Array} arr */ global.flatten = function(arr) { return [].concat.apply([], objectValues(arr)); }; /** * Sort object by keys * * @param {Object} obj */ global.sortObjectKeys = obj => { return Object.keys(obj) .sort() .reduce((r, k) => ((r[k] = obj[k]), r), {}); };
'use strict'; const assert = require('assert'); const path = require('path'); const mock = require('egg-mock'); const utils = require('../lib/utils'); const BaseView = require('../index'); const framework = path.join(__dirname, '../../beidou-core/'); describe('test/view.test.js', () => { it('utils', () => { const { concatUrl } = utils; assert( concatUrl('http://beidou.net', 'docs', 'quickstart') === 'http://beidou.net/docs/quickstart' ); assert( concatUrl('/root/', '/docs/', '/quickstart/') === '/root/docs/quickstart/' ); }); describe('Base view', () => { let app; before(() => { app = mock.app({ baseDir: './base-app', framework, }); }); after(() => { app.close(); }); it('class exist', () => { assert(BaseView); }); const getView = (ctx) => { const view = new BaseView(ctx, { beautify: true, cache: false, doctype: '<!DOCTYPE html>', middlewares: [ 'cache', 'initialprops', 'redux', 'partial', 'mock', 'doctype', 'beautify', ], }); return view; }; it('render', async () => { const ctx = app.mockContext(); const view = getView(ctx); assert(view.ctx === ctx); try { view.renderElement(); } catch (e) { assert(e instanceof Error); } BaseView.prototype.renderElement = function () { return 'test string'; }; const indexPath = path.join( __dirname, 'fixtures/base-app/client/index.jsx' ); const result = await view.render(indexPath, { ctx }); // See fixture/base-app/app/view-middlewares/mock.js assert(result === 'mock data'); }); it('asset helper', () => { const ctx = app.mockContext(); const asset = ctx.helper[Symbol.for('beidou#asset')].bind(ctx.helper); let url = asset('index.js', { assetPath: 'build', }); assert(url === 'build/index.js'); url = asset('index.js', { host: 'http://127.0.0.1', assetPath: 'build', }); assert(url === 'http://127.0.0.1/build/index.js'); url = asset('index.js', { host: '127.0.0.1', assetPath: 'build', }); assert(url === 'http://127.0.0.1/build/index.js'); }); }); });
$(document).foundation() $('#validate').on('input propertychange paste keypress',function() { var x = document.getElementById("validate").value.toLowerCase(); var y = false; for (i = 0; i < database.length; i++) { if (x.includes(database[i])) { $(".result").text("this is a genuine email"); $(".result").css("color","lightgreen"); y = true; } } if (y == false){ $(".result").text("this may not be a genuine email"); $(".result").css("color","red"); } if (x == null || x ==""){ $(".result").text("Paste your suspected scam email here"); $(".result").css("color","white"); } });
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-7ed88828"],{a2d9:function(t,s,i){"use strict";i.r(s);var n=function(){var t=this,s=t.$createElement,i=t._self._c||s;return i("div",{staticClass:"card"},[t.list.length?i("div",{staticClass:"list"},t._l(t.list,(function(s,n){return i("div",{key:n,staticClass:"item"},[i("div",{staticClass:"title"},[t._v("店铺:"+t._s(s.store_name))]),i("div",{staticClass:"bonus",on:{click:function(i){t.$router.push({path:"search",query:{id:s.id}})}}},[t._v("提成记录")])])}))):i("div",{staticClass:"empty"},[t._v("\n 暂无任职店铺\n ")])])},e=[],c={data:function(){return{list:[]}},computed:{token:function(){return this.$store.state.wx.token}},watch:{token:function(){this.token&&this.getList()}},created:function(){this.token&&this.getList()},methods:{getList:function(){var t=this;this.$api.wx.getStaffList().then((function(s){t.list=s.data.map((function(t){return t.staff}))}))}}},a=c,o=(i("dcec"),i("2877")),u=Object(o["a"])(a,n,e,!1,null,"7cf09199",null);u.options.__file="store.vue";s["default"]=u.exports},c6c6:function(t,s,i){},dcec:function(t,s,i){"use strict";var n=i("c6c6"),e=i.n(n);e.a}}]);
"use strict"; exports.__esModule = true; exports.default = void 0; var _vue = require("vue"); var _utils = require("../utils"); var _Swipe = require("../swipe/Swipe"); var _use = require("@vant/use"); var _useExpose = require("../composables/use-expose"); // Utils // Composables var [name, bem] = (0, _utils.createNamespace)('swipe-item'); var _default = (0, _vue.defineComponent)({ name, setup(props, { slots }) { var rendered; var state = (0, _vue.reactive)({ offset: 0, inited: false, mounted: false }); var { parent, index } = (0, _use.useParent)(_Swipe.SWIPE_KEY); if (!parent) { if (process.env.NODE_ENV !== 'production') { console.error('[Vant] <SwipeItem> must be a child component of <Swipe>.'); } return; } var style = (0, _vue.computed)(() => { var style = {}; var { vertical } = parent.props; if (parent.size.value) { style[vertical ? 'height' : 'width'] = parent.size.value + "px"; } if (state.offset) { style.transform = "translate" + (vertical ? 'Y' : 'X') + "(" + state.offset + "px)"; } return style; }); var shouldRender = (0, _vue.computed)(() => { var { loop, lazyRender } = parent.props; if (!lazyRender || rendered) { return true; } // wait for all item to mount, so we can get the exact count if (!state.mounted) { return false; } var active = parent.activeIndicator.value; var maxActive = parent.count.value - 1; var prevActive = active === 0 && loop ? maxActive : active - 1; var nextActive = active === maxActive && loop ? 0 : active + 1; rendered = index.value === active || index.value === prevActive || index.value === nextActive; return rendered; }); var setOffset = offset => { state.offset = offset; }; (0, _vue.onMounted)(() => { (0, _vue.nextTick)(() => { state.mounted = true; }); }); (0, _useExpose.useExpose)({ setOffset }); return () => (0, _vue.createVNode)("div", { "class": bem(), "style": style.value }, [shouldRender.value ? slots.default == null ? void 0 : slots.default() : null]); } }); exports.default = _default;
const path = require("path"); // const HDWalletProvider = require('truffle-hdwallet-provider'); // const infuraUrl = 'https://rinkeby.infura.io/v3/0c7bd415b86d4c8ea9fd81cfc5468d87'; // const fs = require('fs'); // const mnemonic = fs.readFileSync(".secret").toString().trim(); module.exports = { /** * Networks define how you connect to your ethereum client and let you set the * defaults web3 uses to send transactions. If you don't specify one truffle * will spin up a development blockchain for you on port 9545 when you * run `develop` or `test`. You can ask a truffle command to use a specific * network from the command line, e.g * * $ truffle test --network <network-name> */ contracts_build_directory: path.join(__dirname, "client/src/contracts"), networks: { // Useful for testing. The `development` name is special - truffle uses it by default // if it's defined here and no other network is specified at the command line. // You should run a client (like ganache-cli, geth or parity) in a separate terminal // tab if you use this network and you must also set the `host`, `port` and `network_id` // options below to some value. // development: { host: "127.0.0.1", // Localhost (default: none) port: 8545, // Standard Ethereum port (default: none) network_id: "*", // Any network (default: none) }, // rinkeby:{ // provider: () => new HDWalletProvider(mnemonic, infuraUrl), // network_id: 4, // gas: 5500000, // } // Another network with more advanced options... // advanced: { // port: 8777, // Custom port // network_id: 1342, // Custom network // gas: 8500000, // Gas sent with each transaction (default: ~6700000) // gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei) // from: <address>, // Account to send txs from (default: accounts[0]) // websockets: true // Enable EventEmitter interface for web3 (default: false) // }, // Useful for deploying to a public network. // NB: It's important to wrap the provider as a function. // ropsten: { // provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`), // network_id: 3, // Ropsten's id // gas: 5500000, // Ropsten has a lower block limit than mainnet // confirmations: 2, // # of confs to wait between deployments. (default: 0) // timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50) // skipDryRun: true // Skip dry run before migrations? (default: false for public nets ) // }, // Useful for private networks // private: { // provider: () => new HDWalletProvider(mnemonic, `https://network.io`), // network_id: 2111, // This network is yours, in the cloud. // production: true // Treats this network as if it was a public net. (default: false) // } }, // Set default mocha options here, use special reporters etc. mocha: { // timeout: 100000 }, // Configure your compilers compilers: { solc: { // version: "0.5.1", // Fetch exact version from solc-bin (default: truffle's version) // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) // settings: { // See the solidity docs for advice about optimization and evmVersion optimizer: { enabled: false, runs: 200 }, // evmVersion: "byzantium" // } } } }
getAllProducts();
import thunk from 'redux-thunk'; import { createLogger } from 'redux-logger'; import { createStore, applyMiddleware, compose } from 'redux'; import rootReducer from './rootReducer'; /** The Store is the object that brings actions (that represent the facts about * “what happened”) and the reducers (that update the state according to those * actions) together. The store has the following responsibilities: * - Holds application state; * - Allows access to state via getState(); * - Allows state to be updated via dispatch(action); * - Registers listeners via subscribe(listener); * - Handles unregistering of listeners via the function returned by subscribe(listener). */ // neat middleware that logs actions const loggerMiddleware = createLogger(); /** Without middleware, Redux store only supports synchronous data flow. This is * what you get by default with createStore(). You may enhance createStore() with * applyMiddleware(). It is not required, but it lets you express asynchronous * actions in a convenient way. Asynchronous middleware like redux-thunk or * redux-promise wraps the store's dispatch() method and allows you to dispatch * something other than actions, for example, functions or Promises. Any * middleware you use can then interpret anything you dispatch, and in turn, can * pass actions to the next middleware in the chain. For example, a Promise * middleware can intercept Promises and dispatch a pair of begin/end actions * asynchronously in response to each Promise. When the last middleware in the * chain dispatches an action, it has to be a plain object. This is when the * synchronous Redux data flow takes place. */ /* eslint-disable no-underscore-dangle */ const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore( rootReducer, /* preloadedState, */ composeEnhancers(applyMiddleware(thunk, loggerMiddleware)), ); /* eslint-enable */ export default store;
import React from "react" import Lunch from "../../forms/lunchAndLearn" export default function LunchAndLearn({ data }) { const { title, description } = data.primary return ( <div className="contact-wrapper contact-wrap"> <div className="container "> <div className="contact-information "> <div className="title" dangerouslySetInnerHTML={{ __html: title.html }} /> <div className="contact-markdown" dangerouslySetInnerHTML={{ __html: description.html }} /> </div> <Lunch /> </div> </div> ) }
"""Init scheduling-app.""" __version__ = "0.1.0"
CKEDITOR.plugins.setLang("colorbutton","pt-br",{auto:"Automático",bgColorTitle:"Cor do Plano de Fundo",colors:{"000":"Preto",8E5:"Foquete","8B4513":"Marrom 1","2F4F4F":"Cinza 1","008080":"Cerceta","000080":"Azul Marinho","4B0082":"Índigo",696969:"Cinza 2",B22222:"Tijolo de Fogo",A52A2A:"Marrom 2",DAA520:"Vara Dourada","006400":"Verde Escuro","40E0D0":"Turquesa","0000CD":"Azul Médio",800080:"Roxo",808080:"Cinza 3",F00:"Vermelho",FF8C00:"Laranja Escuro",FFD700:"Dourado","008000":"Verde","0FF":"Ciano", "00F":"Azul",EE82EE:"Violeta",A9A9A9:"Cinza Escuro",FFA07A:"Salmão Claro",FFA500:"Laranja",FFFF00:"Amarelo","00FF00":"Lima",AFEEEE:"Turquesa Pálido",ADD8E6:"Azul Claro",DDA0DD:"Ameixa",D3D3D3:"Cinza Claro",FFF0F5:"Lavanda 1",FAEBD7:"Branco Antiguidade",FFFFE0:"Amarelo Claro",F0FFF0:"Orvalho",F0FFFF:"Azure",F0F8FF:"Azul Alice",E6E6FA:"Lavanda 2",FFF:"Branco","1ABC9C":"Ciano Forte","2ECC71":"Esmeralda","3498DB":"Azul Brilhante","9B59B6":"Ametista","4E5F70":"Azul acinzentado",F1C40F:"Amarelo Vívido", "16A085":"Ciano Escuro","27AE60":"Esmeralda Escura","2980B9":"Azul Forte","8E44AD":"Violeta Escura","2C3E50":"Azul Dessaturado",F39C12:"Laranja",E67E22:"Laranja Cenoura",E74C3C:"Vermelho Pálido",ECF0F1:"Prata Brilhante","95A5A6":"Ciano Acinzentado Claro ",DDD:"Cinza Claro",D35400:"Abóbora",C0392B:"Vermelho Forte",BDC3C7:"Prata","7F8C8D":"Ciano Acinzentado",999:"Cinza Escuro"},more:"Mais Cores...",panelTitle:"Cores",textColorTitle:"Cor do Texto"});
""" Copyright (c) 2019 Muhammad Shehriyar Qureshi 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. """ class UpdateQuery: def execute(connection, query_info): # execute user_query connection.execute(query_info.query) # update temporal row connection.execute(query_info.temporal_query) # insert new row in temporal table connection.execute(query_info.temporal_query_insert)
import sys, os import torch import torch.nn as nn import torch.nn.functional as F import torchvision import omnifig as fig import numpy as np # %matplotlib tk from matplotlib import cm import omnilearn as learn from omnilearn import util @fig.Component('point-enc') class PointEncoder(learn.Encodable, learn.Visualizable, learn.FunctionBase): def __init__(self, A): in_shape = A.pull('in_shape', '<>din') latent_dim = A.pull('latent_dim', '<>dout') A.push('in_shape', in_shape, overwrite=False, silent=True) transform = A.pull('transform') # converts the image into a point cloud pout, N = transform.dout A.push('pin', pout) A.push('n_points', N) pointnet = A.pull('pointnet') super().__init__(in_shape, latent_dim) self.transform = transform self.pointnet = pointnet def visualize(self, info, logger): if not self.training or self._viz_counter % 2 == 0: super().visualize(info, logger) else: self._viz_counter += 1 def _visualize(self, out, logger): # TODO for m in self.pointnet.tfms: if isinstance(m, learn.Visualizable): m._visualize(out, logger) def forward(self, x): # images p = self.transform(x) q = self.pointnet(p) return q @fig.AutoComponent('patch-points') class Patch_Points(learn.FunctionBase): ''' Converts an image into a set of unordered points where each point is a concat of the pixels of a unique patch of the image. ''' def __init__(self, in_shape, include_coords=False, patch_size=4, stride=2, dilation=1, padding=0): C, H, W = in_shape try: len(patch_size) except TypeError: patch_size = (patch_size, patch_size) try: len(stride) except TypeError: stride = (stride, stride) try: len(dilation) except TypeError: dilation = (dilation, dilation) try: len(padding) except TypeError: padding = (padding, padding) pout = C * patch_size[0] * patch_size[1] Nh = (H + 2 * padding[0] - dilation[0] * (patch_size[0] - 1) - 1) // stride[0] + 1 Nw = (W + 2 * padding[1] - dilation[1] * (patch_size[1] - 1) - 1) // stride[1] + 1 N = Nh * Nw if include_coords: pout += 2 super().__init__(in_shape, (pout, N)) self.pout = pout self.transform = nn.Unfold(kernel_size=patch_size, stride=stride, dilation=dilation, padding=padding) if include_coords: self.register_buffer('coords', torch.from_numpy(np.mgrid[:1:1j * Nh, :1:1j * Nw]).view(2, -1).float()) else: self.coords = None def forward(self, x): p = self.transform(x) if self.coords is not None: B = p.size(0) p = torch.cat([p, self.coords.expand(B, *self.coords.size())], 1) return p @fig.AutoComponent('1dconv-net') def make_pointnet(pin, pout, hidden=None, nonlin='prelu', output_nonlin=None): if hidden is None: hidden = [] nonlins = [nonlin] * len(hidden) + [output_nonlin] hidden = [pin] + list(hidden) + [pout] layers = [] for in_dim, out_dim, nonlin in zip(hidden, hidden[1:], nonlins): layers.append(nn.Conv1d(in_dim, out_dim, kernel_size=1)) if nonlin is not None: layers.append(util.get_nonlinearity(nonlin)) net = nn.Sequential(*layers) net.pin = pin net.pout = pout return net @fig.Component('point-net') class PointNet(learn.Model): def __init__(self, A): pin = A.pull('pin') # should be the number of channels of the points dout = A.pull('latent_dim', '<>dout') n_points = A.pull('n_points', None) create_module = A.pull('modules') super().__init__(din=pin, dout=dout) modules = [] nxt = create_module.view() # assert nxt is not None, 'no point-net modules provided' nxt.push('pin', pin, silent=True) nxt.push('N', n_points, silent=True) for module in create_module: if hasattr(module, 'nout'): n_points = module.nout modules.append(module) try: nxt = create_module.view() except StopIteration: break else: nxt.push('pin', module.pout, silent=True) nxt.push('pin1', module.pout1, silent=True) nxt.push('pin2', module.pout2, silent=True) nxt.push('N', n_points, silent=True) if nxt.pull('_type', None, silent=True) == 'point-dual': if 'left' in nxt: nxt.push('left.pin', module.pout1, silent=True) if 'right' in nxt: nxt.push('right.pin', module.pout2, silent=True) pout = module.pout assert pout is not None, f'last module must have a single output: {module}' self.tfms = nn.Sequential(*modules) pool_type = A.pull('pool._type', None, silent=True) if pool_type is not None: A.push('pool.din', (pout, n_points), silent=True) # A.pool.pin = pout # A.pool.N = n_points self.pool = A.pull('pool', None) if self.pool is not None: pout = self.pool.dout final_type = A.pull('final._type', None, silent=True) if final_type is not None: A.push('final.din', pout, silent=True) A.push('final.dout', dout, silent=True) final = A.pull('final', None) if final is not None: # make sure final will produce the right output assert final.din == pout and final.dout == dout, f'invalid {final.din} v {pout} and {final.dout} v {dout}' elif pout != dout: # by default fix output to correctly sized output using a dense layer final = nn.Linear(pout, dout) self.final = final def forward(self, pts): pts = self.tfms(pts) B, _, *rest = pts.size() if len(rest): if rest[0] > 1: pts = self.pool(pts) pts = pts.view(B, -1) out = pts if self.final is not None: out = self.final(out) return out # Abstract modules class PointNetModule(learn.FunctionBase): def __init__(self, pin=None, pout=None, pin1=None, pout1=None, pin2=None, pout2=None): super().__init__(pin, pout) self.pin = pin self.pout = pout self.pin1 = pin1 self.pout1 = pout1 self.pin2 = pin2 self.pout2 = pout2 class PointSplit(PointNetModule): def __init__(self, pin, pout1, pout2): super().__init__(pin=pin, pout1=pout1, pout2=pout2) class PointTransform(PointNetModule): def __init__(self, pin, pout): super().__init__(pin=pin, pout=pout) class PointParallel(PointNetModule): def __init__(self, pin1, pin2, pout1, pout2): super().__init__(pin1=pin1, pin2=pin2, pout1=pout1, pout2=pout2) def __call__(self, pts): # so the point net can connect modules by nn.Sequential return super().__call__(*pts) class PointJoin(PointNetModule): def __init__(self, pin1, pin2, pout): super().__init__(pin1=pin1, pin2=pin2, pout=pout) def __call__(self, pts): # so the point net can connect modules by nn.Sequential return super().__call__(*pts) # Point-net operations @fig.AutoComponent('point-split') class PointSplitter(PointSplit): def __init__(self, pin, split): super().__init__(pin=pin, pout1=split, pout2=pin - split) assert pin > split, f'not enough dimensions to split: {pin} vs {split}' self.split = split def extra_repr(self): return f'split={self.split}' def forward(self, p): return p[:, :self.split], p[:, self.split:] @fig.AutoComponent('point-buffer') class PointBuffer(PointSplit): def __init__(self, pin, channels, N): super().__init__(pin=pin, pout1=channels, pout2=pin) self.buffer = nn.Parameter(torch.randn(channels, N), requires_grad=True) def extra_repr(self): return 'chn={}, N={}'.format(*self.buffer.size()) def forward(self, p): B = p.size(0) p1 = self.buffer.expand(B, *self.buffer.shape) p2 = p return p1, p2 @fig.AutoComponent('point-transform-net') class PointTransformNet(PointTransform): def __init__(self, net): super().__init__(net.pin, net.pout) self.net = net def forward(self, p): return self.net(p) @fig.AutoComponent('point-self') class PointSelfTransform(PointTransformNet): def __init__(self, pin, pout, hidden=None, nonlin='prelu', output_nonlin=None): super().__init__(make_pointnet(pin, pout, hidden=hidden, nonlin=nonlin, output_nonlin=output_nonlin)) @fig.AutoComponent('point-dual') class PointDualTransform(PointParallel): def __init__(self, left=None, right=None, pin1=None, pin2=None): assert left is not None or pin1 is not None assert right is not None or pin2 is not None if left is not None: pin1 = left.pin pout1 = left.pout else: pout1 = pin1 if right is not None: pin2 = right.pin pout2 = right.pout else: pout2 = pin2 super().__init__(pin1, pin2, pout1, pout2) self.left = left self.right = right def forward(self, p1, p2): if self.left is not None: p1 = self.left(p1) if self.right is not None: p2 = self.right(p2) return p1, p2 @fig.AutoComponent('point-swap') class PointSwap(PointParallel): def __init__(self, pin1, pin2): super().__init__(pin1=pin1, pin2=pin2, pout1=pin2, pout2=pin1) def forward(self, p1, p2): return p2, p1 @fig.AutoComponent('point-cat') class PointJoiner(PointJoin): def __init__(self, pin1, pin2): super().__init__(pin1=pin1, pin2=pin2, pout=pin1 + pin2) def forward(self, p1, p2): # TODO make sure shapes work out return torch.cat([p1, p2], dim=1) @fig.AutoComponent('point-wsum') class PointWeightedSum(learn.Cacheable, learn.Visualizable, PointJoin): def __init__(self, pin1, pin2, heads=1, keys=1, norm_heads=False, sum_heads=True, gumbel=None, gumbel_min=0.1, gumbel_delta=2e-4): super().__init__(pin1=pin1, pin2=pin2, pout=pin1) self.nout = heads if sum_heads else heads * keys self.weights = nn.Conv1d(pin2, heads * keys, kernel_size=1) self.norm_heads = norm_heads self.sum_heads = sum_heads self.keys = keys self.heads = heads self.N_out = self.keys * self.heads if gumbel is not None and gumbel <= 0: gumbel = None self.gumbel = gumbel self.gumbel_delta = gumbel_delta self.gumbel_start = gumbel self.gumbel_min = gumbel_min self.register_cache('_w') self.cmap = cm.get_cmap('seismic') def compute_weights(self, p): # optionally use gumbel softmax return self.weights(p) def extra_repr(self): return f'heads={self.heads}, keys={self.keys}' def _visualize(self, out, logger): if self._w is not None: w = self._w brightness = 100 * 10 ** (self.gumbel is None) B, G, K, N = w.shape H, W = util.calc_tiling(N) g = w[0] g = g.view(G, K, H, W) out.key_selections = g g = g.view(G * K, H, W) g = torchvision.utils.make_grid(g.unsqueeze(1).mul(brightness).clamp(max=1), nrow=K, padding=1, pad_value=1)[:1] # .mean(dim=0).unsqueeze(0) # g = torch.from_numpy(self.cmap(g.numpy())).permute(0, 3, 1, 2)[:,:3] # g = torchvision.utils.make_grid(g, nrow=K, padding=1, pad_value=1)#.norm(p=1, dim=0) logger.add('image', 'patches-1', g) g = w.sum(0) / B g = g.view(G, K, H, W) out.key_selections = g g = g.view(G * K, H, W) g = torchvision.utils.make_grid(g.unsqueeze(1).mul(brightness).clamp(max=1), nrow=K, padding=1, pad_value=1)[:1] # .mean(dim=0).unsqueeze(0) # g = torch.from_numpy(self.cmap(g.numpy())).permute(0, 3, 1, 2)[:,:3] # g = torchvision.utils.make_grid(g, nrow=K, padding=1, pad_value=1)#.norm(p=1, dim=0) logger.add('image', 'patches-avg', g) def forward(self, p1, p2): # p1 (B, C, N) w = self.compute_weights(p2) # (B, GK, N) B, GK, N = w.shape G = self.heads K = self.keys if self.gumbel is not None: if self.training: self.gumbel = max(self.gumbel - self.gumbel_delta, self.gumbel_min) w += torch.rand_like(w).log().mul(-1).log().mul(-1) w /= self.gumbel w = w.view(B, G, K * N) if self.norm_heads else w.view(B, G, K, N) w = F.softmax(w, dim=-1).view(B, G * K, N) self._w = w.view(B, G, K, N).cpu().detach() w = w.permute(0, 2, 1) v = p1 @ w if self.sum_heads: C = p1.size(1) v = v.view(B, C, G, K).sum(-1) return v # (B, C, G*K) # @fd.AutoComponent('point-wsum') # class PointWeightedSum(fd.Cacheable, fd.Visualizable, PointJoin): # # pass @fig.AutoComponent('pool-points') class Pool_Points(PointTransform): def __init__(self, pin, fn='max', p=2): super().__init__(pin, pin) assert fn in {'max', 'avg', 'sum', 'std', 'norm'}, f'unknown pool type: {fn}' self.fn = fn self.p = p def extra_repr(self): return f'{self.fn}' def forward(self, p): if self.fn == 'max': return p.max(-1, keepdim=True)[0] if self.fn == 'avg': return p.mean(-1, keepdim=True) if self.fn == 'sum': return p.sum(-1, keepdim=True) if self.fn == 'std': return p.std(-1, keepdim=True) if self.fn == 'norm': return p.norm(p=self.p, dim=-1, keepdim=True) @fig.AutoComponent('concat-points') class Concat_Points(PointTransform): def __init__(self, pin, N=None, groups=1): if N is None: print('WARNING: no number of points set') N = 1 super().__init__(pin, N * pin // groups) self.groups = groups def forward(self, p): B = p.size(0) return p.permute(0, 2, 1).contiguous().view(B, self.groups, -1)
// export default function data() { return { dialogs: { help: false, }, loading: false, } }
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.nolimit = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ var info = { load: function(options, callback) { var parts = [options.staticRoot, options.game]; if(options.version) { parts.push(options.version); } parts.push('info.json'); var url = parts.join('/'); var request = new XMLHttpRequest(); function onFail() { var error = request.statusText || 'No error message available; CORS or server missing?'; callback({ error: error }); } request.open('GET', url, true); request.onload = function() { if(request.status >= 200 && request.status < 400) { var info; try { info = JSON.parse(request.responseText); info.staticRoot = [options.staticRoot, info.name, info.version].join('/'); info.aspectRatio = info.size.width / info.size.height; info.infoJson = url; } catch(e) { callback({ error: e.message }); return; } callback(info); } else { onFail(); } }; request.onerror = onFail; request.send(); } }; module.exports = info; },{}],2:[function(require,module,exports){ 'use strict'; /** * @exports nolimitApiFactory * @private */ var nolimitApiFactory = function(target, onload) { var listeners = {}; var unhandledEvents = {}; var unhandledCalls = []; var port; function handleUnhandledCalls(port) { while(unhandledCalls.length > 0) { port.postMessage(unhandledCalls.shift()); } } function addMessageListener(gameWindow) { gameWindow.addEventListener('message', function(e) { if(e.ports && e.ports.length > 0) { port = e.ports[0]; port.onmessage = onMessage; handleUnhandledCalls(port); } }); gameWindow.trigger = trigger; gameWindow.on = on; onload(); } if(target.nodeName === 'IFRAME') { if (target.contentWindow && target.contentWindow.document && target.contentWindow.document.readyState === 'complete') { addMessageListener(target.contentWindow); } else { target.addEventListener('load', function() { addMessageListener(target.contentWindow); }); } } else { addMessageListener(target); } function onMessage(e) { trigger(e.data.method, e.data.params); } function sendMessage(method, data) { var message = { jsonrpc: '2.0', method: method }; if(data) { message.params = data; } if(port) { try { port.postMessage(message); } catch(ignored) { port = undefined; unhandledCalls.push(message); } } else { unhandledCalls.push(message); } } function registerEvents(events) { sendMessage('register', events); } function trigger(event, data) { if(listeners[event]) { listeners[event].forEach(function(callback) { callback(data); }); } else { unhandledEvents[name] = unhandledEvents[name] || []; unhandledEvents[name].push(data); } } function on(event, callback) { listeners[event] = listeners[event] || []; listeners[event].push(callback); while(unhandledEvents[event] && unhandledEvents[event].length > 0) { trigger(event, unhandledEvents[event].pop()); } registerEvents([event]); } /** * Connection to the game using MessageChannel * @exports nolimitApi */ var nolimitApi = { /** * Add listener for event from the started game * * @function on * @param {String} event name of the event * @param {Function} callback callback for the event, see specific event documentation for any parameters * * @example * api.on('deposit', function openDeposit () { * showDeposit().then(function() { * // ask the game to refresh balance from server * api.call('refresh'); * }); * }); */ on: on, /** * Call method in the open game * * @function call * @param {String} method name of the method to call * @param {Object} [data] optional data for the method called, if any * * @example * // reload the game * api.call('reload'); */ call: sendMessage }; return nolimitApi; }; module.exports = nolimitApiFactory; },{}],3:[function(require,module,exports){ module.exports = 'html, body {\n overflow: hidden;\n margin: 0;\n width: 100%;\n height: 100%;\n}\n\nbody {\n position: relative;\n}\n'; },{}],4:[function(require,module,exports){ 'use strict'; var nolimitApiFactory = require('./nolimit-api'); var info = require('./info'); var CDN = '{PROTOCOL}//{ENV}'; var LOADER_URL = '{CDN}/loader/loader-{DEVICE}.html?operator={OPERATOR}&game={GAME}&language={LANGUAGE}'; var REPLACE_URL = '{CDN}/loader/game-loader.html?{QUERY}'; var GAMES_URL = '{CDN}/games'; var DEFAULT_OPTIONS = { device: 'desktop', environment: 'partner', language: 'en', 'nolimit.js': '1.2.30' }; /** * @exports nolimit */ var nolimit = { /** * @property {String} version current version of nolimit.js */ version: '1.2.30', options: {}, /** * Initialize loader with default parameters. Can be skipped if the parameters are included in the call to load instead. * * @param {Object} options * @param {String} options.operator the operator code for the operator * @param {String} [options.language="en"] the language to use for the game * @param {String} [options.device=desktop] type of device: 'desktop' or 'mobile' * @param {String} [options.environment=partner] which environment to use; usually 'partner' or 'production' * @param {String} [options.currency=EUR] currency to use, if not provided by server * @param {Boolean} [options.fullscreen=true] set to false to disable automatic fullscreen on mobile (Android only) * @param {Boolean} [options.clock=true] set to false to disable in-game clock * @param {String} [options.quality] force asset quality. Possible values are 'high', 'medium', 'low'. Defaults to smart loading in each game. * @param {Object} [options.jurisdiction] force a specific jurisdiction to enforce specific license requirements and set specific options and overrides. See README for jurisdiction-specific details. * @param {Object} [options.jurisdiction.name] the name of the jurisdiction, for example "UKGC" or "SE". * @param {Object} [options.realityCheck] set options for reality check. See README for more details. * @param {Object} [options.realityCheck.enabled=true] set to false to disable reality-check dialog. * @param {Number} [options.realityCheck.interval=60] Interval in minutes between showing reality-check dialog. * @param {Number} [options.realityCheck.sessionStart=Date.now()] override session start, default is Date.now(). * @param {Number} [options.realityCheck.nextTime] next time to show dialog, defaults to Date.now() + interval. * @param {Number} [options.realityCheck.bets=0] set initial bets if player already has bets in the session. * @param {Number} [options.realityCheck.winnings=0] set initial winnings if player already has winnings in the session. * @param {Number} [options.realityCheck.message] Message to display when dialog is opened. A generic default is provided. * * @example * nolimit.init({ * operator: 'SMOOTHOPERATOR', * language: 'sv', * device: 'mobile', * environment: 'production', * currency: 'SEK', * jurisdiction: { * name: 'SE' * }, * realityCheck: { * interval: 30 * } * }); */ init: function(options) { this.options = options; }, /** * Load game, replacing target with the game. * * <li> If target is a HTML element, it will be replaced with an iframe, keeping all the attributes of the original element, so those can be used to set id, classes, styles and more. * <li> If target is a Window element, the game will be loaded directly in that. * <li> If target is undefined, it will default to the current window. * * @param {Object} options * @param {String} options.game case sensitive game code, for example 'CreepyCarnival' or 'SpaceArcade' * @param {HTMLElement|Window} [options.target=window] the HTMLElement or Window to load the game in * @param {String} [options.token] the token to use for real money play * @param {Boolean} [options.mute=false] start the game without sound * @param {String} [options.version] force specific game version such as '1.2.3', or 'development' to disable cache * @param {Boolean} [options.hideCurrency] hide currency symbols/codes in the game * * @returns {nolimitApi} The API connection to the opened game. * * @example * var api = nolimit.load({ * game: 'SpaceArcade', * target: document.getElementById('game'), * token: realMoneyToken, * mute: true * }); */ load: function(options) { options = processOptions(mergeOptions(this.options, options)); var target = options.target || window; if(target.Window && target instanceof target.Window) { target = document.createElement('div'); target.setAttribute('style', 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden;'); document.body.appendChild(target); } if(target.ownerDocument && target instanceof target.ownerDocument.defaultView.HTMLElement) { var iframe = makeIframe(target); target.parentNode.replaceChild(iframe, target); return nolimitApiFactory(iframe, function() { html(iframe.contentWindow, options); }); } else { throw 'Invalid option target: ' + target; } }, /** * Load game in a new, separate page. This offers the best isolation, but no communication with the game is possible. * * @param {Object} options * @param {String} options.game case sensitive game code, for example 'CreepyCarnival' or 'SpaceArcade' * @param {String} [options.token] the token to use for real money play * @param {Boolean} [options.mute=false] start the game without sound * @param {String} [options.version] force specific game version such as '1.2.3', or 'development' to disable cache * @param {Boolean} [options.hideCurrency] hide currency symbols/codes in the game * @param {String} [options.lobbyUrl="history:back()"] URL to redirect back to lobby on mobile, if not using a target * @param {String} [options.depositUrl] URL to deposit page, if not using a target element * @param {String} [options.supportUrl] URL to support page, if not using a target element * @param {Boolean} [options.depositEvent] instead of using URL, emit "deposit" event (see event documentation) * @param {Boolean} [options.lobbyEvent] instead of using URL, emit "lobby" event (see event documentation) (mobile only) * @param {String} [options.accountHistoryUrl] URL to support page, if not using a target element * * @example * var api = nolimit.replace({ * game: 'SpaceArcade', * target: document.getElementById('game'), * token: realMoneyToken, * mute: true * }); */ replace: function(options) { location.href = this.url(options); function noop() {} return {on: noop, call: noop}; }, /** * Constructs a URL for manually loading the game in an iframe or via redirect. * @param {Object} options see replace for details * @see {@link nolimit.replace} for details on options * @return {string} */ url: function(options) { var gameOptions = processOptions(mergeOptions(this.options, options)); return REPLACE_URL .replace('{CDN}', gameOptions.cdn) .replace('{QUERY}', makeQueryString(gameOptions)); }, /** * Load information about the game, such as: current version, preferred width/height etc. * * @param {Object} options * @param {String} [options.environment=partner] which environment to use; usually 'partner' or 'production' * @param {String} options.game case sensitive game code, for example 'CreepyCarnival' or 'SpaceArcade' * @param {String} [options.version] force specific version of game to load. * @param {Function} callback called with the info object, if there was an error, the 'error' field will be set * * @example * nolimit.info({game: 'SpaceArcade'}, function(info) { * var target = document.getElementById('game'); * target.style.width = info.size.width + 'px'; * target.style.height = info.size.height + 'px'; * console.log(info.name, info.version); * }); */ info: function(options, callback) { options = processOptions(mergeOptions(this.options, options)); info.load(options, callback); } }; function makeQueryString(options) { var query = []; for(var key in options) { var value = options[key]; if(typeof value === 'undefined') { continue; } if(value instanceof HTMLElement) { continue; } if(typeof value === 'object') { value = JSON.stringify(value); } query.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); } return query.join('&'); } function makeIframe(element) { var iframe = document.createElement('iframe'); copyAttributes(element, iframe); iframe.setAttribute('frameBorder', '0'); iframe.setAttribute('allowfullscreen', ''); iframe.setAttribute('allow', 'autoplay; fullscreen'); iframe.setAttribute('sandbox', 'allow-forms allow-scripts allow-same-origin allow-top-navigation allow-popups'); var name = generateName(iframe.getAttribute('name') || iframe.id); iframe.setAttribute('name', name); return iframe; } function mergeOptions(globalOptions, gameOptions) { delete globalOptions.version; var options = {}, name; for(name in DEFAULT_OPTIONS) { options[name] = DEFAULT_OPTIONS[name]; } for(name in globalOptions) { options[name] = globalOptions[name]; } for(name in gameOptions) { options[name] = gameOptions[name]; } return options; } function insertCss(document) { var style = document.createElement('style'); style.textContent = require('./nolimit.css'); document.head.appendChild(style); } function setupViewport(head) { var viewport = head.querySelector('meta[name="viewport"]'); if(!viewport) { head.insertAdjacentHTML('beforeend', '<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">'); } } function processOptions(options) { options.device = options.device.toLowerCase(); options.mute = options.mute || false; var environment = options.environment.toLowerCase(); if(environment.indexOf('.') === -1) { environment += '.nolimitcdn.com'; } options.cdn = options.cdn || CDN.replace('{PROTOCOL}', location.protocol).replace('{ENV}', environment); options.staticRoot = options.staticRoot || GAMES_URL.replace('{CDN}', options.cdn); return options; } function html(window, options) { var document = window.document; window.focus(); insertCss(document); setupViewport(document.head); var loaderElement = document.createElement('iframe'); loaderElement.setAttribute('frameBorder', '0'); loaderElement.style.backgroundColor = 'black'; loaderElement.style.width = '100vw'; loaderElement.style.height = '100vh'; loaderElement.style.position = 'relative'; loaderElement.style.zIndex = '2147483647'; loaderElement.classList.add('loader'); loaderElement.src = LOADER_URL .replace('{CDN}', options.cdn) .replace('{DEVICE}', options.device) .replace('{OPERATOR}', options.operator) .replace('{GAME}', options.game) .replace('{LANGUAGE}', options.language); document.body.innerHTML = ''; loaderElement.onload = function() { window.on('error', function(error) { if(loaderElement && loaderElement.contentWindow) { loaderElement.contentWindow.postMessage(JSON.stringify({'error': error}), '*'); } }); if(options.weinre) { var weinre = document.createElement('script'); weinre.src = options.weinre; document.body.appendChild(weinre); } nolimit.info(options, function(info) { if(info.error) { window.trigger('error', info.error); loaderElement.contentWindow.postMessage(JSON.stringify(info), '*'); } else { window.trigger('info', info); var gameElement = document.createElement('script'); gameElement.src = info.staticRoot + '/game.js'; options.loadStart = Date.now(); window.nolimit = nolimit; window.nolimit.options = options; window.nolimit.options.version = info.version; document.body.appendChild(gameElement); } }); }; document.body.appendChild(loaderElement); } function copyAttributes(from, to) { var attributes = from.attributes; for(var i = 0; i < attributes.length; i++) { var attr = attributes[i]; to.setAttribute(attr.name, attr.value); } } var generateName = (function() { var generatedIndex = 1; return function(name) { return name || 'Nolimit-' + generatedIndex++; }; })(); module.exports = nolimit; },{"./info":1,"./nolimit-api":2,"./nolimit.css":3}]},{},[4])(4) }); //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCJzcmMvaW5mby5qcyIsInNyYy9ub2xpbWl0LWFwaS5qcyIsInNyYy9ub2xpbWl0LmNzcyIsInNyYy9ub2xpbWl0LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FDQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQy9DQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUN2SUE7O0FDQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyIoZnVuY3Rpb24oKXtmdW5jdGlvbiByKGUsbix0KXtmdW5jdGlvbiBvKGksZil7aWYoIW5baV0pe2lmKCFlW2ldKXt2YXIgYz1cImZ1bmN0aW9uXCI9PXR5cGVvZiByZXF1aXJlJiZyZXF1aXJlO2lmKCFmJiZjKXJldHVybiBjKGksITApO2lmKHUpcmV0dXJuIHUoaSwhMCk7dmFyIGE9bmV3IEVycm9yKFwiQ2Fubm90IGZpbmQgbW9kdWxlICdcIitpK1wiJ1wiKTt0aHJvdyBhLmNvZGU9XCJNT0RVTEVfTk9UX0ZPVU5EXCIsYX12YXIgcD1uW2ldPXtleHBvcnRzOnt9fTtlW2ldWzBdLmNhbGwocC5leHBvcnRzLGZ1bmN0aW9uKHIpe3ZhciBuPWVbaV1bMV1bcl07cmV0dXJuIG8obnx8cil9LHAscC5leHBvcnRzLHIsZSxuLHQpfXJldHVybiBuW2ldLmV4cG9ydHN9Zm9yKHZhciB1PVwiZnVuY3Rpb25cIj09dHlwZW9mIHJlcXVpcmUmJnJlcXVpcmUsaT0wO2k8dC5sZW5ndGg7aSsrKW8odFtpXSk7cmV0dXJuIG99cmV0dXJuIHJ9KSgpIiwidmFyIGluZm8gPSB7XG4gICAgbG9hZDogZnVuY3Rpb24ob3B0aW9ucywgY2FsbGJhY2spIHtcbiAgICAgICAgdmFyIHBhcnRzID0gW29wdGlvbnMuc3RhdGljUm9vdCwgb3B0aW9ucy5nYW1lXTtcbiAgICAgICAgaWYob3B0aW9ucy52ZXJzaW9uKSB7XG4gICAgICAgICAgICBwYXJ0cy5wdXNoKG9wdGlvbnMudmVyc2lvbik7XG4gICAgICAgIH1cbiAgICAgICAgcGFydHMucHVzaCgnaW5mby5qc29uJyk7XG5cbiAgICAgICAgdmFyIHVybCA9IHBhcnRzLmpvaW4oJy8nKTtcbiAgICAgICAgdmFyIHJlcXVlc3QgPSBuZXcgWE1MSHR0cFJlcXVlc3QoKTtcblxuICAgICAgICBmdW5jdGlvbiBvbkZhaWwoKSB7XG4gICAgICAgICAgICB2YXIgZXJyb3IgPSByZXF1ZXN0LnN0YXR1c1RleHQgfHwgJ05vIGVycm9yIG1lc3NhZ2UgYXZhaWxhYmxlOyBDT1JTIG9yIHNlcnZlciBtaXNzaW5nPyc7XG4gICAgICAgICAgICBjYWxsYmFjayh7XG4gICAgICAgICAgICAgICAgZXJyb3I6IGVycm9yXG4gICAgICAgICAgICB9KTtcbiAgICAgICAgfVxuXG4gICAgICAgIHJlcXVlc3Qub3BlbignR0VUJywgdXJsLCB0cnVlKTtcblxuICAgICAgICByZXF1ZXN0Lm9ubG9hZCA9IGZ1bmN0aW9uKCkge1xuICAgICAgICAgICAgaWYocmVxdWVzdC5zdGF0dXMgPj0gMjAwICYmIHJlcXVlc3Quc3RhdHVzIDwgNDAwKSB7XG4gICAgICAgICAgICAgICAgdmFyIGluZm87XG4gICAgICAgICAgICAgICAgdHJ5IHtcbiAgICAgICAgICAgICAgICAgICAgaW5mbyA9IEpTT04ucGFyc2UocmVxdWVzdC5yZXNwb25zZVRleHQpO1xuICAgICAgICAgICAgICAgICAgICBpbmZvLnN0YXRpY1Jvb3QgPSBbb3B0aW9ucy5zdGF0aWNSb290LCBpbmZvLm5hbWUsIGluZm8udmVyc2lvbl0uam9pbignLycpO1xuICAgICAgICAgICAgICAgICAgICBpbmZvLmFzcGVjdFJhdGlvID0gaW5mby5zaXplLndpZHRoIC8gaW5mby5zaXplLmhlaWdodDtcbiAgICAgICAgICAgICAgICAgICAgaW5mby5pbmZvSnNvbiA9IHVybDtcbiAgICAgICAgICAgICAgICB9IGNhdGNoKGUpIHtcbiAgICAgICAgICAgICAgICAgICAgY2FsbGJhY2soe1xuICAgICAgICAgICAgICAgICAgICAgICAgZXJyb3I6IGUubWVzc2FnZVxuICAgICAgICAgICAgICAgICAgICB9KTtcbiAgICAgICAgICAgICAgICAgICAgcmV0dXJuO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICBjYWxsYmFjayhpbmZvKTtcbiAgICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAgICAgb25GYWlsKCk7XG4gICAgICAgICAgICB9XG4gICAgICAgIH07XG5cbiAgICAgICAgcmVxdWVzdC5vbmVycm9yID0gb25GYWlsO1xuXG4gICAgICAgIHJlcXVlc3Quc2VuZCgpO1xuICAgIH1cbn07XG5cbm1vZHVsZS5leHBvcnRzID0gaW5mbztcbiIsIid1c2Ugc3RyaWN0JztcblxuLyoqXG4gKiBAZXhwb3J0cyBub2xpbWl0QXBpRmFjdG9yeVxuICogQHByaXZhdGVcbiAqL1xudmFyIG5vbGltaXRBcGlGYWN0b3J5ID0gZnVuY3Rpb24odGFyZ2V0LCBvbmxvYWQpIHtcblxuICAgIHZhciBsaXN0ZW5lcnMgPSB7fTtcbiAgICB2YXIgdW5oYW5kbGVkRXZlbnRzID0ge307XG4gICAgdmFyIHVuaGFuZGxlZENhbGxzID0gW107XG4gICAgdmFyIHBvcnQ7XG5cbiAgICBmdW5jdGlvbiBoYW5kbGVVbmhhbmRsZWRDYWxscyhwb3J0KSB7XG4gICAgICAgIHdoaWxlKHVuaGFuZGxlZENhbGxzLmxlbmd0aCA+IDApIHtcbiAgICAgICAgICAgIHBvcnQucG9zdE1lc3NhZ2UodW5oYW5kbGVkQ2FsbHMuc2hpZnQoKSk7XG4gICAgICAgIH1cbiAgICB9XG5cbiAgICBmdW5jdGlvbiBhZGRNZXNzYWdlTGlzdGVuZXIoZ2FtZVdpbmRvdykge1xuICAgICAgICBnYW1lV2luZG93LmFkZEV2ZW50TGlzdGVuZXIoJ21lc3NhZ2UnLCBmdW5jdGlvbihlKSB7XG4gICAgICAgICAgICBpZihlLnBvcnRzICYmIGUucG9ydHMubGVuZ3RoID4gMCkge1xuICAgICAgICAgICAgICAgIHBvcnQgPSBlLnBvcnRzWzBdO1xuICAgICAgICAgICAgICAgIHBvcnQub25tZXNzYWdlID0gb25NZXNzYWdlO1xuICAgICAgICAgICAgICAgIGhhbmRsZVVuaGFuZGxlZENhbGxzKHBvcnQpO1xuICAgICAgICAgICAgfVxuICAgICAgICB9KTtcbiAgICAgICAgZ2FtZVdpbmRvdy50cmlnZ2VyID0gdHJpZ2dlcjtcbiAgICAgICAgZ2FtZVdpbmRvdy5vbiA9IG9uO1xuICAgICAgICBvbmxvYWQoKTtcbiAgICB9XG5cbiAgICBpZih0YXJnZXQubm9kZU5hbWUgPT09ICdJRlJBTUUnKSB7XG4gICAgICAgIGlmICh0YXJnZXQuY29udGVudFdpbmRvdyAmJiB0YXJnZXQuY29udGVudFdpbmRvdy5kb2N1bWVudCAmJiB0YXJnZXQuY29udGVudFdpbmRvdy5kb2N1bWVudC5yZWFkeVN0YXRlID09PSAnY29tcGxldGUnKSB7XG4gICAgICAgICAgICBhZGRNZXNzYWdlTGlzdGVuZXIodGFyZ2V0LmNvbnRlbnRXaW5kb3cpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgdGFyZ2V0LmFkZEV2ZW50TGlzdGVuZXIoJ2xvYWQnLCBmdW5jdGlvbigpIHtcbiAgICAgICAgICAgICAgICBhZGRNZXNzYWdlTGlzdGVuZXIodGFyZ2V0LmNvbnRlbnRXaW5kb3cpO1xuICAgICAgICAgICAgfSk7XG4gICAgICAgIH1cbiAgICB9IGVsc2Uge1xuICAgICAgICBhZGRNZXNzYWdlTGlzdGVuZXIodGFyZ2V0KTtcbiAgICB9XG5cbiAgICBmdW5jdGlvbiBvbk1lc3NhZ2UoZSkge1xuICAgICAgICB0cmlnZ2VyKGUuZGF0YS5tZXRob2QsIGUuZGF0YS5wYXJhbXMpO1xuICAgIH1cblxuICAgIGZ1bmN0aW9uIHNlbmRNZXNzYWdlKG1ldGhvZCwgZGF0YSkge1xuICAgICAgICB2YXIgbWVzc2FnZSA9IHtcbiAgICAgICAgICAgIGpzb25ycGM6ICcyLjAnLFxuICAgICAgICAgICAgbWV0aG9kOiBtZXRob2RcbiAgICAgICAgfTtcblxuICAgICAgICBpZihkYXRhKSB7XG4gICAgICAgICAgICBtZXNzYWdlLnBhcmFtcyA9IGRhdGE7XG4gICAgICAgIH1cblxuICAgICAgICBpZihwb3J0KSB7XG4gICAgICAgICAgICB0cnkge1xuICAgICAgICAgICAgICAgIHBvcnQucG9zdE1lc3NhZ2UobWVzc2FnZSk7XG4gICAgICAgICAgICB9IGNhdGNoKGlnbm9yZWQpIHtcbiAgICAgICAgICAgICAgICBwb3J0ID0gdW5kZWZpbmVkO1xuICAgICAgICAgICAgICAgIHVuaGFuZGxlZENhbGxzLnB1c2gobWVzc2FnZSk7XG4gICAgICAgICAgICB9XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICB1bmhhbmRsZWRDYWxscy5wdXNoKG1lc3NhZ2UpO1xuICAgICAgICB9XG4gICAgfVxuXG4gICAgZnVuY3Rpb24gcmVnaXN0ZXJFdmVudHMoZXZlbnRzKSB7XG4gICAgICAgIHNlbmRNZXNzYWdlKCdyZWdpc3RlcicsIGV2ZW50cyk7XG4gICAgfVxuXG4gICAgZnVuY3Rpb24gdHJpZ2dlcihldmVudCwgZGF0YSkge1xuICAgICAgICBpZihsaXN0ZW5lcnNbZXZlbnRdKSB7XG4gICAgICAgICAgICBsaXN0ZW5lcnNbZXZlbnRdLmZvckVhY2goZnVuY3Rpb24oY2FsbGJhY2spIHtcbiAgICAgICAgICAgICAgICBjYWxsYmFjayhkYXRhKTtcbiAgICAgICAgICAgIH0pO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgdW5oYW5kbGVkRXZlbnRzW25hbWVdID0gdW5oYW5kbGVkRXZlbnRzW25hbWVdIHx8IFtdO1xuICAgICAgICAgICAgdW5oYW5kbGVkRXZlbnRzW25hbWVdLnB1c2goZGF0YSk7XG4gICAgICAgIH1cbiAgICB9XG5cbiAgICBmdW5jdGlvbiBvbihldmVudCwgY2FsbGJhY2spIHtcbiAgICAgICAgbGlzdGVuZXJzW2V2ZW50XSA9IGxpc3RlbmVyc1tldmVudF0gfHwgW107XG4gICAgICAgIGxpc3RlbmVyc1tldmVudF0ucHVzaChjYWxsYmFjayk7XG4gICAgICAgIHdoaWxlKHVuaGFuZGxlZEV2ZW50c1tldmVudF0gJiYgdW5oYW5kbGVkRXZlbnRzW2V2ZW50XS5sZW5ndGggPiAwKSB7XG4gICAgICAgICAgICB0cmlnZ2VyKGV2ZW50LCB1bmhhbmRsZWRFdmVudHNbZXZlbnRdLnBvcCgpKTtcbiAgICAgICAgfVxuXG4gICAgICAgIHJlZ2lzdGVyRXZlbnRzKFtldmVudF0pO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIENvbm5lY3Rpb24gdG8gdGhlIGdhbWUgdXNpbmcgTWVzc2FnZUNoYW5uZWxcbiAgICAgKiBAZXhwb3J0cyBub2xpbWl0QXBpXG4gICAgICovXG4gICAgdmFyIG5vbGltaXRBcGkgPSB7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBBZGQgbGlzdGVuZXIgZm9yIGV2ZW50IGZyb20gdGhlIHN0YXJ0ZWQgZ2FtZVxuICAgICAgICAgKlxuICAgICAgICAgKiBAZnVuY3Rpb24gb25cbiAgICAgICAgICogQHBhcmFtIHtTdHJpbmd9ICAgZXZlbnQgICAgbmFtZSBvZiB0aGUgZXZlbnRcbiAgICAgICAgICogQHBhcmFtIHtGdW5jdGlvbn0gY2FsbGJhY2sgY2FsbGJhY2sgZm9yIHRoZSBldmVudCwgc2VlIHNwZWNpZmljIGV2ZW50IGRvY3VtZW50YXRpb24gZm9yIGFueSBwYXJhbWV0ZXJzXG4gICAgICAgICAqXG4gICAgICAgICAqIEBleGFtcGxlXG4gICAgICAgICAqIGFwaS5vbignZGVwb3NpdCcsIGZ1bmN0aW9uIG9wZW5EZXBvc2l0ICgpIHtcbiAgICAgICAgICogICAgIHNob3dEZXBvc2l0KCkudGhlbihmdW5jdGlvbigpIHtcbiAgICAgICAgICogICAgICAgICAvLyBhc2sgdGhlIGdhbWUgdG8gcmVmcmVzaCBiYWxhbmNlIGZyb20gc2VydmVyXG4gICAgICAgICAqICAgICAgICAgYXBpLmNhbGwoJ3JlZnJlc2gnKTtcbiAgICAgICAgICogICAgIH0pO1xuICAgICAgICAgKiB9KTtcbiAgICAgICAgICovXG4gICAgICAgIG9uOiBvbixcblxuICAgICAgICAvKipcbiAgICAgICAgICogQ2FsbCBtZXRob2QgaW4gdGhlIG9wZW4gZ2FtZVxuICAgICAgICAgKlxuICAgICAgICAgKiBAZnVuY3Rpb24gY2FsbFxuICAgICAgICAgKiBAcGFyYW0ge1N0cmluZ30gbWV0aG9kIG5hbWUgb2YgdGhlIG1ldGhvZCB0byBjYWxsXG4gICAgICAgICAqIEBwYXJhbSB7T2JqZWN0fSBbZGF0YV0gb3B0aW9uYWwgZGF0YSBmb3IgdGhlIG1ldGhvZCBjYWxsZWQsIGlmIGFueVxuICAgICAgICAgKlxuICAgICAgICAgKiBAZXhhbXBsZVxuICAgICAgICAgKiAvLyByZWxvYWQgdGhlIGdhbWVcbiAgICAgICAgICogYXBpLmNhbGwoJ3JlbG9hZCcpO1xuICAgICAgICAgKi9cbiAgICAgICAgY2FsbDogc2VuZE1lc3NhZ2VcbiAgICB9O1xuXG4gICAgcmV0dXJuIG5vbGltaXRBcGk7XG59O1xuXG5tb2R1bGUuZXhwb3J0cyA9IG5vbGltaXRBcGlGYWN0b3J5O1xuIiwibW9kdWxlLmV4cG9ydHMgPSAnaHRtbCwgYm9keSB7XFxuICAgIG92ZXJmbG93OiBoaWRkZW47XFxuICAgIG1hcmdpbjogMDtcXG4gICAgd2lkdGg6IDEwMCU7XFxuICAgIGhlaWdodDogMTAwJTtcXG59XFxuXFxuYm9keSB7XFxuICAgIHBvc2l0aW9uOiByZWxhdGl2ZTtcXG59XFxuJzsiLCIndXNlIHN0cmljdCc7XG5cbnZhciBub2xpbWl0QXBpRmFjdG9yeSA9IHJlcXVpcmUoJy4vbm9saW1pdC1hcGknKTtcbnZhciBpbmZvID0gcmVxdWlyZSgnLi9pbmZvJyk7XG5cbnZhciBDRE4gPSAne1BST1RPQ09MfS8ve0VOVn0nO1xudmFyIExPQURFUl9VUkwgPSAne0NETn0vbG9hZGVyL2xvYWRlci17REVWSUNFfS5odG1sP29wZXJhdG9yPXtPUEVSQVRPUn0mZ2FtZT17R0FNRX0mbGFuZ3VhZ2U9e0xBTkdVQUdFfSc7XG52YXIgUkVQTEFDRV9VUkwgPSAne0NETn0vbG9hZGVyL2dhbWUtbG9hZGVyLmh0bWw/e1FVRVJZfSc7XG52YXIgR0FNRVNfVVJMID0gJ3tDRE59L2dhbWVzJztcblxudmFyIERFRkFVTFRfT1BUSU9OUyA9IHtcbiAgICBkZXZpY2U6ICdkZXNrdG9wJyxcbiAgICBlbnZpcm9ubWVudDogJ3BhcnRuZXInLFxuICAgIGxhbmd1YWdlOiAnZW4nLFxuICAgICdub2xpbWl0LmpzJzogJzEuMi4zMCdcbn07XG5cbi8qKlxuICogQGV4cG9ydHMgbm9saW1pdFxuICovXG52YXIgbm9saW1pdCA9IHtcblxuICAgIC8qKlxuICAgICAqIEBwcm9wZXJ0eSB7U3RyaW5nfSB2ZXJzaW9uIGN1cnJlbnQgdmVyc2lvbiBvZiBub2xpbWl0LmpzXG4gICAgICovXG4gICAgdmVyc2lvbjogJzEuMi4zMCcsXG5cbiAgICBvcHRpb25zOiB7fSxcblxuICAgIC8qKlxuICAgICAqIEluaXRpYWxpemUgbG9hZGVyIHdpdGggZGVmYXVsdCBwYXJhbWV0ZXJzLiBDYW4gYmUgc2tpcHBlZCBpZiB0aGUgcGFyYW1ldGVycyBhcmUgaW5jbHVkZWQgaW4gdGhlIGNhbGwgdG8gbG9hZCBpbnN0ZWFkLlxuICAgICAqXG4gICAgICogQHBhcmFtIHtPYmplY3R9ICBvcHRpb25zXG4gICAgICogQHBhcmFtIHtTdHJpbmd9ICBvcHRpb25zLm9wZXJhdG9yIHRoZSBvcGVyYXRvciBjb2RlIGZvciB0aGUgb3BlcmF0b3JcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gIFtvcHRpb25zLmxhbmd1YWdlPVwiZW5cIl0gdGhlIGxhbmd1YWdlIHRvIHVzZSBmb3IgdGhlIGdhbWVcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gIFtvcHRpb25zLmRldmljZT1kZXNrdG9wXSB0eXBlIG9mIGRldmljZTogJ2Rlc2t0b3AnIG9yICdtb2JpbGUnXG4gICAgICogQHBhcmFtIHtTdHJpbmd9ICBbb3B0aW9ucy5lbnZpcm9ubWVudD1wYXJ0bmVyXSB3aGljaCBlbnZpcm9ubWVudCB0byB1c2U7IHVzdWFsbHkgJ3BhcnRuZXInIG9yICdwcm9kdWN0aW9uJ1xuICAgICAqIEBwYXJhbSB7U3RyaW5nfSAgW29wdGlvbnMuY3VycmVuY3k9RVVSXSBjdXJyZW5jeSB0byB1c2UsIGlmIG5vdCBwcm92aWRlZCBieSBzZXJ2ZXJcbiAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IFtvcHRpb25zLmZ1bGxzY3JlZW49dHJ1ZV0gc2V0IHRvIGZhbHNlIHRvIGRpc2FibGUgYXV0b21hdGljIGZ1bGxzY3JlZW4gb24gbW9iaWxlIChBbmRyb2lkIG9ubHkpXG4gICAgICogQHBhcmFtIHtCb29sZWFufSBbb3B0aW9ucy5jbG9jaz10cnVlXSBzZXQgdG8gZmFsc2UgdG8gZGlzYWJsZSBpbi1nYW1lIGNsb2NrXG4gICAgICogQHBhcmFtIHtTdHJpbmd9ICBbb3B0aW9ucy5xdWFsaXR5XSBmb3JjZSBhc3NldCBxdWFsaXR5LiBQb3NzaWJsZSB2YWx1ZXMgYXJlICdoaWdoJywgJ21lZGl1bScsICdsb3cnLiBEZWZhdWx0cyB0byBzbWFydCBsb2FkaW5nIGluIGVhY2ggZ2FtZS5cbiAgICAgKiBAcGFyYW0ge09iamVjdH0gIFtvcHRpb25zLmp1cmlzZGljdGlvbl0gZm9yY2UgYSBzcGVjaWZpYyBqdXJpc2RpY3Rpb24gdG8gZW5mb3JjZSBzcGVjaWZpYyBsaWNlbnNlIHJlcXVpcmVtZW50cyBhbmQgc2V0IHNwZWNpZmljIG9wdGlvbnMgYW5kIG92ZXJyaWRlcy4gU2VlIFJFQURNRSBmb3IganVyaXNkaWN0aW9uLXNwZWNpZmljIGRldGFpbHMuXG4gICAgICogQHBhcmFtIHtPYmplY3R9ICBbb3B0aW9ucy5qdXJpc2RpY3Rpb24ubmFtZV0gdGhlIG5hbWUgb2YgdGhlIGp1cmlzZGljdGlvbiwgZm9yIGV4YW1wbGUgXCJVS0dDXCIgb3IgXCJTRVwiLlxuICAgICAqIEBwYXJhbSB7T2JqZWN0fSAgW29wdGlvbnMucmVhbGl0eUNoZWNrXSBzZXQgb3B0aW9ucyBmb3IgcmVhbGl0eSBjaGVjay4gU2VlIFJFQURNRSBmb3IgbW9yZSBkZXRhaWxzLlxuICAgICAqIEBwYXJhbSB7T2JqZWN0fSAgW29wdGlvbnMucmVhbGl0eUNoZWNrLmVuYWJsZWQ9dHJ1ZV0gc2V0IHRvIGZhbHNlIHRvIGRpc2FibGUgcmVhbGl0eS1jaGVjayBkaWFsb2cuXG4gICAgICogQHBhcmFtIHtOdW1iZXJ9ICBbb3B0aW9ucy5yZWFsaXR5Q2hlY2suaW50ZXJ2YWw9NjBdIEludGVydmFsIGluIG1pbnV0ZXMgYmV0d2VlbiBzaG93aW5nIHJlYWxpdHktY2hlY2sgZGlhbG9nLlxuICAgICAqIEBwYXJhbSB7TnVtYmVyfSAgW29wdGlvbnMucmVhbGl0eUNoZWNrLnNlc3Npb25TdGFydD1EYXRlLm5vdygpXSBvdmVycmlkZSBzZXNzaW9uIHN0YXJ0LCBkZWZhdWx0IGlzIERhdGUubm93KCkuXG4gICAgICogQHBhcmFtIHtOdW1iZXJ9ICBbb3B0aW9ucy5yZWFsaXR5Q2hlY2submV4dFRpbWVdIG5leHQgdGltZSB0byBzaG93IGRpYWxvZywgZGVmYXVsdHMgdG8gRGF0ZS5ub3coKSArIGludGVydmFsLlxuICAgICAqIEBwYXJhbSB7TnVtYmVyfSAgW29wdGlvbnMucmVhbGl0eUNoZWNrLmJldHM9MF0gc2V0IGluaXRpYWwgYmV0cyBpZiBwbGF5ZXIgYWxyZWFkeSBoYXMgYmV0cyBpbiB0aGUgc2Vzc2lvbi5cbiAgICAgKiBAcGFyYW0ge051bWJlcn0gIFtvcHRpb25zLnJlYWxpdHlDaGVjay53aW5uaW5ncz0wXSBzZXQgaW5pdGlhbCB3aW5uaW5ncyBpZiBwbGF5ZXIgYWxyZWFkeSBoYXMgd2lubmluZ3MgaW4gdGhlIHNlc3Npb24uXG4gICAgICogQHBhcmFtIHtOdW1iZXJ9ICBbb3B0aW9ucy5yZWFsaXR5Q2hlY2subWVzc2FnZV0gTWVzc2FnZSB0byBkaXNwbGF5IHdoZW4gZGlhbG9nIGlzIG9wZW5lZC4gQSBnZW5lcmljIGRlZmF1bHQgaXMgcHJvdmlkZWQuXG5cbiAgICAgKlxuICAgICAqIEBleGFtcGxlXG4gICAgICogbm9saW1pdC5pbml0KHtcbiAgICAgKiAgICBvcGVyYXRvcjogJ1NNT09USE9QRVJBVE9SJyxcbiAgICAgKiAgICBsYW5ndWFnZTogJ3N2JyxcbiAgICAgKiAgICBkZXZpY2U6ICdtb2JpbGUnLFxuICAgICAqICAgIGVudmlyb25tZW50OiAncHJvZHVjdGlvbicsXG4gICAgICogICAgY3VycmVuY3k6ICdTRUsnLFxuICAgICAqICAgIGp1cmlzZGljdGlvbjoge1xuICAgICAqICAgICAgICBuYW1lOiAnU0UnXG4gICAgICogICAgfSxcbiAgICAgKiAgICByZWFsaXR5Q2hlY2s6IHtcbiAgICAgKiAgICAgICAgaW50ZXJ2YWw6IDMwXG4gICAgICogICAgfVxuICAgICAqIH0pO1xuICAgICAqL1xuICAgIGluaXQ6IGZ1bmN0aW9uKG9wdGlvbnMpIHtcbiAgICAgICAgdGhpcy5vcHRpb25zID0gb3B0aW9ucztcbiAgICB9LFxuXG4gICAgLyoqXG4gICAgICogTG9hZCBnYW1lLCByZXBsYWNpbmcgdGFyZ2V0IHdpdGggdGhlIGdhbWUuXG4gICAgICpcbiAgICAgKiA8bGk+IElmIHRhcmdldCBpcyBhIEhUTUwgZWxlbWVudCwgaXQgd2lsbCBiZSByZXBsYWNlZCB3aXRoIGFuIGlmcmFtZSwga2VlcGluZyBhbGwgdGhlIGF0dHJpYnV0ZXMgb2YgdGhlIG9yaWdpbmFsIGVsZW1lbnQsIHNvIHRob3NlIGNhbiBiZSB1c2VkIHRvIHNldCBpZCwgY2xhc3Nlcywgc3R5bGVzIGFuZCBtb3JlLlxuICAgICAqIDxsaT4gSWYgdGFyZ2V0IGlzIGEgV2luZG93IGVsZW1lbnQsIHRoZSBnYW1lIHdpbGwgYmUgbG9hZGVkIGRpcmVjdGx5IGluIHRoYXQuXG4gICAgICogPGxpPiBJZiB0YXJnZXQgaXMgdW5kZWZpbmVkLCBpdCB3aWxsIGRlZmF1bHQgdG8gdGhlIGN1cnJlbnQgd2luZG93LlxuICAgICAqXG4gICAgICogQHBhcmFtIHtPYmplY3R9ICAgICAgICAgICAgICBvcHRpb25zXG4gICAgICogQHBhcmFtIHtTdHJpbmd9ICAgICAgICAgICAgICBvcHRpb25zLmdhbWUgY2FzZSBzZW5zaXRpdmUgZ2FtZSBjb2RlLCBmb3IgZXhhbXBsZSAnQ3JlZXB5Q2Fybml2YWwnIG9yICdTcGFjZUFyY2FkZSdcbiAgICAgKiBAcGFyYW0ge0hUTUxFbGVtZW50fFdpbmRvd30gIFtvcHRpb25zLnRhcmdldD13aW5kb3ddIHRoZSBIVE1MRWxlbWVudCBvciBXaW5kb3cgdG8gbG9hZCB0aGUgZ2FtZSBpblxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSAgICAgICAgICAgICAgW29wdGlvbnMudG9rZW5dIHRoZSB0b2tlbiB0byB1c2UgZm9yIHJlYWwgbW9uZXkgcGxheVxuICAgICAqIEBwYXJhbSB7Qm9vbGVhbn0gICAgICAgICAgICAgW29wdGlvbnMubXV0ZT1mYWxzZV0gc3RhcnQgdGhlIGdhbWUgd2l0aG91dCBzb3VuZFxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSAgICAgICAgICAgICAgW29wdGlvbnMudmVyc2lvbl0gZm9yY2Ugc3BlY2lmaWMgZ2FtZSB2ZXJzaW9uIHN1Y2ggYXMgJzEuMi4zJywgb3IgJ2RldmVsb3BtZW50JyB0byBkaXNhYmxlIGNhY2hlXG4gICAgICogQHBhcmFtIHtCb29sZWFufSAgICAgICAgICAgICBbb3B0aW9ucy5oaWRlQ3VycmVuY3ldIGhpZGUgY3VycmVuY3kgc3ltYm9scy9jb2RlcyBpbiB0aGUgZ2FtZVxuICAgICAqXG4gICAgICogQHJldHVybnMge25vbGltaXRBcGl9ICAgICAgICBUaGUgQVBJIGNvbm5lY3Rpb24gdG8gdGhlIG9wZW5lZCBnYW1lLlxuICAgICAqXG4gICAgICogQGV4YW1wbGVcbiAgICAgKiB2YXIgYXBpID0gbm9saW1pdC5sb2FkKHtcbiAgICAgKiAgICBnYW1lOiAnU3BhY2VBcmNhZGUnLFxuICAgICAqICAgIHRhcmdldDogZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoJ2dhbWUnKSxcbiAgICAgKiAgICB0b2tlbjogcmVhbE1vbmV5VG9rZW4sXG4gICAgICogICAgbXV0ZTogdHJ1ZVxuICAgICAqIH0pO1xuICAgICAqL1xuICAgIGxvYWQ6IGZ1bmN0aW9uKG9wdGlvbnMpIHtcbiAgICAgICAgb3B0aW9ucyA9IHByb2Nlc3NPcHRpb25zKG1lcmdlT3B0aW9ucyh0aGlzLm9wdGlvbnMsIG9wdGlvbnMpKTtcblxuICAgICAgICB2YXIgdGFyZ2V0ID0gb3B0aW9ucy50YXJnZXQgfHwgd2luZG93O1xuXG4gICAgICAgIGlmKHRhcmdldC5XaW5kb3cgJiYgdGFyZ2V0IGluc3RhbmNlb2YgdGFyZ2V0LldpbmRvdykge1xuICAgICAgICAgICAgdGFyZ2V0ID0gZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgnZGl2Jyk7XG4gICAgICAgICAgICB0YXJnZXQuc2V0QXR0cmlidXRlKCdzdHlsZScsICdwb3NpdGlvbjogZml4ZWQ7IHRvcDogMDsgbGVmdDogMDsgd2lkdGg6IDEwMCU7IGhlaWdodDogMTAwJTsgb3ZlcmZsb3c6IGhpZGRlbjsnKTtcbiAgICAgICAgICAgIGRvY3VtZW50LmJvZHkuYXBwZW5kQ2hpbGQodGFyZ2V0KTtcbiAgICAgICAgfVxuXG4gICAgICAgIGlmKHRhcmdldC5vd25lckRvY3VtZW50ICYmIHRhcmdldCBpbnN0YW5jZW9mIHRhcmdldC5vd25lckRvY3VtZW50LmRlZmF1bHRWaWV3LkhUTUxFbGVtZW50KSB7XG4gICAgICAgICAgICB2YXIgaWZyYW1lID0gbWFrZUlmcmFtZSh0YXJnZXQpO1xuICAgICAgICAgICAgdGFyZ2V0LnBhcmVudE5vZGUucmVwbGFjZUNoaWxkKGlmcmFtZSwgdGFyZ2V0KTtcblxuICAgICAgICAgICAgcmV0dXJuIG5vbGltaXRBcGlGYWN0b3J5KGlmcmFtZSwgZnVuY3Rpb24oKSB7XG4gICAgICAgICAgICAgICAgaHRtbChpZnJhbWUuY29udGVudFdpbmRvdywgb3B0aW9ucyk7XG4gICAgICAgICAgICB9KTtcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIHRocm93ICdJbnZhbGlkIG9wdGlvbiB0YXJnZXQ6ICcgKyB0YXJnZXQ7XG4gICAgICAgIH1cbiAgICB9LFxuXG4gICAgLyoqXG4gICAgICogTG9hZCBnYW1lIGluIGEgbmV3LCBzZXBhcmF0ZSBwYWdlLiBUaGlzIG9mZmVycyB0aGUgYmVzdCBpc29sYXRpb24sIGJ1dCBubyBjb21tdW5pY2F0aW9uIHdpdGggdGhlIGdhbWUgaXMgcG9zc2libGUuXG4gICAgICpcbiAgICAgKiBAcGFyYW0ge09iamVjdH0gICAgICAgICAgICAgIG9wdGlvbnNcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gICAgICAgICAgICAgIG9wdGlvbnMuZ2FtZSBjYXNlIHNlbnNpdGl2ZSBnYW1lIGNvZGUsIGZvciBleGFtcGxlICdDcmVlcHlDYXJuaXZhbCcgb3IgJ1NwYWNlQXJjYWRlJ1xuICAgICAqIEBwYXJhbSB7U3RyaW5nfSAgICAgICAgICAgICAgW29wdGlvbnMudG9rZW5dIHRoZSB0b2tlbiB0byB1c2UgZm9yIHJlYWwgbW9uZXkgcGxheVxuICAgICAqIEBwYXJhbSB7Qm9vbGVhbn0gICAgICAgICAgICAgW29wdGlvbnMubXV0ZT1mYWxzZV0gc3RhcnQgdGhlIGdhbWUgd2l0aG91dCBzb3VuZFxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSAgICAgICAgICAgICAgW29wdGlvbnMudmVyc2lvbl0gZm9yY2Ugc3BlY2lmaWMgZ2FtZSB2ZXJzaW9uIHN1Y2ggYXMgJzEuMi4zJywgb3IgJ2RldmVsb3BtZW50JyB0byBkaXNhYmxlIGNhY2hlXG4gICAgICogQHBhcmFtIHtCb29sZWFufSAgICAgICAgICAgICBbb3B0aW9ucy5oaWRlQ3VycmVuY3ldIGhpZGUgY3VycmVuY3kgc3ltYm9scy9jb2RlcyBpbiB0aGUgZ2FtZVxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSAgICAgICAgICAgICAgW29wdGlvbnMubG9iYnlVcmw9XCJoaXN0b3J5OmJhY2soKVwiXSBVUkwgdG8gcmVkaXJlY3QgYmFjayB0byBsb2JieSBvbiBtb2JpbGUsIGlmIG5vdCB1c2luZyBhIHRhcmdldFxuICAgICAqIEBwYXJhbSB7U3RyaW5nfSAgICAgICAgICAgICAgW29wdGlvbnMuZGVwb3NpdFVybF0gVVJMIHRvIGRlcG9zaXQgcGFnZSwgaWYgbm90IHVzaW5nIGEgdGFyZ2V0IGVsZW1lbnRcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gICAgICAgICAgICAgIFtvcHRpb25zLnN1cHBvcnRVcmxdIFVSTCB0byBzdXBwb3J0IHBhZ2UsIGlmIG5vdCB1c2luZyBhIHRhcmdldCBlbGVtZW50XG4gICAgICogQHBhcmFtIHtCb29sZWFufSAgICAgICAgICAgICBbb3B0aW9ucy5kZXBvc2l0RXZlbnRdIGluc3RlYWQgb2YgdXNpbmcgVVJMLCBlbWl0IFwiZGVwb3NpdFwiIGV2ZW50IChzZWUgZXZlbnQgZG9jdW1lbnRhdGlvbilcbiAgICAgKiBAcGFyYW0ge0Jvb2xlYW59ICAgICAgICAgICAgIFtvcHRpb25zLmxvYmJ5RXZlbnRdIGluc3RlYWQgb2YgdXNpbmcgVVJMLCBlbWl0IFwibG9iYnlcIiBldmVudCAoc2VlIGV2ZW50IGRvY3VtZW50YXRpb24pIChtb2JpbGUgb25seSlcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gICAgICAgICAgICAgIFtvcHRpb25zLmFjY291bnRIaXN0b3J5VXJsXSBVUkwgdG8gc3VwcG9ydCBwYWdlLCBpZiBub3QgdXNpbmcgYSB0YXJnZXQgZWxlbWVudFxuICAgICAqXG4gICAgICogQGV4YW1wbGVcbiAgICAgKiB2YXIgYXBpID0gbm9saW1pdC5yZXBsYWNlKHtcbiAgICAgKiAgICBnYW1lOiAnU3BhY2VBcmNhZGUnLFxuICAgICAqICAgIHRhcmdldDogZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoJ2dhbWUnKSxcbiAgICAgKiAgICB0b2tlbjogcmVhbE1vbmV5VG9rZW4sXG4gICAgICogICAgbXV0ZTogdHJ1ZVxuICAgICAqIH0pO1xuICAgICAqL1xuICAgIHJlcGxhY2U6IGZ1bmN0aW9uKG9wdGlvbnMpIHtcbiAgICAgICAgbG9jYXRpb24uaHJlZiA9IHRoaXMudXJsKG9wdGlvbnMpO1xuICAgICAgICBmdW5jdGlvbiBub29wKCkge31cbiAgICAgICAgcmV0dXJuIHtvbjogbm9vcCwgY2FsbDogbm9vcH07XG4gICAgfSxcblxuICAgIC8qKlxuICAgICAqIENvbnN0cnVjdHMgYSBVUkwgZm9yIG1hbnVhbGx5IGxvYWRpbmcgdGhlIGdhbWUgaW4gYW4gaWZyYW1lIG9yIHZpYSByZWRpcmVjdC5cblxuICAgICAqIEBwYXJhbSB7T2JqZWN0fSBvcHRpb25zIHNlZSByZXBsYWNlIGZvciBkZXRhaWxzXG4gICAgICogQHNlZSB7QGxpbmsgbm9saW1pdC5yZXBsYWNlfSBmb3IgZGV0YWlscyBvbiBvcHRpb25zXG4gICAgICogQHJldHVybiB7c3RyaW5nfVxuICAgICAqL1xuICAgIHVybDogZnVuY3Rpb24ob3B0aW9ucykge1xuICAgICAgICB2YXIgZ2FtZU9wdGlvbnMgPSBwcm9jZXNzT3B0aW9ucyhtZXJnZU9wdGlvbnModGhpcy5vcHRpb25zLCBvcHRpb25zKSk7XG4gICAgICAgIHJldHVybiBSRVBMQUNFX1VSTFxuICAgICAgICAgICAgLnJlcGxhY2UoJ3tDRE59JywgZ2FtZU9wdGlvbnMuY2RuKVxuICAgICAgICAgICAgLnJlcGxhY2UoJ3tRVUVSWX0nLCBtYWtlUXVlcnlTdHJpbmcoZ2FtZU9wdGlvbnMpKTtcbiAgICB9LFxuXG4gICAgLyoqXG4gICAgICogTG9hZCBpbmZvcm1hdGlvbiBhYm91dCB0aGUgZ2FtZSwgc3VjaCBhczogY3VycmVudCB2ZXJzaW9uLCBwcmVmZXJyZWQgd2lkdGgvaGVpZ2h0IGV0Yy5cbiAgICAgKlxuICAgICAqIEBwYXJhbSB7T2JqZWN0fSAgICAgIG9wdGlvbnNcbiAgICAgKiBAcGFyYW0ge1N0cmluZ30gICAgICBbb3B0aW9ucy5lbnZpcm9ubWVudD1wYXJ0bmVyXSB3aGljaCBlbnZpcm9ubWVudCB0byB1c2U7IHVzdWFsbHkgJ3BhcnRuZXInIG9yICdwcm9kdWN0aW9uJ1xuICAgICAqIEBwYXJhbSB7U3RyaW5nfSAgICAgIG9wdGlvbnMuZ2FtZSBjYXNlIHNlbnNpdGl2ZSBnYW1lIGNvZGUsIGZvciBleGFtcGxlICdDcmVlcHlDYXJuaXZhbCcgb3IgJ1NwYWNlQXJjYWRlJ1xuICAgICAqIEBwYXJhbSB7U3RyaW5nfSAgICAgIFtvcHRpb25zLnZlcnNpb25dIGZvcmNlIHNwZWNpZmljIHZlcnNpb24gb2YgZ2FtZSB0byBsb2FkLlxuICAgICAqIEBwYXJhbSB7RnVuY3Rpb259ICAgIGNhbGxiYWNrICBjYWxsZWQgd2l0aCB0aGUgaW5mbyBvYmplY3QsIGlmIHRoZXJlIHdhcyBhbiBlcnJvciwgdGhlICdlcnJvcicgZmllbGQgd2lsbCBiZSBzZXRcbiAgICAgKlxuICAgICAqIEBleGFtcGxlXG4gICAgICogbm9saW1pdC5pbmZvKHtnYW1lOiAnU3BhY2VBcmNhZGUnfSwgZnVuY3Rpb24oaW5mbykge1xuICAgICAqICAgICB2YXIgdGFyZ2V0ID0gZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoJ2dhbWUnKTtcbiAgICAgKiAgICAgdGFyZ2V0LnN0eWxlLndpZHRoID0gaW5mby5zaXplLndpZHRoICsgJ3B4JztcbiAgICAgKiAgICAgdGFyZ2V0LnN0eWxlLmhlaWdodCA9IGluZm8uc2l6ZS5oZWlnaHQgKyAncHgnO1xuICAgICAqICAgICBjb25zb2xlLmxvZyhpbmZvLm5hbWUsIGluZm8udmVyc2lvbik7XG4gICAgICogfSk7XG4gICAgICovXG4gICAgaW5mbzogZnVuY3Rpb24ob3B0aW9ucywgY2FsbGJhY2spIHtcbiAgICAgICAgb3B0aW9ucyA9IHByb2Nlc3NPcHRpb25zKG1lcmdlT3B0aW9ucyh0aGlzLm9wdGlvbnMsIG9wdGlvbnMpKTtcbiAgICAgICAgaW5mby5sb2FkKG9wdGlvbnMsIGNhbGxiYWNrKTtcbiAgICB9XG59O1xuXG5mdW5jdGlvbiBtYWtlUXVlcnlTdHJpbmcob3B0aW9ucykge1xuICAgIHZhciBxdWVyeSA9IFtdO1xuICAgIGZvcih2YXIga2V5IGluIG9wdGlvbnMpIHtcbiAgICAgICAgdmFyIHZhbHVlID0gb3B0aW9uc1trZXldO1xuICAgICAgICBpZih0eXBlb2YgdmFsdWUgPT09ICd1bmRlZmluZWQnKSB7XG4gICAgICAgICAgICBjb250aW51ZTtcbiAgICAgICAgfVxuICAgICAgICBpZih2YWx1ZSBpbnN0YW5jZW9mIEhUTUxFbGVtZW50KSB7XG4gICAgICAgICAgICBjb250aW51ZTtcbiAgICAgICAgfVxuICAgICAgICBpZih0eXBlb2YgdmFsdWUgPT09ICdvYmplY3QnKSB7XG4gICAgICAgICAgICB2YWx1ZSA9IEpTT04uc3RyaW5naWZ5KHZhbHVlKTtcbiAgICAgICAgfVxuICAgICAgICBxdWVyeS5wdXNoKGVuY29kZVVSSUNvbXBvbmVudChrZXkpICsgJz0nICsgZW5jb2RlVVJJQ29tcG9uZW50KHZhbHVlKSk7XG4gICAgfVxuICAgIHJldHVybiBxdWVyeS5qb2luKCcmJyk7XG59XG5cbmZ1bmN0aW9uIG1ha2VJZnJhbWUoZWxlbWVudCkge1xuICAgIHZhciBpZnJhbWUgPSBkb2N1bWVudC5jcmVhdGVFbGVtZW50KCdpZnJhbWUnKTtcbiAgICBjb3B5QXR0cmlidXRlcyhlbGVtZW50LCBpZnJhbWUpO1xuXG4gICAgaWZyYW1lLnNldEF0dHJpYnV0ZSgnZnJhbWVCb3JkZXInLCAnMCcpO1xuICAgIGlmcmFtZS5zZXRBdHRyaWJ1dGUoJ2FsbG93ZnVsbHNjcmVlbicsICcnKTtcbiAgICBpZnJhbWUuc2V0QXR0cmlidXRlKCdhbGxvdycsICdhdXRvcGxheTsgZnVsbHNjcmVlbicpO1xuICAgIGlmcmFtZS5zZXRBdHRyaWJ1dGUoJ3NhbmRib3gnLCAnYWxsb3ctZm9ybXMgYWxsb3ctc2NyaXB0cyBhbGxvdy1zYW1lLW9yaWdpbiBhbGxvdy10b3AtbmF2aWdhdGlvbiBhbGxvdy1wb3B1cHMnKTtcblxuICAgIHZhciBuYW1lID0gZ2VuZXJhdGVOYW1lKGlmcmFtZS5nZXRBdHRyaWJ1dGUoJ25hbWUnKSB8fCBpZnJhbWUuaWQpO1xuICAgIGlmcmFtZS5zZXRBdHRyaWJ1dGUoJ25hbWUnLCBuYW1lKTtcblxuICAgIHJldHVybiBpZnJhbWU7XG59XG5cbmZ1bmN0aW9uIG1lcmdlT3B0aW9ucyhnbG9iYWxPcHRpb25zLCBnYW1lT3B0aW9ucykge1xuICAgIGRlbGV0ZSBnbG9iYWxPcHRpb25zLnZlcnNpb247XG4gICAgdmFyIG9wdGlvbnMgPSB7fSwgbmFtZTtcbiAgICBmb3IobmFtZSBpbiBERUZBVUxUX09QVElPTlMpIHtcbiAgICAgICAgb3B0aW9uc1tuYW1lXSA9IERFRkFVTFRfT1BUSU9OU1tuYW1lXTtcbiAgICB9XG4gICAgZm9yKG5hbWUgaW4gZ2xvYmFsT3B0aW9ucykge1xuICAgICAgICBvcHRpb25zW25hbWVdID0gZ2xvYmFsT3B0aW9uc1tuYW1lXTtcbiAgICB9XG4gICAgZm9yKG5hbWUgaW4gZ2FtZU9wdGlvbnMpIHtcbiAgICAgICAgb3B0aW9uc1tuYW1lXSA9IGdhbWVPcHRpb25zW25hbWVdO1xuICAgIH1cbiAgICByZXR1cm4gb3B0aW9ucztcbn1cblxuZnVuY3Rpb24gaW5zZXJ0Q3NzKGRvY3VtZW50KSB7XG4gICAgdmFyIHN0eWxlID0gZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgnc3R5bGUnKTtcbiAgICBzdHlsZS50ZXh0Q29udGVudCA9IHJlcXVpcmUoJy4vbm9saW1pdC5jc3MnKTtcbiAgICBkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHN0eWxlKTtcbn1cblxuZnVuY3Rpb24gc2V0dXBWaWV3cG9ydChoZWFkKSB7XG4gICAgdmFyIHZpZXdwb3J0ID0gaGVhZC5xdWVyeVNlbGVjdG9yKCdtZXRhW25hbWU9XCJ2aWV3cG9ydFwiXScpO1xuICAgIGlmKCF2aWV3cG9ydCkge1xuICAgICAgICBoZWFkLmluc2VydEFkamFjZW50SFRNTCgnYmVmb3JlZW5kJywgJzxtZXRhIG5hbWU9XCJ2aWV3cG9ydFwiIGNvbnRlbnQ9XCJ3aWR0aD1kZXZpY2Utd2lkdGgsIGluaXRpYWwtc2NhbGU9MS4wLCBtYXhpbXVtLXNjYWxlPTEuMCwgdXNlci1zY2FsYWJsZT1ub1wiPicpO1xuICAgIH1cbn1cblxuZnVuY3Rpb24gcHJvY2Vzc09wdGlvbnMob3B0aW9ucykge1xuICAgIG9wdGlvbnMuZGV2aWNlID0gb3B0aW9ucy5kZXZpY2UudG9Mb3dlckNhc2UoKTtcbiAgICBvcHRpb25zLm11dGUgPSBvcHRpb25zLm11dGUgfHwgZmFsc2U7XG4gICAgdmFyIGVudmlyb25tZW50ID0gb3B0aW9ucy5lbnZpcm9ubWVudC50b0xvd2VyQ2FzZSgpO1xuICAgIGlmKGVudmlyb25tZW50LmluZGV4T2YoJy4nKSA9PT0gLTEpIHtcbiAgICAgICAgZW52aXJvbm1lbnQgKz0gJy5ub2xpbWl0Y2RuLmNvbSc7XG4gICAgfVxuICAgIG9wdGlvbnMuY2RuID0gb3B0aW9ucy5jZG4gfHwgQ0ROLnJlcGxhY2UoJ3tQUk9UT0NPTH0nLCBsb2NhdGlvbi5wcm90b2NvbCkucmVwbGFjZSgne0VOVn0nLCBlbnZpcm9ubWVudCk7XG4gICAgb3B0aW9ucy5zdGF0aWNSb290ID0gb3B0aW9ucy5zdGF0aWNSb290IHx8IEdBTUVTX1VSTC5yZXBsYWNlKCd7Q0ROfScsIG9wdGlvbnMuY2RuKTtcbiAgICByZXR1cm4gb3B0aW9ucztcbn1cblxuZnVuY3Rpb24gaHRtbCh3aW5kb3csIG9wdGlvbnMpIHtcbiAgICB2YXIgZG9jdW1lbnQgPSB3aW5kb3cuZG9jdW1lbnQ7XG5cbiAgICB3aW5kb3cuZm9jdXMoKTtcblxuICAgIGluc2VydENzcyhkb2N1bWVudCk7XG4gICAgc2V0dXBWaWV3cG9ydChkb2N1bWVudC5oZWFkKTtcblxuICAgIHZhciBsb2FkZXJFbGVtZW50ID0gZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgnaWZyYW1lJyk7XG4gICAgbG9hZGVyRWxlbWVudC5zZXRBdHRyaWJ1dGUoJ2ZyYW1lQm9yZGVyJywgJzAnKTtcbiAgICBsb2FkZXJFbGVtZW50LnN0eWxlLmJhY2tncm91bmRDb2xvciA9ICdibGFjayc7XG4gICAgbG9hZGVyRWxlbWVudC5zdHlsZS53aWR0aCA9ICcxMDB2dyc7XG4gICAgbG9hZGVyRWxlbWVudC5zdHlsZS5oZWlnaHQgPSAnMTAwdmgnO1xuICAgIGxvYWRlckVsZW1lbnQuc3R5bGUucG9zaXRpb24gPSAncmVsYXRpdmUnO1xuICAgIGxvYWRlckVsZW1lbnQuc3R5bGUuekluZGV4ID0gJzIxNDc0ODM2NDcnO1xuICAgIGxvYWRlckVsZW1lbnQuY2xhc3NMaXN0LmFkZCgnbG9hZGVyJyk7XG5cbiAgICBsb2FkZXJFbGVtZW50LnNyYyA9IExPQURFUl9VUkxcbiAgICAgICAgLnJlcGxhY2UoJ3tDRE59Jywgb3B0aW9ucy5jZG4pXG4gICAgICAgIC5yZXBsYWNlKCd7REVWSUNFfScsIG9wdGlvbnMuZGV2aWNlKVxuICAgICAgICAucmVwbGFjZSgne09QRVJBVE9SfScsIG9wdGlvbnMub3BlcmF0b3IpXG4gICAgICAgIC5yZXBsYWNlKCd7R0FNRX0nLCBvcHRpb25zLmdhbWUpXG4gICAgICAgIC5yZXBsYWNlKCd7TEFOR1VBR0V9Jywgb3B0aW9ucy5sYW5ndWFnZSk7XG5cbiAgICBkb2N1bWVudC5ib2R5LmlubmVySFRNTCA9ICcnO1xuXG4gICAgbG9hZGVyRWxlbWVudC5vbmxvYWQgPSBmdW5jdGlvbigpIHtcbiAgICAgICAgd2luZG93Lm9uKCdlcnJvcicsIGZ1bmN0aW9uKGVycm9yKSB7XG4gICAgICAgICAgICBpZihsb2FkZXJFbGVtZW50ICYmIGxvYWRlckVsZW1lbnQuY29udGVudFdpbmRvdykge1xuICAgICAgICAgICAgICAgIGxvYWRlckVsZW1lbnQuY29udGVudFdpbmRvdy5wb3N0TWVzc2FnZShKU09OLnN0cmluZ2lmeSh7J2Vycm9yJzogZXJyb3J9KSwgJyonKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfSk7XG5cbiAgICAgICAgaWYob3B0aW9ucy53ZWlucmUpIHtcbiAgICAgICAgICAgIHZhciB3ZWlucmUgPSBkb2N1bWVudC5jcmVhdGVFbGVtZW50KCdzY3JpcHQnKTtcbiAgICAgICAgICAgIHdlaW5yZS5zcmMgPSBvcHRpb25zLndlaW5yZTtcbiAgICAgICAgICAgIGRvY3VtZW50LmJvZHkuYXBwZW5kQ2hpbGQod2VpbnJlKTtcbiAgICAgICAgfVxuXG4gICAgICAgIG5vbGltaXQuaW5mbyhvcHRpb25zLCBmdW5jdGlvbihpbmZvKSB7XG4gICAgICAgICAgICBpZihpbmZvLmVycm9yKSB7XG4gICAgICAgICAgICAgICAgd2luZG93LnRyaWdnZXIoJ2Vycm9yJywgaW5mby5lcnJvcik7XG4gICAgICAgICAgICAgICAgbG9hZGVyRWxlbWVudC5jb250ZW50V2luZG93LnBvc3RNZXNzYWdlKEpTT04uc3RyaW5naWZ5KGluZm8pLCAnKicpO1xuICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgICB3aW5kb3cudHJpZ2dlcignaW5mbycsIGluZm8pO1xuXG4gICAgICAgICAgICAgICAgdmFyIGdhbWVFbGVtZW50ID0gZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgnc2NyaXB0Jyk7XG4gICAgICAgICAgICAgICAgZ2FtZUVsZW1lbnQuc3JjID0gaW5mby5zdGF0aWNSb290ICsgJy9nYW1lLmpzJztcblxuICAgICAgICAgICAgICAgIG9wdGlvbnMubG9hZFN0YXJ0ID0gRGF0ZS5ub3coKTtcbiAgICAgICAgICAgICAgICB3aW5kb3cubm9saW1pdCA9IG5vbGltaXQ7XG4gICAgICAgICAgICAgICAgd2luZG93Lm5vbGltaXQub3B0aW9ucyA9IG9wdGlvbnM7XG4gICAgICAgICAgICAgICAgd2luZG93Lm5vbGltaXQub3B0aW9ucy52ZXJzaW9uID0gaW5mby52ZXJzaW9uO1xuXG4gICAgICAgICAgICAgICAgZG9jdW1lbnQuYm9keS5hcHBlbmRDaGlsZChnYW1lRWxlbWVudCk7XG4gICAgICAgICAgICB9XG4gICAgICAgIH0pO1xuICAgIH07XG5cbiAgICBkb2N1bWVudC5ib2R5LmFwcGVuZENoaWxkKGxvYWRlckVsZW1lbnQpO1xufVxuXG5mdW5jdGlvbiBjb3B5QXR0cmlidXRlcyhmcm9tLCB0bykge1xuICAgIHZhciBhdHRyaWJ1dGVzID0gZnJvbS5hdHRyaWJ1dGVzO1xuICAgIGZvcih2YXIgaSA9IDA7IGkgPCBhdHRyaWJ1dGVzLmxlbmd0aDsgaSsrKSB7XG4gICAgICAgIHZhciBhdHRyID0gYXR0cmlidXRlc1tpXTtcbiAgICAgICAgdG8uc2V0QXR0cmlidXRlKGF0dHIubmFtZSwgYXR0ci52YWx1ZSk7XG4gICAgfVxufVxuXG52YXIgZ2VuZXJhdGVOYW1lID0gKGZ1bmN0aW9uKCkge1xuICAgIHZhciBnZW5lcmF0ZWRJbmRleCA9IDE7XG4gICAgcmV0dXJuIGZ1bmN0aW9uKG5hbWUpIHtcbiAgICAgICAgcmV0dXJuIG5hbWUgfHwgJ05vbGltaXQtJyArIGdlbmVyYXRlZEluZGV4Kys7XG4gICAgfTtcbn0pKCk7XG5cbm1vZHVsZS5leHBvcnRzID0gbm9saW1pdDtcbiJdfQ==
import numpy as np from utils import * def spectra_sym_gen(eobj, x, y, adv_value=1, testgen_factor=.2, testgen_size=0): v_type=type(adv_value) model=eobj.model failing=[] passing=[] #inputs=[] sp=x.shape x_flag=np.zeros(sp, dtype=bool) portion=int(sp[0]*testgen_factor) incr=1/6*portion if portion<1: portion=1 L0=np.array(np.arange(x.size)) L0=np.reshape(L0, sp) while (not np.all(x_flag)) or len(passing)+len(failing)<testgen_size: #print ('####', len(passing), len(failing)) t=x.copy() i0=np.random.randint(0,sp[0]) i1=np.random.randint(0,sp[1]) h=portion region=L0[ np.max([i0-h,0]) : np.min([i0+h, sp[0]]), np.max([i1-h,0]):np.min([i1+h,sp[1]])].flatten() L=region #L0[0:portion] if v_type==np.ndarray: np.put(t, L, adv_value.take(L)) else: np.put(t, L, adv_value) x_flag.flat[L]=True #np.put(x, L, True) new_y=np.argsort(model.predict(sbfl_preprocess(eobj, np.array([t]))))[0][-eobj.top_classes:] is_adv=(len(np.intersect1d(y, new_y))==0) if is_adv: failing.append(t) ## to find a passing ite=h #testgen_factor while ite>1: #ite>0.01: t2=x.copy() #ite=ite-1#ite//2 #ite=(ite+0)/2 ite=int(ite-incr) if ite<1: break region=L0[ np.max([i0-ite,0]) : np.min([i0+ite, sp[0]]), np.max([i1-ite,0]):np.min([i1+ite,sp[1]])].flatten() L=region #L0[0:portion] if v_type==np.ndarray: np.put(t, L, adv_value.take(L)) else: np.put(t, L, adv_value) x_flag.flat[L]=True #np.put(x, L, True) new_y=np.argsort(model.predict(sbfl_preprocess(eobj, np.array([t]))))[0][-eobj.top_classes:] #is_adv=(len(np.intersect1d(y, new_y))==0) #ite-=0.01 #L2=L0[0:int(ite/testgen_factor*portion)] #if v_type==np.ndarray: # np.put(t2, L2, adv_value.take(L2)) #else: # np.put(t2, L2, adv_value) #new_y=np.argsort(model.predict(sbfl_preprocess(eobj, np.array([t2]))))[0][-eobj.top_classes:] ##print (y, new_y) if (len(np.intersect1d(y, new_y))!=0): passing.append(t2) break else: passing.append(t) ## to find a failing ite=h #testgen_factor while ite<sp[0]/2: #0.99: t2=x.copy() #ite=ite+1#ite*2 ite=int(ite+incr) if ite>sp[0]/2: break region=L0[ np.max([i0-ite,0]) : np.min([i0+ite, sp[0]]), np.max([i1-ite,0]):np.min([i1+ite,sp[1]])].flatten() L=region #L0[0:portion] if v_type==np.ndarray: np.put(t, L, adv_value.take(L)) else: np.put(t, L, adv_value) x_flag.flat[L]=True #np.put(x, L, True) new_y=np.argsort(model.predict(sbfl_preprocess(eobj, np.array([t]))))[0][-eobj.top_classes:] #t2=x.copy() #ite=(ite+1)/2 ##ite+=0.01 #L2=L0[0:int(ite/testgen_factor*portion)] #if v_type==np.ndarray: # np.put(t2, L2, adv_value.take(L2)) #else: # np.put(t2, L2, adv_value) #new_y=np.argsort(model.predict(sbfl_preprocess(eobj, np.array([t2]))))[0][-eobj.top_classes:] if (len(np.intersect1d(y, new_y))==0): failing.append(t2) x_flag.flat[L]=True break return np.array(passing), np.array(failing) def spectra_gen(x, adv_value=1, testgen_factor=0.01, testgen_size=0): #print (adv_value, testgen_factor, testgen_size) v_type=type(adv_value) inputs=[] sp=x.shape x_flag=np.zeros(sp, dtype=bool) portion=int(x.size*testgen_factor) #int(x.size/sp[2]*testgen_factor) while (not np.all(x_flag)) or len(inputs)<testgen_size: t=x.copy() L=np.random.choice(x.size, portion) if v_type==np.ndarray: #t.flat[L]=adv_value.take(L) np.put(t, L, adv_value.take(L)) else: #t.flat[L]=adv_value np.put(t, L, adv_value) x_flag.flat[L]=True #np.put(x, L, True) #for pos in L: # ipos=np.unravel_index(pos,sp) # #if v_type==np.ndarray: # # t.flat[pos]=adv_value.flat[pos] # #else: t.flat[pos]=adv_value # #x_flag.flat[pos]=True #np.put(x, L, True) # for j in range(0, sp[2]): # if v_type==np.ndarray: # t[ipos[0]][ipos[1]][j]=adv_value[ipos[0]][ipos[1]][j] # else: # t[ipos[0]][ipos[1]][j]=adv_value # x_flag[ipos[0]][ipos[1]][j]=True inputs.append(t) return inputs
import pytest # Make sure these tests do not run if ASDF is not installed pytest.importorskip('asdf') import numpy as np import astropy.units as u from astropy.coordinates import FK5 from asdf.tests.helpers import assert_roundtrip_tree import asdf from specutils import Spectrum1D, SpectrumList def create_spectrum1d(xmin, xmax, uncertainty=None): flux = np.ones(xmax-xmin) * u.Jy wavelength = np.arange(xmin, xmax) * u.AA uncertainty = np.ones(xmax-xmin) if uncertainty is not None else None return Spectrum1D(spectral_axis=wavelength, flux=flux, uncertainty=uncertainty) def test_asdf_spectrum1d(tmpdir): spectrum = create_spectrum1d(5100, 5300) tree = dict(spectrum=spectrum) assert_roundtrip_tree(tree, tmpdir) def test_asdf_spectrum1d_uncertainty(tmpdir): spectrum = create_spectrum1d(5100, 5300, uncertainty=True) tree = dict(spectrum=spectrum) assert_roundtrip_tree(tree, tmpdir) def test_asdf_spectrumlist(tmpdir): spectra = SpectrumList([ create_spectrum1d(5100, 5300), create_spectrum1d(5000, 5500), create_spectrum1d(0, 100), create_spectrum1d(1, 5) ]) tree = dict(spectra=spectra) assert_roundtrip_tree(tree, tmpdir) @pytest.mark.filterwarnings("error::UserWarning") def test_asdf_url_mapper(): """Make sure specutils asdf extension url_mapping doesn't interfere with astropy schemas""" frame = FK5() af = asdf.AsdfFile() af.tree = {'frame': frame}
/** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Initializes the FriendlyEats app. */ function FriendlyEats() { this.filters = { city: '', price: '', category: '', sort: 'Rating' }; this.dialogs = {}; firebase.firestore().settings({ timestampsInSnapshots: true }); var that = this; // firebase.auth().signInAnonymously().then(function() { that.initTemplates(); that.initRouter(); that.initReviewDialog(); that.initChartDialog(); that.initFilterDialog(); // }).catch(function(err) { // console.log(err); // }); } /** * Initializes the router for the FriendlyEats app. */ FriendlyEats.prototype.initRouter = function() { this.router = new Navigo(); var that = this; this.router .on({ '/': function() { that.updateQuery(that.filters); } }) .on({ '/setup': function() { that.viewSetup(); } }) .on({ '/restaurants/*': function() { var path = that.getCleanPath(document.location.pathname); var id = path.split('/')[2]; that.viewRestaurant(id); } }) .resolve(); firebase .firestore() .collection('restaurants') .limit(1) .onSnapshot(function(snapshot) { if (snapshot.empty) { that.router.navigate('/setup'); } }); }; FriendlyEats.prototype.getCleanPath = function(dirtyPath) { if (dirtyPath.startsWith('/index.html')) { return dirtyPath.split('/').slice(1).join('/'); } else { return dirtyPath; } }; FriendlyEats.prototype.getFirebaseConfig = function() { return firebase.app().options; }; FriendlyEats.prototype.getRandomItem = function(arr) { return arr[Math.floor(Math.random() * arr.length)]; }; FriendlyEats.prototype.data = { words: [ 'Bar', 'Fire', 'Grill', 'Drive Thru', 'Place', 'Best', 'Spot', 'Prime', 'Eatin\'' ], cities: [ 'Albuquerque', 'Arlington', 'Atlanta', 'Austin', 'Baltimore', 'Boston', 'Charlotte', 'Chicago', 'Cleveland', 'Colorado Springs', 'Columbus', 'Dallas', 'Denver', 'Detroit', 'El Paso', 'Fort Worth', 'Fresno', 'Houston', 'Indianapolis', 'Jacksonville', 'Kansas City', 'Las Vegas', 'Long Island', 'Los Angeles', 'Louisville', 'Memphis', 'Mesa', 'Miami', 'Milwaukee', 'Nashville', 'New York', 'Oakland', 'Oklahoma', 'Omaha', 'Philadelphia', 'Phoenix', 'Portland', 'Raleigh', 'Sacramento', 'San Antonio', 'San Diego', 'San Francisco', 'San Jose', 'Tucson', 'Tulsa', 'Virginia Beach', 'Washington' ], categories: [ 'Brunch', 'Burgers', 'Coffee', 'Deli', 'Dim Sum', 'Indian', 'Italian', 'Mediterranean', 'Mexican', 'Pizza', 'Ramen', 'Sushi' ], ratings: [ { rating: 1, text: 'Would never eat here again!' }, { rating: 2, text: 'Not my cup of tea.' }, { rating: 3, text: 'Exactly okay :/' }, { rating: 4, text: 'Actually pretty good, would recommend!' }, { rating: 5, text: 'This is my favorite place. Literally.' } ] }; window.onload = function() { window.app = new FriendlyEats(); };
/** * NOTE: * * This file is automatically generated by i18n-tools. * DO NOT CHANGE IT BY HAND or your changes will be lost. */ // Norwegian Bokmål export default { 'fabric.atlassianSwitcher.switchTo': 'Bytt til', 'fabric.atlassianSwitcher.switchToTooltip': 'Bytt til …', 'fabric.atlassianSwitcher.recent': 'Nylige', 'fabric.atlassianSwitcher.more': 'Mer', 'fabric.atlassianSwitcher.try': 'Prøv', 'fabric.atlassianSwitcher.manageList': 'Administrer liste', 'fabric.atlassianSwitcher.jiraProject': 'Jira-prosjekt', 'fabric.atlassianSwitcher.confluenceSpace': 'Confluence-område', 'fabric.atlassianSwitcher.people': 'Personer', 'fabric.atlassianSwitcher.administration': 'Administrasjon', 'fabric.atlassianSwitcher.discoverMore': 'Få mer informasjon', 'fabric.atlassianSwitcher.browseApps': 'Bla gjennom Marketplace-apper', 'fabric.atlassianSwitcher.errorHeading': 'Noe har gått galt', 'fabric.atlassianSwitcher.errorText': 'Vi registrerer disse feilene, men ta gjerne kontakt hvis det ikke hjelper å oppdatere', 'fabric.atlassianSwitcher.errorImageAltText': 'En robot som har brutt sammen, og en rekke personer som er opptatt med å fikse den.', 'fabric.atlassianSwitcher.errorTextNetwork': 'Vi kunne ikke laste denne listen. Last inn siden på nytt og prøv igjen.', 'fabric.atlassianSwitcher.errorTextLoggedOut': 'Du er logget av. Logg inn igjen.', 'fabric.atlassianSwitcher.login': 'Logg inn', 'fabric.atlassianSwitcher.show.more.sites': 'Vis flere sider', }; //# sourceMappingURL=nb.js.map